""" FastAPI Universal Code Execution Sandbox with LANDRUN Security Kernel-level sandboxing using Linux Landlock for maximum isolation """ from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse, JSONResponse from fastapi.middleware.cors import CORSMiddleware import subprocess import tempfile import os import base64 import shlex app = FastAPI() # Enable CORS app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) def execute_with_landrun(language: str, code: str) -> dict: """Execute code using landrun kernel-level sandboxing""" # Language configurations configs = { "python": { "ext": ".py", "cmd": ["python3"], "allowed_paths": ["/usr/lib/python3*", "/usr/local/lib/python3*"], }, "javascript": { "ext": ".js", "cmd": ["node"], "allowed_paths": ["/usr/lib/node_modules", "/usr/local/lib/node_modules"], }, "html": { "ext": ".html", "cmd": None, # Static file "allowed_paths": [], }, "react": { "ext": ".jsx", "cmd": ["node"], "allowed_paths": ["/usr/lib/node_modules", "/usr/local/lib/node_modules"], } } config = configs.get(language.lower()) if not config: return {"error": f"Unsupported language: {language}"} # Create temporary file try: with tempfile.NamedTemporaryFile(mode='w', suffix=config['ext'], delete=False, dir='/tmp/sandbox') as f: f.write(code) temp_file = f.name # For HTML/static files, return directly if language.lower() == "html": with open(temp_file, 'r') as f: html_content = f.read() os.unlink(temp_file) return { "output": "HTML rendered successfully", "preview": base64.b64encode(html_content.encode()).decode() } # Build landrun command with security restrictions landrun_cmd = [ "/usr/local/bin/landrun", "--ldd", # Auto-detect library dependencies "--add-exec", # Auto-add executable "--ro", "/usr", # Read-only access to system files "--ro", "/lib", # Read-only access to libraries "--ro", "/lib64", # Read-only 64-bit libraries "--ro", "/etc", # Read-only config (for DNS, etc.) "--rw", "/tmp/sandbox", # Write access to sandbox only "--ro", temp_file, # Read-only access to code file "--connect-tcp", "80,443", # Allow HTTP/HTTPS "--log-level", "error", ] # Add language-specific paths for path in config['allowed_paths']: landrun_cmd.extend(["--ro", path]) # Add execution command landrun_cmd.extend(config['cmd'] + [temp_file]) # Execute with timeout result = subprocess.run( landrun_cmd, capture_output=True, text=True, timeout=10, cwd="/tmp/sandbox" ) # Clean up os.unlink(temp_file) # Prepare output output = result.stdout if result.stderr: output += f"\n--- STDERR ---\n{result.stderr}" # For React/JS with output, create preview preview = None if language.lower() in ["react", "javascript"] and "<" in code: preview = base64.b64encode(code.encode()).decode() return { "output": output or "Execution completed successfully", "exit_code": result.returncode, "preview": preview, "security": "🔒 Landrun kernel-level isolation active" } except subprocess.TimeoutExpired: return {"error": "⏱️ Execution timeout (10s limit)"} except Exception as e: return {"error": f"❌ Execution error: {str(e)}"} finally: # Cleanup temp file if exists if 'temp_file' in locals() and os.path.exists(temp_file): try: os.unlink(temp_file) except: pass @app.get("/", response_class=HTMLResponse) async def root(): """Serve the main UI""" return """
Kernel-Level Security with Linux Landlock