Search code examples
linuxassemblynasm

execute system command (bash) using assembly?


Basically I am trying to execute the command /bin/ls using assembly, but unfortunately I am failing:

SECTION .data
    buf: db "Hello", 5
SECTION .text
global _start

_start:
    xor eax, eax
    mov edx, eax
    push edx
    mov eax, 0x736c2f2f     ; "sl/"
    push eax
    mov eax, 0x6e69622f     ; "nib/"
    push eax
    mov ebx, esp
    push edx
    mov eax, 0x2f
    push eax
    mov ecx, esp
    mov eax, 11
    xor edx, edx
    int 0x80

    mov eax, 1
    int 0x80

But If I change the mov eax, 11 to mov eax, 4 and add mov edx, 7 after xor edx, edx. It do print /bin/ls

Can anyone point the mistake I am making? Compiling the code with nasm -g -f elf -F dwarf ./shell.asm && ld -m elf_i386 -o shell shell.o and my arc is Linux kali 5.2.0-kali2-amd64 #1 SMP Debian 5.2.9-2kali1 (2019-08-22) x86_64 GNU/Linux


Solution

  • Found the problem, as pointed by @Jestor (thank you), I needed to store the executing file at ebx and all the arguments including the filename in ecx and set edx to null as below:

    SECTION .data
    buf: db "./", 0
    SECTION .text
    global _start
    
    _start:
    xor eax, eax
    xor edx, edx
    push eax
    push long 0x736c2f2f    ; "sl/"
    push long 0x6e69622f    ; "nib/"
    mov ebx, esp
    push eax
    push byte 0x2f
    mov esi, esp
    
    push eax
    push esi
    push ebx
    mov ecx, esp
    mov eax, 0x0b
    int 0x80
    
    mov eax, 1
    int 0x80
    

    after my working shell, the ecx looked like below:

    (gdb) x/50x $ecx
    0xffffd370:     0xffffd384      0xffffd37c      0x00000000      0x0000002f
    0xffffd380:     0x00000000      0x6e69622f      0x736c2f2f      0x00000000