Back to skill

Security audit

token-optimizer-off

Security checks for vulnerabilities and agentic risk

Overview

The skill has a coherent token-saving purpose, but it needs review because it can silently persist AI-generated memory, send session or user-chosen file contents to configurable external API endpoints, and its cleanup/test paths can affect global OpenClaw memory.

Install only after you are comfortable with this skill sending session summaries or selected files to the configured AI endpoint and writing persistent global memory that future OpenClaw sessions may load. Avoid using the arbitrary file argument for sensitive files, verify the API URL and credentials, back up ~/.openclaw/memory before use, do not run the documented uninstall command that deletes the whole memory directory unless you intend to erase all OpenClaw memory, and isolate TOKEN_OPTIMIZER_MEMORY_DIR before running tests.

Vulnerability Patterns
  • Agent Memory PoisoningWrites attacker-controlled rules into memory that affect later sessions
  • 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
  • Remote Payload Retrieval and ExecutionFetches external code whose behavior can change after review
Findings (4)

T02 · Agent Memory Poisoning

Error
Location
scripts/compress_session.py:181
Finding
Persistent Prompt Injection Through AI-Generated Session Summaries<![CDATA[ ## Vulnerability Details **File Location**: `scripts/compress_session.py:181-199`, `scripts/compress_session.py:220-226`, `scripts/compress_session.py:309-312`, and `SKILL.md:49-53` **Vulnerability Type**: Persistent prompt injection and memory poisoning **Risk Level**: High ### Vulnerable Code ```python prompt = f"""将以下会话内容压缩到{config['max_chars']}字以内。 压缩要求: 1. 保留:关键配置、路径、已验证方案、错误教训、重要决策 2. 删除:过程描述、重复信息、调试输出、格式说明、冗余解释 3. 输出纯Markdown格式,不加任何额外解释 压缩示例: 原文:用户询问了股票投资的问题,我详细解释了K线图的使用方法,包括阳线、阴线、十字星等形态,还讲解了均线系统的5日、10日、20日、60日均线的作用,以及MACD指标的金叉死叉信号... 压缩:技术分析要点:K线看趋势(阳线涨/阴线跌/十字星变盘),均线判支撑压力(5/10/20/60日),MACD看金叉死叉。 原文:部署过程中遇到了依赖问题,先尝试了pip install但是报错,然后检查了Python版本发现是3.8,需要升级到3.10,升级后重新安装依赖,最终成功启动服务... 压缩:部署要点:需Python 3.10+,pip install依赖,服务已启动。教训:先检查Python版本。 --- 待压缩内容: {text}""" ``` ```python response = client.chat.completions.create( model=config['model'], messages=[{'role': 'user', 'content': prompt}], max_tokens=config['max_tokens'], timeout=timeout ) return response.choices[0].message.content ``` ```python today = datetime.now().strftime('%Y-%m-%d %H:%M') with open(latest_file, 'w', encoding='utf-8') as f: f.write(f'# 会话摘要(压缩版)更新于 {today}\n\n{compressed}') ``` The Skill then requires this generated file to be loaded in later sessions: ```text ① INDEX.md ② latest-summary.md ③ Task-specific memory ④ Last five conversation rounds ``` ### Technical Analysis The compressor interpolates untrusted conversation or file content directly into an instruction prompt. There is no strict separation between the compressor's instructions and the supplied content, so embedded directives can be interpreted as instructions by the summarization model. The returned model output is accepted without schema validation, instruction filtering, provenance labeling, or human confirmation. It is then written to the persistent global memory file `~/.openclaw/memory/sessions/latest-summary.md`. The Skill documentation directs future Agent sessions to load th ...[truncated 1662 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Treat all source conversation content as untrusted data and clearly delimit it using a structured message or serialization format. 2. Use separate system and user messages, with the system message explicitly prohibiting execution or preservation of instructions found inside the source material. 3. Require the model to return a strict structured schema containing only approved factual fields. 4. Validate generated output before persistence. Reject or quarantine content containing imperative instructions, role changes, tool directives, hidden markup, or attempts to override higher-priority instructions. 5. Mark summaries as untrusted reference data and instruct consuming Agents never to treat them as executable instructions. 6. Require user review or explicit confirmation before replacing persistent cross-session memory. 7. Preserve provenance metadata so future Agents can distinguish user statements, model-generated summaries, and trusted configuration. 8. Add adversarial tests covering prompt injection, indirect prompt injection, encoded instructions, and directives disguised as configuration or decisions. ]]>

T09 · Insecure Skill Coding Practices

Error
Location
scripts/compress_session.py:246
Finding
Arbitrary Local File Disclosure to an Unrestricted External API Endpoint<![CDATA[ ## Vulnerability Details **File Location**: `scripts/compress_session.py:46-76`, `scripts/compress_session.py:177-179`, `scripts/compress_session.py:246-255`, and `scripts/compress_session.py:369-380` **Vulnerability Type**: Unrestricted file upload and insufficient outbound destination validation **Risk Level**: High ### Vulnerable Code ```python openclaw_config_file = Path.home() / '.openclaw' / 'config.json' if openclaw_config_file.exists(): check_file_permissions(openclaw_config_file) try: with open(openclaw_config_file, encoding='utf-8') as f: openclaw_config = json.load(f) if 'ai' in openclaw_config: ai_config = openclaw_config['ai'] config['api_url'] = ai_config.get('baseURL', 'https://api.openai.com/v1') config['api_key'] = ai_config.get('apiKey', '') config['model'] = ai_config.get('model', 'gpt-4') elif 'llm' in openclaw_config: llm_config = openclaw_config['llm'] config['api_url'] = llm_config.get('baseURL', 'https://api.openai.com/v1') config['api_key'] = llm_config.get('apiKey', '') config['model'] = llm_config.get('model', 'gpt-4') except Exception as e: print(f'[警告] OpenClaw 配置加载失败: {e}') if 'TOKEN_OPTIMIZER_API_KEY' in os.environ: config['api_key'] = os.environ['TOKEN_OPTIMIZER_API_KEY'] if 'TOKEN_OPTIMIZER_MODEL' in os.environ: config['model'] = os.environ['TOKEN_OPTIMIZER_MODEL'] if 'TOKEN_OPTIMIZER_API_URL' in os.environ: config['api_url'] = os.environ['TOKEN_OPTIMIZER_API_URL'] ``` ```python client = OpenAI( api_key=config['api_key'], base_url=config['api_url'] ) ``` ```python with open(source, encoding='utf-8') as f: content = f.read() old_size = len(content) old_tokens = estimate_tokens(content) if old_size <= config['max_chars']: compressed = content else: compressed = ai_compress(content, config) ``` ...[truncated 2406 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Resolve the supplied path with `Path.resolve()` and require it to remain under an explicitly approved summary directory. 2. Reject symbolic links and non-regular files, and permit only expected summary filename patterns. 3. Remove arbitrary positional file support unless it is essential. If retained, require an explicit acknowledgment that the file will be transmitted externally. 4. Enforce HTTPS for all remote endpoints. 5. Maintain an allowlist of trusted API hosts or require explicit approval whenever the configured host differs from a known provider. 6. Display the destination hostname, model, source path, and data size before transmission. 7. Use separate credentials scoped to this Skill instead of automatically reusing a global OpenClaw credential. 8. Consider local redaction of secrets, tokens, private keys, and personally identifiable information before upload. 9. Add tests for directory traversal, symbolic-link escape, non-HTTPS URLs, untrusted hosts, and environment-based endpoint replacement. ]]>

T09 · Insecure Skill Coding Practices

Warning
Location
tests/test_session_guard.py:12
Finding
Test Suite Overwrites Live OpenClaw Session State<![CDATA[ ## Vulnerability Details **File Location**: `tests/test_session_guard.py:12-17`, `tests/test_session_guard.py:96-100`, and `scripts/session_guard.py:20-22, 72-93` **Vulnerability Type**: Unsafe test isolation and unintended modification of user data **Risk Level**: Medium ### Vulnerable Code ```python from session_guard import detect_task_type, check, load_state, reset_state class TestSessionGuard(unittest.TestCase): """session_guard test class""" def setUp(self): """Reset state before each test""" reset_state() ``` ```python def test_reset_state(self): """Test state reset""" check(task_type='STOCK', rounds=10, context_size=50000) state = reset_state() self.assertEqual(state['rounds'], 0) self.assertEqual(state['task_switches'], 0) ``` The production module resolves the live state path at import time: ```python MEMORY_DIR = os.path.expanduser(os.getenv('TOKEN_OPTIMIZER_MEMORY_DIR', '~/.openclaw/memory')) SESSIONS_DIR = os.path.join(MEMORY_DIR, 'sessions') STATE_FILE = os.path.join(SESSIONS_DIR, '.session_state.json') ``` ```python def save_state(state: dict): """Persist session state""" os.makedirs(SESSIONS_DIR, exist_ok=True) with open(STATE_FILE, 'w', encoding='utf-8') as f: json.dump(state, f, ensure_ascii=False, indent=2) def reset_state(): """Reset session state""" state = { 'session_start': datetime.now().isoformat(), 'rounds': 0, 'task_history': [], 'task_switches': 0, 'peak_tokens': 0, 'last_task': '', } save_state(state) return state ``` ### Technical Analysis The tests import `session_guard` before configuring an isolated temporary memory directory. Unless the caller already set `TOKEN_OPTIMIZER_MEMORY_DIR`, the module binds `STATE_FILE` to the real user path `~/.openclaw/memory/sessions/.session_state.json`. Every test invokes `reset_state()` during setup, and several tests call `check()`, which ...[truncated 1270 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Set `TOKEN_OPTIMIZER_MEMORY_DIR` to a temporary directory before importing `session_guard`. 2. Prefer dependency injection: pass the state path into `load_state()`, `save_state()`, `reset_state()`, and `check()` rather than binding it globally at import time. 3. Use `tempfile.TemporaryDirectory` or pytest's `tmp_path` fixture for each test. 4. Restore any modified environment variables in teardown or use `unittest.mock.patch.dict`. 5. Add a safety check that refuses to run destructive tests when the resolved state path is inside the user's real OpenClaw directory. 6. Add a regression test asserting that no file outside the temporary test directory is created or modified. ]]>

T08 · Insecure Dependencies

Note
Location
requirements.txt:1
Finding
Unbounded and Unhashed Third-Party Dependency<![CDATA[ ## Vulnerability Details **File Location**: `requirements.txt:1` **Vulnerability Type**: Non-reproducible dependency resolution and supply-chain exposure **Risk Level**: Low ### Vulnerable Code ```text openai>=1.0.0 ``` ### Technical Analysis The dependency declaration specifies only a minimum version. Any future release satisfying the constraint may be installed, including versions not reviewed or tested by the project. No lockfile or package hashes are supplied to verify the exact artifact. The package name is the expected official `openai` package, and the audited project contains no evidence of intentional dependency confusion or typosquatting. The issue is therefore an avoidable supply-chain and reproducibility weakness rather than evidence of a malicious dependency. ### Attack Path 1. A user runs `pip install -r requirements.txt`. 2. The package index resolves the newest available version satisfying `>=1.0.0`. 3. That version may contain an incompatible change, a newly introduced vulnerability, or a compromised release. 4. The dependency executes with the same user privileges as the Skill when imported and used. 5. Any malicious or vulnerable behavior in that installed release can affect files, environment data, network requests, and credentials accessible to the process. ### Impact Assessment A compromised dependency would execute with the privileges of the user running the Skill and could access the API credential passed to the OpenAI client, session contents, and other user-readable resources. The likelihood attributable to this project is limited because it references the expected package name from a normal package source. The primary confirmed impact is loss of build reproducibility and inability to guarantee that installations use an audited dependency version. ]]>
Remediation
<![CDATA[ ## Remediation Suggestions 1. Pin the dependency to a reviewed exact version, for example `openai==<reviewed-version>`. 2. Generate and commit a lockfile appropriate to the installation workflow. 3. Use hash checking, such as pip requirements with `--hash` entries and `--require-hashes`. 4. Update dependencies through a controlled review process with compatibility and security testing. 5. Use a trusted package index and prevent fallback to untrusted or user-controlled indexes in production installation instructions. ]]>
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
  • Tool MisuseTool Parameter Abuse, Chaining Abuse, Unsafe Defaults
  • Taint TrackingDirect Taint Flow, Variable-Mediated Taint Flow, Credential Exfiltration Chain
Findings (35)

Tool Parameter Abuse

High
Category
Tool Misuse
Content
```bash
# 删除技能目录
rm -rf ~/.openclaw/workspace/skills/token-optimizer

# 可选:删除记忆文件
rm -rf ~/.openclaw/memory
Confidence
90% 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).

Tool Parameter Abuse

High
Category
Tool Misuse
Content
```bash
# 删除技能目录
rm -rf ~/.openclaw/workspace/skills/token-optimizer

# 可选:删除记忆文件
rm -rf ~/.openclaw/memory
Confidence
90% 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).

Missing User Warnings

High
Confidence
98% confidence
Finding
The uninstall instructions include deletion of `~/.openclaw/memory`, which the document earlier states is a global memory directory shared by OpenClaw rather than being scoped to this skill. Removing that path can destroy unrelated user data and session history, and the warning is only marked as optional rather than clearly describing the data-loss consequences.

Tool Parameter Abuse

High
Category
Tool Misuse
Content
rm -rf ~/.openclaw/workspace/skills/token-optimizer

# 可选:删除记忆文件
rm -rf ~/.openclaw/memory
```

## 获取帮助
Confidence
99% confidence
Finding
This duplicate finding correctly identifies a high-risk deletion command aimed at a global application directory rather than the skill itself. Because the documentation notes that memory is stored globally under `~/.openclaw/memory/`, the uninstall step can cause substantial unintended data loss beyond this skill's footprint.

Tool Parameter Abuse

High
Category
Tool Misuse
Content
rm -rf ~/.openclaw/workspace/skills/token-optimizer

# 可选:删除记忆文件
rm -rf ~/.openclaw/memory
```

## 获取帮助
Confidence
99% confidence
Finding
This duplicate finding correctly identifies a high-risk deletion command aimed at a global application directory rather than the skill itself. Because the documentation notes that memory is stored globally under `~/.openclaw/memory/`, the uninstall step can cause substantial unintended data loss beyond this skill's footprint.

Natural-Language Policy Violations

Medium
Confidence
86% confidence
Finding
All user-facing instructions in the file are presented in Chinese, and there is no indication that the skill is region-specific or that alternative language documentation is available. This can violate language or locale policy when users are not given an explicit language choice.

File System Enumeration

Medium
Category
Data Exfiltration
Content
python3 scripts/status.py

# 查看记忆目录
ls -la ~/.openclaw/memory/
```

## 使用示例
Confidence
60% confidence
Finding
Code scans file system directories looking for sensitive files. This could be reconnaissance for credential theft.

Sudo/Root Execution

Medium
Category
Privilege Escalation
Content
如果看到权限警告:

```bash
chmod 600 ~/.openclaw/config.json
```

### 问题4:测试失败
Confidence
80% confidence
Finding
Commands invoke sudo or root privileges. Verify this elevated access is necessary and justified.

Missing User Warnings

Medium
Confidence
91% confidence
Finding
The README promotes automatic compression and persistent memory storage as core features without warning that user conversation history may be modified, reduced, and stored outside the skill directory. In a tool that operates on session context, failing to disclose persistence and mutation of user data can lead to unintended data loss, privacy issues, and user surprise during normal use.

Missing User Warnings

Medium
Confidence
95% confidence
Finding
The usage section includes a dry-run and then an actual compression command that saves changes, but it does not clearly warn that compression may irreversibly reduce session context fidelity or overwrite the latest summary state. Users may execute the command expecting a safe optimization step, when it actually alters persisted memory and future agent behavior.

Missing User Warnings

Medium
Confidence
95% confidence
Finding
The skill explicitly states that session compression will run automatically and silently, while also describing writes to global memory files under ~/.openclaw/memory/. Silent modification of persistent conversation summaries can change what future sessions load without the user noticing, creating risks of unintended data retention, context tampering, or leakage of sensitive information into long-lived memory.

Natural-Language Policy Violations

Medium
Confidence
95% confidence
Finding
The natural-language description forces a specific language presentation in the manifest metadata. Under the policy, locale or language restrictions should either offer user opt-in or be clearly justified as region-specific, neither of which is present here.

Context-Inappropriate Capability

Medium
Confidence
94% confidence
Finding
The script loads API credentials from local configuration/environment and uses them to send session summary content to a remote LLM service. Even if this is the intended feature, it creates a real data-exposure boundary because potentially sensitive local session data is transmitted off-host without strong scoping, redaction, or explicit consent at the point of use.

External Transmission

Medium
Category
Data Exfiltration
Content
# 提取 AI 配置
                if 'ai' in openclaw_config:
                    ai_config = openclaw_config['ai']
                    config['api_url'] = ai_config.get('baseURL', 'https://api.openai.com/v1')
                    config['api_key'] = ai_config.get('apiKey', '')
                    config['model'] = ai_config.get('model', 'gpt-4')
                elif 'llm' in openclaw_config:
Confidence
60% confidence
Finding
Data is being sent to an external URL. This could be legitimate telemetry or data exfiltration. Manual review is recommended.

External Transmission

Medium
Category
Data Exfiltration
Content
# 提取 AI 配置
                if 'ai' in openclaw_config:
                    ai_config = openclaw_config['ai']
                    config['api_url'] = ai_config.get('baseURL', 'https://api.openai.com/v1')
                    config['api_key'] = ai_config.get('apiKey', '')
                    config['model'] = ai_config.get('model', 'gpt-4')
                elif 'llm' in openclaw_config:
Confidence
60% confidence
Finding
Data is being sent to an external URL. This could be legitimate telemetry or data exfiltration. Manual review is recommended.

External Transmission

Medium
Category
Data Exfiltration
Content
# 提取 AI 配置
                if 'ai' in openclaw_config:
                    ai_config = openclaw_config['ai']
                    config['api_url'] = ai_config.get('baseURL', 'https://api.openai.com/v1')
                    config['api_key'] = ai_config.get('apiKey', '')
                    config['model'] = ai_config.get('model', 'gpt-4')
                elif 'llm' in openclaw_config:
Confidence
60% confidence
Finding
Data is being sent to an external URL. This could be legitimate telemetry or data exfiltration. Manual review is recommended.

External Transmission

Medium
Category
Data Exfiltration
Content
# 提取 AI 配置
                if 'ai' in openclaw_config:
                    ai_config = openclaw_config['ai']
                    config['api_url'] = ai_config.get('baseURL', 'https://api.openai.com/v1')
                    config['api_key'] = ai_config.get('apiKey', '')
                    config['model'] = ai_config.get('model', 'gpt-4')
                elif 'llm' in openclaw_config:
Confidence
60% confidence
Finding
Data is being sent to an external URL. This could be legitimate telemetry or data exfiltration. Manual review is recommended.

Sudo/Root Execution

Medium
Category
Privilege Escalation
Content
# 检查是否其他用户可读(权限过于宽松)
        if file_mode & stat.S_IROTH:
            print(f'[警告] 配置文件 {filepath} 权限过于宽松(其他用户可读)')
            print(f'       建议执行: chmod 600 {filepath}')
    except Exception:
        pass  # 权限检查失败不影响主流程
Confidence
80% confidence
Finding
Commands invoke sudo or root privileges. Verify this elevated access is necessary and justified.

Missing User Warnings

Medium
Confidence
89% confidence
Finding
The code removes backup files in `cleanup_old_backups` and later writes a new `latest-summary.md`, changing persistent local state. While there are status prints for backup and completion, there is no clear up-front disclosure in the tool description/help that running the command will overwrite the latest summary and automatically delete backups older than 7 days.

Missing User Warnings

Medium
Confidence
96% confidence
Finding
The code sends full session content to an external AI API but does not present a clear runtime warning that local data will leave the machine. Users may reasonably assume a summarization utility operates locally, so the absence of explicit disclosure increases the risk of unintentional leakage of secrets, personal data, or internal project details.

Ssd 3

Medium
Confidence
85% confidence
Finding
The compression prompt explicitly tells the model to retain key configuration, paths, validated solutions, lessons learned, and important decisions in a persistent summary. That increases the chance that sensitive operational details, environment structure, or security-relevant context are preserved long-term and possibly transmitted to a third party during compression.

Natural-Language Policy Violations

Medium
Confidence
94% confidence
Finding
This code file contains natural-language instructions, docstrings, and command usage text exclusively in Chinese, which can force a specific language experience on users. The policy allows locale constraints only when they are documented and justified or when users are given a choice, neither of which is present here.

Natural-Language Policy Violations

Medium
Confidence
96% confidence
Finding
This Python file's docstring, CLI descriptions, and printed guidance are entirely in Chinese, and the header states the agent should call this script before every reply. That creates a natural-language locale constraint without any opt-in, fallback, or justification that the skill is intended only for a Chinese-speaking environment.

Tainted flow: 'STATE_FILE' from os.getenv (line 22, credential/environment) → open (file write)

Medium
Category
Data Flow
Content
def save_state(state: dict):
    """保存会话状态"""
    os.makedirs(SESSIONS_DIR, exist_ok=True)
    with open(STATE_FILE, 'w', encoding='utf-8') as f:
        json.dump(state, f, ensure_ascii=False, indent=2)
Confidence
90% confidence
Finding
The script builds MEMORY_DIR from the TOKEN_OPTIMIZER_MEMORY_DIR environment variable and then writes state to STATE_FILE under that path without validation. If an attacker can influence the environment in which the agent runs, they can redirect writes to an arbitrary filesystem location the process can access, causing unintended file creation or overwrite and potentially corrupting other application state.

Natural-Language Policy Violations

Medium
Confidence
96% confidence
Finding
The module docstring and user-facing descriptions are entirely in Chinese, including the usage/help text shown to users. This imposes a specific language/locale without opt-in or justification, which matches the policy category for language or locale violations.

Static analysis

Detected: suspicious.destructive_delete_command

Documentation contains a destructive delete command without an explicit confirmation gate.

Warn
Code
suspicious.destructive_delete_command
Location
INSTALL.md:129