ioctlvoid
ioctlvoid

Reputation: 311

Reliable shellcode testing

Code such as the following is supposed to be able to "test" shellcode, namely execute it.

char shellcode[] = "...";

int main(int argc, char **argv)
{
    int (*func)();
    func = (int (*)()) shellcode;
    (int)(*func)();
}

However, what I get when I find when I try to use examples like these is that the code seems to execute in memory that is not executable, because it receives a segfault at the very first instruction of the shellcode.

If I change the shellcode declaration to a #define instead, I am able to get the shellcode to execute. However the shellcode stops when it tries to write to its own memory (this shellcode assuming that it is executed on the stack).

So my question is simply, what is the most simple and reliable way to test shellcode that assumes an executable (obviously) and writable memory? If I allocate the code on the stack or heap and try to jump to it, I will just run into the NX-bit protection and fail once again. Now obviously I could disable the NX-bit, but is there not some better way to do this testing?

Upvotes: 2

Views: 763

Answers (2)

Yuri Ro
Yuri Ro

Reputation: 1

If all you want is to test functionality, you could just write the corresponding assembly, in a function. However, that will just test the assembly, not the shellcode as bytestring, and if your shellcode is not strictly generated by assembly (For instance if you jump to middle of "non-existing" instruction) that won't work. In this case you have to push your code into executable memory. You can allocate it yourself, or overwrite existing .text section (You'll need to disable the read-only though).

Upvotes: 0

Michael F
Michael F

Reputation: 40830

Allocate a writable and executable memory region (for example with mmap and mprotect) and position your code there, then call it as your main does. In case of executable space protections like W^X, PaX, etc., you can first make your memory area writable to copy the shellcode, then executable only to execute it, but your mileage may vary according to the protection(s) in place.

Upvotes: 1

Related Questions