Yet another attempt at a safe eval() call

Grant Edwards invalid at invalid.invalid
Fri Jan 4 11:38:03 EST 2013


On 2013-01-04, Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> On Thu, 03 Jan 2013 23:25:51 +0000, Grant Edwards wrote:
>
>> I've written a small assembler in Python 2.[67], and it needs to
>> evaluate integer-valued arithmetic expressions in the context of a
>> symbol table that defines integer values for a set of names.

[...]

[ my attaempt at a safer eval() ]

> So, here's my probably-not-safe-either "safe eval":
>
>
> def probably_not_safe_eval(expr):
>     if 'import' in expr.lower():
>         raise ParseError("'import' prohibited")
>     for c in '_"\'.':
>         if c in expr:
>             raise ParseError('prohibited char %r' % c)
>     if len(expr) > 120:
>         raise ParseError('expression too long')
>     globals = {'__builtins__': None}
>     locals  = symbolTable
>     return eval(expr, globals, locals)  # fingers crossed!
>
> I can't think of any way to break out of these restrictions, but that may 
> just mean I'm not smart enough.

I've added equals, backslash, commas, square/curly brackets, colons and semicolons to the
prohibited character list. I also reduced the maximum length to 60
characters.  It's unfortunate that parentheses are overloaded for both
expression grouping and for function calling...

def lessDangerousEval(expr):
    if 'import' in expr.lower():
        raise ParseError("'import' prohibited in expression")
    for c in '_"\'.;:[]{}=\\':
        if c in expr:
            raise ParseError("prohibited char '%r' in expression" % c)
    if len(expr) > 60:
        raise ParseError('expression too long')
    globals = {'__builtins__': None}
    locals  = symbolTable
    return eval(expr, globals, locals)  # fingers crossed!

Exploits anyone?    

-- 
Grant Edwards               grant.b.edwards        Yow! I'm ZIPPY the PINHEAD
                                  at               and I'm totally committed
                              gmail.com            to the festive mode.



More information about the Python-list mailing list