Shell scripts and security Shell scripts and security shell shell

Shell scripts and security


Because of the malleability of the shell, it is difficult to verify that a shell script performs its intended function and only that function in the face of adversarial input. The way the shell behaves depends on the environment, plus the settings of its own numerous configuration variables. Each command line is subject to multiple levels of expansion, evaluation and interpolation. Some shell constructs run in subprocesses while the variables the construct contains are expanded in the parent process. All of this is counter to the KISS principle when designing systems that might be attacked.


Probably because it's just easy to screw up. When the PATH is not set correctly, your script will start executing the wrong commands. Putting a space somewhere in a string might cause it to become two strings later on. These can lead to exploitable security holes. In short: shells give you some guarantees as to how your script will behave, but they're too weak or too complex for truly secure programming.

(To this I would like to add that secure programming is an art in itself, and screwing up is possible in any language.)


I would disagree with that statement, as there is nothing about scripts that make them inherently unsafe. Bash scripting are perfectly safe if some simple guidelines are followed:

  • Does the script contain info that others shouldn't be able to view?If so, make sure it's only readable by the owner.
  • Does the script depend on input data from somewherE? If so, ensure that input datacan not be tainted in any way, or that tainted data can be detectedand discarded.
  • Does it matter if others were to try and run thescript? If so, as with the first point, ensure that nobody can execute it, and preferably not read from it. chmod 0700 is generally a good idea for scripts that perform system functions.
  • And the cases where you'd want a script to have a setuid (via its interpreter) are extremely rare

The two points that separate a script from a compiled program would be that the source is visible, and that an interpreter executes it. As long as the interpreter hasn't been compromised (such as having a setuid bit on it), you'd be fine.

When writing scripts to do system tasks, typos and screwups and general human error when writing it do to some extent represent a potential security failure, but that would also be the case with compiled programs (and a lot of people tend to ignore the fact that compiled programs can also be disassembled)

It is worth noting that in most (if not all) linux flavors, most (if not all, in fact, can't think of any that aren't) services are started via a shellscript.