[solved] C# more x64 dll injection issues menu

User Tag List

Results 1 to 12 of 12
  1. #1
    adaephon's Avatar Active Member
    Reputation
    76
    Join Date
    May 2009
    Posts
    167
    Thanks G/R
    0/0
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    [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 12:55 AM. Reason: solved

    [solved] C# more x64 dll injection issues
  2. #2
    Cypher's Avatar Kynox's Sister's Pimp
    Reputation
    1356
    Join Date
    Apr 2006
    Posts
    5,368
    Thanks G/R
    0/4
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  3. #3
    adaephon's Avatar Active Member
    Reputation
    76
    Join Date
    May 2009
    Posts
    167
    Thanks G/R
    0/0
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Originally Posted by Cypher View Post
    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-03-2009 at 11:19 PM.

  4. #4
    Cypher's Avatar Kynox's Sister's Pimp
    Reputation
    1356
    Join Date
    Apr 2006
    Posts
    5,368
    Thanks G/R
    0/4
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.");
        }
      }

  5. #5
    adaephon's Avatar Active Member
    Reputation
    76
    Join Date
    May 2009
    Posts
    167
    Thanks G/R
    0/0
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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 12:55 AM.

  6. #6
    Cypher's Avatar Kynox's Sister's Pimp
    Reputation
    1356
    Join Date
    Apr 2006
    Posts
    5,368
    Thanks G/R
    0/4
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  7. #7
    adaephon's Avatar Active Member
    Reputation
    76
    Join Date
    May 2009
    Posts
    167
    Thanks G/R
    0/0
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Originally Posted by Cypher View Post
    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

  8. #8
    Cypher's Avatar Kynox's Sister's Pimp
    Reputation
    1356
    Join Date
    Apr 2006
    Posts
    5,368
    Thanks G/R
    0/4
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Originally Posted by adaephon View Post
    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.

  9. #9
    adaephon's Avatar Active Member
    Reputation
    76
    Join Date
    May 2009
    Posts
    167
    Thanks G/R
    0/0
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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. #10
    Cypher's Avatar Kynox's Sister's Pimp
    Reputation
    1356
    Join Date
    Apr 2006
    Posts
    5,368
    Thanks G/R
    0/4
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Originally Posted by adaephon View Post
    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.

  11. #11
    adaephon's Avatar Active Member
    Reputation
    76
    Join Date
    May 2009
    Posts
    167
    Thanks G/R
    0/0
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  12. #12
    adaephon's Avatar Active Member
    Reputation
    76
    Join Date
    May 2009
    Posts
    167
    Thanks G/R
    0/0
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

Similar Threads

  1. [WoW] [C++] Hack Loader (DLL Injection Example)
    By Cypher in forum WoW Memory Editing
    Replies: 28
    Last Post: 07-06-2010, 11:41 PM
  2. [solved] C# Dll Injection error Win 7 x64
    By adaephon in forum WoW Memory Editing
    Replies: 11
    Last Post: 09-30-2009, 07:38 AM
  3. [Tutorial] DLL Injection
    By jagged software in forum Programming
    Replies: 22
    Last Post: 04-21-2009, 03:27 AM
  4. DLL injection with windows SP3
    By Therrm in forum World of Warcraft Bots and Programs
    Replies: 3
    Last Post: 12-06-2008, 03:03 PM
  5. What are the risks with DLL injection?
    By object in forum WoW Memory Editing
    Replies: 14
    Last Post: 08-22-2008, 09:23 PM
All times are GMT -5. The time now is 03:18 AM. Powered by vBulletin® Version 4.2.3
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved. User Alert System provided by Advanced User Tagging (Pro) - vBulletin Mods & Addons Copyright © 2024 DragonByte Technologies Ltd.
Digital Point modules: Sphinx-based search