Skip to content

Security: TheMasterClaw/masterclaw-tools

Security

SECURITY.md

Security Policy and Documentation

MasterClaw Security: This document outlines security features, threat model, vulnerability reporting, and best practices for the MasterClaw CLI ecosystem.

πŸ”’ Security Overview

MasterClaw implements defense-in-depth security across multiple layers:

Layer Protection
Input Validation Path traversal prevention, command injection filtering, prototype pollution protection
Authentication Secure token handling, API key validation, environment-based secrets
Audit Logging Tamper-evident signed logs, comprehensive event tracking
Encryption AES-256-GCM for secrets at rest, secure key derivation
Rate Limiting Command-level throttling to prevent abuse
Circuit Breakers Fail-fast protection against cascading failures
Resource Limits Fork bomb protection, memory limits on container execution

πŸ›‘οΈ Security Features

1. Secrets Encryption at Rest

All secrets are encrypted using AES-256-GCM with:

  • System-derived encryption key - Unique per user/system combination
  • PBKDF2 key derivation - 100,000 iterations
  • Transparent migration - Plaintext secrets auto-encrypted on first load
  • Secure file permissions - 0o600 on all secret files
// Secrets are automatically encrypted when stored
await setSecret('API_KEY', 'sk-...');
// Value is encrypted with AES-256-GCM before writing to disk

2. Audit Log Integrity

Audit logs are cryptographically signed to detect tampering:

  • HMAC-SHA256 signatures on every entry
  • Constant-time verification to prevent timing attacks
  • Automatic rotation support for signing keys
  • Verification command: mc audit-verify
# Verify audit log integrity
mc audit-verify -v

# Results:
# βœ… All entries have valid signatures
# ❌ Invalid signatures detected (possible tampering)

3. Input Validation & Sanitization

All user inputs are validated and sanitized:

Input Type Validation
File Paths Path traversal blocked (../, ..\)
Container Names Whitelist validation
Commands Dangerous characters filtered, blocked command list
Environment Variables Prototype pollution keys rejected
Log Entries Control characters sanitized
Contact Names Max 100 chars, special char ratio limits
Contact Values Email/phone/URL format validation
Export Filenames Path traversal prevention, basename extraction

Contacts Security

The mc contacts command implements comprehensive input validation:

Input Validation:

  • Names: Max 100 chars, control character rejection, special character ratio limits
  • Emails: RFC 5322 format validation
  • Phone numbers: International format support with character filtering
  • URLs: Scheme validation (http/https only), prevents javascript: URLs
  • Tags: Alphanumeric with hyphens only, max 50 chars
  • Search queries: Regex special character sanitization, max 200 chars

Export Security:

  • Path traversal prevention: Filenames sanitized to basename only
  • CSV injection protection: Formula characters (=, +, -, @) prefixed with single quote
  • Markdown sanitization: Contact data escaped for safe markdown rendering

Data Sanitization:

  • All loaded contacts are sanitized to prevent injection from tampered files
  • Truncation of oversized fields (DoS prevention)
  • Filtering of invalid contact methods and tags
  • Default category fallback for invalid inputs

4. Container Execution Security

The mc exec command implements multiple safeguards:

  • Container whitelist - Only MasterClaw containers allowed
  • Blocked commands - rm, dd, mkfs, fdisk, etc. blocked
  • Resource limits:
    • Max 128 processes (fork bomb protection)
    • Max 1GB memory
    • Max 2048 file descriptors
    • Max 8MB stack size
  • Timeout protection - 5 min default, 30 min interactive
  • Audit logging - All executions logged

5. Rate Limiting

Command-level rate limiting prevents abuse:

Category Commands Limit Window
πŸ”’ High Security config-audit, audit-verify, security, exec 3-10 1-5 min
πŸš€ Deployment deploy, revive 5-10 1-5 min
πŸ’Ύ Data Modification cleanup, import 5-10 1 min
πŸ“– Read-Only status, health, logs 30-60 1 min

6. SSRF Protection

Domain validation prevents Server-Side Request Forgery:

  • Private IP ranges blocked (10.x, 192.168.x, 127.x, etc.)
  • Internal hostnames flagged (localhost, internal, etc.)
  • Suspicious patterns detected (.local, .internal, IP-as-domain)

7. Circuit Breaker Pattern

Service resilience through circuit breakers:

  • Fail-fast after 3 consecutive failures
  • Automatic recovery testing in half-open state
  • Per-service isolation - failures don't cascade
  • Error rate monitoring - opens at 60% error rate
  • Graceful degradation - fallback support for continued operation during outages

