killchain-compendium/exploit/binaries/Shellcode.md

1.7 KiB

Shellcode

Writing Shellcode

  • Executing the shellcode relies on syscalls of the system

  • A 32 bit version looks like this

SECTION .data
msg     db      'Hello World!', 0Ah
 
SECTION .text
global  _start
 
_start:
 
    mov     edx, 13
    mov     ecx, msg
    mov     ebx, 1
    mov     eax, 4
    int     80h
 
    mov     ebx, 0      ; return 0 status on exit - 'No Errors'
    mov     eax, 1      ; invoke SYS_EXIT (kernel opcode 1)
    int     80h
  • A 64 bit version looks like this
global _start

section .text
_start:
    jmp MESSAGE      

OUTPUT:
    mov rax, 0x1
    mov rdi, 0x1
    pop rsi          

    mov rdx, 0xd
    syscall

    mov rax, 0x3c
    mov rdi, 0x0
    syscall

MESSAGE:
    call OUTPUT       
    db "Hello, world!", 0dh, 0ah

Compilation

  • Compile and link 32 bit
nasm -f elf helloworld.asm
ld -m elf_i386 helloworld.o -o helloworld
  • Compile and link 64 bit
nasm -f elf64 helloworld.asm
ld helloworld.o -o helloworld

Dump the binary

  • Dump the binary with objdump -d helloworld and take a look at the text section
  • Dump the text section into a file via
objcopy -j .text -O binary helloworld helloworld.text

Format the Shellcode

  • Format and test the code by dumping it into a c file
xxd -i helloworld.text > helloworld.c
sed -i '1s/^/#include<stdio.h>\n\n/' helloworld.c
echo -e "\n\t(*(void(*)())helloworld_text)();\n\treturn 0;\n}" >> helloworld.c
  • Compile the c file with an exectuable stack
gcc -z execstack -g -o helloworld helloworld.c