Search code examples
c#c++dll-injection

C# doesn't inject c++ dll


I tried to make my own simple dll injector on c# which injects a c++ dll. When I run it doesn't throw me any errors.

I think the dll just doesn't execute in the process or it doesn't inject properly.

I'm on windows 8.

Code:

public void Injector(string dll)
    {

        try
        {
            IntPtr allocMem = VirtualAllocEx(pHandle, IntPtr.Zero, (uint)((dll.Length + 1) * Marshal.SizeOf(typeof(char))), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
            UIntPtr bytesWritten;
            WriteProcessMemory(pHandle, allocMem, Encoding.Default.GetBytes(dll), (uint)((dll.Length + 1) * Marshal.SizeOf(typeof(char))), out bytesWritten);

            CreateRemoteThread(pHandle, IntPtr.Zero, 0, Libaddr, allocMem, 0, IntPtr.Zero);
        }
        catch
        {
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }
       
    }

Full code: https://pastebin.com/LRNhfzMc


Solution

  • You never set values to the members IntPtr pHandle; and IntPtr Libaddr; in your injector class.

    Change your constructor to this:

        public injector(string proc_name)
        {
            Process proc = Process.GetProcessesByName(proc_name)[0];
            Console.WriteLine("pId: "+proc.Id);
            pHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, proc.Id);
            Console.WriteLine("Proc handle: "+ pHandle.ToString());
            Libaddr = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
        }