| | WoW Memory Editing WoW Memory Editing for learning purposes only.
This section is more advanced than others on MMOwned Read the section specific rules, infractions will be given out if u break them!That is including the expectations! - If you don't meet them then don't post |  | 
10-04-2009
| | New User | | | Join Date: May 2009
Posts: 31
Reputation: 4 Level up: 60%, 160 Points needed | | | | [solved] C# more x64 dll injection issues So I'm trying to write a DLL Injector in C# (as per previous post). At the moment, it appears to mostly be working. Running as a 32bit process, it can inject a 32bit dll into some other 32bit proces, and then eject it afterwards. Running as a 64bit process, it can inject a 64bit dll into another 64bit process, but the ejecting afterwards doesn't work.
I'm storing the handle retrieved upon injection in a hash-table (Dictionary) and using that handle as the lpParameter when calling CreateRemoteThread with FreeLibrary on ejection. This works fine in x86 world. I can see the Dll being injected in Sysinternals procexp, and then it is removed upon call to EjectLibrary. In x64 however, I can see the dll being injected, but nothing happens on ejection. No processes crash, and no errors are thrown either. Any thoughts on what I'm doing wrong? Relevant code is attached. (For the record, my DllMain simply returns true).
Injection: Code: public void InjectLibrary(string libPath)
{
if (!File.Exists(libPath))
throw new FileNotFoundException("Unable to find the library to inject", libPath);
string fullPath = Path.GetFullPath(libPath);
string libName = Path.GetFileName(fullPath);
if (injectedModules.ContainsKey(libName))
throw new Exception(string.Format("The library {0} has already been injected into this process.", libPath));
// declare resources that need to be freed in finally
IntPtr pLibRemote = IntPtr.Zero; // pointer to allocated memory of lib path string
IntPtr hThread = IntPtr.Zero; // handle to thread from CreateRemoteThread
IntPtr pLibFullPathUnmanaged = Marshal.StringToHGlobalUni(fullPath); // unmanaged C-String pointer
try
{
uint sizeUni = (uint)Encoding.Unicode.GetByteCount(fullPath);
// Get Handle to Kernel32.dll and pointer to LoadLibraryW
IntPtr hKernel32 = Imports.GetModuleHandle("Kernel32");
if (hKernel32 == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error());
IntPtr hLoadLib = Imports.GetProcAddress(hKernel32, "LoadLibraryW");
if (hLoadLib == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error());
// allocate memory to the local process for libFullPath
pLibRemote = Imports.VirtualAllocEx(_process.Handle, IntPtr.Zero, sizeUni, AllocationType.Commit, MemoryProtection.ReadWrite);
if (pLibRemote == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error());
// write libFullPath to pLibPath
int bytesWritten;
if (!Imports.WriteProcessMemory(_process.Handle, pLibRemote, pLibFullPathUnmanaged, sizeUni, out bytesWritten) || bytesWritten != (int)sizeUni)
throw new Win32Exception(Marshal.GetLastWin32Error());
// load dll via call to LoadLibrary using CreateRemoteThread
hThread = Imports.CreateRemoteThread(_process.Handle, IntPtr.Zero, 0, hLoadLib, pLibRemote, 0, IntPtr.Zero);
if (hThread == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error());
if (Imports.WaitForSingleObject(hThread, (uint)ThreadWaitValue.Infinite) != (uint)ThreadWaitValue.Object0)
throw new Win32Exception(Marshal.GetLastWin32Error());
// get address of loaded module
IntPtr hLibModule;// = IntPtr.Zero;
if (!Imports.GetExitCodeThread(hThread, out hLibModule))
throw new Win32Exception(Marshal.GetLastWin32Error());
if (hLibModule == IntPtr.Zero)
throw new Exception("Code executed properly, but unable to get an appropriate module handle, possible Win32Exception", new Win32Exception(Marshal.GetLastWin32Error()));
injectedModules.Add(libName, hLibModule);
}
finally
{
Marshal.FreeHGlobal(pLibFullPathUnmanaged); // free unmanaged string
Imports.CloseHandle(hThread); // close thread from CreateRemoteThread
Imports.VirtualFreeEx(_process.Handle, pLibRemote, 0, AllocationType.Release); // Free memory allocated
}
}
Ejection: Code: public void EjectLibrary(string libName)
{
string libSearchName = File.Exists(libName) ? Path.GetFileName(Path.GetFullPath(libName)) : libName;
if (!injectedModules.ContainsKey(libSearchName))
throw new Exception("That module has not been injected into the app");
// resources that need to be freed
IntPtr hThread = IntPtr.Zero;
try
{
// get handle to kernel32 and FreeLibrary
IntPtr hKernel32 = Imports.GetModuleHandle("Kernel32");
if (hKernel32 == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error());
IntPtr hFreeLib = Imports.GetProcAddress(hKernel32, "FreeLibrary");
if (hFreeLib == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error());
hThread = Imports.CreateRemoteThread(_process.Handle, IntPtr.Zero, 0, hFreeLib, injectedModules[libSearchName], 0, IntPtr.Zero);
if (hThread == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error());
if (Imports.WaitForSingleObject(hThread, (uint)ThreadWaitValue.Infinite) != (uint)ThreadWaitValue.Object0)
throw new Win32Exception(Marshal.GetLastWin32Error());
}
finally
{
Imports.CloseHandle(hThread);
}
}
Last edited by adaephon; 10-04-2009 at 02:55 AM.
Reason: solved
| Donate to remove ads, get your "DONATOR title, and get access to the MMOwned community's elite Shoutbawx. 
10-04-2009
|  | Kynox's sister's pimp Legendary User | | | Join Date: Apr 2006 Location: ntdll.dll
Posts: 4,188
Nominated 63 Times in 4 Posts  TOTM/W Award(s): 1 Reputation: 1085 Points: 55,580, Level: 35 | Level up: 16%, 3,120 Points needed |     | | | First off, just for the future, check the return value of FreeLibrary.
Second, the problem is here:
hThread = Imports.CreateRemoteThread(_process.Handle, IntPtr.Zero, 0, hFreeLib, injectedModules[libSearchName], 0, IntPtr.Zero);
Compare how you're passing in the path in that code, to the code for injection.
Pretty obvious what's going wrong. | 
10-04-2009
| | New User | | | Join Date: May 2009
Posts: 31
Reputation: 4 Level up: 60%, 160 Points needed | | | Quote:
Originally Posted by Cypher First off, just for the future, check the return value of FreeLibrary.
Second, the problem is here:
hThread = Imports.CreateRemoteThread(_process.Handle, IntPtr.Zero, 0, hFreeLib, injectedModules[libSearchName], 0, IntPtr.Zero);
Compare how you're passing in the path in that code, to the code for injection.
Pretty obvious what's going wrong. | I assume you're referring to marshalling a string etc?
In injection, I marshal the string to a pointer and pass an IntPtr which points to the string (as LoadLibrary expects a pointer to a string). FreeLibrary expects a hModule. When I inject the dll, I store the handle in a dictionary injectedModules<string, IntPtr>. Thus, injectedModules[libSearchName] is an IntPtr (the handle obtained in InjectLibrary).
Also, this doesn't explain why it works fine in x86, but fails to eject in x64.
Edit: FreeLibrary is failing by the looks of it, brb trying to see error.
Last edited by adaephon; 10-04-2009 at 01:19 AM.
| 
10-04-2009
|  | Kynox's sister's pimp Legendary User | | | Join Date: Apr 2006 Location: ntdll.dll
Posts: 4,188
Nominated 63 Times in 4 Posts  TOTM/W Award(s): 1 Reputation: 1085 Points: 55,580, Level: 35 | Level up: 16%, 3,120 Points needed |     | | Sorry, misread. I thought your injectedModules contained paths, becaues I was looking up the top. My bad.
I'm hungry so I'm gonna grab some lunch. When I get back I'll have a look at my code, test it to be sure, compare it to yours, and try and work out where the problem is.
In the meantime, here's my current code, untested: Code: // Ejects a module (fully qualified path) via process id
void Injector::EjectLib(DWORD ProcID, const std::wstring& Path)
{
using namespace Cypher;
using namespace std;
// Grab a new snapshot of the process
EnsureCloseHandle Snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,
ProcID));
if (Snapshot == INVALID_HANDLE_VALUE)
{
throw runtime_error("Injector::EjectLib: Could not get module "
"snapshot for remote process.");
}
// Get the HMODULE of the desired library
MODULEENTRY32W ModEntry = { sizeof(ModEntry) };
bool Found = false;
BOOL bMoreMods = Module32FirstW(Snapshot, &ModEntry);
for (; bMoreMods; bMoreMods = Module32NextW(Snapshot, &ModEntry))
{
wstring ModuleName(ModEntry.szModule);
wstring ExePath(ModEntry.szExePath);
Found = (ModuleName == Path || ExePath == Path);
if (Found) break;
}
if (!Found)
{
throw runtime_error("Injector::EjectLib: Could not find module in "
"remote process.");
}
// Get a handle for the target process.
EnsureCloseHandle Process(OpenProcess(PROCESS_QUERY_INFORMATION |
PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION, FALSE, ProcID));
if (!Process)
{
throw runtime_error("Injector::EjectLib: Could not get handle to "
"process.");
}
// Get the real address of FreeLibrary in Kernel32.dll
HMODULE hKernel32 = GetModuleHandleW(L"Kernel32");
if (hKernel32 == NULL)
{
throw runtime_error("Injector::EjectLib: Could not get handle to "
"Kernel32.");
}
FARPROC pFreeLibrary = GetProcAddressCustom(hKernel32, "FreeLibrary");
PTHREAD_START_ROUTINE pfnThreadRtn =
reinterpret_cast<PTHREAD_START_ROUTINE>(pFreeLibrary);
if (pfnThreadRtn == NULL)
{
throw runtime_error("Injector::EjectLib: Could not get pointer to "
"FreeLibrary.");
}
// Create a remote thread that calls FreeLibrary()
EnsureCloseHandle Thread(CreateRemoteThread(Process, NULL, 0,
pfnThreadRtn, ModEntry.modBaseAddr, 0, NULL));
if (!Thread)
{
throw runtime_error("Injector::EjectLib: Could not create thread in "
"remote process.");
}
// Wait for the remote thread to terminate
if (WaitForSingleObject(Thread, INFINITE) != WAIT_OBJECT_0)
{
throw runtime_error("Injector::InjectLib: Waiting for remote thread "
"failed.");
}
// Get thread exit code
DWORD ExitCode = 0;
if (!GetExitCodeThread(Thread,&ExitCode))
{
throw runtime_error("Injector::EjectLib: Could not get thread exit "
"code.");
}
// Check FreeLibrary succeeded and returned non-zero (true)
if(!ExitCode)
{
throw runtime_error("Injector::EjectLib: Call to FreeLibrary in "
"remote process failed.");
}
}
| 
10-04-2009
| | New User | | | Join Date: May 2009
Posts: 31
Reputation: 4 Level up: 60%, 160 Points needed | | | | Ah I think I've found the problem. When injecting into x86, the handle returned corresponds to the base adderss of the module (as would be expected). In x64 however, it seems to be returning a 32bit handle, and thus an invalid base address (base address from procexp is 0x7FEF7940000, and stored handle returned during injection is 0xF7940000 thus only 32bits). GetExitCodeThread stores the return in a DWORD so this would appear to be the problem.
I think I'll instead follow your approach, Cypher, and just look for a corresponding module in the process on ejection, rather than relying on the handle returned.
Edit: Yay that works just iterating through the modules using .Net's Process class. Will just use that to store the base address rather than relying on the out value of GetExitCodeThread
Last edited by adaephon; 10-04-2009 at 02:55 AM.
| 
10-04-2009
|  | Kynox's sister's pimp Legendary User | | | Join Date: Apr 2006 Location: ntdll.dll
Posts: 4,188
Nominated 63 Times in 4 Posts  TOTM/W Award(s): 1 Reputation: 1085 Points: 55,580, Level: 35 | Level up: 16%, 3,120 Points needed |     | | Oh of course, that's why I don't have that problem.
In fact I marked my injection code with the following comment ages ago:
" // TODO: Use remote module enumeration instead of GetThreadExitCode"
Sorry, I shoulda picked up on that. Didn't realize you were storing a 32-bit handle.
Good job on diagnosing the problem. | 
10-06-2009
| | New User | | | Join Date: May 2009
Posts: 31
Reputation: 4 Level up: 60%, 160 Points needed | | | Quote:
Originally Posted by Cypher Good job on diagnosing the problem.  | Thanks. Now to see if there is a way to force an "Any CPU" assembly to load as x86 on x64 machine programmatically at runtime, without wrapping it in an x86 launcher app, and without using corflags to change its bitness | 
10-06-2009
|  | Kynox's sister's pimp Legendary User | | | Join Date: Apr 2006 Location: ntdll.dll
Posts: 4,188
Nominated 63 Times in 4 Posts  TOTM/W Award(s): 1 Reputation: 1085 Points: 55,580, Level: 35 | Level up: 16%, 3,120 Points needed |     | | Quote:
Originally Posted by adaephon Thanks. Now to see if there is a way to force an "Any CPU" assembly to load as x86 on x64 machine programmatically at runtime, without wrapping it in an x86 launcher app, and without using corflags to change its bitness | Unless I'm misunderstanding how the JIT process works, no, that is not possible. | 
10-06-2009
| | New User | | | Join Date: May 2009
Posts: 31
Reputation: 4 Level up: 60%, 160 Points needed | | | | Yeh well my reading hasn't uncovered anything... but it shouldn't be impossible. If I have an Any CPU assembly, on x64 it will run as x64. However, if I have an x86 assembly that loads an Any CPU assembly, the Any CPU assembly will run as x86 even on an x64 machine. Thus, on an x64 machine, the JIT can dynamically chose whether an assembly is run as x64 or x86. All I want to be able to do, is make that choice for it.
But at this stage it's looking like you're right, and it's not possible. | 
10-06-2009
|  | Kynox's sister's pimp Legendary User | | | Join Date: Apr 2006 Location: ntdll.dll
Posts: 4,188
Nominated 63 Times in 4 Posts  TOTM/W Award(s): 1 Reputation: 1085 Points: 55,580, Level: 35 | Level up: 16%, 3,120 Points needed |     | | Quote:
Originally Posted by adaephon Yeh well my reading hasn't uncovered anything... but it shouldn't be impossible. If I have an Any CPU assembly, on x64 it will run as x64. However, if I have an x86 assembly that loads an Any CPU assembly, the Any CPU assembly will run as x86 even on an x64 machine. Thus, on an x64 machine, the JIT can dynamically chose whether an assembly is run as x64 or x86. All I want to be able to do, is make that choice for it.
But at this stage it's looking like you're right, and it's not possible. | Yes, but in order to tell it how to make that choice at "runtime" you need to run some code. You can't run some code without it being JITted. Hence, you are screwed. Unless you take the "loader" approach or force the assembly to always run in x86 mode I don't see how it's possible. | 
10-06-2009
| | New User | | | Join Date: May 2009
Posts: 31
Reputation: 4 Level up: 60%, 160 Points needed | | | | I was more thinking along the lines of starting a new process, i.e. Process.Start(some.exe), where some.exe is compiled as Any CPU, and somehow telling it to start it as x86. Haven't really had much time to look into it, and you're probably right that it's not possible. x86 wrapper is probably cleaner anyway. But I might still see what I can do for interest's sake. | 
10-06-2009
| | New User | | | Join Date: May 2009
Posts: 31
Reputation: 4 Level up: 60%, 160 Points needed | | | | Of course... Thinking more would help. The OS loader would be responsible for determining whether to start x86 or x64 CLR/JIT... I think I'll bump this further down the 'pursue for interest' list for the moment. |  |
Posting Rules
| You may not post new threads You may not post replies You may not post attachments You may not edit your posts HTML code is Off | | | All times are GMT -4. The time now is 11:42 AM. |