Sunjay Varma
Sunjay Varma

Reputation: 5115

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?

Upvotes: 5

Views: 218

Answers (2)

Raymond Hettinger
Raymond Hettinger

Reputation: 226366

Using exec with trusted data is okay; however, in this case it isn't necessary and will slow down your script.

Upvotes: 0

David Robinson
David Robinson

Reputation: 78610

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.

Upvotes: 6

Related Questions