Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to untaint system call in CGI.pm

Tags:

cgi

perl

taint

I have the following CGI script:

#!/usr/bin/perl -T
use strict;
use warnings;
use CGI::Carp qw(fatalsToBrowser);
use CGI qw/:standard/;
my $query = CGI->new();
my $searchterm = param('name');

my $file = "justafile.txt";
# Begin searching terms and ignoring case
my @entries = `grep -i \"$searchterm\" $file`; # Line10
chomp @entries;
# Do something

When I execute the command it gives me this

Insecure dependency in `` while running with -T switch at /foo/cgi-bin/mycode.cgi line 10.

How line 10 can be fixed?

like image 427
neversaint Avatar asked Nov 22 '11 13:11

neversaint


2 Answers

The whole point of tainting is to ensure that unchecked input cannot be supplied to potentially unsafe functions.

In this case, your $searchterm variable might contain unexpected input that might allow an attacker to execute arbitrary programs on your system.

Hence, you either need to:

  1. untaint the variable by ensuring that it matches a pre-determined regexp (see @flesk's answer), at which point Perl assumes that you know what you're doing, or

  2. don't use backticks (per @eugene y's answer).

If you're using backticks you should also specify the full path to the grep command so that you're not depending on $PATH.

like image 164
Alnitak Avatar answered Oct 06 '22 00:10

Alnitak


Use the built-in grep function, e.g.:

open my $fh, '<', $file or die $!;    
my @entries = grep /$searchterm/i, <$fh>;
like image 21
Eugene Yarmash Avatar answered Oct 06 '22 01:10

Eugene Yarmash