McGaida has asked for the wisdom of the Perl Monks concerning the following question:

Hallo I am working on a script that will run with SUID rights, so I have to clean all values that came from outside and that is okay for me, but now I run in the following problem and I am totally confused maybe somebody can help me.

Code version not working:

if ($value =~ /^([\w|\s|\/|\-]+)$/) { $value = $1; } else { die "Reg. exp. failed: $value!\n"; }

The reg.exp. is working, but leaves $value tainted

Code version working but senseless

if ($value =~ /^(.+)$/) { $value = $1; } else { die "Reg. exp. failed: $value!\n"; }

Now $value is untained

I am on a Solaris 10 x64 system with perl version 5.8.4

Replies are listed 'Best First'.
Re: taint mode
by Athanasius (Archbishop) on Mar 17, 2015 at 09:48 UTC

    Hello McGaida, and welcome to the Monastery!

    A side note: Did you really intend to match the | character?

    Within a character class, | is just a character with no special meaning. Also, a hyphen doesn’t need to be backslashed if it’s the first or last character in the class (because Perl is smart enough to know that it doesn’t denote a range in these cases). So, assuming that you did mean to match the | character, your regular expression can be simplified from this:

    /^([\w|\s|\/|\-]+)$/

    to this:

    /^([\w|\s\/-]+)$/

    or, with different delimiters, to this:

    m{^([\w|\s/-]+)$}

    See perlrecharclass#Bracketed-Character-Classes.

    Update: Re-ordered for improved clarity, thanks to MidLifeXis.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Thanks for the welcome and simplifing my reg.exp. but the problem was not there.
      So I learned something thatīs nice.

Re: taint mode
by Anonymous Monk on Mar 17, 2015 at 07:50 UTC

      After a cup of coffee I go on with this workaround but still hoping somebody can explain me why I have to do this.

      if ($value =~ /^([\w|\s|\/|\-]+)$/) { $value = $1; } else { die "Reg. exp. failed: $value!\n"; } if ($value =~ /^(.*)$/) { $value = $1; }

      So it should be save and it is working. And for those interested in the value of $value ("x123uvw1").

        What output do you get for     perl -V?

        Works for me for pretty much any perl 5.8/5.12/5.14/5.16

        $ perl -MScalar::Util=tainted -Te " $value = shift; warn tainted $valu +e; if( $value =~ /^([\w|\s|\/|\-]+)$/ ){ $value = $1; } die tainted $value; " x123uvw1 1 at -e line 1. 0 at -e line 1.