Saturday, May 11, 2019

Python - eval - Untrusted code


Never exec or eval Untrusted Code

Old versions of Python tried to supply tools to ameliorate the risks of using exec and eval, under the heading of “restricted execution,” but those tools were never entirely secure against the ingenuity of able hackers, and current versions of Python have therefore dropped them. If you need to ward against such attacks, take advantage of your operating system’s protection mechanisms: run untrusted code in a separate process, with privileges as restricted as you can possibly make them (study the mechanisms that your OS supplies for the purpose, such as chroot, setuid, and jail), or run untrusted code in a separate, highly constrained virtual machine. To guard against “denial of service” attacks, have the main process monitor the separate one and terminate the latter if and when resource consumption becomes excessive. Processes are covered in “Running Other Programs”.

exec and eval are unsafe with untrusted code

The function exec_with_data is not at all safe against untrusted code: if you pass it, as the argument user_code_string, some string obtained in a way that you cannot entirely trust, there is essentially no limit to the amount of damage it might do. This is unfortunately true of just about any use of both exec and eval, except for those rare cases in which you can set very strict and checkable limits on the code to execute or evaluate, as was the case for the function safer_eval.

No comments:

Post a Comment

Remote Hybrid and Office work