I have a simple program in C, with compiler switches: /GS-
It is just a proof of concept of changing the EIP to the location of the machine code string.
Let's say we set EIP = 0x012f5000, which puts the EIP at the address of the following array:
char code[] = "\x00\x00\x8B\x00\x00";
I don't know exactly what these instructions will do, but the x00 instructions appear to be noops. Switching the EIP to any other location in the program seems to cause to issue, but when I point EIP to this array's address, I get some "access violation" exception at that location of the EIP.
Why am I getting this error? Is this because of some kind of Windows protection mechanism ? Or is it that Windows cannot run intructions in this string form? How do you get the program to execute these instructions?
I guess you using x86 32 bit machine code if not my answer is not correct.
Your machine code gives the following
0000 ADD BYTE PTR DS:[EAX],AL
8B00 MOV EAX,DWORD PTR DS:[EAX]
00XX ADD BYTE PTR ??? ; depends on the next byte
As you can see if you try to execute this it try to access the memory at the address whatever in eax
is. It also dont end with a ret
or something else, so it will run straight forward without care what follows. In most cases this will crash. Anyway it is also possible that you cannot execute code defined in the DATA segment.
If you want to execute some shellcode you can try like the following simple template. The idea is to create the code on the stack and execute it there. The given machine code function is not well implemented but at least correct and will not cause a crash. Its equivalent to the C code
void f( void ) { return; };
compiled by VC++ in Debug mode.
#include <stdio.h>
int main()
{
const char code[] = "\x55\x8B\xEC\x81\xEC\xC0\x00\x00"
"\x00\x53\x56\x57\x8D\xBD\x40\xFF"
"\xFF\xFF\xB9\x30\x00\x00\x00\xB8"
"\xCC\xCC\xCC\xCC\xF3\xAB\x5F\x5E"
"\x5B\x8B\xE5\x5D\xC3";
printf("Start execution\r\n");
((void (*)())code)();
printf("End execution\r\n");
_getch();
}
If the above dont work you can try.
#include "stdafx.h"
#include <stdio.h>
#include <Windows.h>
int main()
{
const char code[] = "\x55\x8B\xEC\x81\xEC\xC0\x00\x00"
"\x00\x53\x56\x57\x8D\xBD\x40\xFF"
"\xFF\xFF\xB9\x30\x00\x00\x00\xB8"
"\xCC\xCC\xCC\xCC\xF3\xAB\x5F\x5E"
"\x5B\x8B\xE5\x5D\xC3";
void *exec = VirtualAlloc(0, sizeof(code), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
memcpy(exec, code, sizeof(code));
printf("Start execution\r\n");
((void(*)())exec)();
printf("End execution\r\n");
//_getch();
}
The idea is to use allocated memory pages with the flag PAGE_EXECUTE_READWRITE
.