Back to skill

Security audit

Aegis Protocol

Security checks for vulnerabilities and agentic risk

Overview

This is a real self-healing monitor, but it can automatically kill sessions, restart services, run shell commands, and make some undisclosed external network checks, so users should review it before installing.

Install only if you intentionally want a host-level OpenClaw watchdog that can run shell diagnostics and perform unattended recovery. Review and constrain the heal path before production use, especially session killing, pm2 restart all, nginx restarts, cron scheduling, and external network checks; run it as a least-privileged account where possible.

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
aegis-protocol.py:546
Finding

Shell Command Injection Through Unvalidated Session Identifiers

Content
View full analysis

Vulnerability Details

File Location: aegis-protocol.py:174-188, aegis-protocol.py:210-222, and aegis-protocol.py:546-550
Vulnerability Type: OS command injection through unquoted data passed to a shell
Risk Level: High

Vulnerable Code

python
def exec_cmd(cmd: str, timeout: int = 30, raise_on_error: bool = False) -> Tuple[int, str, str]:
    """Execute a shell command."""
    try:
        result = subprocess.run(
            cmd,
            shell=True,
            capture_output=True,
            text=True,
            timeout=timeout
        )
        if raise_on_error and result.returncode != 0:
            raise ExternalCommandError(cmd, result.returncode, result.stderr)
        return result.returncode, result.stdout, result.stderr
    except subprocess.TimeoutExpired:
        if raise_on_error:
            raise ExternalCommandError(cmd, -1, "Command timed out")
        return -1, "", "Command timed out"
    except Exception as e:
        if raise_on_error:
            raise ExternalCommandError(cmd, -1, str(e))
        return -1, "", str(e)
python
code, out, err = exec_cmd("openclaw sessions list --limit 100")

if code != 0:
    return {
        "status": "ok",
        "stuck_count": 0,
        "sessions": [],
        "note": "Session checking requires API support"
    }

stuck_sessions: List[str] = []
try:
    sessions = re.findall(r'"key":"([^"]*)".*?"status":"([^"]*)"', out)
    for key, status in sessions:
        if status == "running" and key not in whitelist:
            stuck_sessions.append(key)
except Exception:
    pass
python
def kill_session(session_key: str) -> bool:
    """Terminate a session."""
    start = datetime.now()
    code, out, err = exec_cmd(f"openclaw sessions kill {session_key}")
    duration = (datetime.now() - start).total_seconds()

Technical Analysis

