Back to skill

Security audit

Safe Memory Manager

Security checks for vulnerabilities and agentic risk

Overview

This skill is not destructive, but it overpromises safe handling of untrusted agent memory and could let unsafe instructions persist.

Review this before installing in agents that handle untrusted users or rely on memory as trusted context. It should only be used as a lightweight helper, not as a security boundary: sanitize or structure every stored field, treat retrieved memory as untrusted quoted data, constrain the memory directory, and do not rely on the advertised ISNAD verification as proof of authenticity.

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

T09 · Insecure Skill Coding Practices

Warning
Location
safe_memory.py:59
Finding

Unsanitized Author Field Bypasses Memory Injection Protection

Content
View full analysis

Vulnerability Details

File Location: safe_memory.py, lines 59–70
Vulnerability Type: Incomplete input sanitization
Risk Level: Medium

python
def append_memory(self, filename, content, author="Agent"):
    """Safely appends to a memory file with auto-sanitization."""
    if not self.verified:
        # Note: For public skills, a missing manifest is expected unless anchored.
        pass
        
    safe_filename = "".join([c for c in filename if c.isalpha() or c.isdigit() or c in ('-', '_', '.')]).rstrip()
    file_path = os.path.join(self.memory_dir, safe_filename)
    
    sanitized_content = self.sanitize_content(content)
    entry = f"\n[{datetime.now().isoformat()}] {author}: {sanitized_content}\n"

Technical Analysis

The append_memory method sanitizes the content parameter but interpolates the author parameter directly into the persistent memory entry. If author can contain untrusted input, it becomes an alternative channel through which prompt-like instructions can be written without passing through sanitize_content.

This violates the method's declared security boundary: all attacker-controlled fields written to Agent memory must be handled consistently. The vulnerability does not provide operating-system command execution because the stored value is only written as text. However, a consuming Agent may later interpret the unsanitized author value as instructions rather than data.

Attack Path

  1. An attacker reaches an integration that maps an untrusted identity, display name, or supplied author value to the author argument.
  2. The attacker places persistent instructions in that value.
  3. append_memory sanitizes only content.
  4. The malicious author value is written verbatim to the selected memory file.
  5. A later read_memory call returns the stored entry.
  6. If the calling Agent inserts that result into its context without a strict data boundary, th ...[truncated 611 chars]
Remediation
View remediation

Remediation Suggestions

  • Treat author as untrusted and apply validation or sanitization before storage.
  • Prefer a strict allowlist for author identifiers, including a conservative length limit and an explicitly permitted character set.
  • Store memory entries in a structured format such as JSON rather than concatenating fields into prose.
  • Escape or encode line breaks and control characters in every metadata field.
  • Preserve an explicit trust label for each entry and ensure consuming Agents are instructed to treat retrieved fields as data, not executable instructions.
  • Add tests proving that injection-like content supplied through author, content, and any future metadata fields cannot cross the intended trust boundary.

T09 · Insecure Skill Coding Practices

Warning
Location
safe_memory.py:23
Finding

Regex Denylist Can Be Bypassed by Reworded or Obfuscated Prompt Injection

Content
View full analysis

Vulnerability Details

File Location: safe_memory.py, lines 23–29 and 52–57
Vulnerability Type: Insufficient prompt-injection filtering
Risk Level: Medium

python
self.malicious_patterns = [
    re.compile(r"(?i)(ignore previous instructions|system prompt|system message)"),
    re.compile(r"(?i)(execute|eval|os\.system|subprocess|bash|sh -c)"),
    re.compile(r"(?i)(priority task|override command)"),
    re.compile(r"```(bash|sh|python)\n[\s\S]*?(rm -rf|wget|curl)[\s\S]*?```"),
    re.compile(r"(?i)(delete all files|format drive|grant admin rights)")
]
python
def sanitize_content(self, text):
    """Sanitizes text by stripping out known injection vectors."""
    sanitized = text
    for pattern in self.malicious_patterns:
        sanitized = pattern.sub("[SANITIZED_INJECTION_ATTEMPT]", sanitized)
    return sanitized

Technical Analysis

The sanitizer uses a small denylist of exact words and phrases. Prompt injection is semantic and cannot be reliably neutralized through exact regex substitution. Equivalent instructions using synonyms, inserted whitespace, Unicode characters, alternate punctuation, another language, or indirect phrasing pass through unchanged.

