> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch32-security-model/32.4-security-auditing.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 32.4 Security Auditing

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~290k tokens, Output \~8k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

Security configuration requires continuous verification—even with good system defaults, user customizations can introduce security vulnerabilities. OpenClaw includes an automated security audit system that can scan configuration, file permissions, channel policies, and other dimensions, generating structured security findings reports. This section analyzes the architecture and implementation of this system.

***

## 32.4.1 Audit System (`src/security/audit.ts`)

### Audit Report Structure

The output of security auditing is a structured `SecurityAuditReport`:

```typescript
// src/security/audit.ts

type SecurityAuditSeverity = "info" | "warn" | "critical";

type SecurityAuditFinding = {
  checkId: string;        // Check ID (e.g., "gateway.bind_no_auth")
  severity: SecurityAuditSeverity;
  title: string;          // Short title
  detail: string;         // Detailed description
  remediation?: string;   // Remediation suggestion
};

type SecurityAuditReport = {
  ts: number;                          // Audit timestamp
  summary: { critical, warn, info };   // Count by severity
  findings: SecurityAuditFinding[];    // All findings
  deep?: { gateway?: { ... } };        // Deep probe results
};
```

### Audit Pipeline

`runSecurityAudit` is the entry point for auditing, collecting findings in category order:

```typescript
// src/security/audit.ts (simplified)

export async function runSecurityAudit(opts: SecurityAuditOptions): Promise<SecurityAuditReport> {
  const findings: SecurityAuditFinding[] = [];

  // Layer 1: Attack surface analysis
  findings.push(...collectAttackSurfaceSummaryFindings(cfg));
  findings.push(...collectSyncedFolderFindings({ stateDir, configPath }));

  // Layer 2: Configuration security checks
  findings.push(...collectGatewayConfigFindings(cfg, env));
  findings.push(...collectBrowserControlFindings(cfg));
  findings.push(...collectLoggingFindings(cfg));
  findings.push(...collectElevatedFindings(cfg));
  findings.push(...collectHooksHardeningFindings(cfg));
  findings.push(...collectSecretsInConfigFindings(cfg));
  findings.push(...collectModelHygieneFindings(cfg));
  findings.push(...collectSmallModelRiskFindings({ cfg, env }));
  findings.push(...collectExposureMatrixFindings(cfg));

  // Layer 3: Filesystem auditing
  if (opts.includeFilesystem !== false) {
    findings.push(...await collectFilesystemFindings({ stateDir, configPath, ... }));
    findings.push(...await collectIncludeFilePermFindings({ configSnapshot, ... }));
    findings.push(...await collectStateDeepFilesystemFindings({ cfg, stateDir, ... }));
    findings.push(...await collectPluginsTrustFindings({ cfg, stateDir }));
    if (opts.deep) {
      findings.push(...await collectPluginsCodeSafetyFindings({ stateDir }));
      findings.push(...await collectInstalledSkillsCodeSafetyFindings({ cfg, stateDir }));
    }
  }

  // Layer 4: Channel security checks
  if (opts.includeChannelSecurity !== false) {
    findings.push(...await collectChannelSecurityFindings({ cfg, plugins }));
  }

  // Layer 5: Deep probing (optional)
  if (opts.deep) {
    const deep = await maybeProbeGateway({ cfg, timeoutMs: 5000, probe });
  }

  return { ts: Date.now(), summary: countBySeverity(findings), findings, deep };
}
```

### Gateway Configuration Security Checks

`collectGatewayConfigFindings` checks the security configuration of the Gateway server, one of the most critical checks:

```typescript
// src/security/audit.ts (simplified)

function collectGatewayConfigFindings(cfg, env): SecurityAuditFinding[] {
  const findings = [];

  // Check 1: Non-loopback binding without authentication
  if (bind !== "loopback" && !hasSharedSecret) {
    findings.push({
      checkId: "gateway.bind_no_auth",
      severity: "critical",
      title: "Gateway binds beyond loopback without auth",
      detail: `gateway.bind="${bind}" but no auth token/password configured.`,
      remediation: "Set gateway.auth or bind to loopback.",
    });
  }

  // Check 2: Tailscale Funnel exposure
  if (tailscaleMode === "funnel") {
    findings.push({
      severity: "critical",
      title: "Tailscale Funnel exposure enabled",
      detail: 'gateway.tailscale.mode="funnel" exposes Gateway publicly.',
    });
  }

  // Check 3: Insecure HTTP authentication
  if (cfg.gateway?.controlUi?.allowInsecureAuth === true) {
    findings.push({
      severity: "critical",
      title: "Control UI allows insecure HTTP auth",
    });
  }

  // Check 4: Device authentication disabled
  if (cfg.gateway?.controlUi?.dangerouslyDisableDeviceAuth === true) {
    findings.push({
      severity: "critical",
      title: "DANGEROUS: Control UI device auth disabled",
    });
  }

  // Check 5: Token length insufficient
  if (token && token.length < 24) {
    findings.push({
      severity: "warn",
      title: "Gateway token looks short",
      detail: `token is ${token.length} chars; prefer a long random token.`,
    });
  }

  return findings;
}
```

