in reply to Re: stringification
in thread stringification

I think it is fairly secure: you can set variables but you can't execute anything.
Not true at all. What if someone hands you:
foo__`date`
You've just executed the date command. I'll leave it to you to come up with nastier ones.

There are safer (and faster) ways to walk a tree than to use runtime string eval. See the parents of "RE: (jcwren) RE: varying length multi-dimensional hashes" for better ways.

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: Re: Re: stringification
by dash2 (Hermit) on Feb 28, 2001 at 17:25 UTC
    merlyn: very good point. but, can't you get round this by enclosing the variables in quotes? e.g.

    >perl -e ' sub string_to_struct { my $string = shift; my @refs = split /__/, $string; $string = "\$$refs[0]"; for (1 .. $#refs) { $string .= "-> {q/$refs[$_]/}" }; return eval "\\$string"; } print string_to_struct "foo__`rm xxx`"; ' SCALAR(0x8056ba4) >ls ... xxx ... >perl -e ' sub string_to_struct { my $string = shift; my @refs = split /__/, $string; $string = "\$$refs[0]"; for (1 .. $#refs) { $string .= "-> {$refs[$_]}" }; return eval "\\$string"; } print string_to_struct "foo__`rm xxx`"; ' SCALAR(0x8056bb0) > ls [argh! xxx has been removed]

    Anyway, I'll check the refs and consider making sure all my configs get written in a safe way. It still wouldn't be nice to let them set any variable, I guess....

    update:
    Great reference. That solves it. Once again, chromatic sorts me out.

    update 2:
    Well, not completely. Chromatics solution in the thread referred to above will traverse a hash and show all the keys (and values). I'll have a think how to hack it to go just to the key and value you want.

    update 3:
    And by the way, my claim that the code above would be safe is not true - see replies to this post for why.

    David

      Any solution that uses eval and doesn't do sanity checking on the input is vulnerable.

      For example, in the code snippet where you put q// around the keys, if I pass in the string "foo__/.`rm xxx`.q/" then the line that gets evalled is \$foo-> {q//.`rm xxx`.q//} If you do decide to go with eval, which personally I would not recommend, then you should turn on taint checking and make sure the input is safe before you eval it.

        ah... now that would explain why the node is getting massacred... /me looks suitably chastened, and will rewrite to avoid the "eval" solution.

        dave hj~

      >perl -e ' sub string_to_struct { my $string = shift; my @refs = split /__/, $string; $string = "\$$refs[0]"; for (1 .. $#refs) { $string .= "-> {q/$refs[$_]/}" }; return eval "\\$string"; } print string_to_struct "foo__`rm xxx`"; '
      just to interject here, on every unix system ive ever used, just typing 'perl return' will allow you to code freely until __END__ or control-d and then execute. no need for the -e '...'

      --
      transcending "coolness" is what makes us cool.