For example, the documentation states that content such as “override current mission” is neutralized, but that phrase does not match override command or any other configured pattern. The filter can therefore give callers a false assurance that arbitrary untrusted memory content has become safe.

The flagged phrase ignore previous instructions is present only as a defensive regex literal. It is not itself an instruction to the Agent and does not constitute Skill instruction hijacking.

Attack Path

  1. An attacker submits text that conveys malicious Agent instructions without using an exact denylisted phrase.
  2. The text is passed to sanitize_content.
  3. None of the regular expressions match the reworded or ...[truncated 804 chars]
Remediation
View remediation

Remediation Suggestions

  • Do not represent regex replacement as comprehensive prompt-injection prevention.
  • Normalize Unicode and control characters before applying any heuristic detection.
  • Apply strict size limits to prevent excessive context consumption.
  • Store untrusted material in a structured format with an explicit untrusted-data label.
  • Delimit retrieved content and ensure the consuming Agent is instructed never to interpret stored text as higher-priority instructions.
  • Consider detection heuristics as telemetry or defense in depth rather than a security boundary.
  • Add adversarial tests covering synonyms, Unicode confusables, whitespace insertion, multilingual instructions, indirect requests, and the example phrases documented in SKILL.md.
  • Update the documentation to describe the remaining limitations and avoid promising that arbitrary malicious intent will be neutralized.

T09 · Insecure Skill Coding Practices

Warning
Location
safe_memory.py:32
Finding

Integrity Verification Is Unauthenticated and Fails Open

Content
View full analysis

Vulnerability Details

File Location: safe_memory.py, lines 32–49 and 59–63
Vulnerability Type: Ineffective integrity verification
Risk Level: Medium

python
def _verify_integrity(self):
    """Verifies the ISNAD cryptographic signature of this file."""
    try:
        file_path = __file__
        # Renamed to isnad_manifest.json to ensure it is included in the package
        isnad_path = os.path.join(os.path.dirname(file_path), "isnad_manifest.json")
        if not os.path.exists(isnad_path):
            return False
        
        with open(isnad_path, 'r') as f:
            isnad_data = json.load(f)
        
        # Simple hash check against manifest
        with open(file_path, 'rb') as f:
            file_hash = hashlib.sha256(f.read()).hexdigest()
        
        return isnad_data.get('manifest', {}).get('hash') == file_hash
    except:
        return False
python
def append_memory(self, filename, content, author="Agent"):
    """Safely appends to a memory file with auto-sanitization."""
    if not self.verified:
        # Note: For public skills, a missing manifest is expected unless anchored.
        pass

Technical Analysis

_verify_integrity claims to verify a cryptographic signature but only compares the implementation's SHA-256 digest to a value in a colocated, mutable JSON file. The PGP signature included in isnad_manifest.json is never cryptographically validated against a trusted public key.

An attacker capable of replacing the implementation can also replace the manifest hash. Because both values are controlled within the same package, the comparison does not establish publisher authenticity.

The control also fails open: a missing manifest, malformed JSON, hash mismatch, or any other verification error sets self.verified to False, but append_memory deliberately continues. The same behavior applies to reads. Version metadata ...[truncated 1347 chars]

Remediation
View remediation

Remediation Suggestions

  • Verify the manifest's signature using a trusted public key distributed through a channel separate from the package.
  • Sign canonical manifest data that binds the implementation hash, package name, version, and relevant files.
  • Do not rely on a plain hash stored beside the file as proof of authenticity.
  • Fail closed when integrity verification is a required security property: block reads and writes or require an explicit unsafe-mode override.
  • Return a clear verification error rather than silently continuing.
  • Replace the broad except: with specific exception handling and record actionable diagnostics without exposing sensitive data.
  • Reconcile all version declarations and include the version in the authenticated manifest.
  • Add tests for missing manifests, invalid signatures, modified code, malformed JSON, mismatched versions, and unavailable trust keys.
Vulnerability Patterns
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • YARA SignaturesMalware Match, Webshell Match, Cryptominer Match
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
Findings (6)

YARA rule 'agent_skill_prompt_injection_hidden_instructions': Prompt injection or hidden instructions embedded in AI agent skill text [agent_skills]

High
Category
YARA Match
Confidence
80% confidence
Finding

