Dll Injecting - Writing native code inside another process
-
26-06-2021 - |
Question
Ok so I have a question about step 3 of C++ Dll Injection, that is:
Use CreateRemoteThread(). You can point it at
LoadLibrary()
as the entry point and the file path from steps 1 and 2 as the argument. That's a bit hacky, to be honest, but if you are injecting a DLL you're already being quite hacky. Another technique would be to use steps 1 & 2 to load some machine code into the remote proceess and point it at that.
So my question is: After I allocated memory using VirtualAllocEx
, and writing the code with WriteProcessMemory
, how do I make the call to CreateRemoteThread
— and by that I mean what are the fourth and fifth parameters?
My code:
AllocatedMem = VirtualAllocEx(Proc, IntPtr.Zero, code.Length,
AllocationType.Reserve | AllocationType.Commit, MemoryProtection.ReadWrite);
WriteProcessMemory(Proc, AllocatedMem, code, code.Length, IntPtr.Zero);
CreateRemoteThread(Proc, IntPtr.Zero, 0, AllocatedMem,
IntPtr.Zero, 0, IntPtr.Zero);
Solution
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682437(v=vs.85).aspx
HANDLE WINAPI CreateRemoteThread(
_In_ HANDLE hProcess,
_In_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ SIZE_T dwStackSize,
_In_ LPTHREAD_START_ROUTINE lpStartAddress,
_In_ LPVOID lpParameter,
_In_ DWORD dwCreationFlags,
_Out_ LPDWORD lpThreadId
);
hProcess ia handle to the process in which the thread should be created.
lpThreadAttributes can be NULL to specify "use default"
dwStackSize can be zero to specify "use default"
lpStartAddress is the address IN THE FOREIGN PROCESS where the thread will begin executing
lpParameter is the argument passed to the ThreadMain in the foreign process (i.e. in the foreign process, lpStartAddress is assumed called using WINAPI calling convention with lpParameter as the only parameter).
dwCreationFlags can be zero.
lpThreadId should be a pointer to a DWORD that receives the thread id if successful.
If you set lpStartAddress to the address of LoadLibraryW and set lpParameter to a pointer IN THE FOREIGN PROCESS to L"foo.dll", then when the thread starts in the foreign process it will immediately call LoadLibraryW(L"foo.dll") in the foreign process, allowing you to run code from inside your DllMain.
OTHER TIPS
From the MSDN Documentation
:
HANDLE WINAPI CreateRemoteThread(
_In_ HANDLE hProcess,
_In_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ SIZE_T dwStackSize,
_In_ LPTHREAD_START_ROUTINE lpStartAddress,
_In_ LPVOID lpParameter,
_In_ DWORD dwCreationFlags,
_Out_ LPDWORD lpThreadId
);
So your 4th parameter should be a pointer to LoadLibrary
, and the 5th your code to run.
Update
Example:
LoadLibAddy = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
CreateRemoteThread(
Proc,
IntPtr.Zero,
0,
LoadLibAddy,
AllocatedMem,
0,
IntPtr.Zero
);
Note: You'll need to pinvoke the additional functions, and your 'code' should be the path to your native DLL.