- name
- octoguard-openclaw-security-supervision
- description
- Security governance and audit system for OpenClaw AI agents with real-time policy enforcement, token monitoring, and alert notifications
- triggers
- ["how do I secure my OpenClaw deployment","set up security policies for AI agent actions","monitor and audit OpenClaw tool calls","block dangerous operations in OpenClaw","configure OctoGuard security rules","track token usage and set alerts for AI agents","intercept high-risk AI behaviors","deploy security supervision for OpenClaw"]
# OctoGuard OpenClaw Security Supervision
> Skill by [ara.so](https://ara.so) — Security Skills collection.
OctoGuard (章鱼卫士) is a security governance and audit system designed specifically for OpenClaw AI agents. It provides real-time detection, policy control, and alert notifications for user dialogue commands, tool calls, and execution results. The system acts as a security gateway that intercepts dangerous operations before they execute, monitors token consumption, and maintains comprehensive audit logs.
## What OctoGuard Does
- **Policy-based Interception**: Configure rules to block sensitive file access, dangerous operations, and high-risk behaviors
- **Token Monitoring**: Real-time tracking of token usage with threshold alerts
- **Audit Logging**: Record all OpenClaw events, allowed actions, and blocked attempts
- **Visual Policy Management**: Web-based dashboard for managing security policies
- **OpenClaw Gateway Control**: Monitor and control OpenClaw gateway status
- **Multi-channel Alerts**: Push notifications via DingTalk, WeChat Work, and Email
- **Security Dashboard**: Comprehensive visualization of OpenClaw security posture
## Architecture
OctoGuard sits between external users and OpenClaw, intercepting all requests through a security policy engine before they reach the AI agent. It operates non-invasively without modifying OpenClaw's core functionality.
```
User Request → OctoGuard Security Gateway → Policy Engine → OpenClaw → AI Agent
↓
Audit Logs + Alerts
```
## Installation
### Prerequisites
- Node.js (v14+)
- MySQL database
- OpenClaw instance running
- DingTalk/WeChat Work webhook (optional, for alerts)
### Backend Setup
```bash
# Clone the repository
git clone https://github.com/O-ozzz/OctoGuard--Free-OpenClaw-Security-Supervision-System.git
cd OctoGuard--Free-OpenClaw-Security-Supervision-System
# Install backend dependencies
cd backend
npm install
# Configure database connection
# Edit config/database.js
```
**Database Configuration** (`config/database.js`):
```javascript
module.exports = {
host: process.env.DB_HOST || 'localhost',
port: process.env.DB_PORT || 3306,
user: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME || 'octoguard',
connectionLimit: 10,
waitForConnections: true,
queueLimit: 0
};
```
**Environment Variables** (`.env`):
```bash
# Database
DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=your_password
DB_NAME=octoguard
# Server
PORT=3000
NODE_ENV=production
# OpenClaw Gateway
OPENCLAW_HOST=localhost
OPENCLAW_PORT=8080
OPENCLAW_API_KEY=your_openclaw_key
# Alert Webhooks
DINGTALK_WEBHOOK=https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN
WECHAT_WEBHOOK=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=your_email@gmail.com
EMAIL_PASSWORD=your_app_password
EMAIL_TO=security-team@company.com
```
### Initialize Database
```bash
# Run database migrations
npm run migrate
# Start backend server
npm start
# Backend runs on http://localhost:3000
```
### Frontend Setup
```bash
# Install frontend dependencies
cd ../frontend
npm install
# Configure API endpoint
# Edit .env or config file
echo "VITE_API_BASE_URL=http://localhost:3000" > .env
# Build and run frontend
npm run build
npm run preview
# Or for development
npm run dev
```
## Core API
### Security Policy Management
**Create Security Policy**:
```javascript
// POST /api/policies
const axios = require('axios');
async function createSecurityPolicy() {
const policy = {
name: "Block Sensitive File Access",
description: "Prevent access to /etc/passwd and other system files",
enabled: true,
priority: 1,
conditions: {
type: "tool_call",
tool_name: "file_read",
pattern: ".*(/etc/passwd|/etc/shadow|.*\\.pem|.*\\.key).*",
matchType: "regex"
},
action: "block",
alertChannels: ["dingtalk", "email"]
};
const response = await axios.post(
`${process.env.VITE_API_BASE_URL}/api/policies`,
policy
);
return response.data;
}
```
**List Active Policies**:
```javascript
// GET /api/policies
async function listPolicies() {
const response = await axios.get(
`${process.env.VITE_API_BASE_URL}/api/policies`,
{ params: { enabled: true } }
);
return response.data.policies;
}
```
**Toggle Policy Status**:
```javascript
// PATCH /api/policies/:id
async function togglePolicy(policyId, enabled) {
const response = await axios.patch(
`${process.env.VITE_API_BASE_URL}/api/policies/${policyId}`,
{ enabled }
);
return response.data;
}
```
### Request Interception
**Intercept OpenClaw Request**:
```javascript
// Middleware for intercepting OpenClaw requests
const policyEngine = require('./services/policyEngine');
const auditLogger = require('./services/auditLogger');
async function interceptRequest(req, res, next) {
const { user_input, tool_call, session_id } = req.body;
try {
// Check against all active policies
const evaluation = await policyEngine.evaluate({
userInput: user_input,
toolCall: tool_call,
sessionId: session_id,
timestamp: new Date()
});
if (evaluation.action === 'block') {
// Log blocked attempt
await auditLogger.log({
type: 'BLOCKED',
sessionId: session_id,
reason: evaluation.reason,
policy: evaluation.policyName,
details: { user_input, tool_call }
});
// Send alerts
await sendAlerts(evaluation);
return res.status(403).json({
error: 'Request blocked by security policy',
reason: evaluation.reason,
policy: evaluation.policyName
});
}
// Log allowed request
await auditLogger.log({
type: 'ALLOWED',
sessionId: session_id,
details: { user_input, tool_call }
});
next();
} catch (error) {
console.error('Policy evaluation error:', error);
next(error);
}
}
```
### Token Monitoring
**Track Token Usage**:
```javascript
// POST /api/tokens/track
async function trackTokenUsage(sessionId, tokensUsed, model) {
const response = await axios.post(
`${process.env.VITE_API_BASE_URL}/api/tokens/track`,
{
session_id: sessionId,
tokens_used: tokensUsed,
model: model,
timestamp: new Date().toISOString()
}
);
return response.data;
}
```
**Get Token Statistics**:
```javascript
// GET /api/tokens/stats
async function getTokenStats(startDate, endDate) {
const response = await axios.get(
`${process.env.VITE_API_BASE_URL}/api/tokens/stats`,
{
params: {
start_date: startDate,
end_date: endDate
}
}
);
return {
totalTokens: response.data.total_tokens,
sessionCount: response.data.session_count,
averagePerSession: response.data.average_per_session,
breakdown: response.data.breakdown
};
}
```
**Set Token Threshold Alert**:
```javascript
// POST /api/tokens/threshold
async function setTokenThreshold(threshold, period = '1h') {
const response = await axios.post(
`${process.env.VITE_API_BASE_URL}/api/tokens/threshold`,
{
threshold: threshold,
period: period,
alert_channels: ["email", "dingtalk"]
}
);
return response.data;
}
```
### Audit Logs
**Query Audit Logs**:
```javascript
// GET /api/audit/logs
async function queryAuditLogs(filters) {
const response = await axios.get(
`${process.env.VITE_API_BASE_URL}/api/audit/logs`,
{
params: {
type: filters.type, // 'BLOCKED', 'ALLOWED', 'ERROR'
session_id: filters.sessionId,
start_date: filters.startDate,
end_date: filters.endDate,
limit: filters.limit || 100,
offset: filters.offset || 0
}
}
);
return response.data.logs;
}
```
**Export Audit Report**:
```javascript
// GET /api/audit/export
async function exportAuditReport(format = 'csv') {
const response = await axios.get(
`${process.env.VITE_API_BASE_URL}/api/audit/export`,
{
params: {
format: format, // 'csv' or 'json'
start_date: new Date(Date.now() - 30*24*60*60*1000).toISOString(),
end_date: new Date().toISOString()
},
responseType: 'blob'
}
);
return response.data;
}
```
## Common Security Patterns
### Pattern 1: File System Protection
```javascript
// Prevent access to sensitive system files
const fileSystemPolicy = {
name: "File System Protection",
enabled: true,
priority: 1,
conditions: {
type: "tool_call",
tool_name: ["file_read", "file_write", "file_delete"],
patterns: [
"^/etc/.*",
"^/root/.*",
".*\\.ssh/.*",
".*\\.pem$",
".*\\.key$",
".*password.*",
".*secret.*"
],
matchType: "regex_any"
},
action: "block",
message: "Access to system files and credentials is prohibited"
};
```
### Pattern 2: Network Request Filtering
```javascript
// Block requests to internal network ranges
const networkPolicy = {
name: "Internal Network Protection",
enabled: true,
priority: 2,
conditions: {
type: "tool_call",
tool_name: ["http_request", "curl", "wget"],
patterns: [
"^https?://10\\..*",
"^https?://172\\.(1[6-9]|2[0-9]|3[0-1])\\..*",
"^https?://192\\.168\\..*",
"^https?://localhost.*",
"^https?://127\\.0\\.0\\..*"
],
matchType: "regex_any"
},
action: "block",
message: "Requests to internal network addresses are blocked"
};
```
### Pattern 3: Command Execution Prevention
```javascript
// Prevent dangerous shell commands
const commandPolicy = {
name: "Dangerous Command Prevention",
enabled: true,
priority: 1,
conditions: {
type: "tool_call",
tool_name: ["shell_exec", "bash", "terminal"],
patterns: [
".*(rm -rf|dd if=|mkfs|format).*",
".*(sudo|su ).*",
".*>/dev/sd[a-z].*",
".*(wget|curl).*\\|.*sh.*",
".*nc -l.*",
".*iptables.*"
],
matchType: "regex_any"
},
action: "block",
message: "Dangerous system commands are not allowed"
};
```
### Pattern 4: Data Exfiltration Detection
```javascript
// Detect potential data exfiltration
const exfiltrationPolicy = {
name: "Data Exfiltration Detection",
enabled: true,
priority: 3,
conditions: {
type: "combined",
rules: [
{
tool_name: "file_read",
pattern: ".*(database|backup|export|dump).*"
},
{
GitHubで見る