Back to skill

Security audit

Agent Message Bridge

Security checks for vulnerabilities and agentic risk

Overview

This skill is a coherent agent messaging bridge, but its local file handling is too broad and can read, delete, or write JSON files outside the intended message area if given crafted agent names.

Install only in a tightly controlled local environment. Do not send secrets or sensitive operational data through it, and do not let downstream agents treat received messages as trusted commands. The bridge should validate agent identifiers, constrain all paths to its own data directory, disable deletion by default, and add authentication or signatures before use in real workflows.

Vulnerability Patterns
  • Unauthorized Access and Privilege EscalationObtains permissions beyond the task's legitimate needs
  • 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

Error
Location
agent_bridge.py:24
Finding

Path Traversal Enables Arbitrary Directory Creation and JSON File Placement

Content
View full analysis

Vulnerability Details

File Location: agent_bridge.py, lines 24-49
Vulnerability Type: Unsanitized path construction and path traversal
Risk Level: High

Vulnerable Code

python
class AgentBridge:
    def __init__(self, agent_name: str):
        self.agent_name = agent_name
        self.inbox_dir = INBOX_DIR / agent_name.lower()
        self.outbox_dir = OUTBOX_DIR / agent_name.lower()
        self.inbox_dir.mkdir(parents=True, exist_ok=True)
        self.outbox_dir.mkdir(parents=True, exist_ok=True)
    
    def send_message(self, to: str, subject: str, content: str, priority: str = "normal"):
        timestamp = datetime.utcnow().strftime('%Y%m%d_%H%M%S_%f')
        msg_id = f"msg_{timestamp}"
        
        message = {
            "id": msg_id,
            "from": self.agent_name,
            "to": to,
            "timestamp": datetime.utcnow().isoformat() + 'Z',
            "priority": priority,
            "subject": subject,
            "content": content,
            "read": False
        }
        
        # Directly send to the recipient inbox
        outfile = INBOX_DIR / to.lower() / f"{msg_id}.json"
        outfile.parent.mkdir(parents=True, exist_ok=True)
        
        with open(outfile, 'w', encoding='utf-8') as f:
            json.dump(message, f, indent=2, ensure_ascii=False)

Technical Analysis

The attacker-controlled agent_name and to values are used directly as filesystem path components. The implementation neither validates their format nor resolves and verifies that the resulting paths remain below the intended bridge directory.

A value containing .. components can traverse outside INBOX_DIR or OUTBOX_DIR. With pathlib, an absolute value can also cause the intended base path to be discarded. The call to mkdir(parents=True, exist_ok=True) creates attacker-selected directories, after which send_message() places a JS ...[truncated 1553 chars]

Remediation
View remediation

Remediation Suggestions

  • Restrict agent identifiers to a conservative allowlist, such as ^[A-Za-z0-9_-]{1,64}$.

  • Reject empty identifiers, absolute paths, path separators, drive designators, null bytes, and . or .. components.

  • Resolve the intended destination before creating directories or files, then verify containment:

    python
    SAFE_NAME = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
    
    def safe_agent_directory(base: Path, name: str) -> Path:
        if not SAFE_NAME.fullmatch(name):
            raise ValueError("Invalid agent identifier")
    
        base = base.resolve()
        destination = (base / name.lower()).resolve()
        if destination.parent != base:
            raise ValueError("Agent directory escapes storage root")
        return destination
    
  • Use the validated helper consistently for constructor paths and recipient paths.

  • Create bridge directories with restrictive permissions and run the process under a dedicated, least-privileged account.

  • Add tests covering traversal strings, absolute paths, separators, Unicode edge cases, and excessively long identifiers.

T09 · Insecure Skill Coding Practices

Error
Location
agent_bridge.py:24
Finding

Traversal in Agent Identity Enables Arbitrary JSON File Reading and Deletion

Content
View full analysis

Vulnerability Details

File Location: agent_bridge.py, lines 24-28 and 53-66
Vulnerability Type: Path traversal leading to unauthorized file disclosure and deletion
Risk Level: High

Vulnerable Code

python
class AgentBridge:
    def __init__(self, agent_name: str):
        self.agent_name = agent_name
        self.inbox_dir = INBOX_DIR / agent_name.lower()
        self.outbox_dir = OUTBOX_DIR / agent_name.lower()
        self.inbox_dir.mkdir(parents=True, exist_ok=True)
        self.outbox_dir.mkdir(parents=True, exist_ok=True)
python
    def check_messages(self, delete_read: bool = True):
        messages = []
        if not self.inbox_dir.exists():
            return messages
        
        for f in self.inbox_dir.glob('*.json'):
            try:
                with open(f, 'r', encoding='utf-8') as fp:
                    msg = json.load(fp)
                    messages.append(msg)
                if delete_read:
                    f.unlink()
            except Exception as e:
                print(f"读取消息失败:{e}")
        
        return messages

Technical Analysis

The constructor derives self.inbox_dir directly from an untrusted agent_name. Because no identifier validation or resolved-path containment check is performed, a caller can redirect the inbox to another directory through traversal components or an absolute path.

check_messages() then enumerates every *.json file in that directory. Each successfully parsed file is returned to the caller and deleted by default because delete_read defaults to True. The deletion is not restricted to bridge-created files, known message identifiers, or files owned by the selected agent.

This combines an unsafe path with a destructive default operation, producing both confidentiality and integrity risks.

Attack Path

  1. An attacker with the ability to import or execute the module identi ...[truncated 1209 chars]
Remediation
View remediation

