Perl ã§ã® secure ãªä¸æãã¡ã¤ã«ã®åãæ±ã
Perl 㧠(ã¨ããã Unix ã§) ãã¡ã¤ã«ã open ããå¾ã« unlink ãã¦ã write, read ã¯åºæ¥ããã¨ãããã¹ãã
#!/usr/local/bin/perl use strict; use warnings; use IO::File; my $file = "/var/tmp/test.$$"; print "file = $file\n"; die "$file is symlink\n" if -l $file; die "$file already exists\n" if -e _; umask(066); # my $result = open my $fh, "+>" . $file; # my $result = open my $fh, "+>", $file; my $result = sysopen my $fh, $file, O_RDWR|O_CREAT|O_EXCL; print "sysopen : $result\n"; $result = unlink $file; print "unlink : $result\n"; $result = print $fh "hoge\n"; print "print : $result\n"; $result = seek $fh, 0, SEEK_SET; print "seek : $result\n"; $result = read $fh, my $str, 4096; print "read : $result\n"; print "str : $str"; close $fh;
å®è¡ããã¨
% ./test.pl file = /var/tmp/test.1545 sysopen : 1 unlink : 1 print : 1 seek : 1 read : 5 str : hoge
ãããªé¢¨ã«ãªãã
é«ã Security Level ãè¦æ±ãããããã°ã©ã (Unix ä¸ã®) ã ã¨ãä¸æãã¡ã¤ã«ã¯ open ãã¦ãããã unlink ãã¦ä»ã®ããã»ã¹ããã¯ã¢ã¯ã»ã¹åºæ¥ãªãããã«ããã®ãåºæ¬ã ãããã¨ãè¨ããã¦ããããªãã¨ã¯å
¨ãç¥ããªãã£ãã®ã§ãã¹ããã¦ã¿ã次第ã§ãã
CPAN module ã§åããããªãã¨åºæ¥ãªãã®ããªãã¨æã£ã¦èª¿ã¹ãããæ¨æºæ·»ä»ã® File::Temp ãã¤ã±ã«ã
#!/usr/local/bin/perl use strict; use warnings; use File::Temp qw /tempfile/; File::Temp->safe_level( File::Temp::HIGH ); use Fcntl ':seek'; my $fh = tempfile(); my $result = print $fh "hoge\n"; print "print : $result\n"; $result = seek $fh, 0, SEEK_SET; print "seek : $result\n"; $result = read $fh, my $str, 4096; print "read : $result\n"; print "str : $str"; close $fh;
å®è¡ã
% ./test.pl print : 1 seek : 1 read : 5 str : hoge
ãã File::Temp ã«ã¯ã¡ãã£ã¨çããã£ã¦ãtempfile() ã filename ãæ±ããªãå½¢ã§å¼ã³åºããªãã¨ãããªããè¦ããã«ã
# ok my $fh = tempfile(); # ng my( $fh, $filename ) = tempfile(); # also ng my $fh = new File::Temp; my $filename = $fh->filename;
ãªæããããããªãã source ãæç²ãã¦è§£èª¬ãã¦ã¿ã¾ããããã
source from File::Temp::tempfile
# Return if (wantarray()) { if ($options{'OPEN'}) { return ($fh, $path); } else { return (undef, $path); } } else { # Unlink the file. It is up to unlink0 to decide what to do with # this (whether to unlink now or to defer until later) unlink0($fh, $path) or croak "Error unlinking file $path using unlink0"; # Return just the filehandle. return $fh; }
File::Temp::tempfile() 㯠wantarray ãªå½¢ã§å¼ã³åºã㨠unlink0 (unlink ã® OS ã®éããå¸åãã¦ã subroutine) ãå¼ã³åºããªãããã«ãªã£ã¦ãããã£ã¦ã
my( $fh, $filename ) = tempfile();
㯠NGã
ãã㨠OO ãªè¡¨è¨ã ãã©ãnew ã®ä¸ã® tempfile() ã®å¼ã³åºãã¯å¸¸ã«
source from File::Temp::new
# Open the file and retain file handle and file name my ($fh, $path) = tempfile( @template, %args );
ãªã®ã§ããã NGã
ä»ã«ã File::Temp::_can_unlink_opened_file ãè¦ãã¨ãopen å¾ã« unlink åºæ¥ã OS ããããããã ãæè¿ã® Unix 系㮠OS ã¯åé¡ãªããªã
æ¸ãæ¹ã«ãã£ã¦å¾®å¦ã«åä½ãéãä»æ§ã£ã¦ã©ããªãã ããï¼ç¹ã« OO ã§æ¸ãã¨(å¥ã«ãã®å¾ã§ filename ãå¼ã³åºããªãã¦ã)ä¸æãã¡ã¤ã«ãæ®ããªãã¦ãå¾®å¦ãªä»æ§ã ãª...ã