A word from our sponsors

This is an old revision of the document!


Interpreter

Code interpretion

Bash scripts are not compiled into executable binary files, but are rather fed into the bash interpreter which reads the script character by character from the input it is given. The input is parsed and tokenized, i.e. commands and control structures seperated from data, and finally executed. This character -based approach to interpreting the given input has the upside of having a small memory footprint, but the downside of being susceptible to code injection.

Example:

code_injection.sh
#!/bin/bash
echo "This line will be only printed once!"
padded=$(printf '%*s' $(sed -e 's/^[[:space:]]*//' $0 | wc -c) ' ' | cat - "$0")
echo "$padded" > "$0"

When executed with:

user@host:~$ ./code_injection.sh 
This line will be only printed once!
This line will be only printed once!
This line will be only printed once!
[...]

the above script rewrites itself, shifting the start of the script content to the position after the last previous content. Since the interpreter is currently at this position, it reads and executes the script from there again and again and again.

Command groups

Bash script code can use command groups to encapsulate any number of commands to be read and executed as a single unit. There are two seperate ways of command groups:

  • ( cmd list ) executes the commands in the list in a subshell, causing variable assignments not to be retained.
  • { cmd list; } executes the commands in the list in the current shell.

Example:

code_injection.sh
#!/bin/bash
{
  echo "This line will be only printed once!"
  padded=$(printf '%*s' $(sed -e 's/^[[:space:]]*//' $0 | wc -c) ' ' | cat - "$0")
  echo "$padded" > "$0"
  exit 0
}

When executed with:

user@host:~$ ./code_injection.sh 
This line will be only printed once!
user@host:~$

the above script rewrites itself, shifting the start of the script content to the position after the last previous content.

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website. More information about cookies