Turning String into Numerical Equation

Michael Spencer mahs at telcopartners.com
Wed Mar 16 05:59:48 CET 2005

Giovanni Bajo wrote:
> Steven Bethard wrote:
>>>>I use something along these lines:
>>>>def safe_eval(expr, symbols={}):
>>>>    return eval(expr, dict(__builtins__=None, True=True,
>>>>False=False), symbols)
>>>>import math
>>>>def calc(expr):
>>>>    return safe_eval(expr, vars(math))
>>>That offers only notional security:
>>> >>> calc("acos.__class__.__bases__[0]")
>>> <type 'object'>
>>Yeah, I was concerned about the same thing, but I realized that I
>>can't actually access any of the func_globals attributes:
Interesting, of course I had never actually tried it

> When __builtin__ is not the standard __builtin__, Python is in restricted
> execution mode. 

After a little experimenting, it appears to be a bit stronger than that.  Once a 
frame is set for restricted execution (f_restricted == 1), then even if you set 
f_globals['__builtin__'] = __builtins__, you are still left in resticted 
execution mode.

> In fact, I believe my solution to be totally safe, 

That's a bold claim!  I'll readily concede that I can't access func_globals from 
restricted mode eval (others may know better).  But your interpreter is still be 
vulnerable to DOS-style attack from rogue calculations or quasi-infinite loops.

 > otherwise would love to be proved wrong.


More information about the Python-list mailing list