Back to skill

Security audit

Context Doctor

Security checks for vulnerabilities and agentic risk

Overview

This is a coherent local diagnostic skill that reads OpenClaw workspace and skill metadata for context-size reporting, with no evidence of exfiltration, deception, or persistence.

Install only if you are comfortable with a local diagnostic reading OpenClaw bootstrap files and installed skill metadata. Review any generated terminal, JSON, or PNG output before sharing it, and use an isolated environment or pinned packages if you enable optional PNG dependencies.

Vulnerability Patterns
  • Unauthorized Access and Privilege EscalationObtains permissions beyond the task's legitimate needs
  • Insecure DependenciesIntroduces malicious components through unsafe dependency sources
  • 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
Findings (2)

T05 · Unauthorized Access and Privilege Escalation

Note
Location
scripts/context-doctor.py:59
Finding
Unnecessary Full Reads of Sensitive Agent State Files<![CDATA[ ## Vulnerability Details **File Location**: `scripts/context-doctor.py:59-63`, `scripts/context-doctor.py:81-86`, and `scripts/context-doctor.py:211-220` **Vulnerability Type**: Excessive access to agent memory and profile data **Risk Level**: Low ### Vulnerable Code ```python BOOTSTRAP_FILES = [ "AGENTS.md", "SOUL.md", "TOOLS.md", "IDENTITY.md", "USER.md", "HEARTBEAT.md", "BOOTSTRAP.md", "MEMORY.md", ] EXPECTED_MISSING = {"BOOTSTRAP.md"} ``` ```python def count_chars(path: str) -> int: try: with open(path, "r", encoding="utf-8", errors="replace") as f: return len(f.read()) except (OSError, IOError): return 0 ``` ```python def scan_workspace(workspace: str) -> list: """Scan workspace bootstrap files. Returns list of (name, status, chars, tok).""" files = [] for name in BOOTSTRAP_FILES: path = os.path.join(workspace, name) is_link = os.path.islink(path) exists = os.path.exists(path) if exists: chars = count_chars(path) tok = estimate_tokens(chars) ``` ### Technical Analysis The script needs file-length information to estimate token usage, but it reads every configured bootstrap file completely into a Python string. The affected set includes potentially sensitive state and profile files such as `MEMORY.md`, `USER.md`, `IDENTITY.md`, and `SOUL.md`. The current implementation does not print, persist, or transmit the contents. Consequently, there is no direct data-exfiltration path in the audited version. Nevertheless, full-content reads increase exposure beyond what is necessary for a size-oriented diagnostic operation. Sensitive contents temporarily reside in process memory and may become accessible to debuggers, tracing or instrumentation systems, crash diagnostics, malicious imported dependencies, or future modifications to the script. Although the operating system does not grant the script new privileges, the behavior weakens least ...[truncated 1431 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Avoid loading entire sensitive files into one Python string. 2. If approximate size is sufficient, use filesystem metadata: ```python def count_bytes(path: str) -> int: try: return os.stat(path).st_size except OSError: return 0 ``` 3. If exact Unicode character counts are required, process files incrementally: ```python def count_chars(path: str) -> int: total = 0 try: with open(path, "r", encoding="utf-8", errors="replace") as file: while chunk := file.read(8192): total += len(chunk) return total except OSError: return 0 ``` 4. Clear references to temporary content promptly and ensure that no logging, tracing, or exception handler records file contents. 5. Document explicitly that the diagnostic accesses workspace memory and identity files. 6. Consider offering a metadata-only mode that avoids opening sensitive files and reports byte-based token estimates instead. ]]>

T08 · Insecure Dependencies

Note
Location
SKILL.md:60
Finding
Unpinned Optional Third-Party Dependency Installation<![CDATA[ ## Vulnerability Details **File Location**: `SKILL.md:60-71` and `scripts/context-doctor.py:390-398` **Vulnerability Type**: Mutable and unverified third-party dependencies **Risk Level**: Low ### Vulnerable Code ```markdown ## Image Output (for chat / sharing) Generate a PNG image directly — no terminal screenshot needed: ```bash python3 scripts/context-doctor.py --png /tmp/context-doctor.png ``` The script renders a colored terminal-style image via Rich SVG export. Requires: `rich` (pip3 install rich) + one of: `rsvg-convert` (brew install librsvg) or `cairosvg` (pip3 install cairosvg). ``` ```python def render_png(workspace: str, ctx_size: int, output_path: str) -> None: """Render the visualization as a PNG image (for chat/share use). Uses Rich to capture ANSI output → SVG, then converts to PNG. Requires: rich (Python), rsvg-convert (brew) or cairosvg (pip). """ try: from rich.console import Console as RichConsole from rich.text import Text as RichText except ImportError: print("Error: 'rich' package required for PNG output. Install: pip3 install rich", file=sys.stderr) sys.exit(1) ``` The script later imports the optional CairoSVG package directly: ```python if not converted: try: import cairosvg cairosvg.svg2png(url=svg_path, write_to=output_path, scale=2) converted = True except (ImportError, Exception): pass ``` ### Technical Analysis PNG support instructs users to install `rich` and `cairosvg` without fixed versions, hashes, a lockfile, or an isolated environment. Commands such as `pip3 install rich` resolve the latest compatible package and transitive dependency versions available from the configured package index at installation time. The packages named by the project are established package names, and the audited code does not automatically install them. No evidence of dependency confusion, typosquatting, or a malicious package was f ...[truncated 1709 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Pin reviewed dependency versions rather than recommending unconstrained installation: ```text rich==<reviewed-version> CairoSVG==<reviewed-version> ``` 2. Supply a locked requirements file with cryptographic hashes and instruct users to require hash verification: ```bash python3 -m pip install --require-hashes -r requirements-png.txt ``` 3. Include all transitive dependencies in the lockfile so their versions and artifacts are also controlled. 4. Recommend installing optional rendering dependencies in an isolated virtual environment: ```bash python3 -m venv .venv . .venv/bin/activate python3 -m pip install --require-hashes -r requirements-png.txt ``` 5. Document the expected package index and warn against untrusted mirrors or additional package indexes. 6. Use automated dependency scanning and scheduled review of pinned versions. 7. Where feasible, keep PNG support in a separate optional dependency group so terminal and JSON operation do not require image-rendering packages. ]]>
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
Findings (7)

Env Variable Harvesting

High
Category
Data Exfiltration
Content
import pty as pty_mod

    script_path = os.path.abspath(__file__)
    env = {
        **os.environ,
        "FORCE_COLOR": "1",
        "TERM": "xterm-256color",
Confidence
60% confidence
Finding
Code enumerates, copies, or searches environment variables for secrets. Bulk environment access can collect credentials unrelated to the skill's stated purpose.

os.system() or os exec-family call

High
Category
Dangerous Code Execution
Content
if workspace:
                cmd += ["--workspace", workspace]
            cmd += ["--ctx-size", str(ctx_size)]
            os.execvp(sys.executable, cmd)
            os._exit(127)

        while True:
Confidence
85% confidence
Finding
os.system() and os exec-family calls run shell commands with the process's full privileges, enabling arbitrary command execution.

Lp3

Medium
Category
MCP Least Privilege
Confidence
91% confidence
Finding
The skill instructs the agent to run a local script that auto-detects the workspace, installed skills, bootstrap file sizes, and environment-derived paths, but the manifest does not declare any tool scope or permissions. This creates an authorization/visibility gap: operators cannot clearly see that shell execution, file reads, environment access, and possible file writes are needed, which increases the chance of unintended local data enumeration and weakens least-privilege controls.

subprocess module call

Medium
Category
Dangerous Code Execution
Content
def get_version() -> str:
    try:
        r = subprocess.run(
            ["openclaw", "--version"],
            capture_output=True, text=True, timeout=5,
        )
Confidence
70% confidence
Finding
subprocess module calls execute external commands. Without careful input validation, this enables command injection.

subprocess module call

Medium
Category
Dangerous Code Execution
Content
return os.environ["OPENCLAW_WORKSPACE"]
    # Try openclaw config
    try:
        r = subprocess.run(
            ["openclaw", "config", "get"],
            capture_output=True, text=True, timeout=10,
        )
Confidence
70% confidence
Finding
subprocess module calls execute external commands. Without careful input validation, this enables command injection.

subprocess module call

Medium
Category
Dangerous Code Execution
Content
# Try rsvg-convert
    try:
        subprocess.run(
            ["rsvg-convert", svg_path, "-o", output_path, "-z", "2"],
            check=True, capture_output=True,
        )
Confidence
70% confidence
Finding
subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Missing User Warnings

Low
Confidence
84% confidence
Finding
The documentation encourages running the script for context-health diagnosis but does not clearly warn users that it enumerates local workspace/bootstrap files and installed skills, which may reveal sensitive project structure or internal capability inventory. In shared or privacy-sensitive environments, this can lead to unintended exposure of metadata in terminal output or generated images.

Static analysis

No suspicious patterns detected.