Letting AI Do the Work: A Security Design Guide for Local Execution Layers
Allowing AI models to execute commands directly on a local machine introduces significant security risks. This guide explores how to design a secure local execution layer by defining risk boundaries and implementing four core modules: instruction parsing, permission isolation, result processing, and audit logging. It includes a practical Python example of a whitelist-based executor to help developers safely integrate AI into local operations.
1. Define Risk Boundaries First
Allowing a model to execute commands directly on your local machine is equivalent to handing over partial control of your computer to a fallible program. Model-generated instructions, as well as the web pages and file contents it reads, should all be treated as untrusted data. Therefore, before building the execution layer, you must define three things: which directories it can access, which tools it can invoke, and which operations require manual confirmation.
Design for the worst-case scenario: every model output could be flawed, and every piece of external text read could contain prompts designed to trick the model into performing malicious actions. Start with strict permissions and gradually relax them based on actual needs.
2. Four Core Modules
A minimal viable execution layer typically consists of four modules, each responsible for a specific boundary.
2.1 Instruction Parsing and Structural Validation
The model outputs its intent in a fixed JSON format. The program first checks the structure: whether all fields are present, if the types are correct, and if there are any extraneous fields. Structural validation can be achieved using JSON Schema. For the runtime environment, Python 3.9 or above is recommended. Install the dependency by running pip install jsonschema. After installation, verify it by running python -c "import jsonschema; print(jsonschema.__version__)" to ensure the version number is printed correctly.
Once structural validation passes, semantic validation is required: checking whether the tool name is in the whitelist and whether the parameters fall within the allowed range. Only when both layers pass can the instruction enter the execution phase. If either layer fails, the instruction is rejected immediately, and the raw content is never passed to the executor.
2.2 Permission Isolation and Command Whitelisting
The core principle here is that the model must not directly submit a raw shell command string. It can only select tools from a pre-defined list and provide restricted parameters. Each tool corresponds to a fixed command template, and parameters are passed as a list, bypassing shell interpretation.
Permission isolation can be divided into three layers:
- Execution Identity: Use a dedicated, low-privilege system account. Do not use an administrator account, and do not grant sudo privileges.
- File Scope: Tools can only access a single working directory. After path resolution, the path must still be within this directory to prevent path traversal attacks like
../. - Execution Environment: When conditions permit, place the executor in a container or sandbox, restrict network access, and mount directories that do not need modification as read-only.
Do not use regular expressions to filter dangerous characters as a replacement for a whitelist. Filtering will always miss some variations, whereas a whitelist only permits explicitly listed operations.
2.3 Result Return
Command output can be very long and may contain passwords, tokens, or personal information. The content returned to the model needs to be processed:
- Standard output and standard error should be truncated with limits, such as 4000 characters for stdout and 1000 characters for stderr.
- Return the exit code so the model can determine whether the execution was successful.
- Clearly indicate timeouts using a unified error code, rather than returning the exception stack as-is.
- Desensitize the output before returning it, replacing common key formats, ID numbers, email addresses, and other sensitive information.
Keep the return structure fixed, containing five fields: ok, exit_code, stdout, stderr, and error. A fixed structure makes it easier for the model to parse and for the program to perform subsequent checks.
2.4 Audit Logging
Every execution must leave a record for post-event troubleshooting and accountability. Logs should include the timestamp, tool name, parameter summary or hash, exit code, duration, and call source.
Logs should not record the complete raw instruction, full output, or original exception text. If exception messages contain user input, sensitive content could be written to the logs. The correct approach is to log only the error code and field names, such as error=schema_invalid field=args.path.
Log files should be set to read/write for the owner only and rotated regularly. Logs themselves are sensitive data, and access must be controlled.
3. Whitelist Executor Example
The following example demonstrates the basic implementation of Module 2 and Module 3. It includes only two read-only tools, suitable as a starting point, and should not be directly extended to arbitrary command execution.
import subprocessfrom pathlib import PathWORKSPACE = Path("/srv/agent/workspace").resolve()# Whitelist: each tool corresponds to a fixed command templateALLOWED_TOOLS = {"list_dir": ["ls", "-l"],"git_status": ["git", "status", "--short"],}def _fail(error: str) -> dict:return {"ok": False, "exit_code": None, "stdout": "", "stderr": "", "error": error}def resolve_safe_path(raw: str) -> Path | None:target = (WORKSPACE / raw).resolve()if not target.is_relative_to(WORKSPACE):return Nonereturn targetdef run_tool(tool: str, path: str, timeout_s: int = 5) -> dict:template = ALLOWED_TOOLS.get(tool)if template is None:return _fail("tool_not_allowed")target = resolve_safe_path(path)if target is None:return _fail("path_outside_workspace")try:proc = subprocess.run(template + [str(target)],capture_output=True,text=True
