MasterClaw Security: This document outlines security features, threat model, vulnerability reporting, and best practices for the MasterClaw CLI ecosystem.
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 |
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 diskAudit 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)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 |
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
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
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 |
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)
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
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
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 is a sophisticated attack where:
- An attacker controls a domain that initially resolves to a public IP (passing hostname-based SSRF checks)
- After the DNS TTL expires, the domain resolves to a private/internal IP
- 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.
We take security seriously. If you discover a vulnerability:
- Do NOT open a public issue
- Email security concerns to:
security@masterclaw.local(placeholder) - Allow 90 days for remediation before public disclosure
- Provide detailed reproduction steps
- Description of the vulnerability
- Steps to reproduce
- Potential impact
- Suggested fix (if any)
- Your contact information for coordination
| 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 |
- Run
mc config-auditto verify file permissions - Run
mc secrets checkto validate required secrets - Run
mc audit-verifyto check log integrity - Enable audit logging in production
- Set strong
GATEWAY_TOKEN(min 16 characters) - Review
mc securityoutput regularly - Keep MasterClaw CLI updated
- Use
wrapCommand()for all new commands - Use
httpClientfor 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
- Validate environment with
mc validatebefore deployment - Run smoke tests with
mc smoke-testafter deployment - Set up log rotation for audit logs
- Configure backup encryption
- Enable rate limiting in production
- Set resource limits on containers
# 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# 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# 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# 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>| 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 |
| 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 |
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β User (Trusted) β
βββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ
β MasterClaw CLI (Trusted) β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β Validate β β Audit β β Rate β β
β β Input β β Log β β Limit β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
βββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ
β Docker Daemon (Semi-Trusted) β
βββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ
β MasterClaw Services (Trusted) β
β (core, backend, gateway, chroma) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| 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 |
# Expected permissions
~/.masterclaw/
βββ config.json # 0o600 (rw-------)
βββ secrets.json # 0o600 (rw-------)
βββ .secrets.key # 0o600 (rw-------)
βββ audit/
βββ audit.log # 0o600 (rw-------)
βββ .audit.key # 0o600 (rw-------)# Automated security scanning
mc security --hours 24
# Check for integrity violations
mc audit-verify
# Monitor circuit breaker status
mc circuits- Isolate - Stop affected services if necessary
- Preserve - Backup audit logs before they rotate
- Analyze - Review audit logs with
mc audit --verify - Remediate - Fix the vulnerability
- Verify - Run
mc securityandmc doctor - Document - Update this documentation if needed
| 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.