How can I safely validate an untrusted regex in Perl?

前端 未结 2 1490
情歌与酒
情歌与酒 2021-01-19 15:20

This answer explains that to validate an arbitrary regular expression, one simply uses eval:

while (<>) {
    eval \"qr/$_/;\"
    print $         


        
2条回答
  •  情话喂你
    2021-01-19 16:01

    The solution is simply to change

    eval("qr/$_/")
    

    to

    eval("qr/\$_/")
    

    This can be written more clearly as follows:

    eval('qr/$_/')
    

    But that's still not optimal. The following would be far better as it doesn't involve generating and compiling Perl code at run-time:

    eval { qr/$_/ }
    

    Note that neither solution protects you from denial of service attacks. It's quite easy to write a pattern that will take longer than the life of the universe to complete. To hand that situation, yYou could execute the regex match in a child for which CPU ulimit has been set.

提交回复
热议问题