Back to skill

Security audit

OpenClaw Token Optimizer

Security checks for vulnerabilities and agentic risk

Overview

The skill is mostly a local token-cost helper, but it deserves review because it can write persistent agent instruction files, accepts an unrestricted output path, and makes integrity and credential-handling claims that are not fully supported by the artifact.

Install only after reviewing the generated AGENTS.md and HEARTBEAT.md templates, and do not let an agent run generate-agents --output against arbitrary paths. Prefer the workspace-output option, keep backups, avoid storing live API keys in plaintext config files unless permissions are locked down, and do not rely on the advertised .clawhubsafe verification unless the manifest is actually supplied.

Vulnerability Patterns
  • Insecure DependenciesIntroduces malicious components through unsafe dependency sources
  • 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
Findings (5)

T08 · Insecure Dependencies

Warning
Location
SKILL.md:56
Finding
Unpinned Remote Skill Installation Creates Supply-Chain Risk<![CDATA[ ## Vulnerability Details **File Location**: `SKILL.md:56-60` **Vulnerability Type**: Unpinned third-party installation **Risk Level**: Medium ### Vulnerable Code ```markdown ## Install ```bash openclaw skills install @asif2bd/openclaw-token-optimizer ``` ``` Related unpinned installation instructions also appear in `README.md:16-26` and `SKILL.md:231-234`. ### Technical Analysis The installation command identifies a mutable registry package but does not pin an immutable version, commit, or content digest. Consequently, the content installed later may differ from the artifact covered by this audit. The documentation also promotes another Skill through an unpinned installation command. Although the audited code does not download or execute a remote payload itself, following these instructions introduces a trust dependency on the publisher account, package registry, and mutable upstream package. No evidence was found that the current package source is malicious. The vulnerability is the absence of controls ensuring that users receive the reviewed version. ### Attack Path 1. An attacker compromises the publisher account, registry entry, or upstream repository. 2. The attacker publishes a modified package under the same mutable package identifier. 3. A user follows the documented installation command. 4. OpenClaw installs the modified package rather than the reviewed artifact. 5. The modified Skill gains the execution and Agent-instruction capabilities granted to installed Skills. ### Impact Assessment A compromised future release could introduce malicious Agent instructions, local file access, credential theft, network communication, or arbitrary code execution within the privileges of the OpenClaw process. This finding does not provide privilege escalation by itself; impact is limited to permissions already held by the installing user or Agent. ]]>
Remediation
<![CDATA[ ## Remediation Suggestions - Pin installation examples to a specific package version supported by the registry. - For Git-based installation, use an immutable commit hash rather than the default branch. - Publish a signed release artifact and provide its SHA-256 digest. - Require integrity verification before the Skill is loaded. - Remove unrelated Skill installation promotion from the operational instructions, or place it in a clearly non-operational references section. - Document the exact version and digest covered by each security audit. ]]>

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/context_optimizer.py:389
Finding
Caller-Controlled Output Path Can Overwrite Arbitrary User-Writable Files<![CDATA[ ## Vulnerability Details **File Location**: `scripts/context_optimizer.py:389-399` **Vulnerability Type**: Unrestricted file write and overwrite **Risk Level**: Medium ### Vulnerable Code ```python if "--output" in sys.argv: idx = sys.argv.index("--output") if idx + 1 >= len(sys.argv): print("Usage: context_optimizer.py generate-agents --output <path>") sys.exit(1) output_path = Path(sys.argv[idx + 1]).expanduser() elif "--workspace-output" in sys.argv: output_path = Path.home() / ".openclaw/workspace/AGENTS.md.optimized" if output_path: output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text(content) ``` ### Technical Analysis The `--output` argument accepts an unrestricted filesystem path. The code creates missing parent directories and then calls `Path.write_text()`, which truncates and replaces an existing file. It performs no workspace-containment check, existing-file confirmation, symbolic-link rejection, atomic exclusive creation, or explicit overwrite authorization. The operation requires an explicit command and therefore is not a silent write. Nevertheless, the implementation exceeds the documented workspace-oriented write boundary and can overwrite any file writable by the invoking user. `write_text()` may also follow a symbolic link, allowing a path that appears harmless to resolve to another writable target. ### Attack Path 1. An attacker or untrusted instruction persuades a user or Agent to run: `context_optimizer.py generate-agents --output <target>`. 2. `<target>` names an existing user-writable configuration, script, shell initialization file, or symbolic link. 3. The script creates parent directories if necessary. 4. `write_text()` truncates the destination and writes the generated Agent policy. 5. The overwritten file may disrupt the application or alter behavior when another component later consumes it. ### Impact Assessment The command can overwrite files ac ...[truncated 311 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Restrict output to `~/.openclaw/workspace/` by default. - Resolve the requested path with `Path.resolve()` and verify that it remains under the approved workspace root. - Reject symbolic links in the destination and relevant parent components. - Refuse to replace an existing file unless the user supplies a separate `--force` option. - Use exclusive creation where possible, such as opening with mode `x`. - For permitted replacements, write to a securely created temporary file in the same directory and atomically rename it. - Display the resolved destination and require confirmation for paths outside the normal generated-file location. ]]>

T09 · Insecure Skill Coding Practices

Warning
Location
references/PROVIDERS.md:87
Finding
Documentation Encourages Plaintext API-Key Storage<![CDATA[ ## Vulnerability Details **File Location**: `references/PROVIDERS.md:87-115` **Vulnerability Type**: Insecure credential-storage guidance **Risk Level**: Medium ### Vulnerable Code ```markdown ### OpenRouter Configuration ```json { "provider": "openrouter", "apiKey": "sk-or-v1-...", "models": { "cheap": "google/gemini-2.5-flash", "balanced": "anthropic/claude-sonnet-4.5", "smart": "anthropic/claude-opus-4-5" } } ``` ## API Key Management Store API keys in `~/.openclaw/openclaw.json` or environment variables: ```bash export ANTHROPIC_API_KEY="sk-ant-..." export OPENROUTER_API_KEY="sk-or-v1-..." export OPENAI_API_KEY="sk-proj-..." export GOOGLE_API_KEY="AIza..." ``` ``` ### Technical Analysis The strings shown are placeholders rather than genuine credentials, and the executable scripts do not transmit API-key values. However, the guide recommends storing real API keys directly in `~/.openclaw/openclaw.json` without requiring restrictive permissions, encryption, a secret manager, or exclusion from backups and version control. Environment variables may also be exposed through process inspection, diagnostic output, inherited child processes, or improperly collected support data, depending on the operating environment. ### Attack Path 1. A user follows the provider setup instructions. 2. The user stores a live provider key in plaintext in `~/.openclaw/openclaw.json`. 3. The file has permissive permissions, is copied into a backup, or is included in diagnostic or support data. 4. Another local account, process, backup reader, or unintended recipient obtains the key. 5. The attacker uses the key to submit requests, consume quota, or access provider resources authorized to that credential. ### Impact Assessment Exposure can permit unauthorized use of the affected AI provider account, resulting in financial loss, quota exhaustion, and access to provider-side resources available to the key. The scope depends on the provider permi ...[truncated 116 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Prefer the OpenClaw-supported secret store or an operating-system credential manager. - Avoid embedding API keys directly in JSON configuration. - If file-based storage is unavoidable, require permissions equivalent to `0600` and verify ownership. - Keep credential files outside repositories and shared workspace directories. - Explicitly exclude credential files from backups, support bundles, logs, and version control where appropriate. - Recommend narrowly scoped keys, provider-side spending limits, monitoring, and regular rotation. - Replace examples that resemble live keys with clearly marked placeholders such as `${OPENROUTER_API_KEY}`. ]]>

T09 · Insecure Skill Coding Practices

Note
Location
assets/config-patches.json:199
Finding
Duplicate JSON Key Silently Alters External Provider Routing<![CDATA[ ## Vulnerability Details **File Location**: `assets/config-patches.json:199-205` **Vulnerability Type**: Ambiguous configuration caused by duplicate JSON keys **Risk Level**: Low ### Vulnerable Code ```json { "name": "openrouter-fallback", "type": "openrouter", "apiKey": "${OPENROUTER_API_KEY}", "priority": 2, "models": { "anthropic/claude-sonnet-4-5": "anthropic/claude-sonnet-4", "anthropic/claude-sonnet-4-5": "google/gemini-2.5-flash" } } ``` ### Technical Analysis The `models` object defines `anthropic/claude-sonnet-4-5` twice. Common JSON parsers silently retain only the final value, causing the Anthropic destination to be discarded and the Gemini destination to become effective. This creates a discrepancy between what a human reviewer may infer and what software actually applies. Because the configuration concerns third-party model routing, the defect can cause prompts to be sent to a different model or processing route than intended. The patch is reference documentation and is not automatically applied. Exploitation or impact therefore requires explicit user application. ### Attack Path 1. A user chooses to configure the optional multi-provider fallback. 2. The user applies or copies the documented JSON patch. 3. The JSON parser accepts duplicate keys and retains only the last value. 4. The intended Anthropic mapping is silently replaced by the Gemini mapping. 5. Fallback requests are processed through an unexpected destination. ### Impact Assessment The issue may change model behavior, output quality, billing, data-processing location, or confidentiality assumptions. It does not itself reveal credentials or bypass access controls. Scope is limited to users who manually apply the optional external-provider configuration. ]]>
Remediation
<![CDATA[ ## Remediation Suggestions - Replace the duplicate keys with distinct and valid source-model identifiers. - Define explicit tier-to-model mappings rather than overloaded model aliases. - Validate the file using a parser or linter configured to reject duplicate JSON keys. - Add automated tests that parse the configuration and assert every effective mapping. - Document the exact provider and model that will receive fallback traffic. - Require users to review data-handling implications before activating third-party routing. ]]>

other

Note
Location
README.md:139
Finding
Advertised Integrity Manifest Is Missing from the Distributed Artifact<![CDATA[ ## Vulnerability Details **File Location**: `README.md:139-181` **Vulnerability Type**: Misleading and unavailable integrity verification **Risk Level**: Low ### Vulnerable Code ```markdown ├── .clawhubsafe ← SHA256 integrity manifest (13 files) ├── .clawhubignore ← Files excluded from publish bundle ``` ```markdown Verify integrity: ```bash cd ~/.openclaw/skills/openclaw-token-optimizer sha256sum -c .clawhubsafe ``` ``` Equivalent integrity claims appear in `SKILL.md:199-204` and `SECURITY.md:184-191,271-278`. ### Technical Analysis The supplied project artifact does not contain `.clawhubsafe`, despite repeated claims that the manifest is included and covers every published file. As a result, the documented `sha256sum -c .clawhubsafe` command cannot verify this artifact. A checksum manifest stored beside an artifact is not sufficient against a fully compromised distribution channel unless it is signed or obtained through a separately trusted channel. In this case, even the advertised baseline manifest is unavailable. ### Attack Path 1. A user obtains the distributed artifact and relies on the documentation's integrity assurances. 2. The expected `.clawhubsafe` file is absent. 3. Verification fails or is skipped. 4. Modified files may be used without comparison against the reviewed hashes. 5. If the distribution source is compromised, the user has no functioning advertised control to detect modification. ### Impact Assessment This finding weakens provenance and tamper detection. It does not demonstrate that any supplied file has been modified or that malicious content exists. Potential downstream impact depends on what an attacker changes in a compromised artifact and on the privileges granted when the modified Skill is loaded. ]]>
Remediation
<![CDATA[ ## Remediation Suggestions - Include `.clawhubsafe` in every published artifact that claims to support it. - Ensure the manifest covers every distributed executable, configuration, template, and instruction file. - Regenerate the manifest during release automation and fail publishing if files are missing or stale. - Sign the manifest with a verifiable publisher key or publish its digest through a separately trusted release channel. - Add a continuous-integration test that runs `sha256sum -c .clawhubsafe` against the final packaged artifact. - Remove or correct integrity claims if the publishing platform intentionally excludes the manifest. ]]>
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • Memory PoisoningPersistent Context Injection, Context Window Stuffing, Memory Manipulation
  • Tool MisuseTool Parameter Abuse, Chaining Abuse, Unsafe Defaults
Findings (20)

Tool Parameter Abuse

High
Category
Tool Misuse
Content
grep -r "urllib\|requests\|http\|socket\|download\|fetch" scripts/

# Search for system modifications (should return nothing)  
grep -r "rm -rf\|sudo\|chmod 777\|chown" .
```

### Review Imports
Confidence
80% confidence
Finding
Tool parameters are crafted to achieve unintended or unsafe behavior. Parameter abuse can bypass intended safety checks (e.g. shell=True, --force, dangerous glob patterns).

Tp4

High
Category
MCP Tool Poisoning
Confidence
92% confidence
Finding
The description overstates the implemented functionality. The supplied code does accurately cover one declared area—lazy context loading/context minimization—and partially supports practical cost control through file recommendation and usage tracking. However, several prominently declared capabilities are absent from the actual code: there is no model routing logic, no heartbeat scheduler, no token budget system, no cache TTL mechanism, and no special security-audit-safe command behavior. The generated AGENTS.md contains advisory text about some of these topics, but the script itself does not implement them. Therefore the description does not accurately represent the code chunk's real scope.

Tp4

High
Category
MCP Tool Poisoning
Confidence
87% confidence
Finding
The code does implement part of the description: heartbeat scheduling/optimization and cache-TTL guidance for Anthropic/OpenClaw usage. However, the declared purpose presents a much broader 'token optimizer toolkit' with multiple features not present in the supplied code chunk, including lazy context loading, model-aware routing, and local token budgeting. The actual code's primary function is heartbeat interval management with state persistence and a CLI for planning/checking/recording intervals. It also performs local file reads/writes to ~/.openclaw/workspace/memory/heartbeat-state.json and supports resetting that state, which is more specific operational behavior than the description conveys. This is a material description-to-behavior mismatch due to significant missing claimed capabilities and a narrower actual scope.

Tp4

High
Category
MCP Tool Poisoning
Confidence
76% confidence
Finding
The declared description presents a multi-feature cost-control toolkit, but this code chunk only implements one portion: model selection/routing based on prompt patterns, provider detection, and simple cost metadata. While it does include Sonnet/Opus-aware routing and recognizes heartbeat/background tasks for cheap-tier routing, it does not perform actual scheduling, context loading, budget enforcement, caching guidance, or command-safety behavior. The primary purpose of the code is narrower than the declared description, so the description does not accurately represent what this specific code chunk actually does.

Tp4

High
Category
MCP Tool Poisoning
Confidence
96% confidence
Finding
The description promises a multi-feature optimization toolkit, but the supplied code only implements a simple token budget checker/model suggestion CLI. It stores state in ~/.openclaw/workspace/memory/token-tracker-state.json, supports check/suggest/reset commands, and uses hardcoded model cost guidance. There is no implementation of lazy context loading, routing logic, heartbeat scheduling, cache TTL handling, or any special command safety behavior. Even the tracking portion is incomplete because actual session usage collection is stubbed out with placeholder zeros. The only meaningful overlap with the description is local token budget/cost-control guidance, which is insufficient to represent the broader declared purpose accurately.

Memory Manipulation

High
Category
Memory Poisoning
Content
print(json.dumps(result, indent=2))
    
    elif command == "reset":
        # Reset state
        if STATE_FILE.exists():
            STATE_FILE.unlink()
        print("Heartbeat state reset.")
Confidence
80% confidence
Finding
Skill manipulates agent memory, state, or stored context. Memory corruption can alter personality, override safety rules, or cause unpredictable behavior.

Session Persistence

Medium
Category
Rogue Agent
Content
## Security

All scripts are **local-only** — no network calls and no dynamic code execution. Some explicit commands write local OpenClaw workspace state or templates; those writes are documented in [SECURITY.md](SECURITY.md).

Verify integrity:
```bash
Confidence
60% confidence
Finding
Skill establishes unauthorized persistence across sessions via cron jobs, startup scripts, or state files. Session persistence allows an attacker to maintain access beyond the current interaction.

Session Persistence

Medium
Category
Rogue Agent
Content
- **Network access:** None
- **External API keys:** None required
- **Code execution:** No eval/exec/compile
- **Data storage:** Some commands write local JSON state files in `~/.openclaw/workspace/memory/`
- **Workspace writes:** `generate-agents` writes only when `--output` or `--workspace-output` is supplied
- **Verdict:** Safe to run when you understand which commands write local state
Confidence
60% confidence
Finding
Skill establishes unauthorized persistence across sessions via cron jobs, startup scripts, or state files. Session persistence allows an attacker to maintain access beyond the current interaction.

Session Persistence

Medium
Category
Rogue Agent
Content
- No network requests
- No code execution
- Only standard library imports: `json, os, datetime, pathlib`
- Read/write limited to heartbeat state file
- No system commands

**Data Handling**:
Confidence
60% confidence
Finding
Skill establishes unauthorized persistence across sessions via cron jobs, startup scripts, or state files. Session persistence allows an attacker to maintain access beyond the current interaction.

Sudo/Root Execution

Medium
Category
Privilege Escalation
Content
grep -r "urllib\|requests\|http\|socket\|download\|fetch" scripts/

# Search for system modifications (should return nothing)  
grep -r "rm -rf\|sudo\|chmod 777\|chown" .
```

### Review Imports
Confidence
80% confidence
Finding
Commands invoke sudo or root privileges. Verify this elevated access is necessary and justified.

Session Persistence

Medium
Category
Rogue Agent
Content
## Threat Model

**What this skill CAN do:**
- Read/write JSON files in OpenClaw workspace
- Analyze text for complexity classification
- Generate markdown templates
- Provide recommendations via stdout
Confidence
60% confidence
Finding
Skill establishes unauthorized persistence across sessions via cron jobs, startup scripts, or state files. Session persistence allows an attacker to maintain access beyond the current interaction.

Unrestricted Tool Access

Medium
Category
Excessive Agency
Content
- Provide recommendations via stdout

**What this skill CANNOT do:**
- Execute arbitrary code
- Make network requests
- Modify system files outside workspace
- Access sensitive data
Confidence
80% confidence
Finding
Skill grants unrestricted tool access without appropriate constraints. An agent with unfettered tool access can perform arbitrary actions including file modification, network requests, and code execution.

Sudo/Root Execution

Medium
Category
Privilege Escalation
Content
**What this skill CANNOT do:**
- Execute arbitrary code
- Make network requests
- Modify system files outside workspace
- Access sensitive data
- Run system commands
- Spawn subprocesses
Confidence
60% confidence
Finding
Commands invoke sudo or root privileges. Verify this elevated access is necessary and justified.

Lp3

Medium
Category
MCP Least Privilege
Confidence
90% confidence
Finding
The skill advertises executable scripts and file-writing behavior but does not declare an explicit tool scope such as permissions or allowed-tools. That omission weakens reviewability and containment because consumers cannot easily determine from the manifest what capabilities the skill expects, especially when the content also references external URLs and install flows.

Session Persistence

Medium
Category
Rogue Agent
Content
Built for current OpenClaw 2026.6.x agents by [Asif2BD](https://github.com/Asif2BD) · [GitHub](https://github.com/Asif2BD/OpenClaw-Token-Optimizer) · [Security Notes](https://github.com/Asif2BD/OpenClaw-Token-Optimizer/blob/main/SECURITY.md)

> **Security notice:** local-only optimization toolkit. The Python scripts make no network requests and do not execute dynamic code. Commands that write files are explicit, documented, and backup-safe.

---
Confidence
83% confidence
Finding
The skill explicitly promotes persistent file writes such as generating AGENTS.md and installing HEARTBEAT.md. Even if writes are described as explicit and backup-safe, persistence changes agent behavior across sessions and can become a security issue if users install generated content without careful review, especially when it may influence future agent instructions.

Missing User Warnings

Medium
Confidence
92% confidence
Finding
The template instructs the agent to access email, calendar, weather, and monitoring sources on a schedule, but it does not require any user consent notice, scope limitation acknowledgement, or visibility about what sensitive personal and system data may be accessed. In an autonomous heartbeat workflow, this can normalize background access to private communications and operational telemetry without clear authorization boundaries, increasing privacy and data exposure risk.

Missing User Warnings

Medium
Confidence
91% confidence
Finding
This markdown file includes examples that parse invoices from an inbox and extract customer/support data, which implies handling potentially sensitive user or business information. The guide does not provide any warning or disclosure about privacy, data sensitivity, or verifying that the cronjob has appropriate access and consent before scheduled processing.

Intent-Code Divergence

Medium
Confidence
96% confidence
Finding
The generated AGENTS.md instructs agents not to load yesterday's memory unless explicitly needed, but the actual recommendation logic auto-loads yesterday's log for any full-context prompt. This mismatch can cause unintended access to prior-session data, increasing the chance of oversharing sensitive historical context and violating least-privilege context loading expectations.

Context-Inappropriate Capability

Medium
Confidence
90% confidence
Finding
The manifest describes a practical token-cost-control toolkit with routing behavior, budgets, and safe command behavior, but this code inspects credential-bearing environment variables to infer which external AI provider is configured. Reading secrets is a distinct capability that is not necessary for classifying prompt complexity or mapping tiers to models, and the manifest does not explicitly justify secret/environment inspection.

Natural-Language Policy Violations

Low
Confidence
88% confidence
Finding
The natural-language instructions mandate using Sonnet and explicitly say not to use Opus for routine monitoring. This imposes a fixed model-selection policy on the session without presenting it as an option or documenting user choice.

Static analysis

No suspicious patterns detected.