### Channel Security Checks

Channel security checks cover multiple dimensions including DM policy, group permissions, slash command authorization, etc. Using Discord as an example:

```typescript
// src/security/audit.ts (simplified concept)

// Check 1: Slash commands have no user restrictions
if (!useAccessGroups && guildsConfigured && !hasAnyUserAllowlist) {
  findings.push({
    severity: "critical",
    title: "Discord slash commands are unrestricted",
    detail: "Any user in allowed guild channels can invoke /… commands.",
  });
}

// Check 2: No allowlist causes all commands to be rejected
if (useAccessGroups && !ownerAllowFromConfigured && !hasAnyUserAllowlist) {
  findings.push({
    severity: "warn",
    title: "Discord slash commands have no allowlists",
    detail: "/… commands will be rejected for everyone.",
  });
}
```

***

## 32.4.2 Filesystem Auditing (`src/security/audit-fs.ts`)

### Permission Check Model

Filesystem auditing checks whether the permissions of OpenClaw's critical files and directories are secure. `inspectPathPermissions` is a cross-platform permission checking function:

```typescript
// src/security/audit-fs.ts (simplified)

export async function inspectPathPermissions(targetPath, opts?): Promise<PermissionCheck> {
  const st = await safeStat(targetPath);
  if (!st.ok) return { ok: false, ... };

  const bits = modeBits(st.mode);    // Extract rwxrwxrwx bits
  const platform = opts?.platform ?? process.platform;

  if (platform === "win32") {
    // Windows: use icacls to check ACL
    const acl = await inspectWindowsAcl(targetPath, { exec: opts?.exec });
    return { ..., source: "windows-acl", worldWritable: acl.untrustedWorld.some(e => e.canWrite), ... };
  }

  // POSIX: use traditional mode bits
  return {
    ...,
    source: "posix",
    worldWritable: (bits & 0o002) !== 0,   // Other users writable?
    groupWritable: (bits & 0o020) !== 0,   // Group writable?
    worldReadable: (bits & 0o004) !== 0,   // Other users readable?
    groupReadable: (bits & 0o040) !== 0,   // Group readable?
  };
}
```

> **Sidebar**: Unix/Linux file permissions are represented by 9 binary digits, divided into three groups (owner/group/others), with 3 bits per group (read/write/execute). In octal notation, `0o700` means the owner has all permissions (rwx), and group and others have no permissions. `0o600` means the owner can read and write but not execute. OpenClaw expects state directories to be `0o700` (owner access only) and config files to be `0o600` (owner read-write only), because config files may contain sensitive information like API keys.

### Audit Finding Severity Levels

Filesystem auditing assigns different severity levels based on risk:

| Check Item                         | Condition            | Severity   |
| ---------------------------------- | -------------------- | ---------- |
| State directory world-writable     | `bits & 0o002`       | `critical` |
| State directory group-writable     | `bits & 0o020`       | `warn`     |
| State directory readable by others | `bits & 0o044`       | `warn`     |
| Config file writable by others     | group/world writable | `critical` |
| Config file world-readable         | `bits & 0o004`       | `critical` |
| Config file group-readable         | `bits & 0o040`       | `warn`     |
| Path is symbolic link              | `isSymbolicLink()`   | `warn`     |

Remediation suggestions are automatically generated based on platform—POSIX systems generate `chmod 700 ~/.openclaw`, Windows systems generate `icacls` commands.

***

## 32.4.3 Skill Security Scanning (`src/security/skill-scanner.ts`)

### Why Scan Skill Code

Skills are third-party code installed by users that run in the Agent execution environment. Similar to browser extensions, malicious skills can:

* Execute system commands (`child_process.exec`)
* Steal API keys from environment variables
* Exfiltrate sensitive data over the network
* Use obfuscated code to hide malicious logic

### Scanning Rules

The skill scanner uses two types of rules—**Line Rules** and **Source Rules**:

