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