Testing a File for Trustworthiness
Problem
You want to read from a file, perhaps because it has configuration information. You only want to use the file if it can’t be written to (or perhaps not even be read from) by anyone else than its owner.
Solution
Use the
stat
call to retrieve ownership and file permissions information. You can
use the built-in version, which returns a list:
( $dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks ) = stat($filename) or die "no $filename: $!"; $mode &= 07777; # discard file type info
Or you can use the by-name interface in:
$info = stat($filename) or die "no $filename: $!"; if ($info->uid == 0) { print "Superuser owns $filename\n"; } if ($info->atime > $info->mtime) { print "$filename has been read since it was written.\n"; }
Discussion
Usually you trust users to set file permissions as they wish. If they want others to read their files, or even to write to them, that’s their business. Applications like editors, mailers, and shells are often more discerning, though, refusing to evaluate code in configuration files if anyone but the owner can write to them. This helps avoid Trojan horses attacks. Security-minded programs like ftp and rlogin may even reject config files that can be read by anyone but their owner.
If the file is writable by someone other than the owner or is owned by someone other than the current user or the superuser, it shouldn’t be trusted. To figure out file ownership and permissions, ...
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.