Detecting and Laundering Tainted Data
To test whether a scalar variable contains tainted data, you can use the
following is_tainted
function. It makes use of the fact that eval
STRING raises an exception if you try to
compile tainted data. It doesn’t matter that the $nada variable used in the expression to
compile will always be empty; it will still be tainted if $arg is tainted. The outer eval BLOCK
isn’t doing any compilation. It’s just there to catch the exception
raised if the inner eval is given
tainted data. Since the $@ variable is
guaranteed to be nonempty after each eval if an exception was raised and empty
otherwise, we return the result of testing whether its length was
zero:
sub is_tainted {
my $arg = shift;
my $nada = substr($arg, 0, 0); # zero–length
local $@; # preserve caller's version
eval { eval "# $nada" };
return length($@) != 0;
}The Scalar::Util module, which comes with Perl, already does this for
you with tainted:
use Scalar::Util qw(tainted); print "Tainted!" if tainted( $ARGV[0] );
The Taint::Util CPAN module goes one better. It has a tainted function that does the same thing,
but it also has a taint function
that will make any data tainted:
use Taint::Util qw(tainted taint); my $scalar = 'This is untainted'; # untainted taint( $scalar ); # now tainted
This is handy for test scripts when you want to test with tainted data:
use Test::More; use Taint::Util qw(tainted taint); my $tainted = 'This is untainted'; # untainted taint( $tainted ); # now tainted ok( tainted( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access