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