]> sipb.mit.edu Git - wiki.git/blob - doc/safe-shell.mdwn
more slang, class derivatives, zcrypt link, em dashes
[wiki.git] / doc / safe-shell.mdwn
1 [[!meta title="Writing Safe Shell Scripts"]]
2
3 Writing shell scripts leaves a lot of room to make mistakes, in ways that will
4 cause your scripts to break on certain input, or (if some input is untrusted)
5 open up security vulnerabilities. Here are some tips on how to make your shell
6 scripts safer.
7
8 ## Don't
9
10 The simplest step is to avoid using shell at all. Many higher-level languages
11 are both easier to write the code in in the first place, and avoid some of the
12 issues that shell has. For example, Python will automatically error out if you
13 try to read from an uninitialized variable (though not if you try to write to
14 one), or if some function call you make produces an error.
15
16 One of shell's chief advantages is that it's easy to call out to the huge
17 variety of command-line utilities available. Much of that functionality will be
18 available through libraries in Python or other languages. For the handful of
19 things that aren't, you can still call external programs. In Python, the
20 [subprocess](http://docs.python.org/2/library/subprocess.html) module is very
21 useful for this. You should try to avoid passing `shell=True` to `subprocess` (or using `os.system` or similar functions at all), since that will run a shell, exposing you to many of the same issues as plain shell has. It also has two big advantages over shell — it's a lot easier to avoid
22 [word-splitting](http://www.gnu.org/software/bash/manual/html_node/Word-Splitting.html) or similar issues, and since calls to subprocess will tend to be relatively uncommon, it's easy to scrutinize them especially hard. When using `subprocess` or similar tools, you should still be aware of the suggestions in "Passing filenames or other positional arguments to commands" below.
23
24 ## Shell settings
25
26 POSIX sh and especially bash have a number of settings that can help write safe shell scripts.
27
28 I recommend the following in bash scripts:
29
30     set -euf -o pipefail
31
32 In dash, `set -o` doesn't exist, so use only `set -euf`.
33
34 What do those do?
35
36 ### [`set -e`](http://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html)
37
38 If a command fails, `set -e` will make the whole script exit, instead of just
39 resuming on the next line. If you have commands that can fail without it being
40 an issue, you can append `|| true` or `|| :` to suppress this behavior —
41 for example `set -e` followed by `false || :` will not cause your script to
42 terminate.
43
44 ### [`set -u`](http://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html)
45
46 Treat unset variables as an error, and immediately exit.
47
48 ### [`set -f`](http://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html)
49
50 Disable filename expansion (globbing) upon seeing `*`, `?`, etc..
51
52 If your script depends on globbing, you obviously shouldn't set this. Instead,
53 you may find
54 [`shopt -s failglob`](http://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html) useful, which causes globs that don't get expanded to cause
55 errors, rather than getting passed to the command with the `*` intact.
56
57 ### [`set -o pipefail`](http://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html)
58
59 `set -o pipefail` causes a pipeline (for example, `curl -s http://sipb.mit.edu/
60 | grep foo`) to produce a failure return code if any command errors. Normally,
61 pipelines only return a failure if the last command errors. In combination with
62 `set -e`, this will make your script exit if any command in a pipeline errors.
63
64 ## Quote liberally
65
66 Whenever you pass a variable to a command, you should probably quote it.
67 Otherwise, the shell will perform
68 [word-splitting](http://www.gnu.org/software/bash/manual/html_node/Word-Splitting.html)
69 and
70 [globbing](http://www.gnu.org/software/bash/manual/html_node/Filename-Expansion.html),
71 which is likely not what you want.
72
73 For example, consider the following:
74
75     alex@kronborg tmp [15:23] $ dir="foo bar"
76     alex@kronborg tmp [15:23] $ ls $dir
77     ls: cannot access foo: No such file or directory
78     ls: cannot access bar: No such file or directory
79     alex@kronborg tmp [15:23] $ cd "$dir"
80     alex@kronborg foo bar [15:25] $ file=*.txt
81     alex@kronborg foo bar [15:26] $ echo $file
82     bar.txt foo.txt
83     alex@kronborg foo bar [15:26] $ echo "$file"
84     *.txt
85
86 Depending on what you are doing in your script, it is likely that the
87 word-splitting and globbing shown above are not what you expected to have
88 happen. By using `"$foo"` to access the contents of the `foo` variable instead
89 of just `$foo`, this problem does not arise.
90
91 When writing a wrapper script, you may wish pass along all the arguments your
92 script received. Do that with:
93
94     wrapped-command "$@"
95
96 See ["Special Parameters" in the bash
97 manual](http://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html)
98 for details on the distinction between `$*`, `$@`, and `"$@"` — the first
99 and second are rarely what you want in a safe shell script.
100
101 ## Passing filenames or other positional arguments to commands
102
103 If you get filenames from the user or from shell globbing, or any other kind of positional arguments, you should be aware that those could start with a "-". Even if you quote correctly, this may still act differently from what you intended. For example, consider a script that allows somebody to run commands as `nobody` (exposed over `remctl`, perhaps), consisting of just `sudo -u nobody "$@"`. The quoting is fine, but if a user passes `-u root reboot`, `sudo` will catch the second `-u` and run it as `root`.
104
105 Fixing this depends on what command you're running.
106
107 For many commands, however, `--` is accepted to indicate that any options are done, and future arguments should be parsed as positional parameters — even if they look like options. In the `sudo` example above, `sudo -u nobody -- "$@"` would avoid this attack (though obviously specifying in the `sudo` configuration that commands can only be run as `nobody` is also a good idea).
108
109 Another approach is to prefix each filename with `./`, if the filenames are expected to be in the current directory.
110
111 ## Temporary files
112
113 TODO: mumble `mktemp`?
114
115 ## Other resources
116
117 Google has a [Shell Style Guide](http://google-styleguide.googlecode.com/svn/trunk/shell.xml). As the name suggests, it primarily focuses on good style, but some items are safety/security-relevant.
118
119 ## Conclusion
120
121 When possible, instead of writing a "safe" shell script, *use a higher-level
122 language like Python*. If you can't do that, the shell has several *options* that
123 you can enable that will reduce your chances of having bugs, and you should be
124 sure to *quote liberally*.