Chapter 21. Restricted Shells

Disabled commands in restricted shells

Running a script or portion of a script in restricted mode disables certain commands that would otherwise be available. This is a security measure intended to limit the privileges of the script user and to minimize possible damage from running the script.

Using cd to change the working directory.

Changing the values of the $PATH, $SHELL, $BASH_ENV, or $ENV environmental variables.

Reading or changing the $SHELLOPTS, shell environmental options.

Output redirection.

Invoking commands containing one or more /'s.

Invoking exec to substitute a different process for the shell.

Various other commands that would enable monkeying with or attempting to subvert the script for an unintended purpose.

Getting out of restricted mode within the script.


Example 21-1. Running a script in restricted mode

   1 #!/bin/bash
   2 # Starting the script with "#!/bin/bash -r"
   3 # runs entire script in restricted mode.
   4 
   5 echo
   6 
   7 echo "Changing directory."
   8 cd /usr/local
   9 echo "Now in `pwd`"
  10 echo "Coming back home."
  11 cd
  12 echo "Now in `pwd`"
  13 echo
  14 
  15 # Everything up to here in normal, unrestricted mode.
  16 
  17 set -r
  18 # set --restricted    has same effect.
  19 echo "==> Now in restricted mode. <=="
  20 
  21 echo
  22 echo
  23 
  24 echo "Attempting directory change in restricted mode."
  25 cd ..
  26 echo "Still in `pwd`"
  27 
  28 echo
  29 echo
  30 
  31 echo "\$SHELL = $SHELL"
  32 echo "Attempting to change shell in restricted mode."
  33 SHELL="/bin/ash"
  34 echo
  35 echo "\$SHELL= $SHELL"
  36 
  37 echo
  38 echo
  39 
  40 echo "Attempting to redirect output in restricted mode."
  41 ls -l /usr/bin > bin.files
  42 ls -l bin.files    # Try to list attempted file creation effort.
  43 
  44 echo
  45 
  46 exit 0