pythoncwindowswinapidump

Diffrent hex dump values of function for C and Python code


This is my example C code for dumping MessageBoxA from user32.dll:

#include <windows.h>
#include <stdio.h>

void DumpFun(HANDLE process, LPVOID address, SIZE_T dump_size) {
    BYTE *buffer = (BYTE *)malloc(dump_size);
    if (buffer == NULL) {
        printf("Memory allocation failed\n");
        return;
    }

    SIZE_T bytes_read;
    if (ReadProcessMemory(process, address, buffer, dump_size, &bytes_read)) {
        printf("Dumping function bytes at address 0x%p:\n", address);
        for (SIZE_T i = 0; i < bytes_read; i++) {
            printf("%02X ", buffer[i]);
            if ((i + 1) % 16 == 0) printf("\n");
        }
        printf("\n");
    } else {
        printf("ReadProcessMemory failed with error %lu\n", GetLastError());
    }

    free(buffer);
}

int main() {
    HMODULE user32 = LoadLibraryA("user32.dll");
    if (!user32) {
        printf("Failed to load user32.dll\n");
        return 1;
    }

    FARPROC fun = GetProcAddress(user32, "MessageBoxA");
    if (!fun) {
        printf("Failed to get address of MessageBoxA\n");
        FreeLibrary(user32);
        return 1;
    }

    SIZE_T dump_size = 100;
    DumpFun(GetCurrentProcess(), fun, dump_size);
    FreeLibrary(user32);

    return 0;
}

And this is output:

Dumping function bytes at address 0x75C91600:
8B FF 55 8B EC 83 3D B4 6C CB 75 00 74 22 64 A1
18 00 00 00 BA FC 80 CB 75 8B 48 24 33 C0 F0 0F
B1 0A 85 C0 75 0A C7 05 20 6D CB 75 01 00 00 00
6A FF 6A 00 FF 75 14 FF 75 10 FF 75 0C FF 75 08
...

But when I try with this python code:

import ctypes
user32 = ctypes.WinDLL('user32.dll')
message_box_a = user32.MessageBoxA
message_box_a_addr = ctypes.cast(message_box_a, ctypes.c_void_p).value
print(f'Address of MessageBoxA: {hex(message_box_a_addr)}')
num_bytes = 100
buffer = (ctypes.c_ubyte * num_bytes)()
ctypes.memmove(buffer, message_box_a_addr, num_bytes)
byte_array = bytearray(buffer)
hex_bytes = ' '.join(f'{byte:02x}' for byte in byte_array)
print(f'Bytes of MessageBoxA: {hex_bytes}')

This is output

Address of MessageBoxA: 0x7ffa2749a710
Bytes of MessageBoxA: 48 83 ec 38 45 33 db 44 39 1d 02 8c 03 00 74 2e 65 48 8b 04 25 30 00 00 00 4c 8b 50 48 33 c0 f0 4c 0f b1 15 78 97 03 00 4c 8b 15 79 97 03 00 41 8d 43 01 4c 0f 44 d0 4c 89 15 6a 97 03 00 83 4c 24 28 ff 66 44 89 5c 24 20 e8 e2 02 00 00 48 83 c4 38 c3 cc cc cc cc cc cc cc cc cc cc cc cc cc 48 83 ec 38

When I check user32.dll with HxD I see that output from python is correct, but not from C?


Solution

  • In conclusion, It's just a difference between the output at 32-bit: enter image description here

    and 64-bit:

    enter image description here

    Loading C:\Windows\SysWow64\user32.dll successfully shows that op had run it in 32-bit. Can't load a 32-bit module directly into a 64-bit process, also as @ IInspectable said vice versa.