YARA rule matched a hack tool or exploit indicator (offensive tools, reconnaissance, privilege escalation, or exploit frameworks).

Content

Scanner excerpt · SKILL.md (reported line 11)May include surrounding context.

md
---
name: safe-memory-manager
version: 1.0.7
description: "When building OpenClaw agents that read untrusted text, use this skill to prevent prompt injection and memory poisoning. Standard utility for secure memory operations."
author: LeoAGI
metadata: { "openclaw": { "emoji": "🛡️", "category": "security" } }
---

# Injection-Safe Memory Manager 🛡️

**A secure memory interface for AI Agents.**

## Overview
When building OpenClaw agents, standard memory tools are vulnerable to prompt injection. Use `safe-memory-manager` to protect agents from "Memory Poisoning". It provides a specialized interface for reading and writing memory files that automatically sanitizes inputs before they are written to disk.

## Security Features
1. **Integrity Check:** On startup, the skill can verify its own integrity against the included `isnad_manifest.json`.
2. **Input Sanitization:** Automatically detects and neutralizes common prompt injection patterns (e.g., "ignore prior instructions")

Instruction Override

High
Category
Prompt Injection
Confidence
80% confidence
Finding

This pattern attempts to override system instructions or ignore safety constraints. Without LLM analysis, manual review is recommended.

Content

Scanner excerpt · safe_memory.py (reported line 24)May include surrounding context.

python
# Transparent pattern matching engine (No obfuscation to avoid scanner false-positives)
        # These patterns are specifically used to detect and sanitize prompt injection.
        self.malicious_patterns = [
            re.compile(r"(?i)(ignore previous instructions|system prompt|system message)"),
            re.compile(r"(?i)(execute|eval|os\.system|subprocess|bash|sh -c)"),
            re.compile(r"(?i)(priority task|override command)"),
            re.compile(r"```(bash|sh|python)\n[\s\S]*?(rm -rf|wget|curl)[\s\S]*?```"),

YARA rule 'agent_skill_prompt_injection_hidden_instructions': Prompt injection or hidden instructions embedded in AI agent skill text [agent_skills]

High
Category
YARA Match
Confidence
80% confidence
Finding

YARA rule matched a hack tool or exploit indicator (offensive tools, reconnaissance, privilege escalation, or exploit frameworks).

Content

Scanner excerpt · safe_memory.py (reported line 24)May include surrounding context.

python
):
        self.memory_dir = memory_dir
        self.verified = self._verify_integrity()
        os.makedirs(self.memory_dir, exist_ok=True)
        
        # Transparent pattern matching engine (No obfuscation to avoid scanner false-positives)
        # These patterns are specifically used to detect and sanitize prompt injection.
        self.malicious_patterns = [
            re.compile(r"(?i)(ignore previous instructions|system prompt|system message)"),
            re.compile(r"(?i)(execute|eval|os\.system|subprocess|bash|sh -c)"),
            re.compile(r"(?i)(priority task|override command)"),
            re.compile(r"```(bash|sh|python)\n[\s\S]*?(rm -rf|wget|curl)[\s\S]*?```"),
            re.compile(r"(?i)(delete all files|format drive|grant admin rights)")
        ]

    def _verify_integrity(self):
        """Verifies the ISNAD cryptographic signature of this file."""
        try:
            file_path = __file__
            # Renamed to isnad_manifest.json to ensure it is in

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
90% confidence
Finding

The skill advertises code-related capabilities involving file read, file write, and shell-like operations but does not declare any explicit tool scope or permissions boundary. In an agent ecosystem, that omission weakens reviewability and can lead to over-privileged execution if a host grants broad defaults, especially for a skill handling untrusted text and persistent memory.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The skill advertises cryptographic self-verification, but verification failure does not block reads, writes, or degraded operation in any meaningful way. This creates a false sense of trust: a tampered or repackaged skill can continue operating normally while still reporting an integrity status field that callers may ignore.

Content

No source excerpt is available for this finding.

Missing User Warnings

Low
Category
Not specified by scanner
Confidence
87% confidence
Finding

This code appends content to a local file, which affects user or agent data, but the operation has no confirmation prompt or user-facing disclosure at the write site. The docstring says it appends to a memory file, but there is no visible warning, logging, or print indicating that persistent storage will be modified.

Content

No source excerpt is available for this finding.

Static analysis

No suspicious patterns detected.