Why does CreateRemoteThread work here? - c

I'm trying to inject a thread to another process, which let the process load an external dll.
Here's the code I found on the internet, and it works.
HANDLE hThread = CreateRemoteThread (hProcess, NULL, 0,
(LPTHREAD_START_ROUTINE) GetProcAddress(
GetModuleHandle(L"kernel32"), "LoadLibraryA"),
lpMemory, 0, NULL);
if (hThread == INVALID_HANDLE_VALUE)
{
return false;
}
But from my understandings, the address returned by GetProcAddress lives in the memory space of the current process, not the targeted one.
So why does it work?
Tested on Windows 7

Related

How to write data into global variables from callback function?

According to windows API docs we can use global variable to pass data from creating thread to the new thread and I am assuming the opposite is also possible
Data can also be passed from the creating thread to the new thread using global variables.
Here is a data structure and a callback function, ptr is a pointer to heap allocated memory in main
typedef struct Output
{
char *ptr;
DWORD len;
}Output, *POutput;
Output out; // global variable
DWORD grab_output(LPVOID args)
{
DWORD dread;
BOOL success = FALSE;
while (1)
{
success = ReadFile(g_hChildStd_OUT_Rd,out.ptr, 1024, &dread, NULL);
if (!success || dread == 0 ) break;
out.ptr = realloc(out.ptr, out.len+1024);
out.len += dread;
}
}
int run()
{
BOOL res;
STARTUPINFO si;
PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES sa;
DWORD dwThreadIdArray[1];
DWORD n_size;
memset(&si, 0 ,sizeof(si));
memset(&pi, 0, sizeof(pi));
memset(&sa, 0, sizeof(sa));
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
if (!CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &sa, 0))
return GetLastError();
if (!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0))
return GetLastError();
si.cb = sizeof(STARTUPINFOA);
si.hStdError = g_hChildStd_OUT_Wr;
si.hStdOutput = g_hChildStd_OUT_Wr;
si.dwFlags |= STARTF_USESTDHANDLES;
if(!CreateProcess(NULL,
"C:\\Windows\\System32\\cmd.exe /c dir",
NULL,
NULL,
TRUE,
CREATE_NEW_CONSOLE,
NULL,
NULL,
&si,
&pi
))
{
}
else
{
handle = CreateThread(0, 0, grab_output, NULL, 0, NULL);
}
return 0;
}
int main()
{
out.ptr = malloc(1024);
out.len = 0;
run();
printf("%s\n", out.ptr);
}
when running the code out.ptr returns garbage values
gcc example.c && ./a.exe
└e╔┐═☺
for the sake of this question assume that I will be running a single thread at any given time
The reason this prints garbage values is you assumed for no clear reason that the thread finishes before you accessed the global variable.
There's too many unchecked fault points. Right now, check every function that can error for an error return and produce output in that case, and also set a flag in another global variable. Really, you shouldn't have to, but better to much than not enough. Then close the process and thread handles you aren't using.
Now we should be able to discuss synchronization.
It looks like you want to grab all of the output at once. Thus WaitForSingleObject() on your own thread handle. To produce output incrementally, you need to track input highwater and output highwater and output only the characters in between with putc().
Don't forget to null-terminate your string either, or printf() won't be happy.
You need some means to communicate between the thread and main() that the value has been updated. It is very likely that main() will execute the printf before the thread is done with ReadFile. Also you have a race condition where ReadFile might be writing to the buffer while printf is reading it.
Use a mutex, semaphore, event or similar to communcate between threads, then use WaitForSingleObject etc where appropriate. It's also not advisable to have a busy-loop inside the thread or to exit the creator thread main() while there are threads still running.
EDIT:
Note that you must also return 0 from the thread or your program will go haywire, if you somehow managed to get it compiling in the first place despite the missing return.

How to execute threads in a DLL in C

