DLL Can specify an entrypoint executed when some event occurs. We will code our payload in this entrypoint. There cases in which the entry point will be called:

  • DLL_PROCESS_ATTACHED - A process is loading the DLL.
  • DLL_THREAD_ATTACHED - A process is creating a new thread.
  • DLL_THREAD_DETACH - A thread exits normally.
  • DLL_PROCESS_DETACH - A process unloads the DLL.

It’s possible to use the LoadLibrary, GetModuleHandle and GetProcAddress WinAPIs to import a function from a DLL. This is referred to as dynamic linking. This is a method of loading and linking code (DLLs) at runtime rather than linking them at compile time using the linker and import address table.

DLL Execution code

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

VOID MsgBoxPayload() {
	MessageBoxA(NULL, "Executing payload", "code", MB_OK | MB_ICONINFORMATION);
}

BOOL APIENTRY DllMain (
  HMODULE hModule,    // Handle to DLL module
  DWORD dwReason,     // Reason for calling function
  LPVOID lpReserved   // Reserved
  ){
	switch (dwReason) {
  	case DLL_PROCESS_ATTACH: { // A process is loading the DLL.
	  	MsgBoxPayload();
	    break;
    };
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
    break;
  }
  return TRUE;
}

Invoking the payload

Just load the DLL to invoke the payload.

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

int main(int argc, char* argv[]) {
	if (argc < 2){
	  printf("[!] Missing Argument; Dll Payload To Run \n");
  	return -1;
  }

  printf("[i] Injecting \"%s\" To The Local Process Of Pid: %d \n", argv[1], GetCurrentProcessId());
  printf("[+] Loading Dll... ");

  if (LoadLibraryA(argv[1]) == NULL) {
  	printf("[!] LoadLibraryA Failed With Error : %d \n", GetLastError());
	  return -1;
  }

  return 0;
}