Safe Literal Parsing: ast.literal_eval vs eval()
`eval()` executes arbitrary code and opens severe security holes. In contrast, `ast.literal_eval()` exclusively evaluates Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and `None` 🛡️.
import ast
payload = "{'host': '127.0.0.1', 'port': 8080, 'ssl': False}"
config = ast.literal_eval(payload)
print(f"Port: {config['port']} 🛡️")
try:
# Malicious attempts raise ValueError immediately:
ast.literal_eval("__import__('os').system('id')")
except ValueError:
print("Malicious execution blocked! 🛑")
# 68. Safe Literal Parsing: ast.literal_eval vs eval() `eval()` executes arbitrary code and opens severe security holes. In contrast, `ast.literal_eval()` exclusively evaluates Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and `None` 🛡️. ```python import ast payload = "{'host': '127.0.0.1', 'port': 8080, 'ssl': False}" config = ast.literal_eval(payload) print(f"Port: {config['port']} 🛡️") try: # Malicious attempts raise ValueError immediately: ast.literal_eval("__import__('os').system('id')") except ValueError: print("Malicious execution blocked! 🛑") ``` Even simple arithmetic like `ast.literal_eval('1 + 2')` raises `ValueError`. It parses data structures, not executable expressions 🛡️. --- ### Question What error does `ast.literal_eval` raise when fed a non-literal expression (such as arithmetic operations or function calls)? 🧠 - [ ] a. `ValueError` (or `SyntaxError`), completely blocking code execution 🛡️ - [ ] b. `TypeError` while falling back to standard `eval()` execution - [ ] c. It silently returns `None` without terminating execution - [ ] d. `SecurityWarning` while executing the payload in restricted mode --- ### Challenge Use `ast.literal_eval` to safely parse `'[10, 20, 30]'`. Multiply each integer by 2 and print the resulting list. 🎯 <details> <summary>Solution</summary> ```python import ast data = ast.literal_eval('[10, 20, 30]') print([x * 2 for x in data]) ``` </details>