Question

    unsigned char hexData[14] = {
    0x31, 0xC0, 0xBB, 0x42, 0x24, 0x80, 0x7C, 0x66,
    0xB8, 0x88, 0x13, 0x50, 0xFF, 0xD3
};

void dummy(){}

int main()
{
    void *code_ptr = &dummy;
    PDWORD OP;
    __asm
    {
        call code_ptr
        add code_ptr,10h
    }
    VirtualProtect(code_ptr, 14, PAGE_EXECUTE_WRITECOPY, OP);
    memcpy(code_ptr, hexData, 14);
.
.
.

and in disassembly

_LoadLibraryA@4:
003C11E0  jmp         _LoadLibraryA@4 (03C1430h)  
dummy:
003C11E5  jmp         dummy (03C1A80h)  
_printf:
003C11EA  jmp         _printf (03C1436h)  
_VirtualProtect@16:
003C11EF  jmp         _VirtualProtect@16 (03C143Ch)  
003C11F4  int         3  
003C11F5  int         3  
003C11F6  int         3  
003C11F7  int         3 

so it seems i can copy something 15 blocks after 003C11E5
but when i do that i get access Access violation error

I tried using VirtualAlloc like

void *code_ptr = &dummy;
code_ptr = VirtualAlloc(NULL, 14, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
memcpy(code_ptr, hexData, 14);
__asm
{
    call code_ptr
}

and i got that error again

int (*func)();
func = (int (*)()) code;
(int)(*func)();

that not working either

my IDE is VS2013 and my OS is win8.1

I would appreciate any ideas

Was it helpful?

Solution

Well, OP is an uninitialized pointer. You cannot pass that to VirtualProtect. Instead of

PDWORD OP;

you need:

DWORD OldProtect;

And then pass &OldProtect to VirtualProtect.

VirtualProtect(code_ptr, 14, PAGE_EXECUTE_WRITECOPY, &OldProtect);

You existing code fails on the call to VirtualProtect. You don't check for errors and so continue regardless. Then the call to memcpy fails with a general protection fault, because the memory is read only.

Even if you fix your code, I doubt that it will work though. I see no reason for dummy to be 14 bytes long. You are relying on luck and wishful thinking. So you will probably overwrite the code that you are executing.

If you want 14 bytes of memory to write your code to, call VirtualAlloc. That way you can be certain of success.

As a piece of general advice, you will need to get into the habit of checking return values for errors. You call VirtualProtect and ignore the return value. How do you know that your call to VirtualProtect was successful?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top