Circuit Breaker Fallbacks

When a circuit is open, services can degrade gracefully using fallbacks:

// Static fallback value
const result = await executeWithCircuit('payment-service',
  async () => await processPayment(order),
  { fallbackValue: { status: 'queued', message: 'Payment will be processed later' } }
);

// Dynamic fallback function (e.g., cached data)
const result = await executeWithCircuit('user-service',
  async () => await fetchUserProfile(userId),
  { fallbackFn: async () => await getCachedProfile(userId) }
);

Benefits:

  • Continued operation - Services remain functional during dependency outages
  • Audit trail - Fallback usage is logged for monitoring
  • Metrics - Track fallback frequency to identify chronic issues

8. Secure HTTP Client πŸ†•

The lib/http-client.js module provides a centralized, security-hardened HTTP client for all outbound requests:

Security Features:

Feature Protection
SSRF Prevention Blocks requests to private IPs, internal hostnames, and suspicious domains
DNS Rebinding Protection Validates resolved IP addresses to prevent DNS rebinding attacks
URL Scheme Validation Rejects data:, file:, and javascript: URLs
Header Injection Prevention Sanitizes headers to prevent CRLF injection attacks
Response Size Limits Prevents DoS via oversized responses (10MB max)
Timeout Enforcement Configurable timeouts with safe defaults (10s) and limits
Redirect Limiting Maximum 5 redirect hops to prevent redirect loops
Audit Logging All external calls logged with correlation IDs

DNS Rebinding Protection

DNS rebinding is a sophisticated attack where:

  1. An attacker controls a domain that initially resolves to a public IP (passing hostname-based SSRF checks)
  2. After the DNS TTL expires, the domain resolves to a private/internal IP
  3. The attacker can now access internal services that should be protected

MasterClaw's HTTP client protects against DNS rebinding by:

  • Performing DNS resolution before making the request
  • Validating that resolved IP addresses are not private (unless explicitly allowed)
  • Logging DNS rebinding attempts as CRITICAL security violations

Usage:

const httpClient = require('./lib/http-client');

// Protected against DNS rebinding - validates resolved IPs
const response = await httpClient.get('https://api.example.com/data');

// POST request with audit logging
const result = await httpClient.post(
  'https://api.example.com/webhook',
  { event: 'deployment' },
  httpClient.withAudit({ timeout: 5000 })
);

// Allow private IPs for internal service calls
const health = await httpClient.get(
  'http://localhost:8000/health',
  httpClient.allowPrivateIPs()
);

// Health check helper
const status = await httpClient.healthCheck('https://api.example.com/health');
// Returns: { healthy: true/false, status: 200, responseTime: 45, error: null }

SSRF Protection by Default: The client automatically blocks requests to:

  • Private IP ranges (10.x.x.x, 192.168.x.x, 172.16-31.x.x, 127.x.x.x)
  • Link-local addresses (169.254.x.x)
  • Internal hostnames (localhost, *.local, *.internal, *.lan)
  • Suspicious patterns (IP-as-domain, hex-encoded IPs)

To allow private IPs for legitimate internal service communication:

await httpClient.get(url, httpClient.allowPrivateIPs());

Audit Integration: All external HTTP calls can be audited:

// Log this request to the audit trail
await httpClient.get(url, httpClient.withAudit());

Security violations (SSRF attempts, oversized responses) are automatically logged as SECURITY_VIOLATION events.

πŸ› Reporting Vulnerabilities

We take security seriously. If you discover a vulnerability:

Responsible Disclosure

  1. Do NOT open a public issue
  2. Email security concerns to: security@masterclaw.local (placeholder)
  3. Allow 90 days for remediation before public disclosure
  4. Provide detailed reproduction steps

What to Include

  • Description of the vulnerability
  • Steps to reproduce
  • Potential impact
  • Suggested fix (if any)
  • Your contact information for coordination

Response Process

Timeline Action
Within 48 hours Acknowledgment of report
Within 7 days Initial assessment
Within 90 days Fix released or timeline communicated
Upon fix Public disclosure with credit

πŸ“‹ Security Checklist

For Administrators

  • Run mc config-audit to verify file permissions
  • Run mc secrets check to validate required secrets
  • Run mc audit-verify to check log integrity
  • Enable audit logging in production
  • Set strong GATEWAY_TOKEN (min 16 characters)
  • Review mc security output regularly
  • Keep MasterClaw CLI updated

