develooper Front page | perl.perl5.porters | Postings from June 2011

Re: [perl #76332] Inconsistent tainting when using tainted hash keys

Thread Previous | Thread Next
From:
Dave Mitchell
Date:
June 28, 2011 03:17
Subject:
Re: [perl #76332] Inconsistent tainting when using tainted hash keys
Message ID:
20110628101658.GC2847@iabyn.com
On Thu, Jul 01, 2010 at 01:12:14PM -0700, Jesse wrote:
> #!perl -T
> # Originally brought to my attention by Alex Vandiver <alexmv@bestpractical.com>
> # Known to fail on 5.12.1
> 
> use Scalar::Util qw(tainted);
> my %a = ("jesse" => 42);
> my $x = $a{$ENV{USER}};
> print "tainted 2\n" if tainted( "foo" . $x             );
> print "tainted 1\n" if tainted( "foo" . $a{$ENV{USER}} );

Actually its not inconsistent :-)

The code above can be slightly clarified to

    use Scalar::Util qw(tainted);
    my %a = ("davem" => 42);
    my $u = $ENV{USER};
    die unless tainted($u);

    my $x1 = $a{$u};
    my $x2 = $a{$u} . "x";

    print "tainted \$x1\n" if tainted($x1);
    print "tainted \$x2\n" if tainted($x2);

which gives

    tainted $x2

Perl has two tainting mechanisms. The first one taints a particular
variable (taint magic attached to an SV), while the second taints a whole
expression, PL_tainted, which is set during the course of evaluating an
expression, and is usually only cleared at the start of next statement.

The assignment operator deliberately ignores the value of PL_tainted,
and only taints the dst based on the taintedness of the src; whereas
most other ops (like concat) taint the result based on PL_tainted.

In the above, hash values aren't tainted by their keys, so $a{$u} isn't
tainted, and so $x1 doesn't get tainted in $x1 = $a{$u}.

However, the concat expression $a{u}."x" contains a tainted value ($u)
which sets PL_tainted, which taints the result of the concat, which is
finally assigned to $x2, which then gets tainted.

Or to put it another way, $x1 is "more" correct than $x2 in not being
tainted, but as is well documented, tainting is conservative, which
sometimes means anything in an expression can get tainted, even if there
isn't a direct dependency between the various elements.

-- 
You're only as old as you look.

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About