简体   繁体   中英

How to sanitize input from open files in Perl

I have a Perl script which opens a file, processes it and prints some output. The input file is gzipped.

the path to the $file is passed to the script as an arugment.

Below is the current solution I'm using:

open(my $fh, "-|", "$gzcat $file") or die("Cannot open $file$!");

The script has failed in Checkmarx's security audit recently, with the following error:

<script> gets user input for the $fh element. This element's value then flows through the code without being properly sanitized or validated and is eventually displayed to the user in method <method>. This may enable a CrossSite-Scripting attack.

I have tried validating the file exists with perl -f, and also removing unwanted characters using $file =~ s/[^A-Za-z0-9_\\-\\.\\/]//g; , yet it does not satisfy Checkmarx.

I would like to know what is the proper way of sanitzing an input which contains a path to a file in Perl.

As long as you are on Perl 5.8 or newer on an OS that supports forking, or 5.22 or newer on Windows, you can use the list form of pipe open to bypass the shell when running your command. This avoids problems where the filename contains metacharacters the shell will interpret, such as & and spaces.

open(my $fh, "-|", $gzcat, $file) or die("Cannot open $file: $!");

However, this is not validation or sanitization as requested, but it is important to avoid both vulnerabilities and misbehavior. The cross-site scripting possibility that is mentioned would be due to the filename being displayed as mentioned later; if it is displayed in an HTML page for example, you must HTML-escape it, most templating systems have methods to do this.

I ended up removing unwanted characters with

$file =~ s/[^A-Za-z0-9_\\-\\.\\/]//g;

Checking that the file exists with Perl -f , and opening the file using IO::Uncompress::Gunzip .

This passes Checkmarx's audit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM