Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using 'exec' under controlled conditions a security threat?

Here is an example class:

from datetime import datetime
class Article:
    published = datetime.now()
    for propname in "year month day hour minute second".split():
        exec "%s = property(lambda self: self.published.%s)"%(propname, propname)
    del propname

As you can see, I'm using exec to optimize the creation of multiple property() objects. I often read that using exec is bad and that it is a security hole in your program. In this case, is it?

like image 510
Sunjay Varma Avatar asked May 12 '12 04:05

Sunjay Varma


1 Answers

In this case, it's not really a security threat, since the security threat arises when the executed string is something the user has any kind of access to. In this case, it is a split string literal.

However, even if it's not a security risk, exec is almost always a poor choice. Why not use getattr and setattr instead?

from datetime import datetime
class Article:
    published = datetime.now()

    def __init__(self):
        for propname in "year month day hour minute second".split():
            setattr(self, propname, getattr(self.published, propname))

One flaw is that this has to be done in the __init__ method, so it depends whether you have a good reason not to include it there.

like image 185
David Robinson Avatar answered Sep 27 '22 15:09

David Robinson