Search code examples
cx86buffer-overflowshellcode

Why does my shellcode testing program produce a segfault?


I'm trying to write a simple C program for testing if a given shellcode string works on my machine (64 bit), however every single attempt at running the below code results in a segmentation fault. Even though this "shellcode" is just some nop instructions and a break, can anybody explain what is going wrong? I've had similar experiences with shellcodes & shellcode testing programs written by other people, is there some recently introduced mitigation that I am not aware of? I am running: 5.9.0-kali1-amd64 #1 SMP Debian 5.9.1-1kali2 (2020-10-29) x86_64 GNU/Linux.

#include <stdlib.h>
#include <stdio.h>

#define CODE "\x90\x90\x90\x90\x90\x90\x90\xCC";

int main(int argc, char const *argv[])
{
    int (*func)();
    func = (int (*)()) CODE;
    (int)(*func)();
}

This is the command/flags I use to compile the code.

gcc -fno-stack-protector -z execstack -no-pie -m64 -o shell shell.c

Solution

  • The 0xCC at the end is INT3 or a which should result in Trace/breakpoint trap

    If you change 0xCC to 0xC3, it will return without faulting.

    One possible mitigation would be if your compiler is putting constant strings into .rdata instead of .text .

    Instead of:

    #define CODE #define CODE "\x90\x90\x90\x90\x90\x90\x90\xCC";
    

    try

    __attribute__((section(".text")))
    static const unsigned char code[] = "\x90\x90\x90\x90\x90\x90\x90\xCC";