Home > database >  Trying to execute a bash script in NASM
Trying to execute a bash script in NASM

Time:08-18

Hello I am quite a beginner in nasm. I am trying to write a program that executes a script, that takes one argument, with /bin/bash.

 SECTION .data
      command db '/bin/bash', 0
      script  db 'path/to/script', 0
      script_arg db 'my_arg', 0
      arguments dd command
                dd script  ; arguments to pass to commandline, in this case just the path to the script
                dd script_arg
                dd  0

SECTION .text
global  _start

_start:

    mov edx, 0 ; no environment variables are being used
    mov ecx, arguments ; array of pointers has to be passed
    mov ebx, command    ; bash
    mov eax, 11   ; invoke SYS_EXECVE 
    int     80h

The code above just executes the script with bash but does not add any arguments to the script itself. I tried to pass it as an additional argument but that does nothing. If I add the argument to the path to script string (path/to/script arg1) it breaks the terminal (color theme is set to just white text) and other than that does nothing.

Also what would be the easiest way of changing the contents of the arguments pointer array? How would I define that in .bss section and change its contents while the program is running? At least a point to the documentation about that would be nice...

CodePudding user response:

When I put in run-bash.asm :

SECTION .data
      command db '/bin/bash', 0
      script  db './test.sh', 0
      script_arg db 'my_arg', 0
      arguments dd command
                dd script  ; arguments to pass to commandline, in this case just the path to the script
                dd script_arg
                dd  0

SECTION .text
global  _start

_start:

    mov edx, 0 ; no environment variables are being used
    mov ecx, arguments ; array of pointers has to be passed
    mov ebx, command    ; bash
    mov eax, 11   ; invoke SYS_EXECVE 
    int     80h

And put in test.sh :

#!/usr/bin/env bash
  
echo "First argument is : $1"

The run it with :

nasm -f elf run-bash.asm
ld -m elf_i386 run-bash.o -o run-bash
chmod  x run-bash
./run-bash
# Output : 
# First argument is : my_arg
  • Related