Friday 15 June 2012

regex - Using the ee modifier safely with the s/// operator when the right side is input from user -


I am writing a Perl script where the user can input a regex and a replacement string. The script searches for a set of files and applies changes according to the Pearl implemented with the user input, according to the s /// operator.

To make minor cases complicated, the replacement string is allowed Regex includes the backreinfans to refer to the capture group. For example, if regex is b (. *?) A and the replacement string is a $ 1b the $ 1 does not behave literally Should be done, but rattler as a backfinder to capture the group number one.

In this setting, I am thinking that it is possible to use the ee modifier (the input to evaluate the user in the backtrace) securely s / // with the operator when the user inputs to the right of this operator? For example:

  Use strict; Use warnings; My $ str = 'abaka'; Use my $ replacement = 'make' annexe (home); Unlink "$ HOME / important.txt"}; '; $ Str = ~ s / a (. *?) A / $ replacement / g;  

It will be unfortunate .. but after getting rid of double quotes and dollar signals, I got the idea of ​​user input (putting it inside a pair of double quotes), and Then do replace:

  use qw (say); Strict use; Use warnings; My $ str = 'abaka'; My $ replacement = shift; $ Replacement = ~ s / \ "/ \\\" / g; $ Replacement = ~ s / \ $ (?! \ D) / \\\ $ / g; $ Replacement = '' '. $ Replacement. ' ''; $ Str = ~ s / a (. *?) A / $ replacement / g; Say $ str;  

Does this work at first glance, or have I missed something? For example if the script is called test.pl and the user runs it:

  $ test.pl 'do {"a $ b"}'  

The output is as desirable as just a simple string (and no code has been evaluated):

{"a $ b"} So the question is: Is this really a safe / correct approach?

No comments:

Post a Comment