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