DO NOT USE eval()
DO NOT USE exec()

For the use case mentioned here ("you don't know what the variable name could be"/"you need to dynamically change the name) use getattr() instead.

DO NOT USE eval()
DO NOT USE exec()

If you use eval() and/or exec() in your code, you are literally begging your application to get hacked. You've taken out a billboard saying "please RCE my face"

@r000t I used to say the same thing : "Everything you do with eval can be done more safely without it". Then I thought of ONE use-case where this is not true. Evaluating signed static code downloaded from a remote source. Basically the equivalent of signed binaries loaded as a shared library, but for interpreted languages. That day, I stopped advising against eval, without considering what is done with it first :)


There's always going to be *some* valid use case. "I'm literally letting users pass in executable code because I wanted to provide add-ons" is the one I go to. And of course eval() and exec() can be used safely if you're sanitizing and validating the living shit out of the input.

Might I also suggest the performance argument? getattr() setattr() and hasattr() are likely orders of magnititude faster than setting up the interpreter for a single line.

@r000t Absolutely. :) I just wanted to enumerate at least one valid use case, in case some youngling found your original toot, and took it without a grain of salt. Do not use eval and do not use goto. Well. Most of the time :D

Sign in to participate in the conversation
Infosec Exchange

A Mastodon instance for info/cyber security-minded people.