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

Hi,
I am fairly new to Perl and have been trying to use the Safe module to execute a perl script in a restricted compartment. There does not seem to be many (if any) examples of passing and retrieving parameters from the calling perl into the compartment. Anyhow I am having problems accessing variables passed into the compartment using the share method. My sample code is shown below and is a CGI script running through apache.


#!/usr/bin/perl -w use Safe; print "Content-type: text/html\n\n"; my %params = ( key1 => 'value1', key2 => 'value2', key3 => 'value3', ); # Run as a normal eval my $script = 'return $params{\'key1\'}'; my $ret = eval($script); warn $@ if $@; print "ret=$ret<br>"; # Now run the script in a safe compartment my $compartment = new Safe(); $compartment->share('%params'); $ret = $compartment->reval($script); print "ret=$ret<br>";

The output in the browser window is shown below:

ret=value1 ret=

Showing that the compartment does not return the same result as the normal eval. Does anyone have any idea why this does not work.

Any help is appreciated

Replies are listed 'Best First'.
Re: Problems with Safe compartment reval parameters
by ikegami (Patriarch) on Sep 26, 2009 at 02:34 UTC
    Aside from the missing use Safe;, share says "Each NAME must be the name of a non-lexical variable" (emphasis mine). You successfully shared %main::params, which isn't too useful since you never put a value in it.

      Just updated the code example to make it more clear the initialization of the hash.

      Thanks

        The important bit is that my %params ... declares a lexical variable. share only deals with package variables: %params ... which may make it less useful when strictures (use strict; use warnings;) are used (using strictures is highly recommended btw).


        True laziness is hard work

        Yes, you are initialising a hash, but not the one the one you're sharing. share shares package variables — %main::params in this case — but you're initialising a lexical (my) variable.

        Change my %params to local our %params.