I created a DLL that is running 3 worker threads, and the main thread is in a loop waiting for the threads to complete. The threads get created, but no execution to the threads is done.
I have tried setting MessageBox functions inside the function that gets created with CreateThread() but the box does not appear. I have also tried to debug and the return value from CreateThread() is valid so the thread gets created.
BOOL WINAPI DllMain() {
main();
return 1;
}
int main() {
HANDLE h1, h2, h3;
h1 = CreateThread(first)...
h2 = CreateThread(second)...
h3 = CreateThread(third)...
WaitForSingleObject(h3, INFINITE);
return 1;
}
first() {
MessageBoxA("print some stuff");
return;
}
I have included some pseudocode of what my layout looks like. I am unable to provide the real code due to the sensitivity of it. However this is what is happening. I use LoadLibrary in another project that loads this .DLL. The DLL gets loaded and DllMain is executed. It then calls my main function which creates 3 threads. Each thread is created. But what is inside of the thread does not execute.
EDIT:
// dllmain.cpp : Defines the entry point for the DLL application.
#include <Windows.h>
void mb() {
MessageBoxW(0, L"AAAAAAAAAAAAAAAAAAAAAAAAA", L"AAAAAAAAAAAAAAAAAAAAAAa", 1);
}
void create() {
HANDLE han;
DWORD threadId;
han = CreateThread(NULL, 0, mb, NULL, 0, &threadId);
han = CreateThread(NULL, 0, mb, NULL, 0, &threadId);
han = CreateThread(NULL, 0, mb, NULL, 0, &threadId);
}
BOOL APIENTRY DllMain() {
create();
return 1;
}
[MS.Docs]: DllMain entry point (emphasis is mine) states:
Calling functions that require DLLs other than Kernel32.dll may result in problems that are difficult to diagnose. For example, calling User, Shell, and COM functions can cause access violation errors, because some functions load other system components. Conversely, calling functions such as these during termination can cause access violation errors because the corresponding component may already have been unloaded or uninitialized.
[MS.Docs]: MessageBox function resides in User32.dll, so it's Undefined Behavior (meaning that in different scenarios, it might work, it might work faulty, or it might crash).
Also, as #RbMm noticed, WaitForSingleObject doesn't belong there. I'm not sure about CreateThread either (but I couldn't find any official doc to confirm / infirm it).
Just out of curiosity, could you add a printf("main called.\n"); in main, to see how many times it is called?
because in general case DLL can be unloaded, need add reference to DLL - for it will be not unloaded until thread, which use it code executed. this can be done by call GetModuleHandleEx - increments the module's reference count unless GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT is specified. when thread exit - we dereference DLL code by call FreeLibraryAndExitThread. wait for all threads exit in most case not need. so code, inside dll can be next
ULONG WINAPI DemoThread(void*)
{
MessageBoxW(0, L"text", L"caption", MB_OK);
// dereference dlll and exit thread
FreeLibraryAndExitThread((HMODULE)&__ImageBase, 0);
}
void someFnInDll()
{
HMODULE hmod;
// add reference to dll, because thread will be use it
if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (PCWSTR)&__ImageBase, &hmod))
{
if (HANDLE hThread = CreateThread(0, 0, DemoThread, 0, 0, 0))
{
CloseHandle(hThread);
}
else
{
// dereference dll if thread create fail
FreeLibrary(hmod);
}
}
}
wait inside dll entry point is wrong, because we hold here process wide critical section. if we wait for thread exit - this wait always deadlock - thread before exit (and start) try enter this critical section, but can not because we wait for him here. so we hold critical section and wait for thread(s), but threads(s) wait when we exit from this critical section. deadlock

SetWindowsHookEx injection failed on release mode but worked on debug mode

I'm writing a program which monitors Keystrokes of a target process using SetWindowsHookEx. (IDE: Visual Studio 2013)Here's an overview of my program:
Obtain a HWND of the target process using FindWindow().
If HWND is valid, obtain the process id using GetWindowThreadProcessId()
Obtain a thread id by traversing the thread list with CreateToolhelp32Snapshot(TH32CS_THREAD)
Call SetWindowsHookEx().
Actual code:
//obtain the window handle
HWND hwnd = FindWindowA(NULL, "A valid title");
DWORD pid = 0;
//obtain the process id.
GetWindowThreadProcessId(hwnd, &pid);
//obtain the thread id.
DWORD threadId = GetThreadId(pid);
printf("Injecting to Process: %d Thread: %d\n", pid, threadId);
HMODULE hDll = LoadLibraryA("TestDLL.dll");
if (hDll == INVALID_HANDLE_VALUE)
{
printf("LoadLibrary() failed! %d!\n", GetLastError());
return 0;
}
HOOKPROC hookproc = (HOOKPROC)GetProcAddress(hDll, "KeyboardProc");
if (!hookproc)
{
printf("GetProcAddress() failed\n");
return 0;
}
HHOOK hook = SetWindowsHookEx(WH_CALLWNDPROC, hookproc, hDll, threadId);
if (!hook)
{
printf("SetWindowsHookEx() failed! %d\n", GetLastError());
return 0;
}
//post a message. This will trigger the hook and cause the target process
//to load my dll. Actual key monitoring code is inside the dll.
printf("SendMessage() returns:%d", SendMessage(hwnd, WM_NULL, 0, 0));
printf("Success!\n");
UnhookWindowsHookEx(hook);
getchar();
Under Debug mode, the output shows:
Injecting to process 4052 Thread:460
SendMessage() returns:0
Success!
A simple analysis shows that the target process did load my dll. Which means the program works. However, under release mode, the output is the same but dll is not loaded into the target process. I tried this multiple times with restarting target process each time. But still doesn't work.
How do I resolve this problem?
When you say "under Debug mode" - does it mean that you are debugging inside VS?
If so, my guess that the problem might be in permission set - you can run VS with elevated permissions or under another user/group. Try to run your release version of the app in Admin mode. Otherwise it would be a security flaw if any process can inject code into any another process.

