Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #45644
| From | Frank Millman <frank@chagford.com> |
|---|---|
| Subject | Re: Question about ast.literal_eval |
| Date | 2013-05-21 07:54 +0200 |
| References | <mailman.1863.1369033561.3114.python-list@python.org> <bd9faee1-5b93-46d6-b403-091bf071cc77@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1904.1369115684.3114.python-list@python.org> (permalink) |
On 21/05/2013 04:39, matt.newville@gmail.com wrote:
>
> You might find the asteval module (https://pypi.python.org/pypi/asteval) useful. It provides a relatively safe "eval", for example:
>
> >>> import asteval
> >>> a = asteval.Interpreter()
> >>> a.eval('x = "abc"')
> >>> a.eval('x in ("abc", "xyz")')
> True
> >>> a.eval('import os')
> NotImplementedError
> import os
> 'Import' not supported
> >>> a.eval('__import__("os")')
> NameError
> __import__("os")
> name '__import__' is not defined
>
> This works by maintaining an internal namespace (a flat dictionary), and walking the AST generated for the expression. It supports most Python syntax,
> including if, for, while, and try/except blocks, and function definitions, and with the notable exceptions of eval, exec, class, lambda, yield, and import. This requires Python2.6 and higher, and does work with Python3.3.
>
> Of course, it is not guaranteed to be completely safe, but it does disallow imports, which seems like the biggest vulnerability concern listed here. Currently, there is no explicit protection against long-running calculations for denial of service attacks. If you're exposing an SQL database to user-generated code, that may be worth considering.
Thanks for this, Matt. I will definitely look into it.
Frank
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Question about ast.literal_eval Frank Millman <frank@chagford.com> - 2013-05-20 09:05 +0200
Re: Question about ast.literal_eval matt.newville@gmail.com - 2013-05-20 19:39 -0700
Re: Question about ast.literal_eval Frank Millman <frank@chagford.com> - 2013-05-21 07:54 +0200
csiph-web