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