Avoiding Command Injection in Shell Scripts
Command injection happens when data that was meant to be a plain value ends up being parsed as shell code. A file name, a search term or a form field contains characters such as ;, $( ), quotes or newlines, the script pastes that value into a piece of code, and the shell (or another interpreter such as awk or sed) runs part of the value as a command.
The cause is almost always the same: building code by joining strings. The cure is also always the same: keep code and data separate. Code is written by you, in single quotes or in the script itself. Data travels separately, as arguments, environment variables or standard input, so no interpreter ever reads it as code.
All examples in this lesson use harmless payloads such as echo INJECTED so you can try them safely. In a real attack, the same position would hold a command that deletes files, steals credentials or opens a remote connection.
Understanding the Concept
When Bash runs a command, it first parses the text: it finds the command name, the arguments, the operators such as ; and |, the quotes and the expansions. Only after parsing does it expand variables. This order is what protects ordinary scripts:
input='a.txt; echo INJECTED'
cat -- "$input"
cat: 'a.txt; echo INJECTED': No such file or directory
The ; inside $input is never seen by the parser, because the variable is expanded after parsing, and the double quotes keep the value as one word. cat simply receives a strange file name.
Injection appears when a value is expanded and then parsed again. Every place that parses a string as code is a potential injection point:
| Code that parses a string | Typical mistake |
|---|---|
eval | eval "echo $input" |
bash -c, sh -c | bash -c "cat $input" |
ssh host COMMAND | ssh host "grep $term /var/log/app.log" |
find -exec sh -c, xargs sh -c | sh -c 'echo {}' |
awk program text | awk "/$term/" |
sed script text | sed "s/x/$input/" |
| arithmetic | (( n = input + 1 )) |
| variable names | ${!input}, printf -v "$input", declare "$input=..." |
source, . | source "$user_supplied_file" |
The Classic Case: bash -c and eval
In the following examples, the file a.txt contains the single line hello.
input='a.txt; echo INJECTED'
bash -c "cat $input"
hello
INJECTED
The double-quoted string was expanded first, producing the code cat a.txt; echo INJECTED, and then the new Bash process parsed it. cat printed the file, and the injected command ran too. eval behaves in exactly the same way, because it also parses its argument as code:
eval "echo Hello $input"
Hello a.txt
INJECTED
The Fix: Pass Data as Arguments
bash -c and sh -c accept arguments after the code string. The first one becomes $0 (by convention a short name such as _), and the rest become $1, $2 and so on. The code is written in single quotes, so nothing is expanded when it is built:
bash -c 'cat -- "$1"' _ "$input"
cat: 'a.txt; echo INJECTED': No such file or directory
The value arrives as $1, an ordinary argument that is never parsed. This pattern, fixed code in single quotes plus data as arguments, is the most important technique in this lesson. For eval, the best fix is usually not to use it at all; lesson 157 shows the alternatives.
Injection Through File Names
File names are data that other people can choose. Anyone who can create a file in a folder your script processes can choose a name containing quotes and semicolons. Consider a folder with a file whose name is x"; echo "INJECTED-BY-NAME:
find . -name 'x*' -exec sh -c 'echo "found: {}"' \;
found: ./x
INJECTED-BY-NAME
find pasted the file name into the code string in place of {}, so the quote in the name closed the string and the rest became a new command. The fix is again to pass the name as an argument:
find . -name 'x*' -exec sh -c 'echo "found: $1"' _ {} \;
found: ./x"; echo "INJECTED-BY-NAME
{} now stands alone as a separate argument, which find passes directly. With + instead of \;, many names are passed at once, and the code loops over them with for f; do ...; done. The same pattern works for xargs -0 sh -c '...' _. Never put {} inside the code string.
Injection into awk and sed
awk and sed are programming languages with their own parsers, and they can run commands: awk has system() and sed (GNU) has the e command. Building their programs from user data is just as dangerous as building shell code.
awk: Use -v or ENVIRON
printf 'line one\nline two\n' > log.txt
term='x"; system("echo INJECTED-AWK"); print "'
awk "/one/ { print \"$term\" }" log.txt
x
INJECTED-AWK
The value closed the string in the awk program and added a system() call. Passing the value as an awk variable keeps it as data:
awk -v t="$term" '/one/ { print t }' log.txt
T="$term" awk '/one/ { print ENVIRON["T"] }' log.txt
x"; system("echo INJECTED-AWK"); print "
x"; system("echo INJECTED-AWK"); print "
The two methods differ in one detail. -v processes backslash escapes in the value, while ENVIRON passes it exactly as it is:
awk -v t='a\tb' 'BEGIN { print t }'
T='a\tb' awk 'BEGIN { print ENVIRON["T"] }'
a b
a\tb
When the value must arrive byte for byte, for example a search term, use ENVIRON. Also prefer index($0, t) (literal text) to $0 ~ t (regular expression) when the user means plain text.
sed: Avoid Data in the Script
sed has no clean way to pass a value as data. With GNU sed, an attacker who controls the whole script can run commands with the e command:
user='1e echo INJECTED-SED'
sed "$user" log.txt
INJECTED-SED
line one
line two
Never let user input become a whole sed script. When user data must go into the replacement part of s///, escape the three characters that are special there (