Back to skill

Security audit

Token Optimizer

Security checks for vulnerabilities and agentic risk

Overview

This skill mostly matches its token-optimization purpose, but it can persist private session excerpts and restart the OpenClaw gateway with limited guardrails.

Review before installing if your OpenClaw sessions may contain secrets, customer data, personal information, or proprietary code. Use explicit --session values for compression, treat generated compressed files as confidential, and avoid --cleanup --apply unless a gateway restart is acceptable.

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 (1)

T09 · Insecure Skill Coding Practices

Warning
Location
src/optimizer.py:350
Finding

Plaintext Persistence of Potentially Sensitive Session Content

Content
View full analysis

Vulnerability Details

File Location: src/optimizer.py:350-397
Related Sensitive-Data Extraction: src/compression.py:27-59
Vulnerability Type: Plaintext storage of sensitive conversation content with permissions inherited from the process umask
Risk Level: Medium

Vulnerable Code

python
sid = str(target.get("sessionId") or "")
events = self.transcript_events(sid)
summary = summarize_transcript_events(events, keep_recent=keep_recent)

self.compressed_dir.mkdir(parents=True, exist_ok=True)
out_path = self.compressed_dir / f"{sid}-compressed.md"

lines = [
    f"# Compressed Context: {target.get('key')}",
    "",
    f"- Session ID: `{sid}`",
    f"- Model: `{target.get('model')}`",
    f"- Tokens: `{total}/{context}` ({utilization:.0%})",
    "",
    "## Original Task",
    summary.get("firstUser", "(no user prompt found)"),
    "",
    "## Tool Call Summary",
]

tool_calls = summary.get("toolCalls", {})
if tool_calls:
    for name, count in sorted(tool_calls.items(), key=lambda kv: kv[1], reverse=True):
        lines.append(f"- `{name}`: {count}")
else:
    lines.append("- No tool calls detected.")

lines.extend(["", "## Recent Conversation", ""])
recent = summary.get("recent", [])
if recent:
    for item in recent:
        role = item.get("role", "unknown")
        text = item.get("text", "")
        lines.append(f"- **{role}**: {text}")
else:
    lines.append("- No recent text messages detected.")

lines.extend(
    [
        "",
        "## Compression Guidance",
        "- Keep this file in context, not the full raw transcript.",
        "- Re-run `token-optimize --compress` after major tool-heavy steps.",
        "- If utilization remains high, start a fresh session and continue from this summary.",
    ]
)

out_path.write_text("\n".join(lines).strip() + "\n", encoding="utf-8")

The content placed into that file is extracted as follows:

python
def summarize_transcript_events(events: list[dict], keep_recent: int = 20) 
...[truncated 4310 chars]
Remediation
View remediation

Remediation Suggestions

  1. Create the storage directory with mode 0700 and each snapshot with mode 0600, without relying on the process umask. Use an atomic owner-only file creation mechanism and reject symlink targets.
  2. Redact likely secrets before writing. Cover bearer tokens, API keys, authorization headers, passwords, private keys, connection strings, signed URLs, cookies, and configurable organization-specific patterns.
  3. Require an explicit session identifier for compression, or request confirmation before selecting the main or latest session automatically.
  4. Add a metadata-only or --no-content mode that stores token counts and tool-call statistics without retaining message text.
  5. Clearly warn that compression snapshots can contain confidential conversation content and display the exact output path before or immediately after creation.
  6. Introduce a retention policy and a secure deletion command for old snapshots.
  7. Avoid placing sensitive snapshots in directories subject to automatic synchronization, indexing, or broad Agent access unless the user explicitly opts in.
  8. Consider encrypting snapshots at rest where plaintext retention is unavoidable.
  9. Add tests that verify restrictive permissions, secret redaction, explicit session selection, and safe handling of existing files and symlinks.
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • Memory PoisoningPersistent Context Injection, Context Window Stuffing, Memory Manipulation
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
Findings (12)

Tp4

High
Category
MCP Tool Poisoning
Confidence
92% confidence
Finding

