Search code examples
c#c++wpfwindowsdll-injection

DLL Injection Keeps Failing with Inconsistent Errors


I am attempting to write a DLL Injector in a C# WPF Application. I have written a DLL Injector before in Windows Forms, however I wanted to write a new program from scratch. I have written DLL Injectors before many times in many other languages (using the traditional VirtualAllocEx / WriteProcessMemory / CreateRemoteThread method), however I ran into some peculiar problems. My DLL Injector said that it was succeeding, yet my testing program showed no changes. I did some testing with Marshal.GetLastWin32Error() and got ERROR_FILE_NOT_FOUND as a result for VirtualAllocEx, WriteProcessMemory and CreateRemoteThread. I then created an Injector in C++ to test if C# was the problem. When I tested the C++ DLL Injector, every method threw the ERROR_NO_MORE_FILES error. Finally, I downloaded my old DLL Injector and found that it no longer works.

I have no idea what the problem is at all.

C# Injector Code:

IntPtr handle = OpenProcess(ProcessAccessFlags.All, false, SelectedProcess.Id);
Console.WriteLine("OpenProcess: " + new Win32Exception(Marshal.GetLastWin32Error()).Message); // This does not fail.

foreach (string files in DLLFiles.Items) // Get the files from the ListView control
{
    // Allocate memory
    IntPtr address = VirtualAllocEx(handle, IntPtr.Zero, (uint)(files.Length + 1), AllocationType.Commit, MemoryProtection.ExecuteReadWrite);
    Console.WriteLine("VirtualAllocEx: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);

    // Write in memory
    if (address != IntPtr.Zero)
    {
        bool success = WriteProcessMemory(handle, address, Encoding.ASCII.GetBytes(files), files.Length + 1, out IntPtr lpNumberOfBytesWritten);
        Console.WriteLine("WriteProcessMemory: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
        if (success)
        {
            IntPtr module = LoadLibrary("kernel32.dll"); // Get the module
            Console.WriteLine("LoadLibrary: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
            IntPtr LoadLib = GetProcAddress(module, "LoadLibraryA"); // Get the address of the function
            Console.WriteLine("GetProcAddress: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
            // Create a remote thread in the target process
            IntPtr thread_handle = CreateRemoteThread(handle, IntPtr.Zero, 0, LoadLib, address, 0, out IntPtr lpThreadId);
            Console.WriteLine("CreateRemoteThread: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
            if (thread_handle == IntPtr.Zero)
            {
                Console.Write("[");
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write(files);
                Console.ResetColor();
                Console.WriteLine("] Injection Failed: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
            }
            else
            {
                Console.Write("[");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write(files);
                Console.ResetColor();
                Console.WriteLine("] Injected Successfully.");
            }
        }
    }
}

After running it, the Console said that the injection succeeded yet the error output still kept displaying:

The system cannot find the file specified.

C++ Injector Code:

#include <windows.h>
#include <iostream>
#include <string>

int main() {
    DWORD pid = 25860; // Hardcoded for testing purposes.
    std::string str;
    HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); // Get the process handle
    std::cout << handle << std::endl;
    std::cout << "Error: " << GetLastError() << std::endl;
    LPVOID addr = VirtualAllocEx(handle, NULL, sizeof("C:\\Users\\BenHerebefore\\source\\repos\\InjectionTest\\InjectionTest\\InjectionTest.dll") + 1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    std::cout << addr << std::endl;
    std::cout << "Error: " << GetLastError() << std::endl;
    BOOL success = WriteProcessMemory(handle, addr, "C:\\Users\\BenHerebefore\\source\\repos\\InjectionTest\\InjectionTest\\InjectionTest.dll", sizeof("C:\\Users\\BenHerebefore\\source\\repos\\InjectionTest\\InjectionTest\\InjectionTest.dll") + 1, NULL);
    std::cout << success << std::endl;
    std::cout << "Error: " << GetLastError() << std::endl;
    HMODULE module = LoadLibrary("kernel32");
    std::cout << module << std::endl;
    std::cout << "Error: " << GetLastError() << std::endl;
    FARPROC proc = GetProcAddress(module, "LoadLibraryA");
    std::cout << proc << std::endl;
    std::cout << "Error: " << GetLastError() << std::endl;
    HANDLE test = CreateRemoteThread(handle, NULL, 0, (LPTHREAD_START_ROUTINE)GetProcAddress(LoadLibrary("kernel32"), "LoadLibrary"), addr, 0, NULL);
    std::cout << test << std::endl;
    std::cout << "Error: " << GetLastError() << std::endl;
    std::getline(std::cin, str);
}   

The C++ injector displays Error: 18 after every line. The result for CreateRemoteThread returns 0 and the message is Error: 5. I tried running the program as Administrator but it still didn't work.

I have absolutely no idea what the problem is.


Solution

  • According to Nina's answer, I was compiling it incorrectly. Thanks, Nina!

    Is your injector/dll the same architecture as the process you are injecting into? For example, if you are injecting into a 64bit process, your dll and your injector should be compiled as x64. Likewsie if it's x86 or WOW64 it should be compiled accordingly.