Remediation Suggestions

  • Validate agent_name with a strict allowlist and reject all path syntax.
  • Resolve self.inbox_dir and verify that it is an immediate child of the canonical INBOX_DIR.
  • Change delete_read to default to False.
  • Replace deletion-on-read with an explicit acknowledgement operation that accepts a validated message identifier.
  • Maintain an internal index of bridge-created messages and only permit deletion of indexed files belonging to the authenticated recipient.
  • Before deletion, verify that the target is a regular file, is not a symbolic link, has the expected ownership, and remains under the canonical inbox.
  • Use atomic file operations and restrictive directory permissions.
  • Separate read and delete privileges where the deployment environment permits it.

T05 · Unauthorized Access and Privilege Escalation

Warning
Location
agent_bridge.py:24
Finding

Missing Agent Authentication and Authorization Permits Message Spoofing and Cross-Agent Access

Content
View full analysis

Vulnerability Details

File Location: agent_bridge.py, lines 24-66 and 69-75
Vulnerability Type: Missing authentication, authorization, and message integrity controls
Risk Level: Medium

Vulnerable Code

python
class AgentBridge:
    def __init__(self, agent_name: str):
        self.agent_name = agent_name
        self.inbox_dir = INBOX_DIR / agent_name.lower()
        self.outbox_dir = OUTBOX_DIR / agent_name.lower()
        self.inbox_dir.mkdir(parents=True, exist_ok=True)
        self.outbox_dir.mkdir(parents=True, exist_ok=True)
    
    def send_message(self, to: str, subject: str, content: str, priority: str = "normal"):
        timestamp = datetime.utcnow().strftime('%Y%m%d_%H%M%S_%f')
        msg_id = f"msg_{timestamp}"
        
        message = {
            "id": msg_id,
            "from": self.agent_name,
            "to": to,
            "timestamp": datetime.utcnow().isoformat() + 'Z',
            "priority": priority,
            "subject": subject,
            "content": content,
            "read": False
        }
        
        outfile = INBOX_DIR / to.lower() / f"{msg_id}.json"
        outfile.parent.mkdir(parents=True, exist_ok=True)
        
        with open(outfile, 'w', encoding='utf-8') as f:
            json.dump(message, f, indent=2, ensure_ascii=False)
    
        return {"status": "sent", "message_id": msg_id}
    
    def check_messages(self, delete_read: bool = True):
        messages = []
        if not self.inbox_dir.exists():
            return messages
        
        for f in self.inbox_dir.glob('*.json'):
            try:
                with open(f, 'r', encoding='utf-8') as fp:
                    msg = json.load(fp)
                    messages.append(msg)
                if delete_read:
                    f.unlink()
            except Exception as e:
                print(f"读取消息失败:{e}")
      
...[truncated 2545 chars]
Remediation
View remediation

Remediation Suggestions

  • Authenticate every agent using a securely provisioned identity rather than a caller-selected display name.
  • Enforce authorization rules that bind authenticated identities to their own inboxes and permitted recipients.
  • Sign messages or attach an HMAC covering all security-relevant fields, including sender, recipient, timestamp, message ID, priority, subject, and content.
  • Verify message authenticity and recipient binding before returning a message to an agent.
  • Protect against replay by using cryptographically random message identifiers, timestamps, nonces, and a replay cache.
  • Store each inbox in an access-controlled directory owned by the corresponding operating-system identity or expose storage through a broker that mediates all access.
  • Set restrictive directory and file permissions explicitly rather than relying on ambient umask.
  • Encrypt messages at rest when they may contain sensitive information.
  • Treat all message content as untrusted input and require explicit policy checks before it can trigger privileged tools or automated actions.
  • Record authenticated send, read, acknowledgement, and deletion events in an append-only audit log.
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Supply ChainUnpinned Dependencies, External Script Fetching, Obfuscated Code
Findings (7)

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

The README explicitly promotes complete message history and automatic polling but does not disclose that messages may persist on disk or mention privacy, retention, or access-control considerations. In an agent-to-agent messaging tool, this can lead operators to store potentially sensitive task content, customer data, or operational details in plaintext files without realizing the exposure, increasing the risk of unintended disclosure.

Content

No source excerpt is available for this finding.

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
91% confidence
Finding

The skill documents capabilities that imply file read/write behavior via a local message queue and configuration files, but it does not declare any explicit tool scope or permissions. In an agent ecosystem, undeclared filesystem access weakens least-privilege controls and can cause operators or orchestration layers to grant broader access than intended, increasing the risk of unauthorized data exposure or file tampering.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

The skill promotes direct agent messaging, automatic polling, complete message records, persistence, and paid HTTP/API features, but it does not warn users about confidentiality, integrity, retention, or trust risks. This is dangerous because agents may exchange sensitive prompts, credentials, or operational data through a channel that users may incorrectly assume is private or authenticated, leading to data leakage, spoofed messages, or unsafe automation decisions.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

This code performs persistent file writes when sending messages and deletes message files when checking messages with the default delete_read=True. Although the module has a brief docstring and one internal comment, it does not clearly disclose to users that running these functions will create files under a shared workspace and remove inbox files after reading.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
84% confidence
Finding

Natural-language policy violations include forcing a specific language without user opt-in. This skill documentation presents the operational guidance in Chinese and does not offer an English or multilingual option, nor does it explain that the skill is intentionally limited to a Chinese-speaking or region-specific audience.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
82% confidence
Finding

The manifest description forces a specific language/locale in user-facing skill metadata, which can violate language-choice policy when no alternative or opt-in is provided. The rest of the document is likewise predominantly Chinese, reinforcing a fixed locale rather than a user-selectable one.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
83% confidence
Finding

User-visible strings such as the title, usage text, status output, and error messages are partially or fully in Chinese, while the file otherwise uses English identifiers and CLI structure. This effectively imposes a language preference on users without any opt-in or documented locale limitation.

Content

No source excerpt is available for this finding.