Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Is it safe to use external strings for regexes?

by LanX (Saint)
on Oct 06, 2021 at 18:08 UTC ( [id://11137276]=note: print w/replies, xml ) Need Help??


in reply to Is it safe to use external strings for regexes?

here a way you could go, to counter the problems listed and explained here

  1. code injection by string interpolation, like /@{[ do_evil() ]}/
  2. code injection by regex, like /(?{ do_evil() })/
  3. exponential time regexes with excessive backtracking, something like /((x*)*)*/ IIRC

This will compile a regex into an anonymous sub without executing it

use re qw(debug); my $sub = eval "sub { m/$evil_re/ }";

the re debug will emit regex-opcodes for the regexes involved to STDERR

Final program: 1: EVAL (4) 4: EXACT <\n> (6) 6: END (0)

the 1: EVAL here tells you that an EVAL was involved which you need to reject, you don't want embedded Perl code

$evil_re = "(?{ BEGIN { do_evil() } })";

with Keyword::Simple disabling BEGIN,END,... etc you won't risk that the compilation of the sub inside the eval will run any code (see here)

with Safe you'll be able to additionally disable a bunch of external commands. (see here)

For this to work you need to spawn an external command for each regex and capture STDERR, you can use this to also limit the maximal runtime.

Since your code looks a lot like a test suite, you might wanna use the TAP protocol anyway.

NB: No guaranties whatsoever!

HTH! :)

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11137276]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2024-04-23 22:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found