Search code examples
bashsecuritycode-injection

Is my bash script vulnerable to command injection?


I am in the process of QA'ing a fellow developers bash script. It looks something like this:

#!/bin/bash

TERM=`cat ./termName.txt` || exit $?
./other-script.sh $TERM

Given that the TERM variable isn't quoted in the last line, it feels like a malicious user could take advantage of command injection by manipulating the contents of termName.txt, however my basic attempts to prove this are failing to inject any executable commands.

My questions are:

  1. Is this script vulnerable to command injection?
  2. If yes, can you provide examples of how to execute arbitrary commands. If no, can you explain why it is safe from command injection?

Solution

  • The script is not subject to command injection, because the expansion of $TERM only undergoes word-splitting and pathname expansion before the results are passed literally to other-script.sh. However, it should be quoted so that other-script.sh receives the exact contents of TERM as a single argument.

    If TERM has the value a b, then other-script will receive two arguments, a and b, rather than one. Using "$TERM" passes the exact value a b.

    If TERM has the value *, the exact list of arguments depends the contents of the current working directory. Using "$TERM" passes the exact value *.