Back to skill

Security audit

OpenClaw Self Analyzer - 自分析工具

Security checks for vulnerabilities and agentic risk

Overview

This OpenClaw analyzer is mostly coherent, but its generated hooks can log complete agent context and its write behavior is not clearly scoped, so it needs review before use.

Install only if you are comfortable reviewing and editing the generated hooks before enabling them. Remove full-context logging, validate hook names and output paths, and run the analyzer in a version-controlled or disposable workspace so generated files are easy to inspect and undo.

Vulnerability Patterns
  • Tool Hijacking and SpoofingModifies or replaces tools so legitimate-looking calls execute attacker logic
  • 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 (3)

T09 · Insecure Skill Coding Practices

Warning
Location
generators/hook_generator.py:111
Finding
Generated hooks expose complete pipeline contexts through logging<![CDATA[ ## Vulnerability Details **File Location**: `generators/hook_generator.py`, lines 111-118; generated instances appear at line 8 of every file under `generated_hooks/` **Vulnerability Type**: Sensitive information exposure through logging **Risk Level**: Medium ### Vulnerable Code ```python for stage_name, stage_info in self.architecture['pipeline'].items(): # Generate one sample pre-hook for each stage hook = self.generate_hook_package( hook_name=f"pre_{stage_name}_custom", hook_type='pre', stage=stage_name, logic='// Custom pre-processing logic\nconsole.log("Pre-processing:", context);' ) hooks.append(hook) ``` This produces hooks containing: ```javascript async function pre_llm_submit_custom(context, next) { // Your pre-processing logic here // Custom pre-processing logic console.log("Pre-processing:", context); // Call next stage await next(context); } ``` The same logging behavior is present in these generated files: - `generated_hooks/pre_input_receive_custom.js:8` - `generated_hooks/pre_context_gather_custom.js:8` - `generated_hooks/pre_memory_retrieve_custom.js:8` - `generated_hooks/pre_prompt_assemble_custom.js:8` - `generated_hooks/pre_token_check_custom.js:8` - `generated_hooks/pre_context_compress_custom.js:8` - `generated_hooks/pre_llm_submit_custom.js:8` - `generated_hooks/pre_response_process_custom.js:8` - `generated_hooks/pre_memory_store_custom.js:8` ### Technical Analysis The generator creates pre-hooks for security-sensitive stages and configures each hook to log the complete `context` object. Depending on the OpenClaw runtime's context structure, this object may contain user input, conversation history, retrieved memory, assembled prompts, model requests, model responses, tool arguments, or authentication-related metadata. Logging the entire object violates data-minimization principles. Console output may be captured by process supervisors, containers, ...[truncated 1710 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Remove full-context logging from the default generated hook: ```python logic='// Add custom pre-processing logic here.' ``` 2. If diagnostic logging is necessary, log only fixed event names and explicitly allowlisted metadata: ```javascript console.log("Pre-processing stage entered", { stage: "llm_submit", requestId: context.requestId }); ``` 3. Never log message content, prompts, memory records, tool arguments, authorization headers, API keys, cookies, or tokens. 4. Add a centralized redaction function that recursively removes sensitive fields before structured objects reach any logger. 5. Make debugging logs opt-in and disabled by default in production. 6. Document log sensitivity, access controls, and retention requirements. 7. Remove or regenerate the existing files under `generated_hooks/` so already generated unsafe hooks are not accidentally deployed. ]]>

T09 · Insecure Skill Coding Practices

Warning
Location
generators/hook_generator.py:122
Finding
Unsanitized hook names allow writes outside the selected output directory<![CDATA[ ## Vulnerability Details **File Location**: `generators/hook_generator.py`, lines 83-100 and 122-132 **Vulnerability Type**: Path traversal and unsafe executable-code generation **Risk Level**: Medium ### Vulnerable Code ```python def generate_hook_package(self, hook_name: str, hook_type: str, stage: str, logic: str) -> Dict[str, str]: """Generate a complete hook package""" if hook_type == 'pre': code = self.generate_pre_hook(stage, hook_name, logic) elif hook_type == 'post': code = self.generate_post_hook(stage, hook_name, logic) elif hook_type == 'replace': code = self.generate_replace_hook(stage, hook_name, logic) else: raise ValueError(f"Unknown hook type: {hook_type}") return { 'name': hook_name, 'type': hook_type, 'stage': stage, 'code': code, 'generated_at': str(datetime.now()) } ``` ```python def save_hooks(self, hooks: List[Dict], output_dir: Path): """Save hooks to files""" output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) for hook in hooks: file_name = f"{hook['name']}.js" file_path = output_dir / file_name with open(file_path, 'w') as f: f.write(hook['code']) ``` ### Technical Analysis The public generation API accepts `hook_name` without validating that it is a JavaScript identifier or a safe filename. `save_hooks()` subsequently concatenates the name with `.js` and joins it to `output_dir`. A name containing parent-directory components, such as `../../target`, produces a path outside the intended output directory. An absolute name can also cause `pathlib` path composition to disregard the configured output directory. If the resolved destination exists or its parent directory exists and is writable, `open(..., 'w')` truncates and replaces the target file. The name is additionally inserted directly into JavaScript function declarations and exports: ``` ...[truncated 2031 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Validate hook names before source generation or filesystem use. Require a conservative JavaScript identifier: ```python import re HOOK_NAME_PATTERN = re.compile(r'^[A-Za-z_$][A-Za-z0-9_$]*$') def validate_hook_name(name: str) -> str: if not isinstance(name, str) or not HOOK_NAME_PATTERN.fullmatch(name): raise ValueError("Invalid hook name") return name ``` 2. Reject absolute paths, path separators, `.` and `..` components, null bytes, control characters, and platform-specific separator variants. 3. Resolve and verify every output destination: ```python base = Path(output_dir).resolve() destination = (base / f"{validated_name}.js").resolve() if destination.parent != base: raise ValueError("Hook path escapes the output directory") ``` 4. Treat `hooks` passed to `save_hooks()` as untrusted data and validate every required field again at the write boundary. 5. Avoid directly interpolating untrusted values into executable JavaScript. Use validated identifiers and safely encoded string literals where values are intended to be data. 6. Do not overwrite existing files by default. Use exclusive creation mode or require explicit overwrite authorization. 7. Add tests covering `../`, absolute paths, backslash traversal, Unicode separators, invalid identifiers, and symlink-related destination behavior. ]]>

T07 · Tool Hijacking and Spoofing

Note
Location
run.sh:7
Finding
Entry script may execute attacker-controlled relative Python files after directory-change failure<![CDATA[ ## Vulnerability Details **File Location**: `run.sh`, lines 7-18 **Vulnerability Type**: Unsafe working-directory handling and local tool spoofing **Risk Level**: Low ### Vulnerable Code ```bash cd /root/.openclaw/workspace/skills/openclaw-self-analyzer # 1. Run architecture analysis echo "1️⃣ Running architecture analysis..." python3 core/architecture_analyzer.py echo "" echo "2️⃣ Generating hooks..." python3 generators/hook_generator.py echo "" echo "3️⃣ Generating reports..." python3 reporters/report_generator.py ``` ### Technical Analysis The script attempts to change into a hard-coded installation directory but does not check the command's exit status and does not enable fail-fast shell behavior. If the directory is missing, inaccessible, or replaced with a non-directory object, execution continues from the caller's original working directory. All three Python programs are then referenced through relative paths. If the current directory contains attacker-controlled files at matching locations, the trusted-looking script executes those substitutes. This is a local tool-spoofing condition rather than command injection: the script's command text remains fixed, but failure to establish a trusted working directory changes which files the commands resolve to. ### Attack Path 1. The expected directory `/root/.openclaw/workspace/skills/openclaw-self-analyzer` is unavailable or inaccessible. 2. An attacker prepares a directory containing one or more substitute files: - `core/architecture_analyzer.py` - `generators/hook_generator.py` - `reporters/report_generator.py` 3. The victim changes into that attacker-controlled directory or launches `run.sh` while it is the current working directory. 4. The initial `cd` command fails. 5. Because the script does not stop, `python3` resolves the relative paths against the attacker-controlled current directory. 6. The substitute Python code executes with the victim's existing privileges. ### Impa ...[truncated 534 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Enable strict shell behavior at the beginning of the script: ```bash #!/usr/bin/env bash set -euo pipefail ``` 2. Stop explicitly if the directory change fails: ```bash cd -- /root/.openclaw/workspace/skills/openclaw-self-analyzer || { echo "Unable to enter the trusted project directory" >&2 exit 1 } ``` 3. Prefer resolving the directory containing the script instead of relying on a hard-coded deployment path: ```bash SCRIPT_DIR="$( cd -- "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 pwd -P )" cd -- "$SCRIPT_DIR" ``` 4. Invoke scripts through verified absolute paths: ```bash python3 "$SCRIPT_DIR/core/architecture_analyzer.py" python3 "$SCRIPT_DIR/generators/hook_generator.py" python3 "$SCRIPT_DIR/reporters/report_generator.py" ``` 5. Verify that the resolved project directory and executable files are not writable by untrusted users before privileged execution. ]]>
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Memory PoisoningPersistent Context Injection, Context Window Stuffing, Memory Manipulation
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
Findings (20)

Memory Manipulation

High
Category
Memory Poisoning
Content
"replace": {
            "function": "replace_context_gather",
            "signature": "async replace_context_gather(context, next) => {...}",
            "description": "Hook point: replace context_gather"
          }
        }
      },
Confidence
85% confidence
Finding
Skill manipulates agent memory, state, or stored context. Memory corruption can alter personality, override safety rules, or cause unpredictable behavior.

Memory Manipulation

High
Category
Memory Poisoning
Content
"replace": {
            "function": "replace_context_gather",
            "signature": "async replace_context_gather(context, next) => {...}",
            "description": "Hook point: replace context_gather"
          }
        }
      },
Confidence
85% confidence
Finding
Skill manipulates agent memory, state, or stored context. Memory corruption can alter personality, override safety rules, or cause unpredictable behavior.

Memory Manipulation

High
Category
Memory Poisoning
Content
"replace": {
            "function": "replace_memory_retrieve",
            "signature": "async replace_memory_retrieve(context, next) => {...}",
            "description": "Hook point: replace memory_retrieve"
          }
        }
      },
