Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!news.glorb.com!news-out.readnews.com!transit3.readnews.com!panix!not-for-mail From: Grant Edwards Newsgroups: comp.lang.python Subject: Re: Yet another attempt at a safe eval() call Date: Fri, 4 Jan 2013 16:38:03 +0000 (UTC) Organization: PANIX Public Access Internet and UNIX, NYC Lines: 52 Message-ID: References: <50e6891c$0$30003$c3e8da3$5496439d@news.astraweb.com> NNTP-Posting-Host: dsl.comtrol.com X-Trace: reader1.panix.com 1357317483 805 64.122.56.22 (4 Jan 2013 16:38:03 GMT) X-Complaints-To: abuse@panix.com NNTP-Posting-Date: Fri, 4 Jan 2013 16:38:03 +0000 (UTC) User-Agent: slrn/pre1.0.0-18 (Linux) Xref: csiph.com comp.lang.python:36119 On 2013-01-04, Steven D'Aprano 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.