1PERLSEC(1)             Perl Programmers Reference Guide             PERLSEC(1)
2
3
4

NAME

6       perlsec - Perl security
7

DESCRIPTION

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

SECURITY VULNERABILITY CONTACT INFORMATION

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

SECURITY MECHANISMS AND CONCERNS

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               return ! eval { eval("#" . substr(join("", @_), 0, 0)); 1 };
164           }
165
166       This function makes use of the fact that the presence of tainted data
167       anywhere within an expression renders the entire expression tainted.
168       It would be inefficient for every operator to test every argument for
169       taintedness.  Instead, the slightly more efficient and conservative
170       approach is used that if any tainted value has been accessed within the
171       same expression, the whole expression is considered tainted.
172
173       But testing for taintedness gets you only so far.  Sometimes you have
174       just to clear your data's taintedness.  Values may be untainted by
175       using them as keys in a hash; otherwise the only way to bypass the
176       tainting mechanism is by referencing subpatterns from a regular
177       expression match.  Perl presumes that if you reference a substring
178       using $1, $2, etc., that you knew what you were doing when you wrote
179       the pattern.  That means using a bit of thought--don't just blindly
180       untaint anything, or you defeat the entire mechanism.  It's better to
181       verify that the variable has only good characters (for certain values
182       of "good") rather than checking whether it has any bad characters.
183       That's because it's far too easy to miss bad characters that you never
184       thought of.
185
186       Here's a test to make sure that the data contains nothing but "word"
187       characters (alphabetics, numerics, and underscores), a hyphen, an at
188       sign, or a dot.
189
190           if ($data =~ /^([-\@\w.]+)$/) {
191               $data = $1;                     # $data now untainted
192           } else {
193               die "Bad data in '$data'";      # log this somewhere
194           }
195
196       This is fairly secure because "/\w+/" doesn't normally match shell
197       metacharacters, nor are dot, dash, or at going to mean something
198       special to the shell.  Use of "/.+/" would have been insecure in theory
199       because it lets everything through, but Perl doesn't check for that.
200       The lesson is that when untainting, you must be exceedingly careful
201       with your patterns.  Laundering data using regular expression is the
202       only mechanism for untainting dirty data, unless you use the strategy
203       detailed below to fork a child of lesser privilege.
204
205       The example does not untaint $data if "use locale" is in effect,
206       because the characters matched by "\w" are determined by the locale.
207       Perl considers that locale definitions are untrustworthy because they
208       contain data from outside the program.  If you are writing a locale-
209       aware program, and want to launder data with a regular expression
210       containing "\w", put "no locale" ahead of the expression in the same
211       block.  See "SECURITY" in perllocale for further discussion and
212       examples.
213
214   Switches On the "#!" Line
215       When you make a script executable, in order to make it usable as a
216       command, the system will pass switches to perl from the script's #!
217       line.  Perl checks that any command line switches given to a setuid (or
218       setgid) script actually match the ones set on the #! line.  Some Unix
219       and Unix-like environments impose a one-switch limit on the #!  line,
220       so you may need to use something like "-wU" instead of "-w -U" under
221       such systems.  (This issue should arise only in Unix or Unix-like
222       environments that support #! and setuid or setgid scripts.)
223
224   Taint mode and @INC
225       When the taint mode ("-T") is in effect, the "." directory is removed
226       from @INC, and the environment variables "PERL5LIB" and "PERLLIB" are
227       ignored by Perl. You can still adjust @INC from outside the program by
228       using the "-I" command line option as explained in perlrun. The two
229       environment variables are ignored because they are obscured, and a user
230       running a program could be unaware that they are set, whereas the "-I"
231       option is clearly visible and therefore permitted.
232
233       Another way to modify @INC without modifying the program, is to use the
234       "lib" pragma, e.g.:
235
236         perl -Mlib=/foo program
237
238       The benefit of using "-Mlib=/foo" over "-I/foo", is that the former
239       will automagically remove any duplicated directories, while the later
240       will not.
241
242       Note that if a tainted string is added to @INC, the following problem
243       will be reported:
244
245         Insecure dependency in require while running with -T switch
246
247   Cleaning Up Your Path
248       For "Insecure $ENV{PATH}" messages, you need to set $ENV{'PATH'} to a
249       known value, and each directory in the path must be absolute and non-
250       writable by others than its owner and group.  You may be surprised to
251       get this message even if the pathname to your executable is fully
252       qualified.  This is not generated because you didn't supply a full path
253       to the program; instead, it's generated because you never set your PATH
254       environment variable, or you didn't set it to something that was safe.
255       Because Perl can't guarantee that the executable in question isn't
256       itself going to turn around and execute some other program that is
257       dependent on your PATH, it makes sure you set the PATH.
258
259       The PATH isn't the only environment variable which can cause problems.
260       Because some shells may use the variables IFS, CDPATH, ENV, and
261       BASH_ENV, Perl checks that those are either empty or untainted when
262       starting subprocesses. You may wish to add something like this to your
263       setid and taint-checking scripts.
264
265           delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};   # Make %ENV safer
266
267       It's also possible to get into trouble with other operations that don't
268       care whether they use tainted values.  Make judicious use of the file
269       tests in dealing with any user-supplied filenames.  When possible, do
270       opens and such after properly dropping any special user (or group!)
271       privileges. Perl doesn't prevent you from opening tainted filenames for
272       reading, so be careful what you print out.  The tainting mechanism is
273       intended to prevent stupid mistakes, not to remove the need for
274       thought.
275
276       Perl does not call the shell to expand wild cards when you pass
277       "system" and "exec" explicit parameter lists instead of strings with
278       possible shell wildcards in them.  Unfortunately, the "open", "glob",
279       and backtick functions provide no such alternate calling convention, so
280       more subterfuge will be required.
281
282       Perl provides a reasonably safe way to open a file or pipe from a
283       setuid or setgid program: just create a child process with reduced
284       privilege who does the dirty work for you.  First, fork a child using
285       the special "open" syntax that connects the parent and child by a pipe.
286       Now the child resets its ID set and any other per-process attributes,
287       like environment variables, umasks, current working directories, back
288       to the originals or known safe values.  Then the child process, which
289       no longer has any special permissions, does the "open" or other system
290       call.  Finally, the child passes the data it managed to access back to
291       the parent.  Because the file or pipe was opened in the child while
292       running under less privilege than the parent, it's not apt to be
293       tricked into doing something it shouldn't.
294
295       Here's a way to do backticks reasonably safely.  Notice how the "exec"
296       is not called with a string that the shell could expand.  This is by
297       far the best way to call something that might be subjected to shell
298       escapes: just never call the shell at all.
299
300               use English '-no_match_vars';
301               die "Can't fork: $!" unless defined($pid = open(KID, "-|"));
302               if ($pid) {           # parent
303                   while (<KID>) {
304                       # do something
305                   }
306                   close KID;
307               } else {
308                   my @temp     = ($EUID, $EGID);
309                   my $orig_uid = $UID;
310                   my $orig_gid = $GID;
311                   $EUID = $UID;
312                   $EGID = $GID;
313                   # Drop privileges
314                   $UID  = $orig_uid;
315                   $GID  = $orig_gid;
316                   # Make sure privs are really gone
317                   ($EUID, $EGID) = @temp;
318                   die "Can't drop privileges"
319                       unless $UID == $EUID  && $GID eq $EGID;
320                   $ENV{PATH} = "/bin:/usr/bin"; # Minimal PATH.
321                   # Consider sanitizing the environment even more.
322                   exec 'myprog', 'arg1', 'arg2'
323                       or die "can't exec myprog: $!";
324               }
325
326       A similar strategy would work for wildcard expansion via "glob",
327       although you can use "readdir" instead.
328
329       Taint checking is most useful when although you trust yourself not to
330       have written a program to give away the farm, you don't necessarily
331       trust those who end up using it not to try to trick it into doing
332       something bad.  This is the kind of security checking that's useful for
333       set-id programs and programs launched on someone else's behalf, like
334       CGI programs.
335
336       This is quite different, however, from not even trusting the writer of
337       the code not to try to do something evil.  That's the kind of trust
338       needed when someone hands you a program you've never seen before and
339       says, "Here, run this."  For that kind of safety, check out the Safe
340       module, included standard in the Perl distribution.  This module allows
341       the programmer to set up special compartments in which all system
342       operations are trapped and namespace access is carefully controlled.
343
344   Security Bugs
345       Beyond the obvious problems that stem from giving special privileges to
346       systems as flexible as scripts, on many versions of Unix, set-id
347       scripts are inherently insecure right from the start.  The problem is a
348       race condition in the kernel.  Between the time the kernel opens the
349       file to see which interpreter to run and when the (now-set-id)
350       interpreter turns around and reopens the file to interpret it, the file
351       in question may have changed, especially if you have symbolic links on
352       your system.
353
354       Fortunately, sometimes this kernel "feature" can be disabled.
355       Unfortunately, there are two ways to disable it.  The system can simply
356       outlaw scripts with any set-id bit set, which doesn't help much.
357       Alternately, it can simply ignore the set-id bits on scripts.  If the
358       latter is true, Perl can emulate the setuid and setgid mechanism when
359       it notices the otherwise useless setuid/gid bits on Perl scripts.  It
360       does this via a special executable called suidperl that is
361       automatically invoked for you if it's needed.
362
363       The use of suidperl is considered deprecated, and will be removed in
364       Perl 5.12.0.  It is strongly recommended that all code uses the
365       simplier and more secure C-wrappers described below.
366
367       If the kernel set-id script feature isn't disabled, Perl will complain
368       loudly that your set-id script is insecure.  You'll need to either
369       disable the kernel set-id script feature, or put a C wrapper around the
370       script.  A C wrapper is just a compiled program that does nothing
371       except call your Perl program.   Compiled programs are not subject to
372       the kernel bug that plagues set-id scripts.  Here's a simple wrapper,
373       written in C:
374
375           #define REAL_PATH "/path/to/script"
376           main(ac, av)
377               char **av;
378           {
379               execv(REAL_PATH, av);
380           }
381
382       Compile this wrapper into a binary executable and then make it rather
383       than your script setuid or setgid.
384
385       In recent years, vendors have begun to supply systems free of this
386       inherent security bug.  On such systems, when the kernel passes the
387       name of the set-id script to open to the interpreter, rather than using
388       a pathname subject to meddling, it instead passes /dev/fd/3.  This is a
389       special file already opened on the script, so that there can be no race
390       condition for evil scripts to exploit.  On these systems, Perl should
391       be compiled with "-DSETUID_SCRIPTS_ARE_SECURE_NOW".  The Configure
392       program that builds Perl tries to figure this out for itself, so you
393       should never have to specify this yourself.  Most modern releases of
394       SysVr4 and BSD 4.4 use this approach to avoid the kernel race
395       condition.
396
397       Prior to release 5.6.1 of Perl, bugs in the code of suidperl could
398       introduce a security hole.  The use of suidperl is considered
399       deprecated, and will be removed in Perl 5.12.0.
400
401   Protecting Your Programs
402       There are a number of ways to hide the source to your Perl programs,
403       with varying levels of "security".
404
405       First of all, however, you can't take away read permission, because the
406       source code has to be readable in order to be compiled and interpreted.
407       (That doesn't mean that a CGI script's source is readable by people on
408       the web, though.)  So you have to leave the permissions at the socially
409       friendly 0755 level.  This lets people on your local system only see
410       your source.
411
412       Some people mistakenly regard this as a security problem.  If your
413       program does insecure things, and relies on people not knowing how to
414       exploit those insecurities, it is not secure.  It is often possible for
415       someone to determine the insecure things and exploit them without
416       viewing the source.  Security through obscurity, the name for hiding
417       your bugs instead of fixing them, is little security indeed.
418
419       You can try using encryption via source filters (Filter::* from CPAN,
420       or Filter::Util::Call and Filter::Simple since Perl 5.8).  But crackers
421       might be able to decrypt it.  You can try using the byte code compiler
422       and interpreter described below, but crackers might be able to de-
423       compile it.  You can try using the native-code compiler described
424       below, but crackers might be able to disassemble it.  These pose
425       varying degrees of difficulty to people wanting to get at your code,
426       but none can definitively conceal it (this is true of every language,
427       not just Perl).
428
429       If you're concerned about people profiting from your code, then the
430       bottom line is that nothing but a restrictive license will give you
431       legal security.  License your software and pepper it with threatening
432       statements like "This is unpublished proprietary software of XYZ Corp.
433       Your access to it does not give you permission to use it blah blah
434       blah."  You should see a lawyer to be sure your license's wording will
435       stand up in court.
436
437   Unicode
438       Unicode is a new and complex technology and one may easily overlook
439       certain security pitfalls.  See perluniintro for an overview and
440       perlunicode for details, and "Security Implications of Unicode" in
441       perlunicode for security implications in particular.
442
443   Algorithmic Complexity Attacks
444       Certain internal algorithms used in the implementation of Perl can be
445       attacked by choosing the input carefully to consume large amounts of
446       either time or space or both.  This can lead into the so-called Denial
447       of Service (DoS) attacks.
448
449       ·   Hash Function - the algorithm used to "order" hash elements has
450           been changed several times during the development of Perl, mainly
451           to be reasonably fast.  In Perl 5.8.1 also the security aspect was
452           taken into account.
453
454           In Perls before 5.8.1 one could rather easily generate data that as
455           hash keys would cause Perl to consume large amounts of time because
456           internal structure of hashes would badly degenerate.  In Perl 5.8.1
457           the hash function is randomly perturbed by a pseudorandom seed
458           which makes generating such naughty hash keys harder.  See
459           "PERL_HASH_SEED" in perlrun for more information.
460
461           In Perl 5.8.1 the random perturbation was done by default, but as
462           of 5.8.2 it is only used on individual hashes if the internals
463           detect the insertion of pathological data. If one wants for some
464           reason emulate the old behaviour (and expose oneself to DoS
465           attacks) one can set the environment variable PERL_HASH_SEED to
466           zero to disable the protection (or any other integer to force a
467           known perturbation, rather than random).  One possible reason for
468           wanting to emulate the old behaviour is that in the new behaviour
469           consecutive runs of Perl will order hash keys differently, which
470           may confuse some applications (like Data::Dumper: the outputs of
471           two different runs are no longer identical).
472
473           Perl has never guaranteed any ordering of the hash keys, and the
474           ordering has already changed several times during the lifetime of
475           Perl 5.  Also, the ordering of hash keys has always been, and
476           continues to be, affected by the insertion order.
477
478           Also note that while the order of the hash elements might be
479           randomised, this "pseudoordering" should not be used for
480           applications like shuffling a list randomly (use
481           List::Util::shuffle() for that, see List::Util, a standard core
482           module since Perl 5.8.0; or the CPAN module
483           Algorithm::Numerical::Shuffle), or for generating permutations (use
484           e.g. the CPAN modules Algorithm::Permute or
485           Algorithm::FastPermute), or for any cryptographic applications.
486
487       ·   Regular expressions - Perl's regular expression engine is so called
488           NFA (Non-deterministic Finite Automaton), which among other things
489           means that it can rather easily consume large amounts of both time
490           and space if the regular expression may match in several ways.
491           Careful crafting of the regular expressions can help but quite
492           often there really isn't much one can do (the book "Mastering
493           Regular Expressions" is required reading, see perlfaq2).  Running
494           out of space manifests itself by Perl running out of memory.
495
496       ·   Sorting - the quicksort algorithm used in Perls before 5.8.0 to
497           implement the sort() function is very easy to trick into
498           misbehaving so that it consumes a lot of time.  Starting from Perl
499           5.8.0 a different sorting algorithm, mergesort, is used by default.
500           Mergesort cannot misbehave on any input.
501
502       See <http://www.cs.rice.edu/~scrosby/hash/> for more information, and
503       any computer science textbook on algorithmic complexity.
504

SEE ALSO

506       perlrun for its description of cleaning up environment variables.
507
508
509
510perl v5.10.1                      2009-07-27                        PERLSEC(1)
Impressum