Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Perl as a command executor (with hash variable substitution)

by RecursionBane (Beadle)
on Mar 21, 2013 at 18:46 UTC ( #1024800=perlquestion: print w/replies, xml ) Need Help??
RecursionBane has asked for the wisdom of the Perl Monks concerning the following question:

Greetings, Monks! I am trying to solve a problem with a rather stringent set of limitations. Having tried fruitlessly for several days, I turn to your wisdom to accomplish this.
Please keep in mind that I have greatly simplified the inputs and outputs in order to make it easy for you to read.

This package contains many hashes (simplified below to only contain one hash with one key):
> cat package TEST_PACKAGE; use base 'Exporter'; our @ISA = qw(Exporter); our @EXPORT_OK = qw(%TEST_HASH); our %TEST_HASH; $TEST_HASH{'TEST_KEY'} = 'TEST_VALUE'; 1;
I wish to allow the user to craft any shell command that uses this variable, like so (again, simplified):
xterm> ./ '/bin/touch $TEST_HASH{'TEST_KEY'}' # Would create + a touchfile called TEST_VALUE xterm> ./ 'echo Test key contains $TEST_HASH{'TEST_KEY'}' # Wo +uld echo TEST_VALUE
I've created multiple versions of this program to no avail:
> cat #!/usr/bin/perl my @command = @ARGV; use TEST_PACKAGE qw(%TEST_HASH); my $command_string; for (my $i = 0; $i < scalar(@command); $i++ ) { # Interpret each word in the command string and substitute kno +wn variables $command_string = $command_string . " " . ( sprintf "%s", $com +mand[$i] ); } print "\nExecuting command: $command_string\n"; system "$command_string";
In usage:
xterm> ./ 'echo Test key contains $TEST_HASH{'TEST_KEY'}' # O +ne of many trials, with varying escape characters tried Executing command: echo Test key contains $TEST_HASH{TEST_KEY} Test key contains {TEST_KEY}
I think the problem might be because Perl does not interpolate hash values inside quotes.
Am I going about this the right way? Any suggestions from your collective wisdom would be much appreciated.


Replies are listed 'Best First'.
Re: Perl as a command executor (with hash variable substitution)
by McA (Priest) on Mar 21, 2013 at 19:16 UTC


    We are opening Pandora's box. All the following is never recommended.

    #!/usr/bin/perl use warnings; use strict; our %TESTHASH = ( 'KEY1' => 'VALUE1', 'KEY2' => 'VALUE2', ); foreach my $arg (@ARGV) { my $toeval = '"' . $arg .'";'; print $toeval, "\n"; my $command = eval $toeval; print $command, "\n"; system($command); print "\n"; }

    But you've asked... ;-)


      Thanks! Your solution made me realize that the "system" is required even after the "eval".
      And, yes, this is all inside Pandora's box. :-)
Re: Perl as a command executor (with hash variable substitution)
by kennethk (Abbot) on Mar 21, 2013 at 19:20 UTC
    There are a host of potential problems, security and otherwise, you may have to deal with for this, but let's ignore all those and attack the specific issue you've asked about.

    You need Perl to perform variable interpolation on a previously existing string. You can accomplish this using a string eval, after formatting your input like a string to be interpolated. This means escaping potentially problematic characters first like backslashes and previously existing quotes.

    my %TEST_HASH = (TEST_KEY => 'TEST_VALUE'); my $cmd = '/bin/touch $TEST_HASH{"TEST_KEY"}'; $cmd =~ s/\\/\\\\/g; $cmd =~ s/"/\\"/g; $cmd = eval qq{"$cmd"} or die $@; print $cmd

    Please don't run your intended code on any machine you care about security on, because this is pretty much the definition of injection and privilege escalation.

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      Thank you! I understand the security risks. These commands will be executed by the logged in user with his/her privileges. I will keep security in memory when attempting to deploy this in scale.

        Please don't deploy this. It's so ... evil.

        Tell us what you want to achieve. I'm pretty sure there are solutions where you don't have to sell your soul.


        I will keep security in memory when attempting to deploy this in scale.

        Security will, indeed, be but a memory, and a faint one at that.

Re: Perl as a command executor (with hash variable substitution)
by graff (Chancellor) on Mar 22, 2013 at 04:17 UTC
Re: Perl as a command executor (with hash variable substitution)
by choroba (Bishop) on Mar 22, 2013 at 15:10 UTC
    Instead of using several hashes, use just one hash. Transform the old hashes' names into keys in the new hash:

    #!/usr/bin/perl use warnings; use strict; use Local::Evaluator qw(evaluate); system map { Local::Evaluator::evaluate($_) } @ARGV;


    package Local::Evaluator; use warnings; use strict; use parent 'Exporter'; our @EXPORT_OK = qw( evaluate ); { my %HASH; $HASH{safe}{bin} = '/usr/bin'; $HASH{unsafe}{bin} = '/bin'; sub evaluate { my $word = shift; return $word unless 0 == index $word, '#'; my ($key, $subkey, $rest) = (split /#/, $word, 4)[1 .. 3]; return $HASH{$key}{$subkey} . $rest if $HASH{$key} and exists $HASH{$key}{$su +bkey}; return $word; } } __PACKAGE__


    $ ./ ls -latr \#unsafe#bin#/true -rwxr-xr-x 1 root root 30204 2010-09-21 20:33 /bin/true $ ./ ls -latr \#safe#bin#/true ls: cannot access /usr/bin/true: No such file or directory
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Perl as a command executor (with hash variable substitution)
by Anonymous Monk on Mar 22, 2013 at 00:27 UTC

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1024800]
Approved by vinoth.ree
[LanX]: met a guy from Aberdeen durin holidays, liked Scotsish accent a lot ... very phonetic
[LanX]: ... understood everything after mentally write down what he said.
[choroba]: Trainspotting?
[choroba]: Ouch, trailing commas in JSON :-(
[LanX]: ... though there seems to exist a taxation for the letter 't' in Northern Bri''ain ;-)

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2018-02-19 10:38 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (261 votes). Check out past polls.