`exec_cm ...[truncated 2091 chars]

Remediation
View remediation

Remediation Suggestions

  1. Eliminate shell=True and represent every command as an argument array:

    python
    def exec_cmd(
        command: List[str],
        timeout: int = 30,
        raise_on_error: bool = False
    ) -> Tuple[int, str, str]:
        result = subprocess.run(
            command,
            shell=False,
            capture_output=True,
            text=True,
            timeout=timeout,
            check=False
        )
        if raise_on_error and result.returncode != 0:
            raise ExternalCommandError(
                " ".join(command),
                result.returncode,
                result.stderr
            )
        return result.returncode, result.stdout, result.stderr
    
    def kill_session(session_key: str) -> bool:
        if not re.fullmatch(r"[A-Za-z0-9._:@/-]+", session_key):
            raise RecoveryError("Invalid session identifier")
        code, out, err = exec_cmd(
            ["openclaw", "sessions", "kill", session_key]
        )
        return code == 0
    
  2. Use a documented, restrictive session-identifier grammar rather than the illustrative allowlist above.

  3. Parse structured JSON from OpenClaw instead of applying a broad regular expression to arbitrary text.

  4. Reject identifiers containing control characters, whitespace, or shell metacharacters.

  5. Run the Skill under a dedicated, unprivileged service account and grant only narrowly scoped recovery permissions.

  6. Add unit tests containing semicolons, command substitutions, pipes, redirections, quotes, whitespace, and newline characters.

  7. Refactor all other shell pipelines to argument-based subprocess calls where possible.

T05 · Unauthorized Access and Privilege Escalation

Warning
Location
aegis-protocol.py:558
Finding

Automatic Recovery Can Restart Unrelated PM2 Workloads and Privileged System Services

Content
View full analysis

Vulnerability Details

File Location: aegis-protocol.py:558-572 and aegis-protocol.py:637-653
Vulnerability Type: Over-broad privileged recovery action and insufficient least-privilege controls
Risk Level: Medium

Vulnerable Code

python
def restart_service(service_name: str) -> bool:
    """Restart a service."""
    start = datetime.now()

    if service_name == "pm2":
        code, out, err = exec_cmd("pm2 restart all")
    elif service_name == "nginx":
        code, out, err = exec_cmd("systemctl restart nginx")
    else:
        code, out, err = -1, "", f"Unknown service: {service_name}"

    duration = (datetime.now() - start).total_seconds()
    success = code == 0

    record_incident(
        "service_offline",
        "service_restart",
        success,
        duration,
        {"service": service_name}
    )

    return success
python
elif issue_type == IssueType.SERVICE_DOWN:
    if check_name == "nginx":
        log("→ Restarting: Nginx")
        if restart_service("nginx"):
            actions_taken.append("restart:nginx")
        else:
            errors.append("nginx_restart_failed")

    elif check_name == "pm2":
        log("→ Restarting: PM2")
        if restart_service("pm2"):
            actions_taken.append("restart:pm2")
        else:
            errors.append("pm2_restart_failed")

Technical Analysis

When a PM2 alert is classified as a service failure, the recovery routine runs pm2 restart all. This restarts every workload managed by the current PM2 instance, including processes unrelated to the service that triggered the alert. The code already reads a service whitelist during monitoring, but recovery does not select and restart only a confirmed unhealthy process.

Nginx is restarted through systemctl as soon as the status check reports it inactive. The recovery path does not require operator confirmation ...[truncated 1705 chars]

Remediation
View remediation

Remediation Suggestions

  1. Identify the exact unhealthy PM2 process and restart only that process by an immutable identifier.
  2. Require services eligible for recovery to appear in an explicit recovery allowlist. Treat the existing monitoring whitelist separately from recovery authorization.
  3. Never use pm2 restart all as the default recovery action.
  4. Require nginx -t to succeed immediately before restarting Nginx.
  5. Make destructive recovery opt-in and request operator confirmation unless the Skill runs in a separately configured unattended mode.
  6. Enforce the configured serviceRestart cooldown and persist the last attempt atomically.
  7. Honor the configured recovery action instead of applying a hardcoded restart.
  8. Use a dedicated service account with a narrowly scoped sudo rule permitting only the required service operation. Do not grant unrestricted systemctl, shell, or root access.
  9. Add rate limits, maximum retry counts, and circuit-breaker behavior for repeated failures.
  10. Record the triggering check, target process, precondition results, and authorization decision in the incident log.

other

Note
Location
aegis-protocol.py:846
Finding

Full Health Checks Perform Undisclosed Outbound Network Connections

Content
View full analysis

Vulnerability Details

File Location: aegis-protocol.py:730-733, aegis-protocol.py:846-862, and aegis-protocol.py:890-902
Vulnerability Type: Undisclosed outbound TLS, DNS, and ICMP activity
Risk Level: Low

Vulnerable Code

python
if mode in ["full", "extended"]:
    checks["ssl_cert"] = check_ssl_cert()
    checks["docker"] = check_docker_containers()
    checks["network"] = check_network_connectivity()
    checks["cron"] = check_cron_tasks()
python
def check_ssl_cert(
    domain: str = "nevmatrix.com",
    port: int = 443,
    days_threshold: int = 30
) -> Dict[str, Any]:
    """Check SSL certificate validity."""
    try:
        context = ssl.create_default_context()
        with socket.create_connection((domain, port), timeout=10) as sock:
            with context.wrap_socket(
                sock,
                server_hostname=domain
            ) as ssock:
                cert = ssock.getpeercert()
                expiry = datetime.strptime(
                    cert["notAfter"],
                    "%b %d %H:%M:%S %Y %Z"
                )
                days_left = (expiry - datetime.now()).days
python
def check_network_connectivity(
    hosts: Optional[List[str]] = None
) -> Dict[str, Any]:
    """Check network connectivity."""
    if hosts is None:
        hosts = ["8.8.8.8", "1.1.1.1", "baidu.com"]

    results = []
    for host in hosts:
        code, out, err = exec_cmd(
            f"ping -c 1 -W 2 {host} 2>&1 | grep 'time=' || echo 'failed'"
        )
        reachable = "time=" in out
        results.append({"host": host, "reachable": reachable})

Technical Analysis

Running status --full or check --full opens a TLS connection to the hardcoded domain nevmatrix.com and sends connectivity probes to 8.8.8.8, 1.1.1.1, and baidu.com. Hostname resolution may also disclose DNS act ...[truncated 1603 chars]

Remediation
View remediation

Remediation Suggestions

  1. Correct SKILL.md and user documentation to disclose every outbound connection performed in full mode.
  2. Disable external connectivity checks by default and require an explicit opt-in configuration option.
  3. Remove vendor- or project-specific hardcoded domains unless they are essential to the user's configured monitoring scope.
  4. Let users configure approved endpoints and ports through a validated configuration schema.
  5. Prefer user-owned internal health endpoints in restricted environments.
  6. Validate configured hostnames and IP addresses and invoke ping without a shell.
  7. Provide a strict offline mode that blocks all outbound checks.
  8. Clearly distinguish local system checks from network checks in CLI output and documentation.
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
  • Rogue AgentSelf-Modification, Session Persistence
Findings (37)

Credential Access

High
Category
Privilege Escalation
Confidence
95% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · SECURITY.md (reported line 181)May include surrounding context.

md
If you see any of these, report immediately:

- ❌ Commands to unknown external IPs
- ❌ Attempts to read `~/.ssh/`, `~/.aws/`, `/etc/shadow`
- ❌ Cryptocurrency-related commands
- ❌ Base64-encoded command execution
- ❌ wget/curl to unknown domains

Tp4

High
Category
MCP Tool Poisoning
Confidence
98% confidence
Finding

The skill metadata and documentation present the capability as an AI-agent stability monitor, but the described behavior includes broad host-level monitoring and recovery actions such as service restarts and session termination. This scope mismatch is dangerous because users may invoke the skill without understanding it can affect system services and host state, increasing the risk of unintended disruptive or privileged operations.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
96% confidence
Finding

The skill metadata and documentation present the capability as an AI-agent stability monitor, but the described behavior includes broad host-level monitoring and recovery actions such as service restarts and session termination. This scope mismatch is dangerous because users may invoke the skill without understanding it can affect system services and host state, increasing the risk of unintended disruptive or privileged operations.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
97% confidence
Finding

The skill metadata and documentation present the capability as an AI-agent stability monitor, but the described behavior includes broad host-level monitoring and recovery actions such as service restarts and session termination. This scope mismatch is dangerous because users may invoke the skill without understanding it can affect system services and host state, increasing the risk of unintended disruptive or privileged operations.

Content

No source excerpt is available for this finding.

Lp1

High
Category
MCP Least Privilege
Confidence
95% confidence
Finding

The code has broad shell execution capability but the declared skill purpose is only an AI-agent stability monitor, so users may not expect host-level command execution, service restarts, process termination, cron inspection, and filesystem/network probing. Undeclared powerful capabilities undermine least privilege and can cause severe damage if the skill is invoked in a privileged environment.

Content

No source excerpt is available for this finding.

Missing User Warnings

High
Category
Not specified by scanner
Confidence
94% confidence
Finding

The skill is designed to automatically kill sessions and restart services as part of self-healing, without interactive confirmation, dry-run mode, or strong safety interlocks. In a privileged environment, a false positive or manipulated input could terminate active work, restart production services, or disrupt availability.

Content

No source excerpt is available for this finding.

Tool Parameter Abuse

High
Category
Tool Misuse
Confidence
98% confidence
Finding

Using a generic shell execution wrapper with shell=True creates a tool-parameter-abuse primitive: any future or indirect untrusted input that reaches cmd becomes shell metacharacter injection. This skill already interpolates values into commands (for example host/path/service-derived strings), and it runs host-administration actions, so the context makes misuse materially more dangerous than in a low-privilege utility.

Content

Scanner excerpt · aegis-protocol.py (reported line 177)May include surrounding context.

python
def exec_cmd(cmd: str, timeout: int = 30, raise_on_error: bool = False) -> Tuple[int, str, str]:
    """执行 shell 命令"""
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
        if raise_on_error and result.returncode != 0:
            raise ExternalCommandError(cmd, result.returncode, result.stderr)
        return result.returncode, result.stdout, result.stderr

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The document makes an absolute safety claim of 'No network calls' while later admitting socket usage for SSL certificate checks. Even if limited to localhost, this is still network activity, and such contradictions can mislead reviewers into underestimating the skill's attack surface or trusting inaccurate assurances.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
91% confidence
Finding

This markdown file presents all user-facing content in Chinese, including headings, warnings, and operational guidance, with no indication that the skill is China-specific or that users can opt into another language. That can violate language/locale policy when a skill implicitly forces a specific language without user choice.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
91% confidence
Finding

The report explicitly states '直接使用 exec: 绕过 ACP 限制' ('directly use exec to bypass ACP limits'), which documents an intentional workaround for runtime authentication controls. Even though this is in documentation rather than executable code, it normalizes and may encourage use of unrestricted execution paths that exceed the stated purpose of a stability-monitor skill.

Content

No source excerpt is available for this finding.

Ssd 2

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

The text recommends an evasion-style step—using exec directly to bypass ACP runtime restrictions. Instructions that describe bypassing platform controls are dangerous because they can be adopted by operators or future contributors to sidestep authentication, policy enforcement, and audit boundaries.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The guide instructs users to run cat ~/.clawhub/token.json to copy a live authentication token, but does not warn that this prints credentials into terminal output, shell history capture tools, logs, screenshots, or recorded sessions. Because this is a publishing skill and tokens grant package publication privileges, accidental disclosure could enable unauthorized releases or tampering.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

The documentation includes a version deletion command for ClawHub and Git tags without an explicit warning that these actions are irreversible and can remove published artifacts relied on by users or downstream automation. In a publishing guide, operators may copy-paste commands directly, so omission of safety guidance increases the risk of accidental destructive actions.

Content

No source excerpt is available for this finding.

Session Persistence

Medium
Category
Rogue Agent
Confidence
80% confidence
Finding

Skill establishes unauthorized persistence across sessions via cron jobs, startup scripts, or state files. Session persistence allows an attacker to maintain access beyond the current interaction.

Content

Scanner excerpt · README.md (reported line 29)May include surrounding context.

md
- **Notifications**: Log output only (no push to Telegram/Slack/Feishu)
  - **You can configure**: Log collection (ELK, Loki) or custom notification script
- **Scheduling**: Manual cron setup required
  - **You can configure**: Add cron job for automatic periodic checks
- **Interface**: CLI only (no WebUI)
  - **You can use**: Log viewers like `lnav`, `multitail` for better CLI experience
  - **Planned**: WebUI in v1.1.0

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
91% confidence
Finding

The README explicitly advertises disruptive auto-recovery actions such as terminating sessions and restarting services, but it does not place a clear warning near those features about data loss, interruption, or the need for operator approval. In an agent skill context, normalizing autonomous kill/restart behavior without prominent safeguards increases the chance of unintended denial-of-service or loss of in-flight work when users enable healing blindly.

Content

No source excerpt is available for this finding.

Session Persistence

Medium
Category
Rogue Agent
Confidence
85% confidence
Finding

Skill establishes unauthorized persistence across sessions via cron jobs, startup scripts, or state files. Session persistence allows an attacker to maintain access beyond the current interaction.

Content

Scanner excerpt · README.md (reported line 265)May include surrounding context.

Quick setup:

bash
crontab -e
# Add: */10 * * * * python3 /path/to/aegis-protocol.py heal >> /var/log/aegis-protocol.log 2>&1

Session Persistence

Medium
Category
Rogue Agent
Confidence
85% confidence
Finding

Skill establishes unauthorized persistence across sessions via cron jobs, startup scripts, or state files. Session persistence allows an attacker to maintain access beyond the current interaction.

Content

Scanner excerpt · CLAWHUB_ISSUE_TEMPLATE.md (reported line 50)May include surrounding context.

md
| `nginx -t` | 测试 Nginx 配置 | ✅ 无风险 |
| `df /` | 检查磁盘使用 | ✅ 无风险 |
| `free` | 检查内存使用 | ✅ 无风险 |
| `crontab -l` | 检查 cron 任务 | ✅ 无风险 |
| `docker ps` | 检查 Docker 容器 | ✅ 无风险 |
| `git status` | 检查 Git 状态 | ✅ 无风险 |
| `apt list --upgradable` | 检查系统更新 | ✅ 无风险 |

Session Persistence

Medium
Category
Rogue Agent
Confidence
85% confidence
Finding

Skill establishes unauthorized persistence across sessions via cron jobs, startup scripts, or state files. Session persistence allows an attacker to maintain access beyond the current interaction.

Content

Scanner excerpt · SECURITY.md (reported line 117)May include surrounding context.

md
| `nginx -t` | 测试 Nginx 配置 | ✅ 无风险 |
| `df /` | 检查磁盘使用 | ✅ 无风险 |
| `free` | 检查内存使用 | ✅ 无风险 |
| `crontab -l` | 检查 cron 任务 | ✅ 无风险 |
| `docker ps` | 检查 Docker 容器 | ✅ 无风险 |
| `git status` | 检查 Git 状态 | ✅ 无风险 |
| `apt list --upgradable` | 检查系统更新 | ✅ 无风险 |

Session Persistence

Medium
Category
Rogue Agent
Confidence
85% confidence
Finding

Skill establishes unauthorized persistence across sessions via cron jobs, startup scripts, or state files. Session persistence allows an attacker to maintain access beyond the current interaction.

Content

Scanner excerpt · SECURITY_AUDIT.md (reported line 27)May include surrounding context.

md
| `nginx -t` | 测试 Nginx 配置 | ✅ 无风险 |
| `df /` | 检查磁盘使用 | ✅ 无风险 |
| `free` | 检查内存使用 | ✅ 无风险 |
| `crontab -l` | 检查 cron 任务 | ✅ 无风险 |
| `docker ps` | 检查 Docker 容器 | ✅ 无风险 |
| `git status` | 检查 Git 状态 | ✅ 无风险 |
| `apt list --upgradable` | 检查系统更新 | ✅ 无风险 |

Session Persistence

Medium
Category
Rogue Agent
Confidence
85% confidence
Finding

Skill establishes unauthorized persistence across sessions via cron jobs, startup scripts, or state files. Session persistence allows an attacker to maintain access beyond the current interaction.

Content

Scanner excerpt · aegis-protocol.py (reported line 419)May include surrounding context.

python
| `nginx -t` | 测试 Nginx 配置 | ✅ 无风险 |
| `df /` | 检查磁盘使用 | ✅ 无风险 |
| `free` | 检查内存使用 | ✅ 无风险 |
| `crontab -l` | 检查 cron 任务 | ✅ 无风险 |
| `docker ps` | 检查 Docker 容器 | ✅ 无风险 |
| `git status` | 检查 Git 状态 | ✅ 无风险 |
| `apt list --upgradable` | 检查系统更新 | ✅ 无风险 |

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

The skill advertises automatic recovery and healing but does not prominently warn that these actions may restart services, kill sessions, or otherwise disrupt workloads. In a user-invocable skill with exec, write, and edit permissions, insufficient disclosure can lead to accidental invocation of destructive or availability-impacting actions.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The listed trigger conditions for Claude Code use generic development events such as '新功能开发', 'Bug 修复', and '代码重构' without clarifying scope, exclusions, or how this agent is selected over others. In a workflow or manifest-style markdown file, such broad triggers can overlap with many normal activities and lead to unintended or inconsistent activation.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

Phrases like '新功能完成', '代码修改后', and '版本发布前' are common lifecycle events and do not specify thresholds or constraints for when OpenCode should activate. Without narrower conditions or negative examples, the trigger scope is ambiguous and may cause over-invocation.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The activation phrases '功能完成后', '版本发布前', and '用户反馈后' are broad, everyday project events and do not define precise boundaries for documentation work. This lack of specificity increases the risk of unnecessary or inconsistent skill invocation.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The top-level documentation claims a constrained feature set, while the actual code performs many additional checks and recovery actions. In agent/security contexts, misleading scope is dangerous because operators may approve a skill believing it has narrow behavior when it actually has wider visibility and operational authority.

Content

No source excerpt is available for this finding.