Confidence
85% confidence
Finding
Skill manipulates agent memory, state, or stored context. Memory corruption can alter personality, override safety rules, or cause unpredictable behavior.

Memory Manipulation

High
Category
Memory Poisoning
Content
"replace": {
            "function": "replace_memory_retrieve",
            "signature": "async replace_memory_retrieve(context, next) => {...}",
            "description": "Hook point: replace memory_retrieve"
          }
        }
      },
Confidence
85% confidence
Finding
Skill manipulates agent memory, state, or stored context. Memory corruption can alter personality, override safety rules, or cause unpredictable behavior.

Natural-Language Policy Violations

Medium
Confidence
93% confidence
Finding
The natural-language documentation is entirely in Chinese, with no indication that users may choose another language or that the skill is intended only for a Chinese-speaking audience. Under the language/locale policy, forcing a specific language without user opt-in is a policy concern.

Missing User Warnings

Medium
Confidence
90% confidence
Finding
The skill explicitly advertises automatic hook generation and report saving, both of which can write files into the workspace, but it does not warn users that running these actions may modify project state. In a tool that targets architecture analysis and extension generation, undocumented write behavior increases the risk of unintended code or artifact creation and makes misuse or accidental execution more dangerous.

Natural-Language Policy Violations

Medium
Confidence
95% confidence
Finding
This Python file contains natural-language descriptions such as the module docstring and later console output in Chinese only. Under the policy, forcing a specific language without user opt-in is a locale/language policy violation unless the constraint is explicitly justified.

