This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
fix for [perl #61976] Errno ($!) not evaluated to a error message string
[perl5.git] / t / op / taint.t
1 #!./perl -T
2 #
3 # Taint tests by Tom Phoenix <rootbeer@teleport.com>.
4 #
5 # I don't claim to know all about tainting. If anyone sees
6 # tests that I've missed here, please add them. But this is
7 # better than having no tests at all, right?
8 #
9
10 BEGIN {
11     chdir 't' if -d 't';
12     @INC = '../lib';
13 }
14
15 use strict;
16 use Config;
17 use File::Spec::Functions;
18
19 BEGIN { require './test.pl'; }
20 plan tests => 302;
21
22 $| = 1;
23
24 use vars qw($ipcsysv); # did we manage to load IPC::SysV?
25
26 my ($old_env_path, $old_env_dcl_path, $old_env_term);
27 BEGIN {
28    $old_env_path = $ENV{'PATH'};
29    $old_env_dcl_path = $ENV{'DCL$PATH'};
30    $old_env_term = $ENV{'TERM'};
31   if ($^O eq 'VMS' && !defined($Config{d_setenv})) {
32       $ENV{PATH} = $ENV{PATH};
33       $ENV{TERM} = $ENV{TERM} ne ''? $ENV{TERM} : 'dummy';
34   }
35   if ($Config{'extensions'} =~ /\bIPC\/SysV\b/
36       && ($Config{d_shm} || $Config{d_msg})) {
37       eval { require IPC::SysV };
38       unless ($@) {
39           $ipcsysv++;
40           IPC::SysV->import(qw(IPC_PRIVATE IPC_RMID IPC_CREAT S_IRWXU IPC_NOWAIT));
41       }
42   }
43 }
44
45 my $Is_VMS      = $^O eq 'VMS';
46 my $Is_MSWin32  = $^O eq 'MSWin32';
47 my $Is_NetWare  = $^O eq 'NetWare';
48 my $Is_Dos      = $^O eq 'dos';
49 my $Is_Cygwin   = $^O eq 'cygwin';
50 my $Is_OpenBSD  = $^O eq 'openbsd';
51 my $Invoke_Perl = $Is_VMS      ? 'MCR Sys$Disk:[]Perl.exe' :
52                   $Is_MSWin32  ? '.\perl'               :
53                   $Is_NetWare  ? 'perl'                 :
54                                  './perl'               ;
55 my @MoreEnv = qw/IFS CDPATH ENV BASH_ENV/;
56
57 if ($Is_VMS) {
58     my (%old, $x);
59     for $x ('DCL$PATH', @MoreEnv) {
60         ($old{$x}) = $ENV{$x} =~ /^(.*)$/ if exists $ENV{$x};
61     }
62     # VMS note:  PATH and TERM are automatically created by the C
63     # library in VMS on reference to the their keys in %ENV.
64     # There is currently no way to determine if they did not exist
65     # before this test was run.
66     eval <<EndOfCleanup;
67         END {
68             \$ENV{PATH} = \$old_env_path;
69             warn "# Note: logical name 'PATH' may have been created\n";
70             \$ENV{'TERM'} = \$old_env_term;
71             warn "# Note: logical name 'TERM' may have been created\n";
72             \@ENV{keys %old} = values %old;
73             if (defined \$old_env_dcl_path) {
74                 \$ENV{'DCL\$PATH'} = \$old_env_dcl_path;
75             } else {
76                 delete \$ENV{'DCL\$PATH'};
77             }
78         }
79 EndOfCleanup
80 }
81
82 # Sources of taint:
83 #   The empty tainted value, for tainting strings
84 my $TAINT = substr($^X, 0, 0);
85 #   A tainted zero, useful for tainting numbers
86 my $TAINT0;
87 {
88     no warnings;
89     $TAINT0 = 0 + $TAINT;
90 }
91
92 # This taints each argument passed. All must be lvalues.
93 # Side effect: It also stringifies them. :-(
94 sub taint_these (@) {
95     for (@_) { $_ .= $TAINT }
96 }
97
98 # How to identify taint when you see it
99 sub any_tainted (@) {
100     not eval { join("",@_), kill 0; 1 };
101 }
102 sub tainted ($) {
103     any_tainted @_;
104 }
105 sub all_tainted (@) {
106     for (@_) { return 0 unless tainted $_ }
107     1;
108 }
109
110
111 sub test ($;$) {
112     my($ok, $diag) = @_;
113
114     my $curr_test = curr_test();
115
116     if ($ok) {
117         print "ok $curr_test\n";
118     } else {
119         print "not ok $curr_test\n";
120         printf "# Failed test at line %d\n", (caller)[2];
121         for (split m/^/m, $diag) {
122             print "# $_";
123         }
124         print "\n" unless
125             $diag eq ''
126             or substr($diag, -1) eq "\n";
127     }
128
129     next_test();
130
131     return $ok;
132 }
133
134 # We need an external program to call.
135 my $ECHO = ($Is_MSWin32 ? ".\\echo$$" : ($Is_NetWare ? "echo$$" : "./echo$$"));
136 END { unlink $ECHO }
137 open PROG, "> $ECHO" or die "Can't create $ECHO: $!";
138 print PROG 'print "@ARGV\n"', "\n";
139 close PROG;
140 my $echo = "$Invoke_Perl $ECHO";
141
142 my $TEST = catfile(curdir(), 'TEST');
143
144 # First, let's make sure that Perl is checking the dangerous
145 # environment variables. Maybe they aren't set yet, so we'll
146 # taint them ourselves.
147 {
148     $ENV{'DCL$PATH'} = '' if $Is_VMS;
149
150     if ($Is_MSWin32 && $Config{ccname} =~ /bcc32/ && ! -f 'cc3250mt.dll') {
151         my $bcc_dir;
152         foreach my $dir (split /$Config{path_sep}/, $ENV{PATH}) {
153             if (-f "$dir/cc3250mt.dll") {
154                 $bcc_dir = $dir and last;
155             }
156         }
157         if (defined $bcc_dir) {
158             require File::Copy;
159             File::Copy::copy("$bcc_dir/cc3250mt.dll", '.') or
160                 die "$0: failed to copy cc3250mt.dll: $!\n";
161             eval q{
162                 END { unlink "cc3250mt.dll" }
163             };
164         }
165     }
166     $ENV{PATH} = ($Is_Cygwin) ? '/usr/bin' : '';
167     delete @ENV{@MoreEnv};
168     $ENV{TERM} = 'dumb';
169
170     test eval { `$echo 1` } eq "1\n";
171
172     SKIP: {
173         skip "Environment tainting tests skipped", 4
174           if $Is_MSWin32 || $Is_NetWare || $Is_VMS || $Is_Dos;
175
176         my @vars = ('PATH', @MoreEnv);
177         while (my $v = $vars[0]) {
178             local $ENV{$v} = $TAINT;
179             last if eval { `$echo 1` };
180             last unless $@ =~ /^Insecure \$ENV{$v}/;
181             shift @vars;
182         }
183         test !@vars, "@vars";
184
185         # tainted $TERM is unsafe only if it contains metachars
186         local $ENV{TERM};
187         $ENV{TERM} = 'e=mc2';
188         test eval { `$echo 1` } eq "1\n";
189         $ENV{TERM} = 'e=mc2' . $TAINT;
190         test !eval { `$echo 1` };
191         test $@ =~ /^Insecure \$ENV{TERM}/, $@;
192     }
193
194     my $tmp;
195     if ($^O eq 'os2' || $^O eq 'amigaos' || $Is_MSWin32 || $Is_NetWare || $Is_Dos) {
196         print "# all directories are writeable\n";
197     }
198     else {
199         $tmp = (grep { defined and -d and (stat _)[2] & 2 }
200                      qw(sys$scratch /tmp /var/tmp /usr/tmp),
201                      @ENV{qw(TMP TEMP)})[0]
202             or print "# can't find world-writeable directory to test PATH\n";
203     }
204
205     SKIP: {
206         skip "all directories are writeable", 2 unless $tmp;
207
208         local $ENV{PATH} = $tmp;
209         test !eval { `$echo 1` };
210         test $@ =~ /^Insecure directory in \$ENV{PATH}/, $@;
211     }
212
213     SKIP: {
214         skip "This is not VMS", 4 unless $Is_VMS;
215
216         $ENV{'DCL$PATH'} = $TAINT;
217         test  eval { `$echo 1` } eq '';
218         test $@ =~ /^Insecure \$ENV{DCL\$PATH}/, $@;
219         SKIP: {
220             skip q[can't find world-writeable directory to test DCL$PATH], 2
221               unless $tmp;
222
223             $ENV{'DCL$PATH'} = $tmp;
224             test eval { `$echo 1` } eq '';
225             test $@ =~ /^Insecure directory in \$ENV{DCL\$PATH}/, $@;
226         }
227         $ENV{'DCL$PATH'} = '';
228     }
229 }
230
231 # Let's see that we can taint and untaint as needed.
232 {
233     my $foo = $TAINT;
234     test tainted $foo;
235
236     # That was a sanity check. If it failed, stop the insanity!
237     die "Taint checks don't seem to be enabled" unless tainted $foo;
238
239     $foo = "foo";
240     test not tainted $foo;
241
242     taint_these($foo);
243     test tainted $foo;
244
245     my @list = 1..10;
246     test not any_tainted @list;
247     taint_these @list[1,3,5,7,9];
248     test any_tainted @list;
249     test all_tainted @list[1,3,5,7,9];
250     test not any_tainted @list[0,2,4,6,8];
251
252     ($foo) = $foo =~ /(.+)/;
253     test not tainted $foo;
254
255     $foo = $1 if ('bar' . $TAINT) =~ /(.+)/;
256     test not tainted $foo;
257     test $foo eq 'bar';
258
259     {
260       use re 'taint';
261
262       ($foo) = ('bar' . $TAINT) =~ /(.+)/;
263       test tainted $foo;
264       test $foo eq 'bar';
265
266       $foo = $1 if ('bar' . $TAINT) =~ /(.+)/;
267       test tainted $foo;
268       test $foo eq 'bar';
269     }
270
271     $foo = $1 if 'bar' =~ /(.+)$TAINT/;
272     test tainted $foo;
273     test $foo eq 'bar';
274
275     my $pi = 4 * atan2(1,1) + $TAINT0;
276     test tainted $pi;
277
278     ($pi) = $pi =~ /(\d+\.\d+)/;
279     test not tainted $pi;
280     test sprintf("%.5f", $pi) eq '3.14159';
281 }
282
283 # How about command-line arguments? The problem is that we don't
284 # always get some, so we'll run another process with some.
285 SKIP: {
286     my $arg = tempfile();
287     open PROG, "> $arg" or die "Can't create $arg: $!";
288     print PROG q{
289         eval { join('', @ARGV), kill 0 };
290         exit 0 if $@ =~ /^Insecure dependency/;
291         print "# Oops: \$@ was [$@]\n";
292         exit 1;
293     };
294     close PROG;
295     print `$Invoke_Perl "-T" $arg and some suspect arguments`;
296     test !$?, "Exited with status $?";
297     unlink $arg;
298 }
299
300 # Reading from a file should be tainted
301 {
302     test open(FILE, $TEST), "Couldn't open '$TEST': $!";
303
304     my $block;
305     sysread(FILE, $block, 100);
306     my $line = <FILE>;
307     close FILE;
308     test tainted $block;
309     test tainted $line;
310 }
311
312 # Globs should be forbidden, except under VMS,
313 #   which doesn't spawn an external program.
314 SKIP: {
315     skip "globs should be forbidden", 2 if 1 or $Is_VMS;
316
317     my @globs = eval { <*> };
318     test @globs == 0 && $@ =~ /^Insecure dependency/;
319
320     @globs = eval { glob '*' };
321     test @globs == 0 && $@ =~ /^Insecure dependency/;
322 }
323
324 # Output of commands should be tainted
325 {
326     my $foo = `$echo abc`;
327     test tainted $foo;
328 }
329
330 # Certain system variables should be tainted
331 {
332     test all_tainted $^X, $0;
333 }
334
335 # Results of matching should all be untainted
336 {
337     my $foo = "abcdefghi" . $TAINT;
338     test tainted $foo;
339
340     $foo =~ /def/;
341     test not any_tainted $`, $&, $';
342
343     $foo =~ /(...)(...)(...)/;
344     test not any_tainted $1, $2, $3, $+;
345
346     my @bar = $foo =~ /(...)(...)(...)/;
347     test not any_tainted @bar;
348
349     test tainted $foo;  # $foo should still be tainted!
350     test $foo eq "abcdefghi";
351 }
352
353 # Operations which affect files can't use tainted data.
354 {
355     test !eval { chmod 0, $TAINT }, 'chmod';
356     test $@ =~ /^Insecure dependency/, $@;
357
358     # There is no feature test in $Config{} for truncate,
359     #   so we allow for the possibility that it's missing.
360     test !eval { truncate 'NoSuChFiLe', $TAINT0 }, 'truncate';
361     test $@ =~ /^(?:Insecure dependency|truncate not implemented)/, $@;
362
363     test !eval { rename '', $TAINT }, 'rename';
364     test $@ =~ /^Insecure dependency/, $@;
365
366     test !eval { unlink $TAINT }, 'unlink';
367     test $@ =~ /^Insecure dependency/, $@;
368
369     test !eval { utime $TAINT }, 'utime';
370     test $@ =~ /^Insecure dependency/, $@;
371
372     SKIP: {
373         skip "chown() is not available", 2 unless $Config{d_chown};
374
375         test !eval { chown -1, -1, $TAINT }, 'chown';
376         test $@ =~ /^Insecure dependency/, $@;
377     }
378
379     SKIP: {
380         skip "link() is not available", 2 unless $Config{d_link};
381
382         test !eval { link $TAINT, '' }, 'link';
383         test $@ =~ /^Insecure dependency/, $@;
384     }
385
386     SKIP: {
387         skip "symlink() is not available", 2 unless $Config{d_symlink};
388
389         test !eval { symlink $TAINT, '' }, 'symlink';
390         test $@ =~ /^Insecure dependency/, $@;
391     }
392 }
393
394 # Operations which affect directories can't use tainted data.
395 {
396     test !eval { mkdir "foo".$TAINT, 0755.$TAINT0 }, 'mkdir';
397     test $@ =~ /^Insecure dependency/, $@;
398
399     test !eval { rmdir $TAINT }, 'rmdir';
400     test $@ =~ /^Insecure dependency/, $@;
401
402     test !eval { chdir "foo".$TAINT }, 'chdir';
403     test $@ =~ /^Insecure dependency/, $@;
404
405     SKIP: {
406         skip "chroot() is not available", 2 unless $Config{d_chroot};
407
408         test !eval { chroot $TAINT }, 'chroot';
409         test $@ =~ /^Insecure dependency/, $@;
410     }
411 }
412
413 # Some operations using files can't use tainted data.
414 {
415     my $foo = "imaginary library" . $TAINT;
416     test !eval { require $foo }, 'require';
417     test $@ =~ /^Insecure dependency/, $@;
418
419     my $filename = tempfile();  # NB: $filename isn't tainted!
420     $foo = $filename . $TAINT;
421     unlink $filename;   # in any case
422
423     test !eval { open FOO, $foo }, 'open for read';
424     test $@ eq '', $@;          # NB: This should be allowed
425
426     # Try first new style but allow also old style.
427     # We do not want the whole taint.t to fail
428     # just because Errno possibly failing.
429     test eval('$!{ENOENT}') ||
430         $! == 2 || # File not found
431         ($Is_Dos && $! == 22);
432
433     test !eval { open FOO, "> $foo" }, 'open for write';
434     test $@ =~ /^Insecure dependency/, $@;
435 }
436
437 # Commands to the system can't use tainted data
438 {
439     my $foo = $TAINT;
440
441     SKIP: {
442         skip "open('|') is not available", 4 if $^O eq 'amigaos';
443
444         test !eval { open FOO, "| x$foo" }, 'popen to';
445         test $@ =~ /^Insecure dependency/, $@;
446
447         test !eval { open FOO, "x$foo |" }, 'popen from';
448         test $@ =~ /^Insecure dependency/, $@;
449     }
450
451     test !eval { exec $TAINT }, 'exec';
452     test $@ =~ /^Insecure dependency/, $@;
453
454     test !eval { system $TAINT }, 'system';
455     test $@ =~ /^Insecure dependency/, $@;
456
457     $foo = "*";
458     taint_these $foo;
459
460     test !eval { `$echo 1$foo` }, 'backticks';
461     test $@ =~ /^Insecure dependency/, $@;
462
463     SKIP: {
464         # wildcard expansion doesn't invoke shell on VMS, so is safe
465         skip "This is not VMS", 2 unless $Is_VMS;
466     
467         test join('', eval { glob $foo } ) ne '', 'globbing';
468         test $@ eq '', $@;
469     }
470 }
471
472 # Operations which affect processes can't use tainted data.
473 {
474     test !eval { kill 0, $TAINT }, 'kill';
475     test $@ =~ /^Insecure dependency/, $@;
476
477     SKIP: {
478         skip "setpgrp() is not available", 2 unless $Config{d_setpgrp};
479
480         test !eval { setpgrp 0, $TAINT0 }, 'setpgrp';
481         test $@ =~ /^Insecure dependency/, $@;
482     }
483
484     SKIP: {
485         skip "setpriority() is not available", 2 unless $Config{d_setprior};
486
487         test !eval { setpriority 0, $TAINT0, $TAINT0 }, 'setpriority';
488         test $@ =~ /^Insecure dependency/, $@;
489     }
490 }
491
492 # Some miscellaneous operations can't use tainted data.
493 {
494     SKIP: {
495         skip "syscall() is not available", 2 unless $Config{d_syscall};
496
497         test !eval { syscall $TAINT }, 'syscall';
498         test $@ =~ /^Insecure dependency/, $@;
499     }
500
501     {
502         my $foo = "x" x 979;
503         taint_these $foo;
504         local *FOO;
505         my $temp = tempfile();
506         test open(FOO, "> $temp"), "Couldn't open $temp for write: $!";
507
508         test !eval { ioctl FOO, $TAINT0, $foo }, 'ioctl';
509         test $@ =~ /^Insecure dependency/, $@;
510
511         SKIP: {
512             skip "fcntl() is not available", 2 unless $Config{d_fcntl};
513
514             test !eval { fcntl FOO, $TAINT0, $foo }, 'fcntl';
515             test $@ =~ /^Insecure dependency/, $@;
516         }
517
518         close FOO;
519     }
520 }
521
522 # Some tests involving references
523 {
524     my $foo = 'abc' . $TAINT;
525     my $fooref = \$foo;
526     test not tainted $fooref;
527     test tainted $$fooref;
528     test tainted $foo;
529 }
530
531 # Some tests involving assignment
532 {
533     my $foo = $TAINT0;
534     my $bar = $foo;
535     test all_tainted $foo, $bar;
536     test tainted($foo = $bar);
537     test tainted($bar = $bar);
538     test tainted($bar += $bar);
539     test tainted($bar -= $bar);
540     test tainted($bar *= $bar);
541     test tainted($bar++);
542     test tainted($bar /= $bar);
543     test tainted($bar += 0);
544     test tainted($bar -= 2);
545     test tainted($bar *= -1);
546     test tainted($bar /= 1);
547     test tainted($bar--);
548     test $bar == 0;
549 }
550
551 # Test assignment and return of lists
552 {
553     my @foo = ("A", "tainted" . $TAINT, "B");
554     test not tainted $foo[0];
555     test     tainted $foo[1];
556     test not tainted $foo[2];
557     my @bar = @foo;
558     test not tainted $bar[0];
559     test     tainted $bar[1];
560     test not tainted $bar[2];
561     my @baz = eval { "A", "tainted" . $TAINT, "B" };
562     test not tainted $baz[0];
563     test     tainted $baz[1];
564     test not tainted $baz[2];
565     my @plugh = eval q[ "A", "tainted" . $TAINT, "B" ];
566     test not tainted $plugh[0];
567     test     tainted $plugh[1];
568     test not tainted $plugh[2];
569     my $nautilus = sub { "A", "tainted" . $TAINT, "B" };
570     test not tainted ((&$nautilus)[0]);
571     test     tainted ((&$nautilus)[1]);
572     test not tainted ((&$nautilus)[2]);
573     my @xyzzy = &$nautilus;
574     test not tainted $xyzzy[0];
575     test     tainted $xyzzy[1];
576     test not tainted $xyzzy[2];
577     my $red_october = sub { return "A", "tainted" . $TAINT, "B" };
578     test not tainted ((&$red_october)[0]);
579     test     tainted ((&$red_october)[1]);
580     test not tainted ((&$red_october)[2]);
581     my @corge = &$red_october;
582     test not tainted $corge[0];
583     test     tainted $corge[1];
584     test not tainted $corge[2];
585 }
586
587 # Test for system/library calls returning string data of dubious origin.
588 {
589     # No reliable %Config check for getpw*
590     SKIP: {
591         skip "getpwent() is not available", 1 unless 
592           eval { setpwent(); getpwent() };
593
594         setpwent();
595         my @getpwent = getpwent();
596         die "getpwent: $!\n" unless (@getpwent);
597         test (    not tainted $getpwent[0]
598                   and     tainted $getpwent[1]
599                   and not tainted $getpwent[2]
600                   and not tainted $getpwent[3]
601                   and not tainted $getpwent[4]
602                   and not tainted $getpwent[5]
603                   and     tainted $getpwent[6]          # ge?cos
604                   and not tainted $getpwent[7]
605                   and     tainted $getpwent[8]);        # shell
606         endpwent();
607     }
608
609     SKIP: {
610         # pretty hard to imagine not
611         skip "readdir() is not available", 1 unless $Config{d_readdir};
612
613         local(*D);
614         opendir(D, "op") or die "opendir: $!\n";
615         my $readdir = readdir(D);
616         test tainted $readdir;
617         closedir(D);
618     }
619
620     SKIP: {
621         skip "readlink() or symlink() is not available" unless 
622           $Config{d_readlink} && $Config{d_symlink};
623
624         my $symlink = "sl$$";
625         unlink($symlink);
626         my $sl = "/something/naughty";
627         # it has to be a real path on Mac OS
628         symlink($sl, $symlink) or die "symlink: $!\n";
629         my $readlink = readlink($symlink);
630         test tainted $readlink;
631         unlink($symlink);
632     }
633 }
634
635 # test bitwise ops (regression bug)
636 {
637     my $why = "y";
638     my $j = "x" | $why;
639     test not tainted $j;
640     $why = $TAINT."y";
641     $j = "x" | $why;
642     test     tainted $j;
643 }
644
645 # test target of substitution (regression bug)
646 {
647     my $why = $TAINT."y";
648     $why =~ s/y/z/;
649     test     tainted $why;
650
651     my $z = "[z]";
652     $why =~ s/$z/zee/;
653     test     tainted $why;
654
655     $why =~ s/e/'-'.$$/ge;
656     test     tainted $why;
657 }
658
659
660 SKIP: {
661     skip "no IPC::SysV", 2 unless $ipcsysv;
662
663     # test shmread
664     SKIP: {
665         skip "shm*() not available", 1 unless $Config{d_shm};
666
667         no strict 'subs';
668         my $sent = "foobar";
669         my $rcvd;
670         my $size = 2000;
671         my $id = shmget(IPC_PRIVATE, $size, S_IRWXU);
672
673         if (defined $id) {
674             if (shmwrite($id, $sent, 0, 60)) {
675                 if (shmread($id, $rcvd, 0, 60)) {
676                     substr($rcvd, index($rcvd, "\0")) = '';
677                 } else {
678                     warn "# shmread failed: $!\n";
679                 }
680             } else {
681                 warn "# shmwrite failed: $!\n";
682             }
683             shmctl($id, IPC_RMID, 0) or warn "# shmctl failed: $!\n";
684         } else {
685             warn "# shmget failed: $!\n";
686         }
687
688         skip "SysV shared memory operation failed", 1 unless 
689           $rcvd eq $sent;
690
691         test tainted $rcvd;
692     }
693
694
695     # test msgrcv
696     SKIP: {
697         skip "msg*() not available", 1 unless $Config{d_msg};
698
699         no strict 'subs';
700         my $id = msgget(IPC_PRIVATE, IPC_CREAT | S_IRWXU);
701
702         my $sent      = "message";
703         my $type_sent = 1234;
704         my $rcvd;
705         my $type_rcvd;
706
707         if (defined $id) {
708             if (msgsnd($id, pack("l! a*", $type_sent, $sent), IPC_NOWAIT)) {
709                 if (msgrcv($id, $rcvd, 60, 0, IPC_NOWAIT)) {
710                     ($type_rcvd, $rcvd) = unpack("l! a*", $rcvd);
711                 } else {
712                     warn "# msgrcv failed: $!\n";
713                 }
714             } else {
715                 warn "# msgsnd failed: $!\n";
716             }
717             msgctl($id, IPC_RMID, 0) or warn "# msgctl failed: $!\n";
718         } else {
719             warn "# msgget failed\n";
720         }
721
722         SKIP: {
723             skip "SysV message queue operation failed", 1
724               unless $rcvd eq $sent && $type_sent == $type_rcvd;
725
726             test tainted $rcvd;
727         }
728     }
729 }
730
731 {
732     # bug id 20001004.006
733
734     open IN, $TEST or warn "$0: cannot read $TEST: $!" ;
735     local $/;
736     my $a = <IN>;
737     my $b = <IN>;
738
739     ok tainted($a) && tainted($b) && !defined($b);
740
741     close IN;
742 }
743
744 {
745     # bug id 20001004.007
746
747     open IN, $TEST or warn "$0: cannot read $TEST: $!" ;
748     my $a = <IN>;
749
750     my $c = { a => 42,
751               b => $a };
752
753     ok !tainted($c->{a}) && tainted($c->{b});
754
755
756     my $d = { a => $a,
757               b => 42 };
758     ok tainted($d->{a}) && !tainted($d->{b});
759
760
761     my $e = { a => 42,
762               b => { c => $a, d => 42 } };
763     ok !tainted($e->{a}) &&
764        !tainted($e->{b}) &&
765         tainted($e->{b}->{c}) &&
766        !tainted($e->{b}->{d});
767
768     close IN;
769 }
770
771 {
772     # bug id 20010519.003
773
774     BEGIN {
775         use vars qw($has_fcntl);
776         eval { require Fcntl; import Fcntl; };
777         unless ($@) {
778             $has_fcntl = 1;
779         }
780     }
781
782     SKIP: {
783         skip "no Fcntl", 18 unless $has_fcntl;
784
785         my $evil = "foo" . $TAINT;
786
787         eval { sysopen(my $ro, $evil, &O_RDONLY) };
788         test $@ !~ /^Insecure dependency/, $@;
789         
790         eval { sysopen(my $wo, $evil, &O_WRONLY) };
791         test $@ =~ /^Insecure dependency/, $@;
792         
793         eval { sysopen(my $rw, $evil, &O_RDWR) };
794         test $@ =~ /^Insecure dependency/, $@;
795         
796         eval { sysopen(my $ap, $evil, &O_APPEND) };
797         test $@ =~ /^Insecure dependency/, $@;
798         
799         eval { sysopen(my $cr, $evil, &O_CREAT) };
800         test $@ =~ /^Insecure dependency/, $@;
801         
802         eval { sysopen(my $tr, $evil, &O_TRUNC) };
803         test $@ =~ /^Insecure dependency/, $@;
804         
805         eval { sysopen(my $ro, "foo", &O_RDONLY | $TAINT0) };
806         test $@ !~ /^Insecure dependency/, $@;
807         
808         eval { sysopen(my $wo, "foo", &O_WRONLY | $TAINT0) };
809         test $@ =~ /^Insecure dependency/, $@;
810
811         eval { sysopen(my $rw, "foo", &O_RDWR | $TAINT0) };
812         test $@ =~ /^Insecure dependency/, $@;
813
814         eval { sysopen(my $ap, "foo", &O_APPEND | $TAINT0) };
815         test $@ =~ /^Insecure dependency/, $@;
816         
817         eval { sysopen(my $cr, "foo", &O_CREAT | $TAINT0) };
818         test $@ =~ /^Insecure dependency/, $@;
819
820         eval { sysopen(my $tr, "foo", &O_TRUNC | $TAINT0) };
821         test $@ =~ /^Insecure dependency/, $@;
822
823         eval { sysopen(my $ro, "foo", &O_RDONLY, $TAINT0) };
824         test $@ !~ /^Insecure dependency/, $@;
825         
826         eval { sysopen(my $wo, "foo", &O_WRONLY, $TAINT0) };
827         test $@ =~ /^Insecure dependency/, $@;
828         
829         eval { sysopen(my $rw, "foo", &O_RDWR, $TAINT0) };
830         test $@ =~ /^Insecure dependency/, $@;
831         
832         eval { sysopen(my $ap, "foo", &O_APPEND, $TAINT0) };
833         test $@ =~ /^Insecure dependency/, $@;
834         
835         eval { sysopen(my $cr, "foo", &O_CREAT, $TAINT0) };
836         test $@ =~ /^Insecure dependency/, $@;
837
838         eval { sysopen(my $tr, "foo", &O_TRUNC, $TAINT0) };
839         test $@ =~ /^Insecure dependency/, $@;
840         
841         unlink("foo"); # not unlink($evil), because that would fail...
842     }
843 }
844
845 {
846     # bug 20010526.004
847
848     use warnings;
849
850     my $saw_warning = 0;
851     local $SIG{__WARN__} = sub { $saw_warning = 1 };
852
853     sub fmi {
854         my $divnum = shift()/1;
855         sprintf("%1.1f\n", $divnum);
856     }
857
858     fmi(21 . $TAINT);
859     fmi(37);
860     fmi(248);
861
862     test !$saw_warning;
863 }
864
865
866 {
867     # Bug ID 20010730.010
868
869     my $i = 0;
870
871     sub Tie::TIESCALAR {
872         my $class =  shift;
873         my $arg   =  shift;
874
875         bless \$arg => $class;
876     }
877
878     sub Tie::FETCH {
879         $i ++;
880         ${$_ [0]}
881     }
882
883  
884     package main;
885  
886     my $bar = "The Big Bright Green Pleasure Machine";
887     taint_these $bar;
888     tie my ($foo), Tie => $bar;
889
890     my $baz = $foo;
891
892     ok $i == 1;
893 }
894
895 {
896     # Check that all environment variables are tainted.
897     my @untainted;
898     while (my ($k, $v) = each %ENV) {
899         if (!tainted($v) &&
900             # These we have explicitly untainted or set earlier.
901             $k !~ /^(BASH_ENV|CDPATH|ENV|IFS|PATH|PERL_CORE|TEMP|TERM|TMP)$/) {
902             push @untainted, "# '$k' = '$v'\n";
903         }
904     }
905     test @untainted == 0, "untainted:\n @untainted";
906 }
907
908
909 ok( ${^TAINT} == 1, '$^TAINT is on' );
910
911 eval { ${^TAINT} = 0 };
912 ok( ${^TAINT},  '$^TAINT is not assignable' );
913 ok( $@ =~ /^Modification of a read-only value attempted/,
914                                 'Assigning to ${^TAINT} fails' );
915
916 {
917     # bug 20011111.105
918     
919     my $re1 = qr/x$TAINT/;
920     test tainted $re1;
921     
922     my $re2 = qr/^$re1\z/;
923     test tainted $re2;
924     
925     my $re3 = "$re2";
926     test tainted $re3;
927 }
928
929 SKIP: {
930     skip "system {} has different semantics on Win32", 1 if $Is_MSWin32;
931
932     # bug 20010221.005
933     local $ENV{PATH} .= $TAINT;
934     eval { system { "echo" } "/arg0", "arg1" };
935     test $@ =~ /^Insecure \$ENV/;
936 }
937
938 TODO: {
939     todo_skip 'tainted %ENV warning occludes tainted arguments warning', 22
940       if $Is_VMS;
941
942     # bug 20020208.005 plus some single arg exec/system extras
943     my $err = qr/^Insecure dependency/ ;
944     test !eval { exec $TAINT, $TAINT }, 'exec';
945     test $@ =~ $err, $@;
946     test !eval { exec $TAINT $TAINT }, 'exec';
947     test $@ =~ $err, $@;
948     test !eval { exec $TAINT $TAINT, $TAINT }, 'exec';
949     test $@ =~ $err, $@;
950     test !eval { exec $TAINT 'notaint' }, 'exec';
951     test $@ =~ $err, $@;
952     test !eval { exec {'notaint'} $TAINT }, 'exec';
953     test $@ =~ $err, $@;
954
955     test !eval { system $TAINT, $TAINT }, 'system';
956     test $@ =~ $err, $@;
957     test !eval { system $TAINT $TAINT }, 'system';
958     test $@ =~ $err, $@;
959     test !eval { system $TAINT $TAINT, $TAINT }, 'system';
960     test $@ =~ $err, $@;
961     test !eval { system $TAINT 'notaint' }, 'system';
962     test $@ =~ $err, $@;
963     test !eval { system {'notaint'} $TAINT }, 'system';
964     test $@ =~ $err, $@;
965
966     eval { 
967         no warnings;
968         system("lskdfj does not exist","with","args"); 
969     };
970     test !$@;
971
972     eval {
973         no warnings;
974         exec("lskdfj does not exist","with","args"); 
975     };
976     test !$@;
977
978     # If you add tests here update also the above skip block for VMS.
979 }
980
981 {
982     # [ID 20020704.001] taint propagation failure
983     use re 'taint';
984     $TAINT =~ /(.*)/;
985     test tainted(my $foo = $1);
986 }
987
988 {
989     # [perl #24291] this used to dump core
990     our %nonmagicalenv = ( PATH => "util" );
991     local *ENV = \%nonmagicalenv;
992     eval { system("lskdfj"); };
993     test $@ =~ /^%ENV is aliased to another variable while running with -T switch/;
994     local *ENV = *nonmagicalenv;
995     eval { system("lskdfj"); };
996     test $@ =~ /^%ENV is aliased to %nonmagicalenv while running with -T switch/;
997 }
998 {
999     # [perl #24248]
1000     $TAINT =~ /(.*)/;
1001     test !tainted($1);
1002     my $notaint = $1;
1003     test !tainted($notaint);
1004
1005     my $l;
1006     $notaint =~ /($notaint)/;
1007     $l = $1;
1008     test !tainted($1);
1009     test !tainted($l);
1010     $notaint =~ /($TAINT)/;
1011     $l = $1;
1012     test tainted($1);
1013     test tainted($l);
1014
1015     $TAINT =~ /($notaint)/;
1016     $l = $1;
1017     test !tainted($1);
1018     test !tainted($l);
1019     $TAINT =~ /($TAINT)/;
1020     $l = $1;
1021     test tainted($1);
1022     test tainted($l);
1023
1024     my $r;
1025     ($r = $TAINT) =~ /($notaint)/;
1026     test !tainted($1);
1027     ($r = $TAINT) =~ /($TAINT)/;
1028     test tainted($1);
1029
1030     #  [perl #24674]
1031     # accessing $^O  shoudn't taint it as a side-effect;
1032     # assigning tainted data to it is now an error
1033
1034     test !tainted($^O);
1035     if (!$^X) { } elsif ($^O eq 'bar') { }
1036     test !tainted($^O);
1037     eval '$^O = $^X';
1038     test $@ =~ /Insecure dependency in/;
1039 }
1040
1041 EFFECTIVELY_CONSTANTS: {
1042     my $tainted_number = 12 + $TAINT0;
1043     test tainted( $tainted_number );
1044
1045     # Even though it's always 0, it's still tainted
1046     my $tainted_product = $tainted_number * 0;
1047     test tainted( $tainted_product );
1048     test $tainted_product == 0;
1049 }
1050
1051 TERNARY_CONDITIONALS: {
1052     my $tainted_true  = $TAINT . "blah blah blah";
1053     my $tainted_false = $TAINT0;
1054     test tainted( $tainted_true );
1055     test tainted( $tainted_false );
1056
1057     my $result = $tainted_true ? "True" : "False";
1058     test $result eq "True";
1059     test !tainted( $result );
1060
1061     $result = $tainted_false ? "True" : "False";
1062     test $result eq "False";
1063     test !tainted( $result );
1064
1065     my $untainted_whatever = "The Fabulous Johnny Cash";
1066     my $tainted_whatever = "Soft Cell" . $TAINT;
1067
1068     $result = $tainted_true ? $tainted_whatever : $untainted_whatever;
1069     test $result eq "Soft Cell";
1070     test tainted( $result );
1071
1072     $result = $tainted_false ? $tainted_whatever : $untainted_whatever;
1073     test $result eq "The Fabulous Johnny Cash";
1074     test !tainted( $result );
1075 }
1076
1077 {
1078     # rt.perl.org 5900  $1 remains tainted if...
1079     # 1) The regular expression contains a scalar variable AND
1080     # 2) The regular expression appears in an elsif clause
1081
1082     my $foo = "abcdefghi" . $TAINT;
1083
1084     my $valid_chars = 'a-z';
1085     if ( $foo eq '' ) {
1086     }
1087     elsif ( $foo =~ /([$valid_chars]+)/o ) {
1088         test not tainted $1;
1089     }
1090
1091     if ( $foo eq '' ) {
1092     }
1093     elsif ( my @bar = $foo =~ /([$valid_chars]+)/o ) {
1094         test not any_tainted @bar;
1095     }
1096 }
1097
1098 # at scope exit, a restored localised value should have its old
1099 # taint status, not the taint status of the current statement
1100
1101 {
1102     our $x99 = $^X;
1103     test tainted $x99;
1104
1105     $x99 = '';
1106     test not tainted $x99;
1107
1108     my $c = do { local $x99; $^X };
1109     test not tainted $x99;
1110 }
1111 {
1112     our $x99 = $^X;
1113     test tainted $x99;
1114
1115     my $c = do { local $x99; '' };
1116     test tainted $x99;
1117 }
1118
1119 # an mg_get of a tainted value during localization shouldn't taint the
1120 # statement
1121
1122 {
1123     eval { local $0, eval '1' };
1124     test $@ eq '';
1125 }
1126
1127 # [perl #8262] //g loops infinitely on tainted data
1128
1129 {
1130     my @a;
1131     local $::TODO = 1;
1132     $a[0] = $^X;
1133     my $i = 0;
1134     while($a[0]=~ m/(.)/g ) {
1135         last if $i++ > 10000;
1136     }
1137     cmp_ok $i, '<', 10000, "infinite m//g";
1138 }
1139
1140 SKIP:
1141 {
1142     my $got_dualvar;
1143     eval 'use Scalar::Util "dualvar"; $got_dualvar++';
1144     skip "No Scalar::Util::dualvar" unless $got_dualvar;
1145     my $a = Scalar::Util::dualvar(3, $^X);
1146     my $b = $a + 5;
1147     is ($b, 8, "Arithmetic on tainted dualvars works");
1148 }
1149
1150 # opening '|-' should not trigger $ENV{PATH} check
1151
1152 {
1153     SKIP: {
1154         skip "fork() is not available", 3 unless $Config{'d_fork'};
1155         skip "opening |- is not stable on threaded OpenBSD with taint", 3
1156             if $Config{useithreads} && $Is_OpenBSD;
1157
1158         $ENV{'PATH'} = $TAINT;
1159         local $SIG{'PIPE'} = 'IGNORE';
1160         eval {
1161             my $pid = open my $pipe, '|-';
1162             if (!defined $pid) {
1163                 die "open failed: $!";
1164             }
1165             if (!$pid) {
1166                 kill 'KILL', $$;        # child suicide
1167             }
1168             close $pipe;
1169         };
1170         test $@ !~ /Insecure \$ENV/, 'fork triggers %ENV check';
1171         test $@ eq '',               'pipe/fork/open/close failed';
1172         eval {
1173             open my $pipe, "|$Invoke_Perl -e 1";
1174             close $pipe;
1175         };
1176         test $@ =~ /Insecure \$ENV/, 'popen neglects %ENV check';
1177     }
1178 }
1179
1180 {
1181     package AUTOLOAD_TAINT;
1182     sub AUTOLOAD {
1183         our $AUTOLOAD;
1184         return if $AUTOLOAD =~ /DESTROY/;
1185         if ($AUTOLOAD =~ /untainted/) {
1186             main::ok(!main::tainted($AUTOLOAD), '$AUTOLOAD can be untainted');
1187         } else {
1188             main::ok(main::tainted($AUTOLOAD), '$AUTOLOAD can be tainted');
1189         }
1190     }
1191
1192     package main;
1193     my $o = bless [], 'AUTOLOAD_TAINT';
1194     $o->$TAINT;
1195     $o->untainted;
1196 }
1197
1198 {
1199     # tests for tainted format in s?printf
1200     eval { printf($TAINT . "# %s\n", "foo") };
1201     like($@, qr/^Insecure dependency in printf/, q/printf doesn't like tainted formats/);
1202     eval { printf("# %s\n", $TAINT . "foo") };
1203     ok(!$@, q/printf accepts other tainted args/);
1204     eval { sprintf($TAINT . "# %s\n", "foo") };
1205     like($@, qr/^Insecure dependency in sprintf/, q/sprintf doesn't like tainted formats/);
1206     eval { sprintf("# %s\n", $TAINT . "foo") };
1207     ok(!$@, q/sprintf accepts other tainted args/);
1208 }
1209
1210 {
1211     # 40708
1212     my $n  = 7e9;
1213     8e9 - $n;
1214
1215     my $val = $n;
1216     is ($val, '7000000000', 'Assignment to untainted variable');
1217     $val = $TAINT;
1218     $val = $n;
1219     is ($val, '7000000000', 'Assignment to tainted variable');
1220 }
1221
1222 {
1223     my $val = 0;
1224     my $tainted = '1' . $TAINT;
1225     eval '$val = eval $tainted;';
1226     is ($val, 0, "eval doesn't like tainted strings");
1227     like ($@, qr/^Insecure dependency in eval/);
1228
1229     # Rather nice code to get a tainted undef by from Rick Delaney
1230     open FH, "test.pl" or die $!;
1231     seek FH, 0, 2 or die $!;
1232     $tainted = <FH>;
1233
1234     eval 'eval $tainted';
1235     like ($@, qr/^Insecure dependency in eval/);
1236 }
1237
1238 foreach my $ord (78, 163, 256) {
1239     # 47195
1240     my $line = 'A1' . $TAINT . chr $ord;
1241     chop $line;
1242     is($line, 'A1');
1243     $line =~ /(A\S*)/;
1244     ok(!tainted($1), "\\S match with chr $ord");
1245 }
1246
1247 {
1248     # 59998
1249     sub cr { my $x = crypt($_[0], $_[1]); $x }
1250     sub co { my $x = ~$_[0]; $x }
1251     my ($a, $b);
1252     $a = cr('hello', 'foo' . $TAINT);
1253     $b = cr('hello', 'foo');
1254     ok(tainted($a),  "tainted crypt");
1255     ok(!tainted($b), "untainted crypt");
1256     $a = co('foo' . $TAINT);
1257     $b = co('foo');
1258     ok(tainted($a),  "tainted complement");
1259     ok(!tainted($b), "untainted complement");
1260 }
1261
1262 {
1263     my @data = qw(bonk zam zlonk qunckkk);
1264     # Clearly some sort of usenet bang-path
1265     my $string = $TAINT . join "!", @data;
1266
1267     ok(tainted($string), "tainted data");
1268
1269     my @got = split /!|,/, $string;
1270
1271     # each @got would be useful here, but I want the test for earlier perls
1272     for my $i (0 .. $#data) {
1273         ok(tainted($got[$i]), "tainted result $i");
1274         is($got[$i], $data[$i], "correct content $i");
1275     }
1276
1277     ok(tainted($string), "still tainted data");
1278
1279     my @got = split /[!,]/, $string;
1280
1281     # each @got would be useful here, but I want the test for earlier perls
1282     for my $i (0 .. $#data) {
1283         ok(tainted($got[$i]), "tainted result $i");
1284         is($got[$i], $data[$i], "correct content $i");
1285     }
1286
1287     ok(tainted($string), "still tainted data");
1288
1289     my @got = split /!/, $string;
1290
1291     # each @got would be useful here, but I want the test for earlier perls
1292     for my $i (0 .. $#data) {
1293         ok(tainted($got[$i]), "tainted result $i");
1294         is($got[$i], $data[$i], "correct content $i");
1295     }
1296 }
1297
1298 # Bug RT #52552 - broken by change at git commit id f337b08
1299 {
1300     my $x = $TAINT. q{print "Hello world\n"};
1301     my $y = pack "a*", $x;
1302     ok(tainted($y), "pack a* preserves tainting");
1303
1304     my $z = pack "A*", q{print "Hello world\n"}.$TAINT;
1305     ok(tainted($z), "pack A* preserves tainting");
1306
1307     my $zz = pack "a*a*", q{print "Hello world\n"}, $TAINT;
1308     ok(tainted($zz), "pack a*a* preserves tainting");
1309 }
1310
1311 # Bug RT #61976 tainted $! would show numeric rather than string value
1312
1313 {
1314     my $tainted_path = substr($^X,0,0) . "/no/such/file";
1315     my $err;
1316     # $! is used in a tainted expression, so gets tainted
1317     open my $fh, $tainted_path or $err= "$!";
1318     unlike($err, qr/^\d+$/, 'tainted $!');
1319 }
1320
1321
1322 # This may bomb out with the alarm signal so keep it last
1323 SKIP: {
1324     skip "No alarm()"  unless $Config{d_alarm};
1325     # Test from RT #41831]
1326     # [PATCH] Bug & fix: hang when using study + taint mode (perl 5.6.1, 5.8.x)
1327
1328     my $DATA = <<'END' . $TAINT;
1329 line1 is here
1330 line2 is here
1331 line3 is here
1332 line4 is here
1333
1334 END
1335
1336     #study $DATA;
1337
1338     ## don't set $SIG{ALRM}, since we'd never get to a user-level handler as
1339     ## perl is stuck in a regexp infinite loop!
1340
1341     alarm(10);
1342
1343     if ($DATA =~ /^line2.*line4/m) {
1344         fail("Should not be a match")
1345     } else {
1346         pass("Match on tainted multiline data should fail promptly");
1347     }
1348
1349     alarm(0);
1350 }
1351 __END__
1352 # Keep the previous test last