/** * CodeExecutionGuard (L11) * * Validates and sandboxes agent-generated code before execution. * Prevents RCE (Remote Code Execution) attacks via malicious code generation. * * Threat Model: * - ASI05: Unexpected Code Execution (RCE) * - Code injection via LLM outputs * - Sandbox escape attempts * * Protection Capabilities: * - Static code analysis for dangerous patterns * - Import/require blocklist enforcement * - System call detection * - Resource limit enforcement * - Language-specific security rules */ /** A single finding from a pluggable code-analysis backend. */ export interface CodeFinding { name: string; /** Added to the risk score (0-100 scale). */ severity: number; kind?: string; } /** * Pluggable code-analysis backend (e.g. an AST parser such as acorn or oxc). * * Default is regex-only (zero dependencies). Provide a backend to add AST-level * detection — sandbox-escape gadget chains, the Function constructor, dynamic * import — that regex cannot reliably see. Findings are ADDITIVE: a backend can * only add detections, never remove them, and a throwing backend never crashes * the guard. See `examples/acorn-code-analyzer.ts` for a reference implementation. * * (The Python package uses stdlib `ast` directly; JS has no stdlib parser, so the * npm package keeps regex zero-dep by default and takes any parser via this seam.) */ export type CodeAnalyzerBackend = (code: string, language: string) => CodeFinding[]; export interface CodeExecutionGuardConfig { /** Allowed programming languages */ allowedLanguages?: string[]; /** Blocked imports/modules */ blockedImports?: string[]; /** Blocked function calls */ blockedFunctions?: string[]; /** Maximum code length in characters */ maxCodeLength?: number; /** Maximum execution time in milliseconds */ maxExecutionTime?: number; /** Allow network access */ allowNetwork?: boolean; /** Allow file system access */ allowFileSystem?: boolean; /** Allow shell/subprocess execution */ allowShell?: boolean; /** Allow environment variable access */ allowEnvAccess?: boolean; /** Custom dangerous patterns */ customPatterns?: Array<{ name: string; pattern: RegExp; severity: number; }>; /** Risk threshold for blocking (0-100) */ riskThreshold?: number; /** Optional pluggable AST analyzer (acorn/oxc/etc.). Additive on top of regex. */ analyzerBackend?: CodeAnalyzerBackend; } export interface CodeAnalysisResult { allowed: boolean; reason: string; violations: string[]; request_id: string; code_analysis: { language: string; length: number; dangerous_imports: string[]; dangerous_functions: string[]; system_calls: string[]; network_access: boolean; file_access: boolean; shell_access: boolean; env_access: boolean; risk_score: number; complexity_score: number; }; sanitized_code?: string; sandbox_config?: SandboxConfig; recommendations: string[]; } export interface SandboxConfig { timeout: number; memoryLimit: number; allowedSyscalls: string[]; networkPolicy: "none" | "localhost" | "allowlist"; filesystemPolicy: "none" | "readonly" | "temponly"; envVars: Record; } export declare class CodeExecutionGuard { private config; private analyzerBackend?; private readonly DANGEROUS_PATTERNS; private readonly PYTHON_GADGET_TOKENS; private readonly PYTHON_GADGET_PROXIMITY_WINDOW; private hasPythonGadgetChain; private readonly DEFAULT_BLOCKED_IMPORTS; private readonly DEFAULT_BLOCKED_FUNCTIONS; constructor(config?: CodeExecutionGuardConfig); /** Register/replace the pluggable AST analyzer backend at runtime. */ setAnalyzerBackend(backend: CodeAnalyzerBackend): void; /** * Analyze code for dangerous patterns before execution */ analyze(code: string, language: string, requestId?: string): CodeAnalysisResult; /** * Validate code structure (syntax check simulation) */ validateSyntax(code: string, language: string): { valid: boolean; errors: string[]; }; /** * Generate secure sandbox configuration */ generateSandboxConfig(needsNetwork: boolean, needsFileSystem: boolean, needsShell: boolean, needsEnv: boolean): SandboxConfig; /** * Sanitize code by removing dangerous patterns */ sanitizeCode(code: string, language: string): string; /** * Get allowed languages */ getAllowedLanguages(): string[]; /** * Add custom dangerous pattern */ addDangerousPattern(language: string, name: string, pattern: RegExp, severity: number): void; private calculateComplexity; private getAllowedSyscalls; private generateRecommendations; }