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