Skip to content
Advertisement

Why does my shellcode segfault when executed from C, but not as a stand-alone executable?

I’m trying to execute a shell with shellcode. I’ve made this code in a 64-bits machine:

section .text
    global _start

_start:
    xor rax, rax
    push rax
    mov rbx, "/bin//sh"
    push rbx
    mov rdi, rsp
    mov al, 59
    syscall

    mov al, 60
    xor rdi, rdi
    syscall

After using nasm and linking with ld if i execute the file this works fine. The problem is if i get the shellcode from this and tried to execute it with this program:

int main(){
    char *shellcode = "x48x31xc0x50x48xbbx2fx62x69x6ex2fx2fx73x68x53x48x89xe7xb0x3bx0fx05xb0x3cx48x31xffx0fx05";

    (*(void(*)()) shellcode)();
}

It gives me a segmentation fault error. I can’t see what’s wrong here. Any help would be appreciated.

EDIT: Already tried the gcc -z execstack to make the stack executable, still gives a segmentation fault error

Advertisement

Answer

It is normal, because your shellcode is not setting the registers rsi and rdx, and when your C program executes the shellcode will have garbage in the registers rdi and rdx. It is because the syscall execve needs more arguments.

int execve (const char *filename, const char *argv [], const char *envp[]);

As extra information, the segmentation fault is because after your execve syscall you will get an error in rax and you will move 60 to the last 8 bits of rax and call to this syscall that doesn’t exist.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement