Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About "eval is evil" and "consenting adults" [closed]

I see many saying "eval is evil/dangerous/insecure", because one can do things like:

eval("os.system('rm -rf /')")

While in other posts, pythoner are considered as "consenting adults", you don't have to do type checking because of python is of style duck typing.

Then what about the following code:

def foo(duck):
    duck.quack()

class EvilDuck(object):
    def quack(self):
        os.system('rm -rf /')

foo(EvilDuck())

How do you usually avoid such cases? When are pythoner consenting adults, and when not?

like image 903
zhangxaochen Avatar asked Mar 03 '14 06:03

zhangxaochen


2 Answers

eval is evil because user input gets into it at some point. You don’t (well, shouldn’t) have to be worried about code pretending to not delete all files, because code can do that anyways – tada:

def foo(duck):
    duck.quack()

class EvilDuck(object):
    os.system('rm -rf /')

    def quack(self):
        pass

And rm -rf / has a good chance of not working, too. ;)

Basically, “consenting adults” is “trust your code”. eval is “trust all code”. Depending on where you get that code, eval can be fine, but it’s unnecessary 99% of the time, and it can also be hard to guarantee as secure.

like image 82
Ry- Avatar answered Nov 15 '22 22:11

Ry-


It would seem silly for Python to try and police users to stop them executing commands from their program that they could just as easily type directly into a shell command line without involving Python at all.

Duck typing is OK, because it doesn't involve running code written by J. Random internet-User. You are (presumably) capabale of calling the objects you define in a manner consistent with their intended use.

eval() and exec (also a function in Python 3, but a statement in Python 2) are considered dangerous when applied to insufficiently-validated user inputs because without validation you lay yourself open to the will of a poitentially malicious user base.

In other words, code like

eval(raw_input("How may I hack you today? "))

is dangerous precisely because the user may choose to enter

os.system("switch off your antivirus protection")

or something else that similarly involves risk to you.

like image 35
holdenweb Avatar answered Nov 15 '22 21:11

holdenweb