Back to skill

Security audit

Cn Math Expression

Security checks for vulnerabilities and agentic risk

Overview

This skill is presented as a safe math calculator, but its script can evaluate non-math Python expressions despite claiming there is no import, file, or command access.

Review before installing. Use this only for fully trusted expressions, not user-submitted or copied expressions, unless the evaluator is replaced with a strict AST-based math parser and resource limits are added.

Vulnerability Patterns
  • Insecure Skill Coding PracticesFinds exploitable flaws such as hardcoded secrets or command injection
  • Skill Instruction HijackingAlters the agent's session goals or safety constraints when the skill loads
  • Agent Memory PoisoningWrites attacker-controlled rules into memory that affect later sessions
  • Remote Payload Retrieval and ExecutionFetches external code whose behavior can change after review
  • Embedded Malicious CodeShips malicious scripts inside the skill and executes them locally
Findings (2)

T09 · Insecure Skill Coding Practices

Error
Location
scripts/math_eval.py:11
Finding
Restricted eval Sandbox Escape Enables Arbitrary Code Execution## Vulnerability Details **File Location**: `scripts/math_eval.py`, lines 11-12 **Vulnerability Type**: Unsafe evaluation of attacker-controlled Python expressions **Risk Level**: High **Vulnerable Code**: ```python def safe_eval(expr): return eval(expr, {"__builtins__": {}}, SAFE_NAMES) ``` ### Technical Analysis The evaluator passes an attacker-controlled expression directly to Python's `eval()`. Removing `__builtins__` from the supplied global namespace is not an effective security boundary. Python literals created inside the expression remain full Python objects. An expression can traverse attributes such as `__class__`, `__base__`, and `__subclasses__` to inspect the runtime object graph. From suitable classes, an attacker may access function globals, recover built-in functions such as `__import__`, import operating-system modules, and invoke command-execution or file-access functions. The evaluator does not parse the expression into an abstract syntax tree or reject dangerous constructs such as attribute access, subscripting, comprehensions, lambdas, or arbitrary object traversal. Consequently, the documented mathematical namespace allowlist does not constrain the expression to mathematical operations. ### Attack Path 1. An attacker supplies a crafted Python expression through the `--expr` command-line argument. 2. The argument is passed unchanged to `safe_eval()`. 3. `eval()` interprets the expression as Python code rather than as a restricted mathematical grammar. 4. The expression traverses Python's object hierarchy through attributes such as `__class__` and `__subclasses__`. 5. It locates an accessible function or class whose globals expose built-in functionality. 6. It recovers import functionality, loads a system-access module, and invokes command execution or file operations. 7. The resulting operation runs with the operating-system permissions and environment of the evaluator process. ### Impac ...[truncated 748 chars]
Remediation
## Remediation Suggestions Remove `eval()` entirely and implement a strict expression interpreter using `ast.parse(expr, mode="eval")`. The interpreter should: 1. Allow only numeric constants. 2. Allow only explicitly approved arithmetic operators, such as addition, subtraction, multiplication, division, modulo, and bounded exponentiation. 3. Permit function calls only when the function target is a simple approved name present in `SAFE_NAMES`. 4. Permit only explicitly approved constants such as `pi` and `e`. 5. Reject attribute access, subscripting, lambdas, comprehensions, container literals, assignment expressions, and every unrecognized AST node. 6. Evaluate approved nodes directly rather than compiling the validated tree and passing it back to `eval()`. 7. Add regression tests containing known Python sandbox-escape techniques to ensure they are rejected. Operating-system sandboxing, a low-privilege service account, filesystem restrictions, and network isolation should be used as defense in depth, not as substitutes for removing unsafe evaluation.

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/math_eval.py:4
Finding
Unbounded Mathematical Evaluation Enables Resource-Exhaustion Attacks## Vulnerability Details **File Location**: `scripts/math_eval.py`, lines 4-19 **Vulnerability Type**: Uncontrolled resource consumption **Risk Level**: Medium **Vulnerable Code**: ```python SAFE_NAMES = { "abs": abs, "round": round, "min": min, "max": max, "pow": pow, "sqrt": math.sqrt, "sin": math.sin, "cos": math.cos, "tan": math.tan, "log": math.log, "log10": math.log10, "pi": math.pi, "e": math.e, "floor": math.floor, "ceil": math.ceil, } def safe_eval(expr): return eval(expr, {"__builtins__": {}}, SAFE_NAMES) def main(): parser = argparse.ArgumentParser(description="Math Expression Evaluator") parser.add_argument("--expr", required=True) args = parser.parse_args() try: result = safe_eval(args.expr) ``` ### Technical Analysis The evaluator accepts an expression of unrestricted length and complexity and exposes exponentiation through both the `**` operator and `pow()`. It imposes no limits on integer size, exponent magnitude, nesting depth, execution time, memory consumption, or serialized result size. Python integers have arbitrary precision. Expressions that construct extremely large integers can therefore consume substantial CPU time and memory. Deeply nested expressions can also impose excessive parsing and evaluation costs. Error handling only catches exceptions after evaluation; it does not interrupt computations that consume excessive resources. ### Attack Path 1. An attacker submits a very long, deeply nested, or computationally expensive expression through `--expr`. 2. The parser accepts the input without a length or complexity check. 3. `eval()` executes expensive arithmetic, such as large or repeated exponentiation. 4. Python allocates increasing amounts of memory and CPU time while calculating or serializing the result. 5. The evaluator becomes unresponsive, is terminated by the operating system, or deprives colocated workloads of resour ...[truncated 585 chars]
Remediation
## Remediation Suggestions Apply resource controls at both the expression and process levels: 1. Reject input exceeding a conservative maximum character count. 2. Parse the expression into an AST and limit total node count and nesting depth. 3. Restrict numeric literal length and integer bit length. 4. Set strict bounds on exponent values and reject nested or repeated exponentiation beyond a defined complexity budget. 5. Limit the number and arity of function calls. 6. Bound the size of the result before JSON serialization. 7. Run evaluation in a separate low-privilege worker process with operating-system CPU, memory, process-count, and wall-clock limits. 8. Terminate workers that exceed a short timeout. 9. Apply request throttling when the evaluator is exposed to multiple or remote users. 10. Add tests confirming that oversized, deeply nested, and expensive expressions are rejected before evaluation.
Vulnerability Patterns
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Supply ChainUnpinned Dependencies, External Script Fetching, Obfuscated Code
Findings (1)

eval() call detected

High
Category
Dangerous Code Execution
Content
}

def safe_eval(expr):
    return eval(expr, {"__builtins__": {}}, SAFE_NAMES)

def main():
    parser = argparse.ArgumentParser(description="Math Expression Evaluator")
Confidence
93% confidence
Finding
The script evaluates attacker-controlled input from the --expr argument using Python's eval(). Although __builtins__ is removed and a restricted locals dictionary is provided, eval on untrusted input remains dangerous because Python object traversal and unexpected expression behavior can still expose attack paths or enable denial-of-service through expensive computations; the intended 'math-only' context does not eliminate this risk.

Static analysis

Detected: suspicious.dynamic_code_execution

Dynamic code execution detected.

Critical
Code
suspicious.dynamic_code_execution
Location
scripts/math_eval.py:12