You could do something like this and eval the code you are being given but use a bareblock and a last to ensure that it COMPILES but does not actually ever RUN. The last causes an immediate exit from the block. Comment out the $code = "{last; $code}" to see how this works.

Even using this methodology a malicious coder could force code execution if you allow BEGIN blocks. Comment out the s/BEGIN// to see what I mean. BEGIN {`format C:`} might be a bit of a bummer so we kill these off. By deleting the 'BEGIN' they become ordinary blocks that will never execute owing to the {last; ... } structure.

There may be other security holes in this solution, no doubt they will be duly noted. I used this method in a script (not a CGI!) a while ago because I was totally unable to capture the output of perl -c - it goes to STDOUT on Win32 despite all efforts otherwise. Perl -c also allows BEGIN blocks to !$#% you over as they get EXECUTED even though the rest of the code does not. Abigail has demonstrated a virus based on this behaviour BTW.

Update

jplindstrom reminded me about END blocks and I refresh my memory on CHECK blocks - both these will execute in this structure so I have updated the code to just remove all the blocks constructs.

cheers

tachyon

$code = <<'CODE'; print "Hello World!\n"; BEGIN {print '# hacked #';} CODE $code =~ s/BEGIN|CHECK|INIT|END//g; # kill blocks here $code = "{last; $code}"; # stop test code running eval $code; # now have a look see at $@ to see if it contains an error # due to the test code being invalid. print $@ ? "Invalid\n" : "Syntax OK\n";

In reply to Re: evaluating syntax of code blocks (code) by tachyon
in thread evaluating syntax of code blocks (code) by deprecated

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.