Practically I'm trying to execute a shellcode created from a small program in Asm x64, the problem is that it always gives me a segmentation fault error even if my shellcode is clean and I have compiled the program in C in the correct way.
Assembly code:
global _start
section .text
_start:
jmp code
string: db "Hello world", 0xa
code:
add al, 1
xor rdi, rdi
add rdi, 1
lea rsi, [rel string]
xor rdx, rdx
add rdx, 12
syscall
xor rax, rax
add rax, 60
xor rdi, rdi
syscall
Shellcode from assembly:
\xeb\x0c\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x0a\x04\x01\x48\x31\xff\x48\x83\xc7\x01\x48\x8d\x35\xe4\xff\xff\xff\x48\x31\xd2\x48\x83\xc2\x0c\x0f\x05\x48\x31\xc0\x48\x83\xc0\x3c\x48\x31\xff\x0f\x05
C code:
#include<stdio.h>
#include<string.h>
unsigned char code[] = "\xeb\x0c\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x0a\x04\x01\x48\x31\xff\x48\x83\xc7\x01\x48\x8d\x35\xe4\xff\xff\xff\x48\x31\xd2\x48\x83\xc2\x0c\x0f\x05\x48\x31\xc0\x48\x83\xc0\x3c\x48\x31\xff\x0f\x05";
int main() {
printf("Shellcode Length: %d\n", strlen(code));
int (*ret)() = (int(*)())code;
ret();
}
C compilation command:
gcc -fno-stack-protector -z execstack execSC.c -o execSC
I have the same problem even if i try to do something simple like "\x90"
If I try to run the same shellcode with Python it work and doesn't give me the segmentation fault error
import ctypes, mmap, sys
# Check Python version
if sys.version_info >= (3, 0):
def b(string, charset='latin-1'):
if isinstance(string, bytes) and not isinstance(string, str):
return (string)
else:
return bytes(string, charset)
else:
def b(string):
return bytes(string)
def create_shellcode_function (shellcode_str):
shellcode_bytes = b(shellcode_str)
# Allocate memory with a RWX private anonymous mmap
exec_mem = mmap.mmap(-1, len(shellcode_bytes),
prot = mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC,
flags = mmap.MAP_ANONYMOUS | mmap.MAP_PRIVATE)
# Copy shellcode from bytes object to executable memory
exec_mem.write(shellcode_bytes)
# Cast the memory to a C function object
ctypes_buffer = ctypes.c_int.from_buffer(exec_mem)
function = ctypes.CFUNCTYPE( ctypes.c_int64 )(ctypes.addressof(ctypes_buffer))
function._avoid_gc_for_mmap = exec_mem
# Return pointer to shell code function in executable memory
return function
shellcode = "shellcode"
create_shellcode_function(shellcode)()