Spaces:
Sleeping
Sleeping
Commit ·
b299500
1
Parent(s): b851ab5
LANDRUN INTEGRATION - Kernel-level Linux sandbox with Landlock security
Browse filesFiles changed (18)
- app.py+331-863
- landrun-main/.github/workflows/build.ymlAdded+31
- landrun-main/.github/workflows/go-compatibility.ymlAdded+24
- landrun-main/.gitignoreAdded+31
- landrun-main/LICENSEAdded+21
- landrun-main/README.mdAdded+400
- landrun-main/demo.gifAdded
- landrun-main/go.modAdded+16
- landrun-main/go.sumAdded+14
- landrun-main/internal/elfdeps/elfdeps.goAdded+230
- landrun-main/internal/elfdeps/elfdeps_test.goAdded+222
- landrun-main/internal/elfdeps/testdata/liba.cAdded+1
- landrun-main/internal/elfdeps/testdata/libb.cAdded+2
- landrun-main/internal/elfdeps/testdata/main.cAdded+2
- landrun-main/internal/exec/runner.goAdded+21
- landrun-main/internal/log/log.goAdded+64
- landrun-main/internal/sandbox/sandbox.goAdded+192
- landrun-main/test.shAdded+314
1234567891011121314151617182 unmodified lines21222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971"""FastAPI Universal Code Execution Sandbox for Hugging Face SpacesSupports: HTML, React, Python, Node.js, Java, Ruby, PHP, Go, Rust, C++, C#, Swift, Kotlin, and more!"""from fastapi import FastAPI, Requestfrom fastapi.responses import HTMLResponse, StreamingResponse, JSONResponsefrom fastapi.middleware.cors import CORSMiddlewareimport osimport asyncioimport shutilapp = FastAPI()# Enable CORS for iframe embeddingapp.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)# Language configurationsLANGUAGE_CONFIG = {"python": {"extension": ".py","command": lambda file: ["python3", file],"runtime_check": "python3"},"node": {"extension": ".mjs","command": lambda file: ["node", file],"runtime_check": "node"},"java": {"extension": ".java","compile": lambda file: ["javac", file],"command": lambda: ["java", "-cp", "/tmp", "Main"],"runtime_check": "javac","needs_compile": True},"ruby": {"extension": ".rb","command": lambda file: ["ruby", file],"runtime_check": "ruby"},"php": {"extension": ".php","command": lambda file: ["php", file],"runtime_check": "php"},"go": {"extension": ".go","command": lambda file: ["go", "run", file],"runtime_check": "go"},"rust": {"extension": ".rs","compile": lambda file: ["rustc", file, "-o", "/tmp/rust_output"],"command": lambda: ["/tmp/rust_output"],"runtime_check": "rustc","needs_compile": True},"cpp": {"extension": ".cpp","compile": lambda file: ["g++", file, "-o", "/tmp/cpp_output"],"command": lambda: ["/tmp/cpp_output"],"runtime_check": "g++","needs_compile": True},"c": {"extension": ".c","compile": lambda file: ["gcc", file, "-o", "/tmp/c_output"],"command": lambda: ["/tmp/c_output"],"runtime_check": "gcc","needs_compile": True},"csharp": {"extension": ".cs","compile": lambda file: ["mcs", file, "-out:/tmp/csharp_output.exe"],"command": lambda: ["mono", "/tmp/csharp_output.exe"],"runtime_check": "mcs","needs_compile": True},"swift": {"extension": ".swift","command": lambda file: ["swift", file],"runtime_check": "swift"},"kotlin": {"extension": ".kt","compile": lambda file: ["kotlinc", file, "-include-runtime", "-d", "/tmp/kotlin_output.jar"],"command": lambda: ["java", "-jar", "/tmp/kotlin_output.jar"],"runtime_check": "kotlinc","needs_compile": True},"perl": {"extension": ".pl","command": lambda file: ["perl", file],"runtime_check": "perl"},"lua": {"extension": ".lua","command": lambda file: ["lua", file],"runtime_check": "lua"},"bash": {"extension": ".sh","command": lambda file: ["bash", file],"runtime_check": "bash"},"r": {"extension": ".r","command": lambda file: ["Rscript", file],"runtime_check": "Rscript"},"scala": {"extension": ".scala","command": lambda file: ["scala", file],"runtime_check": "scala"}}@app.get("/health")async def health():"""Health check for pre-warming the Space"""return {"status": "ok"}@app.get("/capabilities")async def capabilities():"""Check which language runtimes are available"""caps = {}for lang, config in LANGUAGE_CONFIG.items():runtime = config.get("runtime_check")caps[lang] = shutil.which(runtime) is not Nonereturn caps@app.get("/languages")async def list_languages():"""List all supported languages with availability"""result = []for lang, config in LANGUAGE_CONFIG.items():runtime = config.get("runtime_check")available = shutil.which(runtime) is not Noneresult.append({"language": lang,"available": available,"extension": config["extension"],"needs_compile": config.get("needs_compile", False)})return {"languages": result}async def stream_execution(language: str, code: str):"""Execute code for any supported language and stream output"""config = LANGUAGE_CONFIG.get(language)if not config:yield f"Error: Unsupported language '{language}'\n"yield "done\n"return# Check runtime availabilityruntime = config.get("runtime_check")if not shutil.which(runtime):yield f"Error: {language} runtime not available\n"yield "done\n"return# Determine filenameif language == "java":code_path = "/tmp/Main.java"else:code_path = f"/tmp/code{config['extension']}"# Write code to filetry:with open(code_path, "w") as f:f.write(code)except Exception as e:yield f"Error writing code: {e}\n"yield "done\n"returntry:# Compile if neededif config.get("needs_compile"):compile_cmd = config["compile"](code_path)compile_process = await asyncio.create_subprocess_exec(*compile_cmd,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT)# Stream compilation outputwhile True:line = await compile_process.stdout.readline()if not line:breakyield line.decode('utf-8', errors='replace')exit_code = await compile_process.wait()if exit_code != 0:yield f"Compilation failed with exit code {exit_code}\n"yield "done\n"return# Executeif config.get("needs_compile") and callable(config["command"]):run_cmd = config["command"]()else:run_cmd = config["command"](code_path)run_process = await asyncio.create_subprocess_exec(*run_cmd,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT)# Stream execution outputwhile True:line = await run_process.stdout.readline()if not line:breakyield line.decode('utf-8', errors='replace')await run_process.wait()yield "done\n"except Exception as e:yield f"Execution error: {e}\n"yield "done\n"finally:# Clean uptry:os.remove(code_path)# Clean up compiled outputsif language == "java":os.remove("/tmp/Main.class")elif language == "rust":os.remove("/tmp/rust_output")elif language == "cpp":os.remove("/tmp/cpp_output")elif language == "c":os.remove("/tmp/c_output")elif language == "csharp":os.remove("/tmp/csharp_output.exe")elif language == "kotlin":os.remove("/tmp/kotlin_output.jar")except Exception:pass# Schedule exitasyncio.create_task(delayed_exit())async def delayed_exit():"""Exit the process after a short delay"""await asyncio.sleep(0.5)os._exit(0)@app.post("/run")async def run_code(request: Request):"""Execute code in any supported language and stream output"""body = await request.json()language = body.get("language", "").lower()code = body.get("code", "")if not code:return JSONResponse({"error": "NO_CODE"}, status_code=400)if language not in LANGUAGE_CONFIG:return JSONResponse({"error": f"UNSUPPORTED_LANGUAGE: {language}"},status_code=400)# Check if runtime is availableconfig = LANGUAGE_CONFIG[language]runtime = config.get("runtime_check")if not shutil.which(runtime):return JSONResponse({"error": f"{language.upper()}_NOT_AVAILABLE"},status_code=503)return StreamingResponse(stream_execution(language, code),media_type="text/plain")@app.get("/", response_class=HTMLResponse)async def root():"""Serve the HTML UI with multi-language support"""html_content = """<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Universal Code Sandbox</title><!-- CDN Scripts --><script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.6/dist/purify.min.js"></script><script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script><script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script><script src="https://unpkg.com/@babel/standalone/babel.min.js"></script><style>* {margin: 0;padding: 0;box-sizing: border-box;}body {font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;background: #1e1e1e;color: #d4d4d4;height: 100vh;overflow: hidden;display: flex;flex-direction: column;}.app-container {display: flex;flex-direction: column;height: 100vh;padding: 20px;gap: 15px;}h1 {color: #4ec9b0;font-size: 28px;margin: 0;}.controls {display: flex;gap: 10px;align-items: center;flex-wrap: wrap;flex-shrink: 0;}label {color: #9cdcfe;font-weight: bold;}select, button {background: #252526;color: #d4d4d4;border: 1px solid #3c3c3c;padding: 10px 15px;border-radius: 4px;font-family: inherit;font-size: 14px;cursor: pointer;transition: all 0.2s;}select:hover {border-color: #007acc;}select:focus, button:focus {outline: none;border-color: #007acc;}button {background: #007acc;color: white;border: none;font-weight: bold;padding: 10px 20px;}button:hover:not(:disabled) {background: #005a9e;transform: translateY(-1px);}button:active:not(:disabled) {transform: translateY(0);}button:disabled {background: #3c3c3c;cursor: not-allowed;opacity: 0.6;}.workspace {flex: 1;display: grid;grid-template-rows: minmax(250px, 1fr) minmax(250px, 1fr);gap: 15px;min-height: 0;overflow: hidden;}.editor-panel {display: flex;flex-direction: column;min-height: 0;}.panel-label {color: #9cdcfe;font-weight: bold;margin-bottom: 8px;font-size: 13px;text-transform: uppercase;letter-spacing: 1px;}textarea {flex: 1;background: #252526;color: #d4d4d4;border: 1px solid #3c3c3c;border-radius: 4px;padding: 15px;font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;font-size: 14px;line-height: 1.6;resize: none;outline: none;min-height: 0;}textarea:focus {border-color: #007acc;}.output-panel {display: flex;flex-direction: column;min-height: 0;position: relative;}#output {flex: 1;background: #0c0c0c;color: #00ff00;border: 1px solid #00ff00;border-radius: 4px;padding: 15px;overflow-y: auto;font-size: 13px;line-height: 1.6;white-space: pre-wrap;word-wrap: break-word;font-family: 'Courier New', monospace;min-height: 0;}#html-preview, #react-root {flex: 1;background: white;border: 1px solid #3c3c3c;border-radius: 4px;overflow: auto;min-height: 0;}#html-preview {border: 1px solid #3c3c3c;}.error { color: #f48771; }.success { color: #4ec9b0; }.info { color: #9cdcfe; }.badge {display: inline-block;padding: 3px 8px;border-radius: 3px;font-size: 11px;margin-left: 5px;font-weight: bold;}.badge-available { background: #4ec9b0; color: #000; }.badge-unavailable { background: #f48771; color: #000; }/* Scrollbar styling */::-webkit-scrollbar {width: 10px;height: 10px;}::-webkit-scrollbar-track {background: #1e1e1e;}::-webkit-scrollbar-thumb {background: #3c3c3c;border-radius: 5px;}::-webkit-scrollbar-thumb:hover {background: #007acc;}@media (max-width: 768px) {.workspace {grid-template-rows: 300px 1fr;}h1 {font-size: 20px;}}</style></head><body><div class="app-container"><h1>🚀 Universal Code Sandbox</h1><div class="controls"><label for="language">Language:</label><select id="language" onchange="switchLanguage()"><optgroup label="Client-Side"><option value="html">HTML</option><option value="react">React/JSX</option></optgroup><optgroup label="Scripting Languages"><option value="python">Python</option><option value="node">Node.js/JavaScript</option><option value="ruby">Ruby</option><option value="php">PHP</option><option value="perl">Perl</option><option value="lua">Lua</option><option value="bash">Bash</option><option value="r">R</option></optgroup><optgroup label="Compiled Languages"><option value="java">Java</option><option value="cpp">C++</option><option value="c">C</option><option value="go">Go</option><option value="rust">Rust</option><option value="csharp">C#</option><option value="swift">Swift</option><option value="kotlin">Kotlin</option><option value="scala">Scala</option></optgroup></select><button id="runBtn" onclick="runCode()">▶ Run</button><button onclick="checkAvailability()">🔍 Check Available</button><span id="status" class="info"></span></div><div class="workspace"><div class="editor-panel"><div class="panel-label">◆ Code Editor</div><textarea id="editor" placeholder="Enter your code here..." spellcheck="false"></textarea></div><div class="output-panel"><div class="panel-label">◆ Output / Preview</div><pre id="output" style="display: none;"></pre><iframe id="html-preview" style="display: none;" sandbox="allow-scripts"></iframe><div id="react-root" style="display: none;"></div></div></div></div><script>const editor = document.getElementById('editor');const output = document.getElementById('output');const htmlPreview = document.getElementById('html-preview');const reactRoot = document.getElementById('react-root');const languageSelect = document.getElementById('language');const runBtn = document.getElementById('runBtn');const status = document.getElementById('status');let capabilities = {};// Fetch capabilities on loadfetch('/capabilities').then(res => res.json()).then(data => {capabilities = data;updateLanguageSelector();});function updateLanguageSelector() {const options = languageSelect.querySelectorAll('option');options.forEach(opt => {const lang = opt.value;if (lang === 'html' || lang === 'react') {return; // Client-side always available}if (capabilities[lang] !== undefined) {const badge = capabilities[lang] ?'<span class="badge badge-available">✓</span>' :'<span class="badge badge-unavailable">✗</span>';opt.innerHTML = opt.innerHTML.split('<')[0] + ' ' + (capabilities[lang] ? '✓' : '✗');}});}async function checkAvailability() {status.textContent = '🔍 Checking...';status.className = 'info';const response = await fetch('/languages');const data = await response.json();output.style.display = 'block';htmlPreview.style.display = 'none';reactRoot.style.display = 'none';output.textContent = 'Available Languages:\\n\\n';data.languages.forEach(lang => {const badge = lang.available ? '✅' : '❌';output.textContent += `${badge} ${lang.language.toUpperCase()} (${lang.extension})\\n`;});status.textContent = '✓ Check complete';status.className = 'success';}const examples = {python: `# Python exampleprint("Hello from Python!")for i in range(5):print(f"Number: {i + 1}")print("Done!")`,node: `// Node.js exampleconsole.log('Hello from Node.js!');for (let i = 0; i < 5; i++) {console.log('Step ' + (i + 1));await new Promise(r => setTimeout(r, 200));}console.log('Done!');`,java: `public class Main {public static void main(String[] args) {System.out.println("Hello from Java!");for (int i = 0; i < 5; i++) {System.out.println("Step " + (i + 1));}System.out.println("Done!");}}`,ruby: `# Ruby exampleputs "Hello from Ruby!"5.times do |i|puts "Step #{i + 1}"endputs "Done!"`,php: `<?phpecho "Hello from PHP!\\n";for ($i = 1; $i <= 5; $i++) {echo "Step $i\\n";}echo "Done!\\n";?>`,go: `package mainimport "fmt"func main() {fmt.Println("Hello from Go!")for i := 1; i <= 5; i++ {fmt.Printf("Step %d\\n", i)}fmt.Println("Done!")}`,rust: `fn main() {println!("Hello from Rust!");for i in 1..=5 {println!("Step {}", i);}println!("Done!");}`,cpp: `#include <iostream>using namespace std;int main() {cout << "Hello from C++!" << endl;for (int i = 1; i <= 5; i++) {cout << "Step " << i << endl;}cout << "Done!" << endl;return 0;}`,c: `#include <stdio.h>int main() {printf("Hello from C!\\n");for (int i = 1; i <= 5; i++) {printf("Step %d\\n", i);}printf("Done!\\n");return 0;}`,csharp: `using System;class Program {static void Main() {Console.WriteLine("Hello from C#!");for (int i = 1; i <= 5; i++) {Console.WriteLine($"Step {i}");}Console.WriteLine("Done!");}}`,swift: `print("Hello from Swift!")for i in 1...5 {print("Step \\(i)")}print("Done!")`,kotlin: `fun main() {println("Hello from Kotlin!")for (i in 1..5) {println("Step $i")}println("Done!")}`,perl: `# Perl exampleprint "Hello from Perl!\\n";for my $i (1..5) {print "Step $i\\n";}print "Done!\\n";`,lua: `-- Lua exampleprint("Hello from Lua!")for i = 1, 5 doprint("Step " .. i)endprint("Done!")`,bash: `#!/bin/bashecho "Hello from Bash!"for i in {1..5}; doecho "Step $i"doneecho "Done!"`,r: `# R exampleprint("Hello from R!")for (i in 1:5) {print(paste("Step", i))}print("Done!")`,scala: `object Main extends App {println("Hello from Scala!")for (i <- 1 to 5) {println(s"Step $i")}println("Done!")}`,html: `<!DOCTYPE html><html><head><style>body { font-family: Arial; padding: 20px; }h1 { color: #007acc; }</style></head><body><h1>Hello from HTML!</h1><p>This is rendered client-side.</p><button onclick="alert('Clicked!')">Click Me</button></body></html>`,react: `function App() {const [count, setCount] = React.useState(0);return (<div style={{padding: '20px', fontFamily: 'Arial'}}><h1>Hello from React!</h1><p>Count: {count}</p><button onClick={() => setCount(count + 1)}>Increment</button></div>);}ReactDOM.createRoot(document.getElementById('react-root')).render(<App />);`};function switchLanguage() {const lang = languageSelect.value;editor.value = examples[lang] || '';// Hide all output areasoutput.style.display = 'none';htmlPreview.style.display = 'none';reactRoot.style.display = 'none';// Show appropriate output areaif (lang === 'html') {htmlPreview.style.display = 'block';} else if (lang === 'react') {reactRoot.style.display = 'block';} else {output.style.display = 'block';}output.textContent = '';status.textContent = '';}async function runCode() {const lang = languageSelect.value;const code = editor.value.trim();if (!code) {status.textContent = '⚠️ No code to run';status.className = 'error';return;}output.textContent = '';status.textContent = '🚀 Running...';status.className = 'info';if (lang === 'html') {runHTML(code);} else if (lang === 'react') {runReact(code);} else {await runServerSide(lang, code);}}function runHTML(code) {try {const clean = DOMPurify.sanitize(code);htmlPreview.srcdoc = clean;status.textContent = '✓ Rendered';status.className = 'success';} catch (error) {output.style.display = 'block';htmlPreview.style.display = 'none';output.textContent = 'Error: ' + error.message;status.textContent = '❌ Error';status.className = 'error';}}function runReact(code) {try {reactRoot.innerHTML = '';const transformed = Babel.transform(code, {presets: ['react']}).code;eval(transformed);status.textContent = '✓ Rendered';status.className = 'success';} catch (error) {reactRoot.innerHTML = '<div style="padding: 20px; color: red; font-family: monospace;">' +'<strong>Error:</strong><br>' + error.message + '</div>';status.textContent = '❌ Error';status.className = 'error';}}async function runServerSide(lang, code) {runBtn.disabled = true;editor.disabled = true;output.textContent = '';try {const response = await fetch('/run', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ language: lang, code: code })});if (!response.ok) {const error = await response.json();output.textContent = 'Error: ' + (error.error || 'Unknown error');status.textContent = '❌ Error';status.className = 'error';runBtn.disabled = false;editor.disabled = false;return;}const reader = response.body.getReader();const decoder = new TextDecoder();while (true) {const { value, done } = await reader.read();if (done) break;const chunk = decoder.decode(value, { stream: true });output.textContent += chunk;output.scrollTop = output.scrollHeight;if (chunk.includes('done')) {status.textContent = '✓ Complete (Space restarting...)';status.className = 'success';}}} catch (error) {output.textContent += '\\n\\nConnection error: ' + error.message;status.textContent = '❌ Error';status.className = 'error';} finally {runBtn.disabled = false;editor.disabled = false;}}// Tab key supporteditor.addEventListener('keydown', (e) => {if (e.key === 'Tab') {e.preventDefault();const start = editor.selectionStart;const end = editor.selectionEnd;editor.value = editor.value.substring(0, start) + ' ' + editor.value.substring(end);editor.selectionStart = editor.selectionEnd = start + 4;}});// Ctrl+Enter to runeditor.addEventListener('keydown', (e) => {if (e.ctrlKey && e.key === 'Enter') {e.preventDefault();runCode();}});// InitializeswitchLanguage();</script></body></html>"""return HTMLResponse(content=html_content)if __name__ == "__main__":12345678910111213141516171819202 unmodified lines2324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439"""FastAPI Universal Code Execution Sandbox with LANDRUN SecurityKernel-level sandboxing using Linux Landlock for maximum isolation"""from fastapi import FastAPI, Requestfrom fastapi.responses import HTMLResponse, JSONResponsefrom fastapi.middleware.cors import CORSMiddlewareimport subprocessimport tempfileimport osimport base64import shlexapp = FastAPI()# Enable CORSapp.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)def execute_with_landrun(language: str, code: str) -> dict:"""Execute code using landrun kernel-level sandboxing"""# Language configurationsconfigs = {"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 filetry: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 directlyif 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 restrictionslandrun_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 pathsfor path in config['allowed_paths']:landrun_cmd.extend(["--ro", path])# Add execution commandlandrun_cmd.extend(config['cmd'] + [temp_file])# Execute with timeoutresult = subprocess.run(landrun_cmd,capture_output=True,text=True,timeout=10,cwd="/tmp/sandbox")# Clean upos.unlink(temp_file)# Prepare outputoutput = result.stdoutif result.stderr:output += f"\n--- STDERR ---\n{result.stderr}"# For React/JS with output, create previewpreview = Noneif 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 existsif '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 """<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>🔒 Landrun Sandbox - Kernel-Level Security</title><style>* { margin: 0; padding: 0; box-sizing: border-box; }body {font-family: 'Segoe UI', system-ui, sans-serif;background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);min-height: 100vh;padding: 20px;}.container {max-width: 1400px;margin: 0 auto;background: white;border-radius: 20px;box-shadow: 0 20px 60px rgba(0,0,0,0.3);overflow: hidden;}.header {background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);color: white;padding: 30px;text-align: center;}.header h1 { font-size: 2.5em; margin-bottom: 10px; }.header p { opacity: 0.9; font-size: 1.1em; }.security-badge {display: inline-block;background: rgba(255,255,255,0.2);padding: 8px 16px;border-radius: 20px;margin-top: 10px;font-weight: bold;}.content {display: grid;grid-template-columns: 1fr 1fr;gap: 20px;padding: 30px;}.panel {background: #f8f9fa;border-radius: 12px;padding: 20px;}.panel h2 {color: #667eea;margin-bottom: 15px;font-size: 1.3em;}textarea {width: 100%;height: 300px;font-family: 'Monaco', 'Courier New', monospace;font-size: 14px;padding: 15px;border: 2px solid #ddd;border-radius: 8px;resize: vertical;background: white;}select {width: 100%;padding: 12px;margin-bottom: 15px;border: 2px solid #ddd;border-radius: 8px;font-size: 16px;background: white;}button {background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);color: white;border: none;padding: 15px 30px;font-size: 16px;font-weight: bold;border-radius: 8px;cursor: pointer;width: 100%;margin-top: 10px;transition: transform 0.2s;}button:hover { transform: scale(1.05); }button:disabled {background: #ccc;cursor: not-allowed;transform: none;}.output {background: #1e1e1e;color: #d4d4d4;padding: 20px;border-radius: 8px;font-family: 'Monaco', 'Courier New', monospace;font-size: 14px;white-space: pre-wrap;min-height: 300px;max-height: 500px;overflow-y: auto;}.preview {width: 100%;height: 400px;border: 2px solid #ddd;border-radius: 8px;background: white;}.status {padding: 10px;border-radius: 8px;margin-bottom: 15px;font-weight: bold;}.status.success {background: #d4edda;color: #155724;border: 1px solid #c3e6cb;}.status.error {background: #f8d7da;color: #721c24;border: 1px solid #f5c6cb;}.examples {display: grid;grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));gap: 10px;margin-bottom: 15px;}.example-btn {padding: 10px;background: white;border: 2px solid #667eea;color: #667eea;border-radius: 8px;cursor: pointer;font-size: 14px;transition: all 0.2s;}.example-btn:hover {background: #667eea;color: white;}</style></head><body><div class="container"><div class="header"><h1>🔒 Landrun Sandbox</h1><p>Kernel-Level Security with Linux Landlock</p><div class="security-badge">🛡️ Maximum Isolation • Zero Trust • Kernel Enforced</div></div><div class="content"><div class="panel"><h2>📝 Code Editor</h2><select id="language"><option value="python">Python</option><option value="javascript">JavaScript (Node.js)</option><option value="react">React (JSX)</option><option value="html">HTML</option></select><div class="examples"><button class="example-btn" onclick="loadExample('hello')">Hello World</button><button class="example-btn" onclick="loadExample('math')">Math Demo</button><button class="example-btn" onclick="loadExample('html')">HTML Page</button><button class="example-btn" onclick="loadExample('react')">React App</button></div><textarea id="code" placeholder="Write your code here...">print("Hello from Landrun Sandbox!")print("🔒 Running with kernel-level security!")import sysprint(f"Python version: {sys.version}")</textarea><button id="runBtn" onclick="executeCode()">▶️ Run Code (Landrun Secured)</button></div><div class="panel"><h2>📺 Output</h2><div id="status"></div><div id="output" class="output">Ready to execute code...</div></div></div><div style="padding: 0 30px 30px 30px;"><div class="panel"><h2>🖼️ Preview</h2><iframe id="preview" class="preview"></iframe></div></div></div><script>const examples = {hello: {python: 'print("Hello from Landrun Sandbox!")\\nprint("🔒 Running with kernel-level security!")',javascript: 'console.log("Hello from Landrun Sandbox!");\\nconsole.log("🔒 Running with kernel-level security!");',react: 'export default function App() {\\n return <div><h1>Hello from React!</h1><p>🔒 Landrun secured</p></div>;\\n}',html: '<!DOCTYPE html>\\n<html>\\n<head><title>Hello</title></head>\\n<body><h1>Hello from HTML!</h1></body>\\n</html>'},math: {python: 'import math\\nprint(f"π = {math.pi}")\\nprint(f"e = {math.e}")\\nprint(f"sqrt(16) = {math.sqrt(16)}")',javascript: 'console.log(`π = ${Math.PI}`);\\nconsole.log(`e = ${Math.E}`);\\nconsole.log(`sqrt(16) = ${Math.sqrt(16)}`);'},html: {html: '<!DOCTYPE html>\\n<html>\\n<head><style>body{font-family:Arial;text-align:center;padding:50px}</style></head>\\n<body><h1>🔒 Landrun Sandbox</h1><p>Kernel-level security active!</p></body>\\n</html>'},react: {react: 'export default function App() {\\n return (\\n <div style={{textAlign:"center",padding:"50px"}}>\\n <h1>🔒 Landrun Sandbox</h1>\\n <p>React app with kernel-level security!</p>\\n </div>\\n );\\n}'}};function loadExample(type) {const lang = document.getElementById('language').value;const code = examples[type]?.[lang] || examples[type]?.python || examples.hello[lang];document.getElementById('code').value = code;}async function executeCode() {const code = document.getElementById('code').value;const language = document.getElementById('language').value;const output = document.getElementById('output');const status = document.getElementById('status');const runBtn = document.getElementById('runBtn');const preview = document.getElementById('preview');runBtn.disabled = true;runBtn.textContent = '⏳ Executing with Landrun...';status.innerHTML = '<div class="status">⚙️ Executing in kernel-secured sandbox...</div>';output.textContent = 'Executing...';try {const response = await fetch('/execute', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({language, code})});const result = await response.json();if (result.error) {status.innerHTML = `<div class="status error">❌ Error: ${result.error}</div>`;output.textContent = result.error;} else {status.innerHTML = `<div class="status success">✅ Success! ${result.security || ''}</div>`;output.textContent = result.output || 'Execution completed successfully';if (result.preview) {const decoded = atob(result.preview);preview.srcdoc = decoded;}}} catch (error) {status.innerHTML = `<div class="status error">❌ Network Error</div>`;output.textContent = error.message;} finally {runBtn.disabled = false;runBtn.textContent = '▶️ Run Code (Landrun Secured)';}}document.getElementById('language').addEventListener('change', () => {loadExample('hello');});</script></body></html>"""@app.post("/execute")async def execute(request: Request):"""Execute code with landrun sandboxing"""data = await request.json()language = data.get("language", "python")code = data.get("code", "")if not code:return JSONResponse({"error": "No code provided"})result = execute_with_landrun(language, code)return JSONResponse(result)@app.get("/health")async def health():"""Health check endpoint"""return {"status": "healthy", "sandbox": "landrun", "security": "kernel-level"}if __name__ == "__main__":
12345678910111213141516171819202122232425262728293031name: Build
on: push: branches: [main] pull_request: branches: [main]
jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4
- name: Set up Go uses: actions/setup-go@v5 with: go-version: "1.24.1" check-latest: true
- name: Install dependencies run: go mod download
- name: Build run: go build -v -o landrun ./cmd/landrun/main.go
- name: Upload binary uses: actions/upload-artifact@v4 with: name: landrun-linux-amd64 path: ./landrun123456789101112131415161718192021222324name: Go version compatibility
on: [push, pull_request]
jobs: build: runs-on: ubuntu-latest strategy: matrix: go: ["1.18", "1.20", "1.22", "1.24"] name: Go ${{ matrix.go }} build steps: - uses: actions/checkout@v3
- name: Set up Go ${{ matrix.go }} uses: actions/setup-go@v4 with: go-version: ${{ matrix.go }}
- name: Download dependencies run: go mod tidy
- name: Build landrun run: go build ./cmd/landrun12345678910111213141516171819202122232425262728293031# If you prefer the allow list template instead of the deny list, see community template:# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore## Binaries for programs and plugins*.exe*.exe~*.dll*.so*.dylib
# Test binary, built with `go test -c`*.test
# Output of the go coverage tool, specifically when used with LiteIDE*.out
# Dependency directories (remove the comment below to include it)# vendor/
# Go workspace filego.workgo.work.sum
# env file.envmaintmpinternal/sandbox/test_rwinternal/sandbox/test_rotest_envlandrun123456789101112131415161718192021MIT License
Copyright (c) 2025 Armin ranjbar
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400# Landrun <img src="https://avatars.githubusercontent.com/u/21111839?s=48&v=4" align="right"/>
A lightweight, secure sandbox for running Linux processes using Landlock. Think firejail, but with kernel-level security and minimal overhead.
Linux Landlock is a kernel-native security module that lets unprivileged processes sandbox themselves.
Landrun is designed to make it practical to sandbox any command with fine-grained filesystem and network access controls. No root. No containers. No SELinux/AppArmor configs.
It's lightweight, auditable, and wraps Landlock v5 features (file access + TCP restrictions).
## Features
- 🔒 Kernel-level security using Landlock- 🚀 Lightweight and fast execution- 🛡️ Fine-grained access control for directories and files- 🔄 Support for read and write paths- ⚡ Path-specific execution permissions- 🌐 TCP network access control (binding and connecting)
## Demo
<p align="center"> <img src="demo.gif" alt="landrun demo" width="700"/></p>
## Requirements
- Linux kernel 5.13 or later with Landlock enabled- Linux kernel 6.7 or later for network restrictions (TCP bind/connect)- Go 1.18 or later (for building from source)
## Installation
### Quick Install
```bashgo install github.com/zouuup/landrun/cmd/landrun@latest```
### From Source
```bashgit clone https://github.com/zouuup/landrun.gitcd landrungo build -o landrun cmd/landrun/main.gosudo cp landrun /usr/local/bin/```
### Distros
#### Arch (AUR)
- [stable](https://aur.archlinux.org/packages/landrun) maintained by [Vcalv](https://github.com/vcalv)- [latest commit](https://aur.archlinux.org/packages/landrun-git) maintained by [juxuanu](https://github.com/juxuanu/)
#### Slackware
maintained by [r1w1s1](https://github.com/r1w1s1)
[Slackbuild](https://slackbuilds.org/repository/15.0/network/landrun/?search=landrun)```bashsudo sbopkg -i packagename```
## Usage
Basic syntax:
```bashlandrun [options] <command> [args...]```
### Options
- `--ro <path>`: Allow read-only access to specified path (can be specified multiple times or as comma-separated values)- `--rox <path>`: Allow read-only access with execution to specified path (can be specified multiple times or as comma-separated values)- `--rw <path>`: Allow read-write access to specified path (can be specified multiple times or as comma-separated values)- `--rwx <path>`: Allow read-write access with execution to specified path (can be specified multiple times or as comma-separated values)- `--bind-tcp <port>`: Allow binding to specified TCP port (can be specified multiple times or as comma-separated values)- `--connect-tcp <port>`: Allow connecting to specified TCP port (can be specified multiple times or as comma-separated values)- `--env <var>`: Environment variable to pass to the sandboxed command (format: KEY=VALUE or just KEY to pass current value)- `--best-effort`: Use best effort mode, falling back to less restrictive sandbox if necessary [default: disabled]- `--log-level <level>`: Set logging level (error, info, debug) [default: "error"]- `--unrestricted-network`: Allows unrestricted network access (disables all network restrictions)- `--unrestricted-filesystem`: Allows unrestricted filesystem access (disables all filesystem restrictions)- `--add-exec`: Automatically adds the executing binary to --rox- `--ldd`: Automatically adds required libraries to --rox
### Important Notes
- You must explicitly add the directory or files to the command you want to run with `--rox` flag- For system commands, you typically need to include `/usr/bin`, `/usr/lib`, and other system directories- Use `--rwx` for directories or files where you need both write access and the ability to execute files- Network restrictions require Linux kernel 6.7 or later with Landlock ABI v4- By default, no environment variables are passed to the sandboxed command. Use `--env` to explicitly pass environment variables- The `--best-effort` flag allows graceful degradation on older kernels that don't support all requested restrictions- Paths can be specified either using multiple flags or as comma-separated values (e.g., `--ro /usr,/lib,/home`)- If no paths or network rules are specified and neither unrestricted flag is set, landrun will apply maximum restrictions (denying all access)
### Environment Variables
- `LANDRUN_LOG_LEVEL`: Set logging level (error, info, debug)
### Examples
1. Run a command that allows exec access to a specific file
```bashlandrun --rox /usr/bin/ls --rox /usr/lib --ro /home ls /home```
2. Run a command with read-only access to a directory:
```bashlandrun --rox /usr/ --ro /path/to/dir ls /path/to/dir```
3. Run a command with write access to a directory:
```bashlandrun --rox /usr/bin --ro /lib --rw /path/to/dir touch /path/to/dir/newfile```
4. Run a command with write access to a file:
```bashlandrun --rox /usr/bin --ro /lib --rw /path/to/dir/newfile touch /path/to/dir/newfile```
5. Run a command with execution permissions:
```bashlandrun --rox /usr/ --ro /lib,/lib64 /usr/bin/bash```
6. Run with debug logging:
```bashlandrun --log-level debug --rox /usr/ --ro /lib,/lib64,/path/to/dir ls /path/to/dir```
7. Run with network restrictions:
```bashlandrun --rox /usr/ --ro /lib,/lib64 --bind-tcp 8080 --connect-tcp 80 /usr/bin/my-server```
This will allow the program to only bind to TCP port 8080 and connect to TCP port 80.
8. Run a DNS client with appropriate permissions:
```bashlandrun --log-level debug --ro /etc,/usr --rox /usr/ --connect-tcp 443 nc kernel.org 443```
This allows connections to port 443, requires access to /etc/resolv.conf for resolving DNS.
9. Run a web server with selective network permissions:
```bashlandrun --rox /usr/bin --ro /lib,/lib64,/var/www --rwx /var/log --bind-tcp 80,443 /usr/bin/nginx```
10. Running anything without providing parameters is... maximum security jail!
```bashlandrun ls```
11. If you keep getting permission denied without knowing what exactly going on, best to use strace with it.
```bashlandrun --rox /usr strace -f -e trace=all ls```
12. Run with specific environment variables:
```bashlandrun --rox /usr --ro /etc --env HOME --env PATH --env CUSTOM_VAR=my_value -- env```
This example passes the current HOME and PATH variables, plus a custom variable named CUSTOM_VAR.
13. Run command with explicity access to files instead of directories:```bashlandrun --rox /usr/lib/libc.so.6 --rox /usr/lib64/ld-linux-x86-64.so.2 --rox /usr/bin/true /usr/bin/true```
14. Run a command with --add-exec which automatically adds target binary to --rox
```bashlandrun --rox /usr/lib/ --add-exec /usr/bin/true```
15. Run a command with --ldd and --add-exec which automatically adds required libraries and target binary to --rox
```bashlandrun --ldd --add-exec /usr/bin/true```
Note that shared libs always need exec permission due to how they are loaded, PROT_EXEC on mmap() etc.
## Systemd Integration
landrun can be integrated with systemd to run services with enhanced security. Here's an example of running nginx with landrun:
1. Create a systemd service file (e.g., `/etc/systemd/system/nginx-landrun.service`):
```ini[Unit]Description=nginx with landrun sandboxAfter=network.target
[Service]Type=simpleExecStart=/usr/bin/landrun \ --rox /usr/bin,/usr/lib \ --ro /etc/nginx,/etc/ssl,/etc/passwd,/etc/group,/etc/nsswitch.conf \ --rwx /var/log/nginx \ --rwx /var/cache/nginx \ --bind-tcp 80,443 \ /usr/bin/nginx -g 'daemon off;'Restart=alwaysUser=nginxGroup=nginx
[Install]WantedBy=multi-user.target```
2. Enable and start the service:
```bashsudo systemctl daemon-reloadsudo systemctl enable nginx-landrunsudo systemctl start nginx-landrun```
3. Check the service status:
```bashsudo systemctl status nginx-landrun```
This configuration:- Runs nginx with minimal required permissions- Allows binding to ports 80 and 443- Provides read-only access to configuration files- Allows write access only to log and cache directories- Runs as the nginx user and group- Automatically restarts on failure
You can adjust the permissions based on your specific needs. For example, if you need to serve static files from `/var/www`, add `--ro /var/www` to the ExecStart line.
## Security
landrun uses Linux's Landlock to create a secure sandbox environment. It provides:
- File system access control- Directory access restrictions- Execution control- TCP network restrictions- Process isolation- Default restrictive mode when no rules are specified
Landlock is an access-control system that enables processes to securely restrict themselves and their future children. As a stackable Linux Security Module (LSM), it creates additional security layers on top of existing system-wide access controls, helping to mitigate security impacts from bugs or malicious behavior in applications.
### Landlock Access Control Rights
landrun leverages Landlock's fine-grained access control mechanisms, which include:
**File-specific rights:**
- Execute files (`LANDLOCK_ACCESS_FS_EXECUTE`)- Write to files (`LANDLOCK_ACCESS_FS_WRITE_FILE`)- Read files (`LANDLOCK_ACCESS_FS_READ_FILE`)- Truncate files (`LANDLOCK_ACCESS_FS_TRUNCATE`) - Available since Landlock ABI v3- IOCTL operations on devices (`LANDLOCK_ACCESS_FS_IOCTL_DEV`) - Available since Landlock ABI v5
**Directory-specific rights:**
- Read directory contents (`LANDLOCK_ACCESS_FS_READ_DIR`)- Remove directories (`LANDLOCK_ACCESS_FS_REMOVE_DIR`)- Remove files (`LANDLOCK_ACCESS_FS_REMOVE_FILE`)- Create various filesystem objects (char devices, directories, regular files, sockets, etc.)- Refer/reparent files across directories (`LANDLOCK_ACCESS_FS_REFER`) - Available since Landlock ABI v2
**Network-specific rights** (requires Linux 6.7+ with Landlock ABI v4):
- Bind to specific TCP ports (`LANDLOCK_ACCESS_NET_BIND_TCP`)- Connect to specific TCP ports (`LANDLOCK_ACCESS_NET_CONNECT_TCP`)
### Limitations
- Landlock must be supported by your kernel- Network restrictions require Linux kernel 6.7 or later with Landlock ABI v4- Some operations may require additional permissions- Files or directories opened before sandboxing are not subject to Landlock restrictions
## Kernel Compatibility Table
| Feature | Minimum Kernel Version | Landlock ABI Version || ---------------------------------- | ---------------------- | -------------------- || Basic filesystem sandboxing | 5.13 | 1 || File referring/reparenting control | 5.19 | 2 || File truncation control | 6.2 | 3 || Network TCP restrictions | 6.7 | 4 || IOCTL on special files | 6.10 | 5 |
## Troubleshooting
If you receive "permission denied" or similar errors:
1. Ensure you've added all necessary paths with `--ro` or `--rw`2. Try running with `--log-level debug` to see detailed permission information3. Check that Landlock is supported and enabled on your system: ```bash grep -E 'landlock|lsm=' /boot/config-$(uname -r) # alternatively, if there are no /boot/config-* files zgrep -iE 'landlock|lsm=' /proc/config.gz # another alternate method grep -iE 'landlock|lsm=' /lib/modules/$(uname -r)/config ``` You should see `CONFIG_SECURITY_LANDLOCK=y` and `lsm=landlock,...` in the output4. For network restrictions, verify your kernel version is 6.7+ with Landlock ABI v4: ```bash uname -r ```
## Technical Details
### Implementation
This project uses the [landlock-lsm/go-landlock](https://github.com/landlock-lsm/go-landlock) package for sandboxing, which provides both filesystem and network restrictions. The current implementation supports:
- Read/write/execute restrictions for files and directories- TCP port binding restrictions- TCP port connection restrictions- Best-effort mode for graceful degradation on older kernels
### Best-Effort Mode
When using `--best-effort` (disabled by default), landrun will gracefully degrade to using the best available Landlock version on the current kernel. This means:
- On Linux 6.7+: Full filesystem and network restrictions- On Linux 6.2-6.6: Filesystem restrictions including truncation, but no network restrictions- On Linux 5.19-6.1: Basic filesystem restrictions including file reparenting, but no truncation control or network restrictions- On Linux 5.13-5.18: Basic filesystem restrictions without file reparenting, truncation control, or network restrictions- On older Linux: No restrictions (sandbox disabled)
When no rules are specified and neither unrestricted flag is set, landrun will apply maximum restrictions available for the current kernel version.
### Tests
The project includes a comprehensive test suite that verifies:
- Basic filesystem access controls (read-only, read-write, execute)- Directory traversal and path handling- Network restrictions (TCP bind/connect)- Environment variable isolation- System command execution- Edge cases and regression tests
Run the tests with:
```bash./test.sh```
Use `--keep-binary` to preserve the test binary after completion:
```bash./test.sh --keep-binary```
Use `--use-system` to test against the system-installed landrun binary:
```bash./test.sh --use-system```
## Future Features
Based on the Linux Landlock API capabilities, we plan to add:
- 🔒 Enhanced filesystem controls with more fine-grained permissions- 🌐 Support for UDP and other network protocol restrictions (when supported by Linux kernel)- 🔄 Process scoping and resource controls- 🛡️ Additional security features as they become available in the Landlock API
## Acknowledgements
This project wouldn't exist without:
- [Landlock](https://landlock.io), the kernel security module enabling unprivileged sandboxing - maintained by [@l0kod](https://github.com/l0kod)- [go-landlock](https://github.com/landlock-lsm/go-landlock), the Go bindings powering this tool - developed by [@gnoack](https://github.com/gnoack)
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.12345678910111213141516module github.com/zouuup/landrun
go 1.18
require ( github.com/landlock-lsm/go-landlock v0.0.0-20250303204525-1544bccde3a3 github.com/urfave/cli/v2 v2.27.6)
require ( github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect golang.org/x/sys v0.26.0 // indirect kernel.org/pub/linux/libs/security/libcap/psx v1.2.70 // indirect)1234567891011121314github.com/cpuguy83/go-md2man/v2 v2.0.5 h1:ZtcqGrnekaHpVLArFSe4HK5DoKx1T0rq2DwVB0alcyc=github.com/cpuguy83/go-md2man/v2 v2.0.5/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=github.com/landlock-lsm/go-landlock v0.0.0-20250303204525-1544bccde3a3 h1:zcMi8R8vP0WrrXlFMNUBpDy/ydo3sTnCcUPowq1XmSc=github.com/landlock-lsm/go-landlock v0.0.0-20250303204525-1544bccde3a3/go.mod h1:RSub3ourNF8Hf+swvw49Catm3s7HVf4hzdFxDUnEzdA=github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=github.com/urfave/cli/v2 v2.27.6 h1:VdRdS98FNhKZ8/Az8B7MTyGQmpIr36O1EHybx/LaZ4g=github.com/urfave/cli/v2 v2.27.6/go.mod h1:3Sevf16NykTbInEnD0yKkjDAeZDS0A6bzhBH5hrMvTQ=github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4=github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=kernel.org/pub/linux/libs/security/libcap/psx v1.2.70 h1:HsB2G/rEQiYyo1bGoQqHZ/Bvd6x1rERQTNdPr1FyWjI=kernel.org/pub/linux/libs/security/libcap/psx v1.2.70/go.mod h1:+l6Ee2F59XiJ2I6WR5ObpC1utCQJZ/VLsEbQCD8RG24=123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230package elfdeps
import ( "debug/elf" "io" "os" osexec "os/exec" "path/filepath" "strings")
// ldconfigRunner runs `ldconfig -p` and returns its output. Tests may override// this variable to inject fake output. It is unexported on purpose to allow// test injection within the package.var ldconfigRunner = func() ([]byte, error) { return osexec.Command("ldconfig", "-p").Output()}
// getLdmap runs `ldconfig -p` and returns a map of soname -> path.func getLdmap() map[string]string { m := map[string]string{} out, err := ldconfigRunner() if err != nil { return m } lines := strings.Split(string(out), "\n") for _, line := range lines { if !strings.Contains(line, "=>") { continue } parts := strings.Split(line, "=>") if len(parts) < 2 { continue } path := strings.TrimSpace(parts[len(parts)-1]) left := strings.TrimSpace(parts[0]) toks := strings.Fields(left) if len(toks) == 0 { continue } soname := toks[0] if path == "" || soname == "" { continue } if _, err := os.Stat(path); err == nil { if _, exists := m[soname]; !exists { m[soname] = path } } } return m}
// parseInterp extracts the PT_INTERP interpreter path from an ELF file.func parseInterp(f *elf.File) string { for _, prog := range f.Progs { if prog.Type == elf.PT_INTERP { r := prog.Open() if r == nil { // Can't read interpreter return "" } if data, err := io.ReadAll(r); err == nil { return strings.TrimRight(string(data), "\x00") } } } return ""}
// parseDynamic extracts DT_NEEDED and RPATH/RUNPATH entries from the .dynamic section.func parseDynamic(f *elf.File) (needed []string, rpaths []string) { needed = []string{} rpaths = []string{}
if libs, err := f.DynString(elf.DT_NEEDED); err == nil { needed = append(needed, libs...) }
// DT_RPATH and DT_RUNPATH may both be present; split on ':' and append if rp, err := f.DynString(elf.DT_RPATH); err == nil { for _, v := range rp { if v == "" { continue } rpaths = append(rpaths, strings.Split(v, ":")...) } } if rp, err := f.DynString(elf.DT_RUNPATH); err == nil { for _, v := range rp { if v == "" { continue } rpaths = append(rpaths, strings.Split(v, ":")...) } } return}
// normalizeRpaths expands common tokens like $ORIGIN and makes relative// rpath entries absolute using the provided origin directory.func normalizeRpaths(rpaths []string, origin string) []string { out := []string{} for _, rp := range rpaths { if rp == "" { continue } // expand $ORIGIN (common token in RPATH/RUNPATH) rp = strings.ReplaceAll(rp, "$ORIGIN", origin) rp = strings.ReplaceAll(rp, "${ORIGIN}", origin) // make relative rpath entries absolute using origin if !filepath.IsAbs(rp) { rp = filepath.Join(origin, rp) } out = append(out, rp) } return out}
// resolveSingleSoname attempts to resolve a single soname using rpaths,// standard dirs and ldconfig fallback. It takes a pointer to ldmap so the// caller can lazily populate and reuse it.func resolveSingleSoname(soname string, rpaths []string, stdDirs []string, ldmap *map[string]string) string { // check rpaths first for _, rp := range rpaths { candidate := filepath.Join(rp, soname) if _, err := os.Stat(candidate); err == nil { return candidate } }
// then check standard dirs for _, d := range stdDirs { candidate := filepath.Join(d, soname) if _, err := os.Stat(candidate); err == nil { return candidate } }
// fallback: consult parsed ldconfig map (populate lazily) if *ldmap == nil { *ldmap = getLdmap() } if p, ok := (*ldmap)[soname]; ok { return p }
return ""}
// resolveSonames attempts to resolve sonames to absolute paths using rpaths,// standard library directories and falling back to parsing `ldconfig -p` output.func resolveSonames(needed []string, rpaths []string) []string { resolved := map[string]string{} stdDirs := []string{"/lib", "/lib64", "/usr/lib", "/usr/lib64", "/usr/local/lib"} var ldmap map[string]string
for _, soname := range needed { if _, ok := resolved[soname]; ok { continue } resolved[soname] = resolveSingleSoname(soname, rpaths, stdDirs, &ldmap) }
out := []string{} for _, r := range resolved { if r != "" { out = append(out, r) } } return out}
// GetLibraryDependencies returns a list of library paths that the given binary depends onfunc GetLibraryDependencies(binary string) ([]string, error) { queue := []string{binary} processed := map[string]struct{}{} finalMap := map[string]struct{}{}
// Add /etc/ld.so.cache if present if _, err := os.Stat("/etc/ld.so.cache"); err == nil { finalMap["/etc/ld.so.cache"] = struct{}{} }
for len(queue) > 0 { // Dequeue curr := queue[0] queue = queue[1:]
if _, ok := processed[curr]; ok { continue } processed[curr] = struct{}{}
f, err := elf.Open(curr) if err != nil { // This can happen with non-ELF files in the dependency chain // (e.g. ld.so.cache). Ignore them. continue } defer f.Close()
// The first binary in the queue is the main one; grab its interpreter if curr == binary { if interpPath := parseInterp(f); interpPath != "" { finalMap[interpPath] = struct{}{} queue = append(queue, interpPath) } }
needed, rpaths := parseDynamic(f) origin := filepath.Dir(curr) rpaths = normalizeRpaths(rpaths, origin) libPaths := resolveSonames(needed, rpaths)
for _, p := range libPaths { if _, ok := finalMap[p]; !ok { finalMap[p] = struct{}{} queue = append(queue, p) } } }
out := make([]string, 0, len(finalMap)) for p := range finalMap { out = append(out, p) }
return out, nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222package elfdeps
import ( "debug/elf" "os" "os/exec" "path/filepath" "testing")
// Test helpers against a known binary in the system: find `true` via LookPathfunc TestParseAndResolveTrue(t *testing.T) { bin, err := exec.LookPath("true") if err != nil { t.Fatalf("failed to find 'true' binary: %v", err) }
f, err := elf.Open(bin) if err != nil { t.Fatalf("failed to open %s: %v", bin, err) } defer f.Close()
interp := parseInterp(f) if interp == "" { t.Fatalf("expected interpreter for %s, got empty", bin) }
needed, rpaths := parseDynamic(f) if needed == nil { needed = []string{} }
origin := filepath.Dir(bin) rpaths = normalizeRpaths(rpaths, origin) paths := resolveSonames(needed, rpaths) if paths == nil { paths = []string{} }
// Ensure interpreter path exists on filesystem if _, err := os.Stat(interp); err != nil { t.Fatalf("interp path %s does not exist: %v", interp, err) }
// If there are resolved library paths, they must exist for _, p := range paths { if _, err := os.Stat(p); err != nil { t.Fatalf("resolved library path %s does not exist: %v", p, err) } }}
func TestRecursiveDependencies(t *testing.T) { if _, err := exec.LookPath("gcc"); err != nil { t.Skip("gcc not found, skipping test") } // Create a temporary directory for compiled artifacts tempDir := t.TempDir()
// Compile liba.so libaSrc := "testdata/liba.c" libaSo := filepath.Join(tempDir, "liba.so") cmd := exec.Command("gcc", "-fPIC", "-shared", "-o", libaSo, libaSrc) if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("failed to compile liba.so: %v\n%s", err, string(out)) }
// Compile libb.so libbSrc := "testdata/libb.c" libbSo := filepath.Join(tempDir, "libb.so") cmd = exec.Command("gcc", "-fPIC", "-shared", "-o", libbSo, libbSrc, "-L"+tempDir, "-la", "-Wl,-rpath,$ORIGIN") if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("failed to compile libb.so: %v\n%s", err, string(out)) }
// Compile test_binary mainSrc := "testdata/main.c" testBin := filepath.Join(tempDir, "test_binary") cmd = exec.Command("gcc", "-o", testBin, mainSrc, "-L"+tempDir, "-lb", "-Wl,-rpath,$ORIGIN") if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("failed to compile test_binary: %v\n%s", err, string(out)) }
// Run the actual test logic deps, err := GetLibraryDependencies(testBin) if err != nil { t.Fatalf("GetLibraryDependencies failed: %v", err) }
foundA := false foundB := false for _, dep := range deps { if dep == libaSo { foundA = true } if dep == libbSo { foundB = true } }
if !foundA { t.Errorf("expected to find %s in dependency list, but didn't. Found: %v", libaSo, deps) } if !foundB { t.Errorf("expected to find %s in dependency list, but didn't. Found: %v", libbSo, deps) }}
func TestGetLibraryDependencies(t *testing.T) { bin, err := exec.LookPath("true") if err != nil { t.Fatalf("failed to find 'true' binary: %v", err) } paths, err := GetLibraryDependencies(bin) if err != nil { t.Fatalf("GetLibraryDependencies failed: %v", err) } if len(paths) == 0 { t.Fatalf("expected non-empty dependency list for %s", bin) } // ensure returned paths are absolute and exist for _, p := range paths { if !filepath.IsAbs(p) { t.Fatalf("expected absolute path, got %s", p) } if _, err := os.Stat(p); err != nil { t.Fatalf("path %s does not exist: %v", p, err) } }}
func TestGetLdmapWithFakeOutput(t *testing.T) { // fake ldconfig output with a single mapping original := ldconfigRunner defer func() { ldconfigRunner = original }()
// create a fake file on disk to satisfy os.Stat checks in getLdmap tmpDir := t.TempDir() tmp := filepath.Join(tmpDir, "libfake.so") f, err := os.Create(tmp) if err != nil { t.Fatalf("failed to create tmp file: %v", err) } f.Close()
// Because getLdmap checks the path exists, return tmp in the fake output ldconfigRunner = func() ([]byte, error) { return []byte("libfake.so (libc6,x86-64) => " + tmp + "\n"), nil }
m := getLdmap() if got, ok := m["libfake.so"]; !ok { t.Fatalf("expected libfake.so in map") } else if got != tmp { t.Fatalf("expected path %s, got %s", tmp, got) }}
func TestResolveSonamesUsesLdmapFallback(t *testing.T) { original := ldconfigRunner defer func() { ldconfigRunner = original }()
tmpDir := t.TempDir() tmp := filepath.Join(tmpDir, "libfake2.so") f, err := os.Create(tmp) if err != nil { t.Fatalf("failed to create tmp file: %v", err) } f.Close()
ldconfigRunner = func() ([]byte, error) { return []byte("libfake2.so (libc6,x86-64) => " + tmp + "\n"), nil }
// needed contains a soname that won't be found in rpaths or std dirs rpaths := normalizeRpaths([]string{}, tmpDir) out := resolveSonames([]string{"libfake2.so"}, rpaths) if len(out) != 1 { t.Fatalf("expected 1 resolved path, got %d", len(out)) } if out[0] != tmp { t.Fatalf("expected %s, got %s", tmp, out[0]) }}
func TestResolveSonamesOriginExpansion(t *testing.T) { // Create a temp dir and a lib subdir to simulate $ORIGIN/lib tmpDir := t.TempDir() libDir := filepath.Join(tmpDir, "lib") if err := os.Mkdir(libDir, 0755); err != nil { t.Fatalf("failed create lib dir: %v", err) }
libName := "liborigin.so" libPath := filepath.Join(libDir, libName) f, err := os.Create(libPath) if err != nil { t.Fatalf("failed to create lib file: %v", err) } f.Close()
// rpath using $ORIGIN should resolve to tmpDir/lib rpaths1 := normalizeRpaths([]string{"$ORIGIN/lib"}, tmpDir) out := resolveSonames([]string{libName}, rpaths1) if len(out) != 1 { t.Fatalf("expected 1 resolved path for $ORIGIN, got %d", len(out)) } if out[0] != libPath { t.Fatalf("expected %s, got %s", libPath, out[0]) }
// relative rpath should also resolve against origin rpaths2 := normalizeRpaths([]string{"lib"}, tmpDir) out2 := resolveSonames([]string{libName}, rpaths2) if len(out2) != 1 { t.Fatalf("expected 1 resolved path for relative rpath, got %d", len(out2)) } if out2[0] != libPath { t.Fatalf("expected %s, got %s", libPath, out2[0]) }}1int a() { return 1; }12int a();int b() { return a(); }12int b();int main() { b(); return 0; }123456789101112131415161718192021package exec
import ( "os/exec" "syscall"
"github.com/zouuup/landrun/internal/log")
func Run(args []string, env []string) error { binary, err := exec.LookPath(args[0]) if err != nil { return err }
log.Info("Executing: %v", args)
// Only pass the explicitly specified environment variables // If env is empty, no environment variables will be passed return syscall.Exec(binary, args, env)}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364package log
import ( "log" "os" "strings")
type Level int
const ( LevelError Level = iota LevelInfo LevelDebug)
var ( debug = log.New(os.Stderr, "[landrun:debug] ", log.LstdFlags) info = log.New(os.Stderr, "[landrun] ", log.LstdFlags) error = log.New(os.Stderr, "[landrun:error] ", log.LstdFlags)
currentLevel = LevelInfo // default level)
// SetLevel sets the logging levelfunc SetLevel(level string) { switch strings.ToLower(level) { case "error": currentLevel = LevelError case "info": currentLevel = LevelInfo case "debug": currentLevel = LevelDebug default: currentLevel = LevelError }}
// Debug logs a debug messagefunc Debug(format string, v ...interface{}) { if currentLevel >= LevelDebug { debug.Printf(format, v...) }}
// Info logs an info messagefunc Info(format string, v ...interface{}) { if currentLevel >= LevelInfo { info.Printf(format, v...) }}
// Error logs an error messagefunc Error(format string, v ...interface{}) { if currentLevel >= LevelError { error.Printf(format, v...) }}
// Fatal logs an error message and exitsfunc Fatal(format string, v ...interface{}) { error.Printf(format, v...) os.Exit(1)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192package sandbox
import ( "fmt" "os"
"github.com/landlock-lsm/go-landlock/landlock" "github.com/landlock-lsm/go-landlock/landlock/syscall" "github.com/zouuup/landrun/internal/log")
type Config struct { ReadOnlyPaths []string ReadWritePaths []string ReadOnlyExecutablePaths []string ReadWriteExecutablePaths []string BindTCPPorts []int ConnectTCPPorts []int BestEffort bool UnrestrictedFilesystem bool UnrestrictedNetwork bool}
// getReadWriteExecutableRights returns a full set of permissions including executionfunc getReadWriteExecutableRights(dir bool) landlock.AccessFSSet { accessRights := landlock.AccessFSSet(0) accessRights |= landlock.AccessFSSet(syscall.AccessFSExecute) accessRights |= landlock.AccessFSSet(syscall.AccessFSReadFile) accessRights |= landlock.AccessFSSet(syscall.AccessFSWriteFile) accessRights |= landlock.AccessFSSet(syscall.AccessFSTruncate) accessRights |= landlock.AccessFSSet(syscall.AccessFSIoctlDev)
if dir { accessRights |= landlock.AccessFSSet(syscall.AccessFSReadDir) accessRights |= landlock.AccessFSSet(syscall.AccessFSRemoveDir) accessRights |= landlock.AccessFSSet(syscall.AccessFSRemoveFile) accessRights |= landlock.AccessFSSet(syscall.AccessFSMakeChar) accessRights |= landlock.AccessFSSet(syscall.AccessFSMakeDir) accessRights |= landlock.AccessFSSet(syscall.AccessFSMakeReg) accessRights |= landlock.AccessFSSet(syscall.AccessFSMakeSock) accessRights |= landlock.AccessFSSet(syscall.AccessFSMakeFifo) accessRights |= landlock.AccessFSSet(syscall.AccessFSMakeBlock) accessRights |= landlock.AccessFSSet(syscall.AccessFSMakeSym) accessRights |= landlock.AccessFSSet(syscall.AccessFSRefer) }
return accessRights}
func getReadOnlyExecutableRights(dir bool) landlock.AccessFSSet { accessRights := landlock.AccessFSSet(0) accessRights |= landlock.AccessFSSet(syscall.AccessFSExecute) accessRights |= landlock.AccessFSSet(syscall.AccessFSReadFile) if dir { accessRights |= landlock.AccessFSSet(syscall.AccessFSReadDir) } return accessRights}
// getReadOnlyRights returns permissions for read-only accessfunc getReadOnlyRights(dir bool) landlock.AccessFSSet { accessRights := landlock.AccessFSSet(0) accessRights |= landlock.AccessFSSet(syscall.AccessFSReadFile) if dir { accessRights |= landlock.AccessFSSet(syscall.AccessFSReadDir) } return accessRights}
// getReadWriteRights returns permissions for read-write accessfunc getReadWriteRights(dir bool) landlock.AccessFSSet { accessRights := landlock.AccessFSSet(0) accessRights |= landlock.AccessFSSet(syscall.AccessFSReadFile) accessRights |= landlock.AccessFSSet(syscall.AccessFSWriteFile) accessRights |= landlock.AccessFSSet(syscall.AccessFSTruncate) accessRights |= landlock.AccessFSSet(syscall.AccessFSIoctlDev) if dir { accessRights |= landlock.AccessFSSet(syscall.AccessFSReadDir) accessRights |= landlock.AccessFSSet(syscall.AccessFSRemoveDir) accessRights |= landlock.AccessFSSet(syscall.AccessFSRemoveFile) accessRights |= landlock.AccessFSSet(syscall.AccessFSMakeChar) accessRights |= landlock.AccessFSSet(syscall.AccessFSMakeDir) accessRights |= landlock.AccessFSSet(syscall.AccessFSMakeReg) accessRights |= landlock.AccessFSSet(syscall.AccessFSMakeSock) accessRights |= landlock.AccessFSSet(syscall.AccessFSMakeFifo) accessRights |= landlock.AccessFSSet(syscall.AccessFSMakeBlock) accessRights |= landlock.AccessFSSet(syscall.AccessFSMakeSym) accessRights |= landlock.AccessFSSet(syscall.AccessFSRefer) }
return accessRights}
// isDirectory checks if the given path is a directoryfunc isDirectory(path string) bool { fileInfo, err := os.Stat(path) if err != nil { return false } return fileInfo.IsDir()}
func Apply(cfg Config) error { log.Info("Sandbox config: %+v", cfg)
// Get the most advanced Landlock version available llCfg := landlock.V5 if cfg.BestEffort { llCfg = llCfg.BestEffort() }
// Collect our rules var file_rules []landlock.Rule var net_rules []landlock.Rule
// Process executable paths for _, path := range cfg.ReadOnlyExecutablePaths { log.Debug("Adding read-only executable path: %s", path) file_rules = append(file_rules, landlock.PathAccess(getReadOnlyExecutableRights(isDirectory(path)), path)) }
for _, path := range cfg.ReadWriteExecutablePaths { log.Debug("Adding read-write executable path: %s", path) file_rules = append(file_rules, landlock.PathAccess(getReadWriteExecutableRights(isDirectory(path)), path)) }
// Process read-only paths for _, path := range cfg.ReadOnlyPaths { log.Debug("Adding read-only path: %s", path) file_rules = append(file_rules, landlock.PathAccess(getReadOnlyRights(isDirectory(path)), path)) }
// Process read-write paths for _, path := range cfg.ReadWritePaths { log.Debug("Adding read-write path: %s", path) file_rules = append(file_rules, landlock.PathAccess(getReadWriteRights(isDirectory(path)), path)) }
// Add rules for TCP port binding for _, port := range cfg.BindTCPPorts { log.Debug("Adding TCP bind port: %d", port) net_rules = append(net_rules, landlock.BindTCP(uint16(port))) }
// Add rules for TCP connections for _, port := range cfg.ConnectTCPPorts { log.Debug("Adding TCP connect port: %d", port) net_rules = append(net_rules, landlock.ConnectTCP(uint16(port))) }
if cfg.UnrestrictedFilesystem && cfg.UnrestrictedNetwork { log.Info("Unrestricted filesystem and network access enabled; no rules applied.") return nil }
if cfg.UnrestrictedFilesystem { log.Info("Unrestricted filesystem access enabled.") }
if cfg.UnrestrictedNetwork { log.Info("Unrestricted network access enabled") }
// If we have no rules, just return if len(file_rules) == 0 && len(net_rules) == 0 && !cfg.UnrestrictedFilesystem && !cfg.UnrestrictedNetwork { log.Error("No rules provided, applying default restrictive rules, this will restrict anything landlock can do.") err := llCfg.Restrict() if err != nil { return fmt.Errorf("failed to apply default Landlock restrictions: %w", err) } log.Info("Default restrictive Landlock rules applied successfully") return nil }
// Apply all rules at once log.Debug("Applying Landlock restrictions") if !cfg.UnrestrictedFilesystem { err := llCfg.RestrictPaths(file_rules...) if err != nil { return fmt.Errorf("failed to apply Landlock filesystem restrictions: %w", err) } } if !cfg.UnrestrictedNetwork { err := llCfg.RestrictNet(net_rules...) if err != nil { return fmt.Errorf("failed to apply Landlock network restrictions: %w", err) } }
log.Info("Landlock restrictions applied successfully") return nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314#!/bin/bash
# Check if we should keep the binaryKEEP_BINARY=falseUSE_SYSTEM_BINARY=falseNO_BUILD=false# Whether we should try to do network calls during testing.INTERNET_ACCESS=true
while [ "$#" -gt 0 ]; do case "$1" in "--keep-binary") KEEP_BINARY=true shift ;; "--use-system") USE_SYSTEM_BINARY=true shift ;; "--no-build") NO_BUILD=true shift ;; "--offline") INTERNET_ACCESS=false shift ;; *) echo "Unknown parameter: $1" exit 1 ;; esacdone
# Don't exit on error, we'll handle errors in the run_test functionset +e
# Colors for outputRED='\033[0;31m'GREEN='\033[0;32m'YELLOW='\033[1;33m'NC='\033[0m' # No Color
# Function to print colored outputprint_status() { echo -e "${YELLOW}[TEST]${NC} $1"}
print_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"}
print_error() { echo -e "${RED}[ERROR]${NC} $1"}
# Build the binary if not using system binaryif [ "$USE_SYSTEM_BINARY" = false ]; then if [ "$NO_BUILD" = false ]; then print_status "Building landrun binary..." go build -o landrun cmd/landrun/main.go if [ $? -ne 0 ]; then print_error "Failed to build landrun binary" exit 1 fi print_success "Binary built successfully" else print_success "Using already built landrun binary" fifi
# Create test directoriesTEST_DIR="test_env"RO_DIR="$TEST_DIR/ro"RO_DIR_NESTED_RO="$RO_DIR/ro_nested_ro_1"RO_DIR_NESTED_RW="$RO_DIR/ro_nested_rw_1"RO_DIR_NESTED_EXEC="$RO_DIR/ro_nested_exec"
RW_DIR="$TEST_DIR/rw"RW_DIR_NESTED_RO="$RW_DIR/rw_nested_ro_1"RW_DIR_NESTED_RW="$RW_DIR/rw_nested_rw_1"RW_DIR_NESTED_EXEC="$RW_DIR/rw_nested_exec"
EXEC_DIR="$TEST_DIR/exec"NESTED_DIR="$TEST_DIR/nested/path/deep"
print_status "Setting up test environment..."rm -rf "$TEST_DIR"mkdir -p "$RO_DIR" "$RW_DIR" "$EXEC_DIR" "$NESTED_DIR" "$RO_DIR_NESTED_RO" "$RO_DIR_NESTED_RW" "$RO_DIR_NESTED_EXEC" "$RW_DIR_NESTED_RO" "$RW_DIR_NESTED_RW" "$RW_DIR_NESTED_EXEC"
# Create test filesecho "readonly content" > "$RO_DIR/test.txt"echo "readwrite content" > "$RW_DIR/test.txt"echo "nested content" > "$NESTED_DIR/test.txt"echo "#!/bin/bash" > "$EXEC_DIR/test.sh"echo "echo 'executable content'" >> "$EXEC_DIR/test.sh"chmod +x "$EXEC_DIR/test.sh"cp $EXEC_DIR/test.sh $EXEC_DIR/test2.sh
cp "$RO_DIR/test.txt" "$RO_DIR_NESTED_RO/test.txt"cp "$RO_DIR/test.txt" "$RW_DIR_NESTED_RO/test.txt"
cp "$RW_DIR/test.txt" "$RO_DIR_NESTED_RW/test.txt"cp "$RW_DIR/test.txt" "$RW_DIR_NESTED_RW/test.txt"
cp "$EXEC_DIR/test.sh" "$RO_DIR_NESTED_EXEC/test.sh"cp "$EXEC_DIR/test.sh" "$RW_DIR_NESTED_EXEC/test.sh"cp "$EXEC_DIR/test.sh" "$RO_DIR_NESTED_RO/test.sh"cp "$EXEC_DIR/test.sh" "$RW_DIR_NESTED_RO/test.sh"cp "$EXEC_DIR/test.sh" "$RO_DIR_NESTED_RW/test.sh"cp "$EXEC_DIR/test.sh" "$RW_DIR_NESTED_RW/test.sh"
# Create a script in RW dir to test execution in RW dirsecho "#!/bin/bash" > "$RW_DIR/rw_script.sh"echo "echo 'this script is in a read-write directory'" >> "$RW_DIR/rw_script.sh"chmod +x "$RW_DIR/rw_script.sh"
# Function to run a test caserun_test() { local name="$1" local cmd="$2" local expected_exit="$3" # Replace ./landrun with landrun if using system binary if [ "$USE_SYSTEM_BINARY" = true ]; then cmd="${cmd//.\/landrun/landrun}" fi print_status "Running test: $name" eval "$cmd" local exit_code=$? if [ $exit_code -eq $expected_exit ]; then print_success "Test passed: $name" return 0 else print_error "Test failed: $name (expected exit $expected_exit, got $exit_code)" exit 1 fi}
# Test casesprint_status "Starting test cases..."
# Basic access testsrun_test "Read-only access to file" \ "./landrun --log-level debug --rox /usr --ro /lib --ro /lib64 --ro $RO_DIR -- cat $RO_DIR/test.txt" \ 0
run_test "Read-only access to nested file" \ "./landrun --log-level debug --rox /usr --ro /lib --ro /lib64 --ro $RO_DIR -- cat $RO_DIR_NESTED_RO/test.txt" \ 0
run_test "Write access to nested directory writable nested in read-only directory" \ "./landrun --log-level debug --rox /usr --ro /lib --ro /lib64 --ro $RO_DIR --rw $RO_DIR_NESTED_RW -- touch $RO_DIR_NESTED_RW/created_file" \ 0
run_test "Write access to nested file writable nested in read-only directory" \ "./landrun --log-level debug --rox /usr --ro /lib --ro /lib64 --ro $RO_DIR --rw $RO_DIR_NESTED_RW/created_file -- touch $RO_DIR_NESTED_RW/created_file" \ 0
run_test "Read-write access to file" \ "./landrun --log-level debug --rox /usr --ro /lib --ro /lib64 --ro $RO_DIR --rw $RW_DIR touch $RW_DIR/new.txt" \ 0
run_test "No write access to read-only directory" \ "./landrun --log-level debug --rox /usr --ro /lib --ro /lib64 --ro $RO_DIR --rw $RW_DIR touch $RO_DIR/new.txt" \ 1
# Executable permission testsrun_test "Execute access with rox flag" \ "./landrun --log-level debug --rox /usr --ro /lib --ro /lib64 --rox $EXEC_DIR -- $EXEC_DIR/test.sh" \ 0
run_test "Execute access with rox flag on file" \ "./landrun --log-level debug --rox /usr --ro /lib --ro /lib64 --rox $EXEC_DIR/test.sh -- $EXEC_DIR/test.sh" \ 0
run_test "Execute access with rox flag on a file that is executable in same directory that one is allowed" \ "./landrun --log-level debug --rox /usr --ro /lib --ro /lib64 --rox $EXEC_DIR/test.sh -- $EXEC_DIR/test2.sh" \ 1
run_test "Execute a file with --add-exec flag" \ "./landrun --log-level debug --add-exec --rox /usr --ro /lib --ro /lib64 --rox $EXEC_DIR/test.sh -- $EXEC_DIR/test2.sh" \ 0
run_test "Execute a file with --add-exec and --ldd flag" \ "./landrun --log-level debug --add-exec --ldd -- $(which true)" \ 0
run_test "No execute access with just ro flag" \ "./landrun --log-level debug --rox /usr --ro /lib --ro /lib64 --ro $EXEC_DIR -- $EXEC_DIR/test.sh" \ 1
run_test "Execute access in read-write directory" \ "./landrun --log-level debug --rox /usr --ro /lib --ro /lib64 --rwx $RW_DIR -- $RW_DIR/rw_script.sh" \ 0
run_test "No execute access in read-write directory without rwx" \ "./landrun --log-level debug --rox /usr --ro /lib --ro /lib64 --rw $RW_DIR -- $RW_DIR/rw_script.sh" \ 1
# Directory traversal testsrun_test "Directory traversal with root access" \ "./landrun --log-level debug --rox / -- ls /usr" \ 0
run_test "Deep directory traversal" \ "./landrun --log-level debug --rox / -- ls $NESTED_DIR" \ 0
# Multiple paths and complex specificationsrun_test "Multiple read paths" \ "./landrun --log-level debug --rox /usr --ro /lib --ro /lib64 --ro $RO_DIR --ro $NESTED_DIR -- cat $NESTED_DIR/test.txt" \ 0
run_test "Comma-separated paths" \ "./landrun --log-level debug --rox /usr --ro /lib,/lib64,$RO_DIR -- cat $RO_DIR/test.txt" \ 0
# System command testsrun_test "Simple system command" \ "./landrun --log-level debug --rox /usr --ro /etc -- whoami" \ 0
run_test "System command with arguments" \ "./landrun --log-level debug --rox / -- ls -la /usr/bin" \ 0
# Edge casesrun_test "Non-existent read-only path" \ "./landrun --log-level debug --ro /usr --ro /lib --ro /lib64 --ro /nonexistent/path -- ls" \ 1
run_test "No configuration" \ "./landrun --log-level debug -- ls /" \ 1
# Process creation and redirection testsrun_test "Process creation with pipe" \ "./landrun --log-level debug --rox / --env PATH -- bash -c 'ls /usr | grep bin'" \ 0
run_test "File redirection" \ "./landrun --log-level debug --rox / --rw $RW_DIR --env PATH -- bash -c 'ls /usr > $RW_DIR/output.txt && cat $RW_DIR/output.txt'" \ 0
# Network restrictions tests (if kernel supports it)$INTERNET_ACCESS && run_test "TCP connection without permission" \ "./landrun --log-level debug --rox /usr --ro / -- curl -s --connect-timeout 2 https://example.com" \ 7
$INTERNET_ACCESS && run_test "TCP connection with permission" \ "./landrun --log-level debug --rox /usr --ro / --connect-tcp 443 -- curl -s --connect-timeout 2 https://example.com" \ 0
# Environment isolation testsexport TEST_ENV_VAR="test_value_123"run_test "Environment isolation" \ "./landrun --log-level debug --rox /usr --ro / -- bash -c 'echo \$TEST_ENV_VAR'" \ 0
run_test "Environment isolation (no variables should be passed)" \ "./landrun --log-level debug --rox /usr --ro / -- bash -c '[[ -z \$TEST_ENV_VAR ]] && echo \"No env var\" || echo \$TEST_ENV_VAR'" \ 0
run_test "Passing specific environment variable" \ "./landrun --log-level debug --rox /usr --ro / --env TEST_ENV_VAR --env PATH -- bash -c 'echo \$TEST_ENV_VAR | grep \"test_value_123\"'" \ 0
run_test "Passing custom environment variable" \ "./landrun --log-level debug --rox /usr --ro / --env CUSTOM_VAR=custom_value --env PATH -- bash -c 'echo \$CUSTOM_VAR | grep \"custom_value\"'" \ 0
# Combining different permission typesrun_test "Mixed permissions" \ "./landrun --log-level debug --rox /usr --ro /lib --ro /lib64 --rox $EXEC_DIR --rwx $RW_DIR --env PATH -- bash -c '$EXEC_DIR/test.sh > $RW_DIR/output.txt && cat $RW_DIR/output.txt'" \ 0
# Specific regression tests for bugs we fixedrun_test "Root path traversal regression test" \ "./landrun --log-level debug --rox /usr -- $(which ls) /usr" \ 0
run_test "Execute from read-only paths regression test" \ "./landrun --log-level debug --rox /usr --ro /usr/bin -- $(which id)" \ 0
run_test "Unrestricted filesystem access" \ "./landrun --log-level debug --unrestricted-filesystem ls /usr" \ 0
$INTERNET_ACCESS && run_test "Unrestricted network access" \ "./landrun --log-level debug --unrestricted-network --rox /usr --ro /etc -- curl -s --connect-timeout 2 https://example.com" \ 0
run_test "Restricted filesystem access" \ "./landrun --log-level debug ls /usr" \ 1
$INTERNET_ACCESS && run_test "Restricted network access" \ "./landrun --log-level debug --rox /usr --ro /etc -- curl -s --connect-timeout 2 https://example.com" \ 7
# Cleanupprint_status "Cleaning up..."rm -rf "$TEST_DIR"if [ "$KEEP_BINARY" = false ] && [ "$USE_SYSTEM_BINARY" = false ]; then rm -f landrunfi
print_success "All tests completed!" app.py+331-863
landrun-main/.github/workflows/build.ymlAdded+31
landrun-main/.github/workflows/go-compatibility.ymlAdded+24
landrun-main/.gitignoreAdded+31
landrun-main/LICENSEAdded+21
landrun-main/README.mdAdded+400
landrun-main/demo.gifAdded

landrun-main/go.modAdded+16
landrun-main/go.sumAdded+14
landrun-main/internal/elfdeps/elfdeps.goAdded+230
landrun-main/internal/elfdeps/elfdeps_test.goAdded+222
landrun-main/internal/elfdeps/testdata/liba.cAdded+1
landrun-main/internal/elfdeps/testdata/libb.cAdded+2
landrun-main/internal/elfdeps/testdata/main.cAdded+2
landrun-main/internal/exec/runner.goAdded+21
landrun-main/internal/log/log.goAdded+64
landrun-main/internal/sandbox/sandbox.goAdded+192
landrun-main/test.shAdded+314