Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Python functions "compile" and "compiler.parse" safe (sandboxed)?

I plan to use those functions in web-environment, so my concern is if those functions can be exploited and used for executing malicious software on the server.

Edit: I don't execute the result. I parse the AST tree and/or catch SyntaxError.

This is the code in question:

try:
    #compile the code and check for syntax errors
    compile(code_string, filename, "exec")
except SyntaxError, value:
    msg = value.args[0]

    (lineno, offset, text) = value.lineno, value.offset, value.text

    if text is None:
        return [{"line": 0, "offset": 0, 
            "message": u"Problem decoding source"}]

    else:
        line = text.splitlines()[-1]

        if offset is not None:
            offset = offset - (len(text) - len(line))
        else:
            offset = 0

        return [{"line": lineno, "offset": offset, "message": msg}]

else:
    #no syntax errors, check it with pyflakes
    tree = compiler.parse(code_string)
    w = checker.Checker(tree, filename)
    w.messages.sort(lambda a, b: cmp(a.lineno, b.lineno))

checker.Checker is pyflakes class that parses the AST tree.

like image 299
dekomote Avatar asked Dec 22 '22 22:12

dekomote


1 Answers

I think the more interesting question is what are you doing with the compiled functions? Running them is definitely unsafe.

I've tested the few exploits i could think of seeing as its just a syntax checker (can't redefine classes/functions etc) i don't think there is anyway to get python to execute arbitrary code at compile time

like image 71
tobyodavies Avatar answered Feb 24 '23 15:02

tobyodavies