The documented behavior promises broad token optimization, compression, hygiene checks, and deduplication analysis, while the implementation reportedly lacks much of that functionality. This mismatch can mislead operators into trusting the skill for optimization or cleanup decisions it cannot actually perform, causing unsafe automation choices, accidental data modification, or a false sense of security around cost and context management.

Content

No source excerpt is available for this finding.

Memory Manipulation

High
Category
Memory Poisoning
Confidence
80% confidence
Finding

Skill manipulates agent memory, state, or stored context. Memory corruption can alter personality, override safety rules, or cause unpredictable behavior.

Content

Scanner excerpt · references/operating-notes.md (reported line 16)May include surrounding context.

md
- `--cleanup` is plan-only by default.
- `--cleanup --apply` currently performs only one automated action:
  - `openclaw gateway restart` if stuck sessions are detected.
- It does not delete files, reset state, or remove sessions.

## Compression Behavior

Context-Inappropriate Capability

High
Category
Not specified by scanner
Confidence
91% confidence
Finding

This skill's stated purpose is token analysis, compression guidance, deduplication insights, model selection guidance, and hygiene checks. While reading OpenClaw session metadata is expected, the general subprocess execution capability culminates in service-control behavior and is broader than what is justified for a token optimizer.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

High
Category
Not specified by scanner
Confidence
98% confidence
Finding

The skill is described as analyzing and reducing token waste, but apply_cleanup can restart the gateway, creating an unexpected operational side effect. In an agent setting, this can interrupt other sessions, cause denial of service for active users, and enable misuse of the skill as a control primitive rather than an advisory tool.

Content

No source excerpt is available for this finding.

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
92% confidence
Finding

The skill documents executable shell commands and references scripts that imply file read, file write, and shell capabilities, but it does not declare any explicit tool scope or permissions. This weakens least-privilege controls and makes it easier for a consumer or platform to invoke a skill with broader capabilities than users expect, especially since it includes operations that write config files and apply cleanup changes.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The skill documents a '--cleanup --apply' command without a nearby warning that it will modify session data or generated artifacts. In a skill focused on automated optimization and cleanup, users may run the command assuming it is a safe analysis step, leading to unintended deletion or alteration of state that may be difficult to recover.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

The manifest describes invocation as 'Use $token-optimizer to analyze and reduce token waste across sessions,' but it does not define the trigger scope, boundaries, or non-applicable cases. This leaves activation conditions underspecified and may cause unintended use in loosely related session-management contexts.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
85% confidence
Finding

The usage examples document commands that modify local configuration, write files to /tmp, and especially perform cleanup with an optional apply step that can restart a gateway, but they provide no warning, confirmation guidance, or explanation of side effects. In an agent skill context, users may copy-paste these commands directly, so undocumented state-changing operations increase the risk of unintended service disruption, configuration changes, or data loss.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · src/optimizer.py (reported line 26)May include surrounding context.

python
self.compressed_dir = self.output_dir / "compressed"

    def _run_json(self, args: list[str]) -> dict:
        proc = subprocess.run(args, capture_output=True, text=True, check=True)
        return json.loads(proc.stdout)

    def get_sessions(self) -> list[dict]:

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
93% confidence
Finding

This code performs an actual gateway restart as a side effect of a token-optimization skill, crossing from analysis into operational control. Even though the command is fixed and not shell-injected, it can disrupt active sessions or workflows and is dangerous because it grants service-control capability unrelated to the stated purpose.

Content

Scanner excerpt · src/optimizer.py (reported line 320)May include surrounding context.

python
"plan": plan,
            }

        subprocess.run(["openclaw", "gateway", "restart"], check=False)
        return {
            "applied": True,
            "message": "Gateway restart requested due to stuck sessions near context limit.",

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

compress_session writes a markdown file containing original task text and recent conversation excerpts from session transcripts into the workspace without any consent, masking, or sensitivity checks. Because transcripts may contain secrets, personal data, or proprietary content, this creates a persistence and secondary-exposure risk beyond the original session storage.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
77% confidence
Finding

The default return values force specific vendor/model identifiers in natural-language-like config strings, which can impose an implicit provider choice on users. The file does not indicate any user opt-in, alternative locale/provider choice, or documentation justifying this constraint.

Content

No source excerpt is available for this finding.

Static analysis

No suspicious patterns detected.