Natural-Language Policy Violations

Medium
Confidence
94% confidence
Finding
The script prints progress and status messages only in Chinese during execution. Because this affects runtime interaction and no language selection or justification is provided, it violates the language/locale policy for natural-language content in code.

Intent-Code Divergence

Medium
Confidence
92% confidence
Finding
The code synthesizes hook points for every detected or inferred stage and then emits them with concrete file and line metadata, which can mislead downstream users into believing those hooks were actually discovered in the target codebase. In a security or architecture context, fabricated analysis results can drive unsafe modifications, incorrect trust decisions, or conceal the fact that no real hook exists at that location.

Missing User Warnings

Medium
Confidence
96% confidence
Finding
The hook logs the entire `context` object before passing control onward, which can expose sensitive user input, credentials, tokens, prompts, or other internal state to application logs. Because this is a pre-input hook, it is positioned to capture raw inbound data broadly, making accidental data leakage more likely across many requests.

Missing User Warnings

Medium
Confidence
97% confidence
Finding
The hook logs the entire `context` object before submitting to the next stage, which can expose prompts, user inputs, credentials, tokens, or other sensitive runtime metadata to logs. In an LLM pre-submit hook, this is more dangerous because `context` commonly contains raw user content and operational secrets, and logs are often broadly accessible and retained.

