# OpenClaw Security Hooks

Automated security validation hooks for OpenClaw's event-driven hook system.

## Overview

OpenClaw Security Hooks provide **automatic, real-time protection** for AI agent interactions by intercepting and validating:

- **User Input** (before submission to the agent) - via `command:new` event
- **Tool Calls** (before execution) - via `tool_result_persist` plugin API

## Hook System Architecture

Each hook follows OpenClaw's hook system specification:

```
hook-name/
├── HOOK.md          # Metadata with YAML frontmatter
└── handler.ts       # Handler implementation
```

**Installation Path:** `~/.openclaw/hooks/`

## Available Hooks

### 1. Security Input Validator

**Directory:** `security-input-validator/`

**Event:** `command:new`

**Purpose:** Validates user prompts before submission to AI agents.

**Detects:**
- Prompt injection attempts
- Command injection patterns
- Malicious URLs and SSRF attacks
- Path traversal attempts
- Secret exposure
- Obfuscation techniques

**Actions:**
- ✅ **ALLOW** - Safe input, proceed normally
- ⚠️  **WARN** - Potential issues, allow but log
- 🚫 **BLOCK** - Security threat detected, reject input

### 2. Security Tool Validator

**Directory:** `security-tool-validator/`

**Event:** `agent:bootstrap`

**Plugin API:** `tool_result_persist`

**Purpose:** Validates tool call parameters before execution.

**Validates:**
- Shell command parameters (Bash, exec)
- File path parameters (Read, Write, Edit)
- URL parameters (WebFetch, curl, wget)
- Content parameters

**Protected Tools:**
- `bash`, `exec` - Command injection validation
- `read`, `write`, `edit` - Path traversal validation
- `web_fetch`, `curl`, `wget` - SSRF validation

## Installation

### Automatic Installation (Recommended)

Run the installation script:

```bash
cd hooks/
./install-hooks.sh
```

This will:
1. Create `~/.openclaw/hooks/` directory
2. Copy hook directories to the hooks directory
3. Create symlinks to the OpenClaw Security codebase
4. Enable hooks via `openclaw` CLI (if available)

### Manual Installation

1. **Create hooks directory:**
   ```bash
   mkdir -p ~/.openclaw/hooks
   ```

2. **Copy hook directories:**
   ```bash
   cp -r security-input-validator ~/.openclaw/hooks/
   cp -r security-tool-validator ~/.openclaw/hooks/
   ```

3. **Create symlink to OpenClaw Security:**
   ```bash
   ln -s /path/to/openclaw-sec ~/.openclaw/openclaw-sec
   ```

4. **Enable hooks:**
   ```bash
   openclaw hooks enable security-input-validator
   openclaw hooks enable security-tool-validator
   ```

### Verify Installation

```bash
# List installed hooks
openclaw hooks list

# Check hook status
openclaw hooks status security-input-validator
openclaw hooks status security-tool-validator
```

## Configuration

Hooks use the same configuration as the OpenClaw Security Suite.

### Config File Locations (in priority order):

1. `./.openclaw-sec.yaml` (current directory)
2. `~/.openclaw/security-config.yaml` (user home directory)
3. Default configuration (if no file found)

### Example Configuration

Create `~/.openclaw/security-config.yaml` or `.openclaw-sec.yaml`:

```yaml
openclaw_security:
  enabled: true
  sensitivity: medium  # paranoid | strict | medium | permissive

  modules:
    prompt_injection:
      enabled: true
    command_validator:
      enabled: true
    url_validator:
      enabled: true
    path_validator:
      enabled: true
    secret_detector:
      enabled: true
    content_scanner:
      enabled: true

  actions:
    SAFE: allow
    LOW: log
    MEDIUM: warn
    HIGH: block
    CRITICAL: block_notify

  database:
    path: .openclaw-sec.db
    analytics_enabled: true
    retention_days: 365

  logging:
    enabled: true
    level: info
    file: ~/.openclaw/logs/security-events.log
```

## Testing Hooks

Hooks are tested automatically by OpenClaw when events are triggered. You can also test them manually:

### Test with OpenClaw CLI

```bash
# Test security-input-validator
openclaw hooks test security-input-validator --event command:new --data '{"input":"rm -rf /"}'

# Test security-tool-validator
openclaw hooks test security-tool-validator --event agent:bootstrap
```

### Monitor Hook Activity

```bash
# View hook logs
openclaw hooks logs security-input-validator

# View security events generated by hooks
openclaw-sec events --context hookType:security-input-validator
openclaw-sec events --context hookType:security-tool-validator
```

## Hook Behavior

### Security Input Validator (command:new)

