Skip to content

C# Remote Codecave Injection x64

C# Remote Codecave Injection x64

Below is an implementation to perform a remote codecave injection onto a x64 process using c#. Since x64 does not offer jmp absolute_addr anymore, we will have to do it using 2 steps – mov rax, addr and jmp rax In your codecave, you will have to remember to do two things – executing the original memory code, before jumping back to original code.
// 12 bytes
byte[] patch = {
    0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rax, absolute addr
    0xFF, 0xE0 // jmp rax

public IntPtr Codecave_x64(IntPtr hProcess, IntPtr addressToHook, IntPtr gotoAddress, int numOfBytes)
    byte[] gotoAddressBytes = BitConverter.GetBytes((long)gotoAddress.ToInt64());
    Array.Copy(gotoAddressBytes, 0, patch, 2, 8);

    // Write bytes for hook
    uint oldProtect;
    VirtualProtectEx(hProcess, addressToHook, (UInt32)patch.Length, (uint)Protection.PAGE_EXECUTE_READWRITE, out oldProtect);
    WriteBuffer(hProcess, addressToHook, patch);

    // Fill Nops
    if (numOfBytes > patch.Length)
        for (int i = 0; i < patch.Length - numOfBytes; i++)
            WriteByte(addressToHook + patch.Length + i, 0x90);

    VirtualProtectEx(hProcess, addressToHook, (UInt32)patch.Length, oldProtect, out oldProtect);

    return IntPtr.Zero;
Enjoyed the content ? Share it with your friends !
Published inDevelopmentProgramming

Be First to Comment

Leave a Reply

Your email address will not be published.