Safe eval of insecure strings containing Python data structures?

George Sakkis george.sakkis at gmail.com
Wed Oct 8 21:29:52 EDT 2008


On Oct 8, 8:34 pm, "Warren DeLano" <war... at delsci.com> wrote:

> I would like to parse arbitrary insecure text string containing nested
> Python data structures in eval-compatible form:  
>
> # For example, given a "config.txt" such as:
>
> {
>   'my_atom' : 1.20,
>   'my_dict' : { 2:50 , 'hi':'mom'},
>   'my_list' : [ (1,2,3), [4.5,6.9], 'foo', 0 ]
>
> }
>
> # I would like to do something like this:
>
> empty_space = {'__builtins__' : {}}
>
> try:
>     config = eval(open("config.txt").read(), empty_space, empty_space)
> except:
>     config = {}
>
> print config
>
> # But I know for certain that the above approach is NOT secure since
> object attributes can still be accessed...
>
> So is there an equally convenient yet secure alternative available for
> parsing strings containing Python data structure definitions?
>
> Thanks in advance for any pointers!

This topic comes up every other month or so in this list, so if you
had taken a minute to search for "python safe eval" or a variation
thereof in your favorite search engine, you'd get more than enough
pointers.

George



More information about the Python-list mailing list