Safe eval of insecure strings containing Python data structures?

Aaron "Castironpi" Brady castironpi at gmail.com
Thu Oct 9 00:07:41 EDT 2008


On Oct 8, 7: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:  
>
...
> # 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!
>
> Cheers,
> Warren

As mentioned, I don't know if everything has been tried or how secure
what attempts have been.  I haven't seen this one:

Python 2.6 (r26:66721, Oct  2 2008, 11:35:03) [MSC v.1500 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> del __builtins__
>>> a= [ x for x in (1).__class__.__bases__[0].__subclasses__() if x.__name__==
'file' ][ 0 ]
>>> a
<type 'file'>
>>> a('abc.txt','w')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: file() constructor not accessible in restricted mode
>>> import os
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: __import__ not found

So, at least one of the newsgroup favorites is gone.  Take a shot
though!  Maybe a variant would be sufficient.  No warranty.



More information about the Python-list mailing list