I'm looking for security feedback on the following fully functional code.
The code is trying to safely use the Unix 'file' command to give details about the file.
A hard link is used to create a safe filename that can be used in a command line.
The paramref is a hash read from config, and considered safe. file_base_dir
is a directory with only alphanumerics in the name. The 'file' command is the standard one.
What ways could my code be exploited?
sub file_details {
my ( $self, %arg ) = @_;
my $filename = $arg{'filename'};
my $paramref = $arg{'paramref'};
my $file_cmd = '/usr/bin/file';
my $safe_filename = $$paramref{'file_base_dir'} . "/link_to_unsafe_file_file_type_build";
# Just in case the link exists.
unlink($safe_filename);
if ( not link( $filename, $safe_filename ) ) {
confess "Failed to create link $safe_filename to $filename because $!";
}
my $file_type = `$file_cmd '$safe_filename'`;
# remove the link
unlink($safe_filename);
$file_type =~ s/\A[^:]+://x;
chomp $file_type;
return $file_type;
} ## end sub file_details