Perl: safe eval?

I am curious if there is any good information on performing limited grades.

Looking at the docs, there is use Safe , which has a reval method, but I'm not sure how safe this is.

I want to do in order to be able to pass various conditional statements as a string to a function without a source abusing eval.

For instance:

 sub foo { my $stmt = shift; my $a = 3; say eval($stmt)?"correct":"wrong") , "($stmt)"; } foo( q{1 == $a} ); foo( q{$a =~ /3/ ); foo( q{(sub {return 3})->() eq 3} ); 

Would use Safe be good for this? All I have to do is compare, not having access to the disk or manipulating variables.

+4
source share
1 answer

As indicated in the docs , eval($stmt) evaluates $stmt "in the lexical context of the current Perl program, so any configuration variable or routines and format definitions remain after that." This is useful for delaying the execution of $stmt until runtime.

If you reval($stmt) in the Safe section, essentially the same thing happens, the statement has the value eval'd, but it is eval'd in a new lexical context that only the namespace of the safe space can see and in which you can control what types of operators are allowed.

So yes, if you declare a safe separation and reval($stmt) in this compartment, then (a) executing $stmt will not change the functioning of your program without your consent (I think this is what you mean "without source, abusing eval "). And (b) yes, $stmt will not be able to access the disk without your consent if you reval($stmt) . In (a) “your consent” requires explicit play with the symbol table, and in (b) “your consent” will require you to specify a set of op codes that will allow access to the disk.

I'm not sure how safe this is. However, you can see it in action if you configure it and execute it in the debugger.

+4
source

Source: https://habr.com/ru/post/1394809/


All Articles