1PERLSEC(1) Perl Programmers Reference Guide PERLSEC(1)
2
3
4
6 perlsec - Perl security
7
9 Perl is designed to make it easy to program securely even when running
10 with extra privileges, like setuid or setgid programs. Unlike most
11 command line shells, which are based on multiple substitution passes on
12 each line of the script, Perl uses a more conventional evaluation
13 scheme with fewer hidden snags. Additionally, because the language has
14 more builtin functionality, it can rely less upon external (and possi‐
15 bly untrustworthy) programs to accomplish its purposes.
16
17 Perl automatically enables a set of special security checks, called
18 taint mode, when it detects its program running with differing real and
19 effective user or group IDs. The setuid bit in Unix permissions is
20 mode 04000, the setgid bit mode 02000; either or both may be set. You
21 can also enable taint mode explicitly by using the -T command line
22 flag. This flag is strongly suggested for server programs and any pro‐
23 gram run on behalf of someone else, such as a CGI script. Once taint
24 mode is on, it's on for the remainder of your script.
25
26 While in this mode, Perl takes special precautions called taint checks
27 to prevent both obvious and subtle traps. Some of these checks are
28 reasonably simple, such as verifying that path directories aren't
29 writable by others; careful programmers have always used checks like
30 these. Other checks, however, are best supported by the language
31 itself, and it is these checks especially that contribute to making a
32 set-id Perl program more secure than the corresponding C program.
33
34 You may not use data derived from outside your program to affect some‐
35 thing else outside your program--at least, not by accident. All com‐
36 mand line arguments, environment variables, locale information (see
37 perllocale), results of certain system calls ("readdir()", "read‐
38 link()", the variable of "shmread()", the messages returned by
39 "msgrcv()", the password, gcos and shell fields returned by the "getp‐
40 wxxx()" calls), and all file input are marked as "tainted". Tainted
41 data may not be used directly or indirectly in any command that invokes
42 a sub-shell, nor in any command that modifies files, directories, or
43 processes, with the following exceptions:
44
45 · Arguments to "print" and "syswrite" are not checked for tainted‐
46 ness.
47
48 · Symbolic methods
49
50 $obj->$method(@args);
51
52 and symbolic sub references
53
54 &{$foo}(@args);
55 $foo->(@args);
56
57 are not checked for taintedness. This requires extra carefulness
58 unless you want external data to affect your control flow. Unless
59 you carefully limit what these symbolic values are, people are able
60 to call functions outside your Perl code, such as POSIX::system, in
61 which case they are able to run arbitrary external code.
62
63 For efficiency reasons, Perl takes a conservative view of whether data
64 is tainted. If an expression contains tainted data, any subexpression
65 may be considered tainted, even if the value of the subexpression is
66 not itself affected by the tainted data.
67
68 Because taintedness is associated with each scalar value, some elements
69 of an array or hash can be tainted and others not. The keys of a hash
70 are never tainted.
71
72 For example:
73
74 $arg = shift; # $arg is tainted
75 $hid = $arg, 'bar'; # $hid is also tainted
76 $line = <>; # Tainted
77 $line = <STDIN>; # Also tainted
78 open FOO, "/home/me/bar" or die $!;
79 $line = <FOO>; # Still tainted
80 $path = $ENV{'PATH'}; # Tainted, but see below
81 $data = 'abc'; # Not tainted
82
83 system "echo $arg"; # Insecure
84 system "/bin/echo", $arg; # Considered insecure
85 # (Perl doesn't know about /bin/echo)
86 system "echo $hid"; # Insecure
87 system "echo $data"; # Insecure until PATH set
88
89 $path = $ENV{'PATH'}; # $path now tainted
90
91 $ENV{'PATH'} = '/bin:/usr/bin';
92 delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
93
94 $path = $ENV{'PATH'}; # $path now NOT tainted
95 system "echo $data"; # Is secure now!
96
97 open(FOO, "< $arg"); # OK - read-only file
98 open(FOO, "> $arg"); # Not OK - trying to write
99
100 open(FOO,"echo $arg⎪"); # Not OK
101 open(FOO,"-⎪")
102 or exec 'echo', $arg; # Also not OK
103
104 $shout = `echo $arg`; # Insecure, $shout now tainted
105
106 unlink $data, $arg; # Insecure
107 umask $arg; # Insecure
108
109 exec "echo $arg"; # Insecure
110 exec "echo", $arg; # Insecure
111 exec "sh", '-c', $arg; # Very insecure!
112
113 @files = <*.c>; # insecure (uses readdir() or similar)
114 @files = glob('*.c'); # insecure (uses readdir() or similar)
115
116 # In Perl releases older than 5.6.0 the <*.c> and glob('*.c') would
117 # have used an external program to do the filename expansion; but in
118 # either case the result is tainted since the list of filenames comes
119 # from outside of the program.
120
121 $bad = ($arg, 23); # $bad will be tainted
122 $arg, `true`; # Insecure (although it isn't really)
123
124 If you try to do something insecure, you will get a fatal error saying
125 something like "Insecure dependency" or "Insecure $ENV{PATH}".
126
127 The exception to the principle of "one tainted value taints the whole
128 expression" is with the ternary conditional operator "?:". Since code
129 with a ternary conditional
130
131 $result = $tainted_value ? "Untainted" : "Also untainted";
132
133 is effectively
134
135 if ( $tainted_value ) {
136 $result = "Untainted";
137 } else {
138 $result = "Also untainted";
139 }
140
141 it doesn't make sense for $result to be tainted.
142
143 Laundering and Detecting Tainted Data
144
145 To test whether a variable contains tainted data, and whose use would
146 thus trigger an "Insecure dependency" message, you can use the
147 "tainted()" function of the Scalar::Util module, available in your
148 nearby CPAN mirror, and included in Perl starting from the release
149 5.8.0. Or you may be able to use the following "is_tainted()" func‐
150 tion.
151
152 sub is_tainted {
153 return ! eval { eval("#" . substr(join("", @_), 0, 0)); 1 };
154 }
155
156 This function makes use of the fact that the presence of tainted data
157 anywhere within an expression renders the entire expression tainted.
158 It would be inefficient for every operator to test every argument for
159 taintedness. Instead, the slightly more efficient and conservative
160 approach is used that if any tainted value has been accessed within the
161 same expression, the whole expression is considered tainted.
162
163 But testing for taintedness gets you only so far. Sometimes you have
164 just to clear your data's taintedness. Values may be untainted by
165 using them as keys in a hash; otherwise the only way to bypass the
166 tainting mechanism is by referencing subpatterns from a regular expres‐
167 sion match. Perl presumes that if you reference a substring using $1,
168 $2, etc., that you knew what you were doing when you wrote the pattern.
169 That means using a bit of thought--don't just blindly untaint anything,
170 or you defeat the entire mechanism. It's better to verify that the
171 variable has only good characters (for certain values of "good") rather
172 than checking whether it has any bad characters. That's because it's
173 far too easy to miss bad characters that you never thought of.
174
175 Here's a test to make sure that the data contains nothing but "word"
176 characters (alphabetics, numerics, and underscores), a hyphen, an at
177 sign, or a dot.
178
179 if ($data =~ /^([-\@\w.]+)$/) {
180 $data = $1; # $data now untainted
181 } else {
182 die "Bad data in '$data'"; # log this somewhere
183 }
184
185 This is fairly secure because "/\w+/" doesn't normally match shell
186 metacharacters, nor are dot, dash, or at going to mean something spe‐
187 cial to the shell. Use of "/.+/" would have been insecure in theory
188 because it lets everything through, but Perl doesn't check for that.
189 The lesson is that when untainting, you must be exceedingly careful
190 with your patterns. Laundering data using regular expression is the
191 only mechanism for untainting dirty data, unless you use the strategy
192 detailed below to fork a child of lesser privilege.
193
194 The example does not untaint $data if "use locale" is in effect,
195 because the characters matched by "\w" are determined by the locale.
196 Perl considers that locale definitions are untrustworthy because they
197 contain data from outside the program. If you are writing a locale-
198 aware program, and want to launder data with a regular expression con‐
199 taining "\w", put "no locale" ahead of the expression in the same
200 block. See "SECURITY" in perllocale for further discussion and exam‐
201 ples.
202
203 Switches On the "#!" Line
204
205 When you make a script executable, in order to make it usable as a com‐
206 mand, the system will pass switches to perl from the script's #! line.
207 Perl checks that any command line switches given to a setuid (or set‐
208 gid) script actually match the ones set on the #! line. Some Unix and
209 Unix-like environments impose a one-switch limit on the #! line, so
210 you may need to use something like "-wU" instead of "-w -U" under such
211 systems. (This issue should arise only in Unix or Unix-like environ‐
212 ments that support #! and setuid or setgid scripts.)
213
214 Taint mode and @INC
215
216 When the taint mode ("-T") is in effect, the "." directory is removed
217 from @INC, and the environment variables "PERL5LIB" and "PERLLIB" are
218 ignored by Perl. You can still adjust @INC from outside the program by
219 using the "-I" command line option as explained in perlrun. The two
220 environment variables are ignored because they are obscured, and a user
221 running a program could be unaware that they are set, whereas the "-I"
222 option is clearly visible and therefore permitted.
223
224 Another way to modify @INC without modifying the program, is to use the
225 "lib" pragma, e.g.:
226
227 perl -Mlib=/foo program
228
229 The benefit of using "-Mlib=/foo" over "-I/foo", is that the former
230 will automagically remove any duplicated directories, while the later
231 will not.
232
233 Note that if a tainted string is added to @INC, the following problem
234 will be reported:
235
236 Insecure dependency in require while running with -T switch
237
238 Cleaning Up Your Path
239
240 For "Insecure $ENV{PATH}" messages, you need to set $ENV{'PATH'} to a
241 known value, and each directory in the path must be absolute and non-
242 writable by others than its owner and group. You may be surprised to
243 get this message even if the pathname to your executable is fully qual‐
244 ified. This is not generated because you didn't supply a full path to
245 the program; instead, it's generated because you never set your PATH
246 environment variable, or you didn't set it to something that was safe.
247 Because Perl can't guarantee that the executable in question isn't
248 itself going to turn around and execute some other program that is
249 dependent on your PATH, it makes sure you set the PATH.
250
251 The PATH isn't the only environment variable which can cause problems.
252 Because some shells may use the variables IFS, CDPATH, ENV, and
253 BASH_ENV, Perl checks that those are either empty or untainted when
254 starting subprocesses. You may wish to add something like this to your
255 setid and taint-checking scripts.
256
257 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)}; # Make %ENV safer
258
259 It's also possible to get into trouble with other operations that don't
260 care whether they use tainted values. Make judicious use of the file
261 tests in dealing with any user-supplied filenames. When possible, do
262 opens and such after properly dropping any special user (or group!)
263 privileges. Perl doesn't prevent you from opening tainted filenames for
264 reading, so be careful what you print out. The tainting mechanism is
265 intended to prevent stupid mistakes, not to remove the need for
266 thought.
267
268 Perl does not call the shell to expand wild cards when you pass "sys‐
269 tem" and "exec" explicit parameter lists instead of strings with possi‐
270 ble shell wildcards in them. Unfortunately, the "open", "glob", and
271 backtick functions provide no such alternate calling convention, so
272 more subterfuge will be required.
273
274 Perl provides a reasonably safe way to open a file or pipe from a
275 setuid or setgid program: just create a child process with reduced
276 privilege who does the dirty work for you. First, fork a child using
277 the special "open" syntax that connects the parent and child by a pipe.
278 Now the child resets its ID set and any other per-process attributes,
279 like environment variables, umasks, current working directories, back
280 to the originals or known safe values. Then the child process, which
281 no longer has any special permissions, does the "open" or other system
282 call. Finally, the child passes the data it managed to access back to
283 the parent. Because the file or pipe was opened in the child while
284 running under less privilege than the parent, it's not apt to be
285 tricked into doing something it shouldn't.
286
287 Here's a way to do backticks reasonably safely. Notice how the "exec"
288 is not called with a string that the shell could expand. This is by
289 far the best way to call something that might be subjected to shell
290 escapes: just never call the shell at all.
291
292 use English '-no_match_vars';
293 die "Can't fork: $!" unless defined($pid = open(KID, "-⎪"));
294 if ($pid) { # parent
295 while (<KID>) {
296 # do something
297 }
298 close KID;
299 } else {
300 my @temp = ($EUID, $EGID);
301 my $orig_uid = $UID;
302 my $orig_gid = $GID;
303 $EUID = $UID;
304 $EGID = $GID;
305 # Drop privileges
306 $UID = $orig_uid;
307 $GID = $orig_gid;
308 # Make sure privs are really gone
309 ($EUID, $EGID) = @temp;
310 die "Can't drop privileges"
311 unless $UID == $EUID && $GID eq $EGID;
312 $ENV{PATH} = "/bin:/usr/bin"; # Minimal PATH.
313 # Consider sanitizing the environment even more.
314 exec 'myprog', 'arg1', 'arg2'
315 or die "can't exec myprog: $!";
316 }
317
318 A similar strategy would work for wildcard expansion via "glob",
319 although you can use "readdir" instead.
320
321 Taint checking is most useful when although you trust yourself not to
322 have written a program to give away the farm, you don't necessarily
323 trust those who end up using it not to try to trick it into doing some‐
324 thing bad. This is the kind of security checking that's useful for
325 set-id programs and programs launched on someone else's behalf, like
326 CGI programs.
327
328 This is quite different, however, from not even trusting the writer of
329 the code not to try to do something evil. That's the kind of trust
330 needed when someone hands you a program you've never seen before and
331 says, "Here, run this." For that kind of safety, check out the Safe
332 module, included standard in the Perl distribution. This module allows
333 the programmer to set up special compartments in which all system oper‐
334 ations are trapped and namespace access is carefully controlled.
335
336 Security Bugs
337
338 Beyond the obvious problems that stem from giving special privileges to
339 systems as flexible as scripts, on many versions of Unix, set-id
340 scripts are inherently insecure right from the start. The problem is a
341 race condition in the kernel. Between the time the kernel opens the
342 file to see which interpreter to run and when the (now-set-id) inter‐
343 preter turns around and reopens the file to interpret it, the file in
344 question may have changed, especially if you have symbolic links on
345 your system.
346
347 Fortunately, sometimes this kernel "feature" can be disabled. Unfortu‐
348 nately, there are two ways to disable it. The system can simply outlaw
349 scripts with any set-id bit set, which doesn't help much. Alternately,
350 it can simply ignore the set-id bits on scripts. If the latter is
351 true, Perl can emulate the setuid and setgid mechanism when it notices
352 the otherwise useless setuid/gid bits on Perl scripts. It does this
353 via a special executable called suidperl that is automatically invoked
354 for you if it's needed.
355
356 However, if the kernel set-id script feature isn't disabled, Perl will
357 complain loudly that your set-id script is insecure. You'll need to
358 either disable the kernel set-id script feature, or put a C wrapper
359 around the script. A C wrapper is just a compiled program that does
360 nothing except call your Perl program. Compiled programs are not sub‐
361 ject to the kernel bug that plagues set-id scripts. Here's a simple
362 wrapper, written in C:
363
364 #define REAL_PATH "/path/to/script"
365 main(ac, av)
366 char **av;
367 {
368 execv(REAL_PATH, av);
369 }
370
371 Compile this wrapper into a binary executable and then make it rather
372 than your script setuid or setgid.
373
374 In recent years, vendors have begun to supply systems free of this
375 inherent security bug. On such systems, when the kernel passes the
376 name of the set-id script to open to the interpreter, rather than using
377 a pathname subject to meddling, it instead passes /dev/fd/3. This is a
378 special file already opened on the script, so that there can be no race
379 condition for evil scripts to exploit. On these systems, Perl should
380 be compiled with "-DSETUID_SCRIPTS_ARE_SECURE_NOW". The Configure pro‐
381 gram that builds Perl tries to figure this out for itself, so you
382 should never have to specify this yourself. Most modern releases of
383 SysVr4 and BSD 4.4 use this approach to avoid the kernel race condi‐
384 tion.
385
386 Prior to release 5.6.1 of Perl, bugs in the code of suidperl could
387 introduce a security hole.
388
389 Protecting Your Programs
390
391 There are a number of ways to hide the source to your Perl programs,
392 with varying levels of "security".
393
394 First of all, however, you can't take away read permission, because the
395 source code has to be readable in order to be compiled and interpreted.
396 (That doesn't mean that a CGI script's source is readable by people on
397 the web, though.) So you have to leave the permissions at the socially
398 friendly 0755 level. This lets people on your local system only see
399 your source.
400
401 Some people mistakenly regard this as a security problem. If your pro‐
402 gram does insecure things, and relies on people not knowing how to
403 exploit those insecurities, it is not secure. It is often possible for
404 someone to determine the insecure things and exploit them without view‐
405 ing the source. Security through obscurity, the name for hiding your
406 bugs instead of fixing them, is little security indeed.
407
408 You can try using encryption via source filters (Filter::* from CPAN,
409 or Filter::Util::Call and Filter::Simple since Perl 5.8). But crackers
410 might be able to decrypt it. You can try using the byte code compiler
411 and interpreter described below, but crackers might be able to de-com‐
412 pile it. You can try using the native-code compiler described below,
413 but crackers might be able to disassemble it. These pose varying
414 degrees of difficulty to people wanting to get at your code, but none
415 can definitively conceal it (this is true of every language, not just
416 Perl).
417
418 If you're concerned about people profiting from your code, then the
419 bottom line is that nothing but a restrictive licence will give you
420 legal security. License your software and pepper it with threatening
421 statements like "This is unpublished proprietary software of XYZ Corp.
422 Your access to it does not give you permission to use it blah blah
423 blah." You should see a lawyer to be sure your licence's wording will
424 stand up in court.
425
426 Unicode
427
428 Unicode is a new and complex technology and one may easily overlook
429 certain security pitfalls. See perluniintro for an overview and perlu‐
430 nicode for details, and "Security Implications of Unicode" in perluni‐
431 code for security implications in particular.
432
433 Algorithmic Complexity Attacks
434
435 Certain internal algorithms used in the implementation of Perl can be
436 attacked by choosing the input carefully to consume large amounts of
437 either time or space or both. This can lead into the so-called Denial
438 of Service (DoS) attacks.
439
440 · Hash Function - the algorithm used to "order" hash elements has
441 been changed several times during the development of Perl, mainly
442 to be reasonably fast. In Perl 5.8.1 also the security aspect was
443 taken into account.
444
445 In Perls before 5.8.1 one could rather easily generate data that as
446 hash keys would cause Perl to consume large amounts of time because
447 internal structure of hashes would badly degenerate. In Perl 5.8.1
448 the hash function is randomly perturbed by a pseudorandom seed
449 which makes generating such naughty hash keys harder. See
450 "PERL_HASH_SEED" in perlrun for more information.
451
452 The random perturbation is done by default but if one wants for
453 some reason emulate the old behaviour one can set the environment
454 variable PERL_HASH_SEED to zero (or any other integer). One possi‐
455 ble reason for wanting to emulate the old behaviour is that in the
456 new behaviour consecutive runs of Perl will order hash keys differ‐
457 ently, which may confuse some applications (like Data::Dumper: the
458 outputs of two different runs are no more identical).
459
460 Perl has never guaranteed any ordering of the hash keys, and the
461 ordering has already changed several times during the lifetime of
462 Perl 5. Also, the ordering of hash keys has always been, and con‐
463 tinues to be, affected by the insertion order.
464
465 Also note that while the order of the hash elements might be ran‐
466 domised, this "pseudoordering" should not be used for applications
467 like shuffling a list randomly (use List::Util::shuffle() for that,
468 see List::Util, a standard core module since Perl 5.8.0; or the
469 CPAN module Algorithm::Numerical::Shuffle), or for generating per‐
470 mutations (use e.g. the CPAN modules Algorithm::Permute or Algo‐
471 rithm::FastPermute), or for any cryptographic applications.
472
473 · Regular expressions - Perl's regular expression engine is so called
474 NFA (Non-Finite Automaton), which among other things means that it
475 can rather easily consume large amounts of both time and space if
476 the regular expression may match in several ways. Careful crafting
477 of the regular expressions can help but quite often there really
478 isn't much one can do (the book "Mastering Regular Expressions" is
479 required reading, see perlfaq2). Running out of space manifests
480 itself by Perl running out of memory.
481
482 · Sorting - the quicksort algorithm used in Perls before 5.8.0 to
483 implement the sort() function is very easy to trick into misbehav‐
484 ing so that it consumes a lot of time. Nothing more is required
485 than resorting a list already sorted. Starting from Perl 5.8.0 a
486 different sorting algorithm, mergesort, is used. Mergesort is
487 insensitive to its input data, so it cannot be similarly fooled.
488
489 See <http://www.cs.rice.edu/~scrosby/hash/> for more information, and
490 any computer science text book on the algorithmic complexity.
491
493 perlrun for its description of cleaning up environment variables.
494
495
496
497perl v5.8.8 2006-01-07 PERLSEC(1)