What is eval in Python?
eval() function in Python lets you execute random Python code from a string. It can be really convenient when you need to execute arbitrary code coming from an input.
For example, let’s say you have a variable
bla and want to do some operations on it. You can then invoke the following code (here, just print the variable).
bla = “hello”
Why eval in Python is not safe nor secure?
eval() is not secure because you never know if the code you execute can be trusted. You can limit the scope of the variables being accessed with the second argument passed to
eval() but there are many cases when the content of the command itself is secure or not.
Imagine that your user uses a malicious command to execute code to get the list of users on your system like the one below. The user can get information about your system, or even worse, delete information from your system (such as data, logs, etc).
cmd = "print(open(\"/etc/passwd\").readlines())"
And even if you attempt to mitigate the issue (for example, by removing the user of global variables), the user input cannot be trusted. See this blog post for a deeper understanding. Even
the official Python documentation
has notes about security issues with
literal_eval() for secure and safe Python code
The safe and secure alternative is to use
literal_eval() from the ast package.
literal_eval() does not let you run code from another module, it only processes Python datatype (e.g. if you need to manipulate data, not call any other functions). You can read more about the restrictions of
literal_eval() in its documentation.
The main benefit from using
literal_eval() is that any attempt from untrusted source to execute malicious code will fail and raise a ValueError exception. In other words, the calling
literal_eval() with malicious code will fail and raise an exception developers needs to handle.
The downside of using
literal_eval() is that you cannot execute other functions based on any input. In such cases, you need to implement the behavior yourself and never rely on calling the
Automatically detect unsafe or insecure use of
With the Codiga plugin, you can automatically detect safe or insecure Python code. It integrates in your IDE as well as your CI/CD pipelines, thanks to all our integrations. You can even try the rule to avoid unsafe uses of
To use this rule consistently, all you need to do is to install the integration in your IDE (for VS Code or JetBrains) or code management system and add a
codiga.yml file at the root of your profile with the following content:
It will then check all your Python code against 100+ rules that detect unsafe and insecure code and suggests fixes for each of them.