For Developers

  • Use wrapCommand() for all new commands
  • Use httpClient for all outbound HTTP requests
  • Sanitize all user inputs with sanitizeForLog()
  • Mask sensitive data with maskSensitiveData()
  • Log security events via logAudit()
  • Validate file paths with containsPathTraversal()
  • Use constant-time comparison for secrets
  • Add tests for security-critical paths

For Deployment

  • Validate environment with mc validate before deployment
  • Run smoke tests with mc smoke-test after deployment
  • Set up log rotation for audit logs
  • Configure backup encryption
  • Enable rate limiting in production
  • Set resource limits on containers

πŸ” Security Best Practices

1. Secrets Management

# Good: Use CLI secrets management
mc secrets set GATEWAY_TOKEN "$(openssl rand -hex 32)"
mc secrets rotate GATEWAY_TOKEN

# Bad: Hardcode in scripts or commit to git
echo "TOKEN=hardcoded" > .env  # ❌ Don't do this

2. Audit Log Monitoring

# Check for security violations
mc audit -t SECURITY_VIOLATION --hours 24

# Monitor for failed authentications
mc audit -t AUTH_FAILURE -s warning

# Set up automated integrity checks
mc audit-verify --hours 168  # Weekly

3. Container Access

# Good: Use resource-limited exec
mc exec mc-core "python --version"

# Bad: Bypass security with env override
MC_EXEC_NO_RESOURCE_LIMITS=1 mc exec mc-core "heavy-command"  # ⚠️ Avoid

4. Backup Security

# Verify backup integrity
mc backup-verify

# Enable cloud backup encryption
mc backup cloud setup  # Uses server-side encryption

# Test restore procedure regularly
mc restore preview <backup-name>

🎯 Threat Model

Assets

Asset Value Protection
API Keys High Encryption at rest, masked display
Audit Logs High HMAC signatures, append-only
Container Access High Whitelist, resource limits
User Data Medium Access controls, validation
Configuration Medium File permissions, validation

Threats

Threat Likelihood Impact Mitigation
Path Traversal Medium High Input validation, path sanitization
Command Injection Low Critical Command filtering, blocked commands
Secret Exposure Medium Critical Encryption, masking, secure permissions
Audit Tampering Low High HMAC signatures, integrity checks
DoS via Resource Exhaustion Medium Medium Rate limiting, resource limits
Prototype Pollution Low Medium Key validation, safe merge
SSRF Low High Domain validation, IP filtering

Trust Boundaries

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                      User (Trusted)                         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                            β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                MasterClaw CLI (Trusted)                     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”        β”‚
β”‚  β”‚   Validate   β”‚ β”‚    Audit     β”‚ β”‚    Rate      β”‚        β”‚
β”‚  β”‚    Input     β”‚ β”‚     Log      β”‚ β”‚    Limit     β”‚        β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                            β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              Docker Daemon (Semi-Trusted)                   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                            β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              MasterClaw Services (Trusted)                  β”‚
β”‚         (core, backend, gateway, chroma)                    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ”§ Security Configuration

Environment Variables

Variable Purpose Security Level
MC_JSON_OUTPUT Structured logging Info
MC_VERBOSE Debug output Warning (may leak data)
MC_CORRELATION_ID Request tracing Info
MC_EXEC_NO_RESOURCE_LIMITS Disable limits Critical (avoid in prod)
GATEWAY_TOKEN Auth token Critical
OPENAI_API_KEY API access Critical

File Permissions

# Expected permissions
~/.masterclaw/
β”œβ”€β”€ config.json          # 0o600 (rw-------)
β”œβ”€β”€ secrets.json         # 0o600 (rw-------)
β”œβ”€β”€ .secrets.key         # 0o600 (rw-------)
└── audit/
    β”œβ”€β”€ audit.log        # 0o600 (rw-------)
    └── .audit.key       # 0o600 (rw-------)

🚨 Security Incident Response

Detection

# Automated security scanning
mc security --hours 24

# Check for integrity violations
mc audit-verify

# Monitor circuit breaker status
mc circuits

Response Playbook

  1. Isolate - Stop affected services if necessary
  2. Preserve - Backup audit logs before they rotate
  3. Analyze - Review audit logs with mc audit --verify
  4. Remediate - Fix the vulnerability
  5. Verify - Run mc security and mc doctor
  6. Document - Update this documentation if needed

πŸ“š Additional Resources

πŸ“ Version History

Version Date Changes
1.0 2026-02-18 Initial security documentation

Note: This is a living document. Security features and practices evolve. Please contribute improvements via pull requests or report issues through the responsible disclosure process.

There aren't any published security advisories