How to start a thread with _beginthreadex?

I read on stackoverflow that when using the Windows API to start a thread _beginthreadex() is preferred over CreateThread().
I am creating threads like this using CreateThread():
DWORD WINAPI ThreadFunc(void* data)
{
// code for the thread functionality.
}
HANDLE Multicast = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
if (Multicast) { } // thread started successfully.
How do I do this with _beginthreadex() rather than CreateThread()?
Can anyone post an example?
_beginthreadex(NULL, 0, ThreadFunc, NULL,0,NULL);
should do the trick for you. You can ignore those additional parameters as most of those are optional.
The following SO links might be useful for you:
Windows threading: _beginthread vs _beginthreadex vs CreateThread C++
_beginthread vs CreateThread

Is there any possible to get the memory entry point of function?

I created a child process from within my process with CreateProcess() and suspend the child process. I can get the main entry point in the memory of child process, but how should I get function entry point of child process?
This is how I get the main entry point of child process
DWORD FindEntryPointAddress( TCHAR *exeFile )
{
BY_HANDLE_FILE_INFORMATION bhfi;
HANDLE hMapping;
char *lpBase;
HANDLE hFile = CreateFile(exeFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE)
;
if (!GetFileInformationByHandle(hFile, &bhfi))
;
hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, bhfi.nFileSizeHigh, bhfi.nFileSizeLow, NULL);
if (!hMapping)
;
lpBase = (char *)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, bhfi.nFileSizeLow);
if (!lpBase)
;
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)lpBase;
if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
;
PIMAGE_NT_HEADERS32 ntHeader = (PIMAGE_NT_HEADERS32)(lpBase + dosHeader->e_lfanew);
if (ntHeader->Signature != IMAGE_NT_SIGNATURE)
;
DWORD pEntryPoint = ntHeader->OptionalHeader.ImageBase + ntHeader->OptionalHeader.AddressOfEntryPoint;
UnmapViewOfFile((LPCVOID)lpBase);
CloseHandle(hMapping);
CloseHandle(hFile);
printf( "test.exe entry point: %p\n", pEntryPoint );
return pEntryPoint;
} // FindEntryPointAddress()
And how should I get the function foo() entry point of child process?
child process like this
void foo()
{
char str[10];
strcpy( str, "buffer\n" );
} // foo()
int main()
{
foo();
return 0;
} // main()
May one ask - what for? If you want to run the child process, CreateProcess() does that for you. Running the process from an arbitrary function makes zero sense; since the RTL won't be initialized, the process is quite likely to crash.
If you want to call a function for/from the creator process, that's what LoadLibrary()/GetProcAddress() are for. CreateProcess() is something completely different.
If you want to debug in terms of individual functions, parsing the MAP file and/or the debug symbols is the way. If the function happens to be global and exported, parsing the PE export table might help.
Also, in modern compilers, the compile-time function may not have one definite entry point in the EXE file. Inlining and all that.
I worked on something similar a long time ago and don't remember exactly so this might be off. But I believe you can get the function address from SymFromName if there is enough symbol information. Or if it's exported, just get the address directly via GetProcAddress.
To patch the entry point, you can either do a static patch on the entry point through the PE header, or suspend the process once you run it and change EIP through SetThreadContext.
use EXPORTS in the .DEF file of your child process program,
then your program can search the IAT table to find the address.
You can also search the code to find those instructions that sets the frame pointer ,
then find a possible entry point .
But you can not totally trust that address.

Resources