```
┌─────────────────┐
│   User Input    │
│  (command:new)  │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  Security Scan  │ ← All 6 modules run in parallel
│ (SecurityEngine)│
└────────┬────────┘
         │
         ▼
    ┌────────┐
    │Action? │
    └───┬────┘
        │
    ┌───┴───┬──────────┬────────┐
    ▼       ▼          ▼        ▼
  ALLOW   LOG/WARN   BLOCK   BLOCK_NOTIFY
    │       │          │        │
    ▼       ▼          ▼        ▼
 Submit  Submit +   Reject    Reject +
         Warning   + Error    Error
```

### Security Tool Validator (tool_result_persist)

```
┌─────────────────┐
│   Tool Call     │
│  (with params)  │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Extract & Scan  │ ← Validate relevant parameters
│   Parameters    │   (SecurityEngine per param)
└────────┬────────┘
         │
         ▼
    ┌────────┐
    │Action? │
    └───┬────┘
        │
    ┌───┴───┬──────┐
    ▼       ▼      ▼
  ALLOW   WARN   BLOCK
    │       │      │
    ▼       ▼      ▼
 Execute  Execute Reject
         + Log   + Error
```

## Performance

- **Validation Time:** ~20-50ms per check
- **Async Writes:** Database writes don't block validation
- **Parallel Scanning:** All modules run concurrently
- **Minimal Overhead:** Negligible impact on user experience

## Security Events

All validations are logged to the database:

```bash
# View recent events
openclaw-sec events --limit 50

# View events for specific user
openclaw-sec events --user-id "alice@example.com"

# View high-severity events
openclaw-sec events --severity HIGH
```

## Troubleshooting

### Hooks not running?

1. **Check hooks are installed:**
   ```bash
   openclaw hooks list
   ```

2. **Check hooks are enabled:**
   ```bash
   openclaw hooks status security-input-validator
   openclaw hooks status security-tool-validator
   ```

3. **Check hooks directory:**
   ```bash
   ls -la ~/.openclaw/hooks/
   ```

4. **Verify symlink exists:**
   ```bash
   ls -la ~/.openclaw/openclaw-sec
   ```

### Hooks failing silently?

Hooks fail-open by default (allow on error) to prevent breaking the workflow.

**Check logs:**
```bash
# View hook execution logs
openclaw hooks logs security-input-validator
openclaw hooks logs security-tool-validator

# View security event logs
tail -f ~/.openclaw/logs/security-events.log
```

### Disable hooks temporarily

```bash
# Disable specific hook
openclaw hooks disable security-input-validator
openclaw hooks disable security-tool-validator

# Or disable in config
# Edit ~/.openclaw/security-config.yaml:
# openclaw_security:
#   enabled: false
```

### Re-enable hooks

```bash
openclaw hooks enable security-input-validator
openclaw hooks enable security-tool-validator
```

## Advanced Configuration

### Sensitivity Levels

- **paranoid** - Maximum security, may have false positives
- **strict** - High security with balanced accuracy
- **medium** - Default, good balance (recommended)
- **permissive** - Minimal blocking, focus on logging

### Module-Specific Settings

Override sensitivity per module:

```yaml
modules:
  prompt_injection:
    enabled: true
    sensitivity: strict
  command_validator:
    enabled: true
    sensitivity: paranoid
  url_validator:
    enabled: true
    sensitivity: medium
```

### Custom Actions

Override actions by severity:

```yaml
actions:
  SAFE: allow
  LOW: allow        # Don't even log low severity
  MEDIUM: log       # Log but allow
  HIGH: warn        # Show warning but allow
  CRITICAL: block   # Block without notification
```

## Hook Event Details

### security-input-validator

**Event:** `command:new`

**Triggers when:**
- User submits a new prompt/command to the agent
- New conversation starts
- User sends follow-up messages

**Event data structure:**
```typescript
{
  type: "command",
  action: "new",
  data: {
    input: string,      // User's prompt
    userId?: string,
    sessionId?: string
  }
}
```

### security-tool-validator

**Event:** `agent:bootstrap`

**Registers plugin:** `tool_result_persist`

**Triggers when:**
- Agent starts up and bootstraps hooks
- Registers a plugin that intercepts all tool calls

**Plugin intercepts:**
- All tool/function calls before execution
- Validates parameters for security-sensitive tools
- Blocks or allows based on validation results

## Integration with OpenClaw

### Install as Dependency

Add to your OpenClaw project:

```bash
npm install openclaw-sec
```

### Programmatic Hook Registration

```typescript
import { SecurityEngine } from 'openclaw-sec';

// Hooks are automatically loaded from ~/.openclaw/hooks/
// when enabled via: openclaw hooks enable <hook-name>
```

### CI/CD Integration

```bash
# Install hooks in CI environment
cd your-project
npm install openclaw-sec
./node_modules/.bin/openclaw-sec hooks install

# Run with hooks enabled
openclaw agent run --hooks-enabled
```

## Support

- **Documentation:** See main [README.md](../README.md)
- **Issues:** Report at GitHub
- **Configuration:** See [SKILL.md](../SKILL.md)

## License

Part of the OpenClaw Security Suite - See LICENSE file
