473,385 Members | 1,766 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

eval(source, {'builtins': {}}) archived as Faq

Absent from http://www.python.org/doc/current/li...-in-funcs.html
but now copied to the Faq list of http://pyfaq.infogami.com/suggest,
from these clp archives:

///

Q: How can I tell Python to calculate what quoted strings and numbers
mean, without also accidentally accepting OS commands as input?

A: eval(source, {'builtins': {}})

Note: What eval may do to you remains as surprising as ever if you
mistype this idiom as: eval(source, {})

Note: This idiom makes sense of ordinary Python literals (such as 010,
0x8, 8.125e+0, and "\x45ight"). This idiom also correctly interprets
simple literal expressions, such as 64**0.5.

Sep 28 '06 #1
4 1265
p.*******@ieee.org wrote:
Absent from http://www.python.org/doc/current/li...-in-funcs.html
but now copied to the Faq list of http://pyfaq.infogami.com/suggest,
from these clp archives:

///

Q: How can I tell Python to calculate what quoted strings and numbers
mean, without also accidentally accepting OS commands as input?

A: eval(source, {'builtins': {}})

Note: What eval may do to you remains as surprising as ever if you
mistype this idiom as: eval(source, {})

Note: This idiom makes sense of ordinary Python literals (such as 010,
0x8, 8.125e+0, and "\x45ight"). This idiom also correctly interprets
simple literal expressions, such as 64**0.5.
This is an _extremely_ bad idea. _Never_ use eval in a case where you
are trying to validate input.
>>def e(source): return eval(source, {'builtins': {}})
....
>>e('__import__("sys").exit()')
Oops, the interpreter exited.

Just when you think you've covered all the bases, you haven't.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
A man's life is what his thoughts make it.
-- Marcus Aurelius
Sep 28 '06 #2
p.*******@ieee.org writes:
Q: How can I tell Python to calculate what quoted strings and numbers
mean, without also accidentally accepting OS commands as input?

A: eval(source, {'builtins': {}})
That is dangerous. Consider source = "9**9**9". There's a better
recipe on ASPN:

http://aspn.activestate.com/ASPN/Coo.../Recipe/364469
Sep 28 '06 #3
Erik Max Francis <ma*@alcyone.comwrote:
This is an _extremely_ bad idea. _Never_ use eval in a case where you
are trying to validate input.
>def e(source): return eval(source, {'builtins': {}})
...
>e('__import__("sys").exit()')

Oops, the interpreter exited.
I'm slightly surprised that nobody has yet pointed out that the OP failed
at the very first hurdle here. If you are going to do this dangerous trick
then 'builtins' should be spelled '__builtins__':
>>def e(source): return eval(source, {'__builtins__': {}})
>>e('__import__("sys").exit()')
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
e('__import__("sys").exit()')
File "<pyshell#8>", line 1, in e
def e(source): return eval(source, {'__builtins__': {}})
File "<string>", line 1, in <module>
NameError: name '__import__' is not defined
>>>
but it is still not going to stop nasty things happening, it just makes
them a little more complex:
>>e("[ c for c in 1 .__class__.__bases__[0].__subclasses__() if
c.__name__=='Quitter'][0]('bang')()")

Sep 29 '06 #4
Duncan Booth wrote:
I'm slightly surprised that nobody has yet pointed out that the OP failed
at the very first hurdle here. If you are going to do this dangerous trick
then 'builtins' should be spelled '__builtins__':
I did, because otherwise the exploit I gave wouldn't have worked so easily.

The bottom line here is that you shouldn't even try to go through the
exercise of seeing if you can bullet-proof a solution using eval;
instead, you shouldn't even try.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
Everyone wants to look good at his own funeral.
-- Louis Wu
Sep 29 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Fernando Rodriguez | last post by:
Hi, Is ti possible to get the source code of a given function object? O:-) TIA
6
by: Leif K-Brooks | last post by:
In Python 2.4, although None can't be directly assigned to, globals() can still be; however, that won't change the value of the expression "None" in ordinary statements. Except with the eval...
3
by: Michael Hoffman | last post by:
I was compelled to write this today for some reason. builtins = """__import__ abs basestring bool callable chr classmethod cmp compile complex delattr dict dir divmod enumerate eval execfile...
3
by: Jeremy Sanders | last post by:
Hi - I'm trying to subclass a dict which is used as the globals environment of an eval expression. For instance: class Foo(dict): def __init__(self): self.update(globals()) self = 42
0
by: Michelle Keys | last post by:
Subject: DataBinder.Eval Error! Server Error in '/MSPOS' Application. ------------------------------------------------------------------------ -------- DataBinder.Eval:...
135
by: Xah Lee | last post by:
Tabs versus Spaces in Source Code Xah Lee, 2006-05-13 In coding a computer program, there's often the choices of tabs or spaces for code indentation. There is a large amount of confusion about...
0
by: Babar K. Zafar | last post by:
Hi guys! I know this subject has been beaten to death and I am not going to whine about lacking features for proper restricted execution in the Python runtime. It's the OS job, I get it. ...
1
by: =?ISO-8859-1?Q?Tor_Erik_S=F8nvisen?= | last post by:
Hi, A while ago I asked a question on the list about a simple eval function, capable of eval'ing simple python constructs (tuples, dicts, lists, strings, numbers etc) in a secure manner:...
0
by: J. Clifford Dyer | last post by:
On Tue, 2007-12-11 at 16:55 -0800, katie smith wrote: Katie, First, please provide a useful subject heading when posting to the list. It makes everyone's life easier when searching the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.