```typescript
// src/security/skill-scanner.ts (simplified)

// Line rules: match line by line
const LINE_RULES = [
  {
    ruleId: "dangerous-exec",
    severity: "critical",
    message: "Shell command execution detected (child_process)",
    pattern: /\b(exec|execSync|spawn|spawnSync)\s*\(/,
    requiresContext: /child_process/,  // File must also reference child_process
  },
  {
    ruleId: "dynamic-code-execution",
    severity: "critical",
    message: "Dynamic code execution detected",
    pattern: /\beval\s*\(|new\s+Function\s*\(/,
  },
  {
    ruleId: "crypto-mining",
    severity: "critical",
    message: "Possible crypto-mining reference detected",
    pattern: /stratum\+tcp|coinhive|cryptonight|xmrig/i,
  },
];

// Source rules: match across lines
const SOURCE_RULES = [
  {
    ruleId: "potential-exfiltration",
    severity: "warn",
    message: "File read + network send — possible data exfiltration",
    pattern: /readFileSync|readFile/,
    requiresContext: /\bfetch\b|\bpost\b|http\.request/i,
  },
  {
    ruleId: "env-harvesting",
    severity: "critical",
    message: "Environment variable access + network send — possible credential harvesting",
    pattern: /process\.env/,
    requiresContext: /\bfetch\b|\bpost\b|http\.request/i,
  },
  {
    ruleId: "obfuscated-code",
    severity: "warn",
    message: "Large base64 payload with decode call detected",
    pattern: /(?:atob|Buffer\.from)\s*\(\s*["'][A-Za-z0-9+/=]{200,}["']/,
  },
];
```

**`requiresContext` double-check** is a clever false positive control mechanism—`exec` is a common function name, and without the secondary verification of `requiresContext: /child_process/`, regex matching on the `.exec()` method of tools would also be falsely reported as dangerous operations.

### Directory Scanning

`scanDirectory` traverses the skill directory, scanning all `.js`/`.ts`/`.mjs`/`.cjs` and similar files:

```typescript
// src/security/skill-scanner.ts (simplified)

const SCANNABLE_EXTENSIONS = new Set([".js", ".ts", ".mjs", ".cjs", ".mts", ".cts", ".jsx", ".tsx"]);
const DEFAULT_MAX_SCAN_FILES = 500;        // Max 500 files to scan
const DEFAULT_MAX_FILE_BYTES = 1024 * 1024; // Max 1MB per file

export async function scanDirectoryWithSummary(dirPath, opts?): Promise<SkillScanSummary> {
  const files = await collectScannableFiles(dirPath, normalizedOpts);
  const allFindings = [];
  let scannedFiles = 0;

  for (const file of files) {
    const source = await readScannableSource(file, maxFileBytes);
    if (source == null) continue;
    scannedFiles++;
    allFindings.push(...scanSource(source, file));
  }

  return { scannedFiles, critical: ..., warn: ..., info: ..., findings: allFindings };
}
```

Security limits protect the scanner itself from DoS:

* **File count limit** (500): Prevents huge `node_modules` directories from slowing down scanning
* **File size limit** (1MB): Skips abnormally large files
* **Skip `node_modules` and hidden directories**: Avoids scanning dependency libraries

***

## 32.4.4 External Content Security (`src/security/external-content.ts`)

This module was analyzed in detail in Section 32.1. Here are some additional audit-related APIs:

```typescript
// Determine if session is from external hook
export function isExternalHookSession(sessionKey: string): boolean {
  return sessionKey.startsWith("hook:gmail:") ||
         sessionKey.startsWith("hook:webhook:") ||
         sessionKey.startsWith("hook:");
}

// Extract hook type
export function getHookType(sessionKey: string): ExternalContentSource {
  if (sessionKey.startsWith("hook:gmail:")) return "email";
  if (sessionKey.startsWith("hook:webhook:")) return "webhook";
  return "unknown";
}

// Web content wrapping (simplified)
export function wrapWebContent(content: string, source: "web_search" | "web_fetch"): string {
  // web_fetch includes comprehensive security warning, web_search only marks source
  return wrapExternalContent(content, { source, includeWarning: source === "web_fetch" });
}
```

***

## 32.4.5 `openclaw security audit` Command

Security auditing is triggered through CLI command:

```bash
# Basic audit
openclaw security audit

# Deep audit (includes Gateway probing and code safety scanning)
openclaw security audit --deep

# JSON output (for CI/CD integration)
openclaw security audit --json
```

Audit results are output with color-coded severity:

* **CRITICAL** (red): Serious security issues requiring immediate fix
* **WARN** (yellow): Security concerns recommended for fixing
* **INFO** (gray): Informational hints

Each finding includes remediation suggestions (`remediation`), for example:

```
CRITICAL: Config file is world-readable
  ~/.openclaw/openclaw.json mode=644; config can contain tokens.
  Fix: chmod 600 ~/.openclaw/openclaw.json
```

***

## Summary of This Section

1. **Structured audit report** contains findings at three severity levels (critical/warn/info), each with check ID, details, and remediation suggestions.
2. **Five-layer audit pipeline**: Attack surface analysis → Configuration security checks → Filesystem permissions → Channel security → Deep probing.
3. **Cross-platform file permission checking**: POSIX uses mode bits, Windows uses icacls ACL, unified as boolean properties like `worldWritable`/`groupWritable`.
4. **Skill security scanner** uses line-level + source-level dual rules with `requiresContext` mechanism to control false positives.
5. **External content security module** provides session source determination and tiered Web content wrapping capabilities.
6. **CLI integration** supports basic/deep modes and JSON output, suitable for manual inspection and CI/CD automation.