Missing User Warnings

Medium
Confidence
95% confidence
Finding
The hook logs the entire `context` object before a memory retrieval operation, which may contain prompts, user data, system instructions, tokens, or other sensitive runtime state. Even if intended for debugging, broad context logging can expose confidential information to logs, log processors, or operators without any minimization or redaction.

Missing User Warnings

Medium
Confidence
96% confidence
Finding
The hook logs the entire `context` object, which commonly contains prompts, user inputs, tokens, credentials, conversation state, or other sensitive runtime data. Writing this wholesale to logs can create an unintended disclosure channel, especially if logs are retained, centralized, or accessible to operators and downstream systems.

Natural-Language Policy Violations

Medium
Confidence
94% confidence
Finding
Multiple natural-language elements in the file, including the module docstring and runtime status messages, are presented exclusively in Chinese. Under the stated policy, forcing a specific language without offering a user choice is a natural-language policy violation.

Missing User Warnings

Medium
Confidence
91% confidence
Finding
This Python code creates directories and writes multiple files under the configured output path, but provides no prompt, cautionary comment, or docstring warning that it will modify the filesystem. Although it prints a count after saving, that disclosure happens only after the writes and does not warn the user beforehand.

Natural-Language Policy Violations

Medium
Confidence
93% confidence
Finding
The module docstrings and all user-facing status text are written in Chinese, indicating the skill is intended to operate in a single language. Under the policy, forcing a specific language without user opt-in or a documented regional justification is a natural-language policy concern.

Natural-Language Policy Violations

Medium
Confidence
93% confidence
Finding
This Python file contains natural-language descriptions in Chinese in the module docstring, and the same locale-specific pattern continues in user-facing print output later in the file. Because the skill does not offer language selection or explain that it is intended only for a Chinese-speaking context, it violates the language/locale policy for all file types.

Natural-Language Policy Violations

Medium
Confidence
95% confidence
Finding
The main execution path prints status and results exclusively in Chinese, which creates a locale-specific user experience regardless of user preference. The file provides no option to select another language and no documented reason for restricting runtime messaging to Chinese.

Intent-Code Divergence

Low
Confidence
96% confidence
Finding
The method is documented as analyzing 'tool implementations', which implies inspection of executable code. In practice it only scans markdown files under docs/tools and returns their stems, so the behavior contradicts the stated analysis intent.

Natural-Language Policy Violations

Low
Confidence
92% confidence
Finding
This markdown file presents all headings and guidance in Chinese, with no indication that the language is selectable or that the report is intentionally region-specific. The policy requires avoiding fixed language or locale constraints unless users can opt in or the constraint is clearly justified.

Static analysis

No suspicious patterns detected.