eval() == evil? --- How to use it safely?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Aug 28 20:12:50 EDT 2008


On Thu, 28 Aug 2008 14:51:57 -0700, Fett wrote:

> I read that by using eval(code,{"__builtins__":None},{}) I can prevent
> them from using pretty much anything, 

No, it can prevent them from some obvious dangers, but not all obvious 
dangers and possibly not unobvious ones.

> and my nested dictionary of
> strings is still allowable. What I want to know is:
> 
> What are the dangers of eval?

You're executing code on your server that was written by arbitrary and 
untrusted people over the Internet.


> - I originally was using exec() but switched to eval() because I didn't
> want some hacker to be able to delete/steal files off my clients
> computers. I assume this is not an issue with eval(), since eval wont
> execute commands.

Bare eval() certainly can:

eval('__import__("os").system("ls *")')  # or worse...

eval() with the extra arguments given makes that sort of thing harder, 
but does it make it impossible? Are you willing to bet your server on it?

> - What exactly can someone do by modifying my code string in a command
> like: thing = eval(code{"__builtins__":None},{}), anything other than
> assign their own values to the object thing?

They can cause an exception:

code = '0.0/0.0'
thing = eval(code, {"__builtins__": None}, {})

They can cause a denial of service attack:

code = '10**10**10'

They can feed you bad data:

code = "{ 'akey': 'Something You Don\'t Expect' }"

You have to deal with bad data no matter what you do, but why make it 
easy for them to cause exceptions?

BTW, in case you think that you only have to deal with malicious attacks, 
you also have to deal with accidents caused by incompetent users.


-- 
Steven



More information about the Python-list mailing list