Python is the most widely used programming language worldwide. Its clear syntax, extensive libraries, and adaptability make it suitable for beginners, researchers, and professionals alike. But security is a growing critical concern for Python code. AI-generated code — is not secure by default and human programmers are no security experts.
A fantastic built in function that can be used in Python is `exec`.
You can use `exec` to dynamically generate functions. This can seem great functionality! Like e.g.:
exec("func = lambda x:x**4")
Or:
function_code = """
def greet(name):
return f"Hello, {name}!"
"""
exec(function_code) # Defines the function
# Now you can call it
message = greet("NOComplexity")
print(message)
# Output: Hello, {with_some_text}!
The problem is that the exec function executes code dynamically. Although this capability is intentionally part of the Python Standard Library (PSL) due to its simplicity in running external code—such as script files, data from an API, or user-provided input—its use presents a major security vulnerability.
Calling `exec` with user-supplied input may lead to security vulnerabilities. When `exec` is used in a Python program that executes some user input an attacker can e.g.:
- Delete files
- Upload/download data to remote servers
- Install malware
- Read any file on the system
- Crash the process
- Access all your variables/secrets

The risks of `exec` are perfectly explained in CWE-94: Improper Control of Generation of Code (‘Code Injection’).

(source image: https://cwe.mitre.org/data/definitions/94.html)
So Never ever use `exec()` (or `eval()` ) on user-supplied input unless you’re inside a proper sandbox (e.g., restricted Python environments like Pyodide with limitations.
Using `exec` in a single line of Python code is one of the fastest ways to turn your Python script into a remote code execution vulnerability.
The use of `exec` in a Python program must be immediately flagged for review. This function introduces a significant security risk, enabling code injection from vectors like APIs or dynamically loaded modules.
If you are a developer think of these mitigations before using `exec`:
- Avoid using
eval,execandcompile: Find a secure way by design, so rethink your design again from a security perspective. There is always a better and safer solution. - Use a battle-tested safe expression evaluator.
- Rethink your architecture to eliminate exec(), which introduces unnecessary risk.
- For in-browser sandboxing, use Pyodide (e.g., via JupyterLite).
- Call Functions or Methods by Name (String Input) If a function needs to be called based on a string name (e.g., from user input), store the functions in a dictionary and look them up by key. Avoid:
func_name = input("Enter function to run: ")
exec(f"{func_name}()")
Recommended Alternative (Dictionary of Functions):
def greet():
print("Hello!")
def quit_app():
import sys
sys.exit()
available_functions = {
"greet": greet,
"quit": quit_app
}
func_name = input("Enter function to run (greet or quit): ")
if func_name in available_functions:
available_functions[func_name]()
else:
print("Unknown function")
- For evaluating simple, safe expressions, use ast.literal_eval() which safely evaluates basic Python literals without allowing full code execution. Avoid:
exec("import os; os.system('your_command')")
Recommended alternative (ast.literal_eval):
import ast
user_input = "(2 + 3) * 5"
try:
result = ast.literal_eval(user_input)
print(result)
except (ValueError, SyntaxError):
print("Invalid input")
So a simple advice before running any Python program from others:
- Perform a simple Static Application Security Testing (SAST) on the code before running it.
You can use Python Code Audit (https://github.com/nocomplexity/codeaudit ) This open source SAST tool is created for users of Python programs to check security weaknesses. You do not have to be a security expert to use this tool.
But if you really want to avoid security disasters when running Python code of others:
Use this checklist with key security principles before running Python programs from others.
The use of `exec` in Python code is a potential weakness, it might not be a vulnerability since context matters! Programs should put a comment line in the code that the creators are aware of the use of `exec` and they explain why they think that it will not lead to a vulnerability.
