- name
- afrexai-cybersecurity-engine
- description
- Complete cybersecurity assessment, threat modeling, and hardening system. Use when conducting security audits, threat modeling, penetration testing, incident response, or building security programs from scratch. Works with any stack — zero external dependencies.
- metadata
- {"openclaw":{"emoji":"🛡️","os":["linux","darwin","win32"]}}
# Cybersecurity Engine
Complete methodology for security assessment, threat modeling, vulnerability management, incident response, and security program design. No tools required — pure agent knowledge that works with any codebase, infrastructure, or organization.
## Phase 1: Security Posture Assessment
### Quick Health Check (5 minutes)
Run through these three tiers:
**Tier 1 — Critical (fix today):**
- [ ] Default credentials in production
- [ ] Secrets in source code or environment files committed to git
- [ ] No authentication on admin endpoints
- [ ] SQL injection in user-facing forms
- [ ] Unencrypted sensitive data at rest
- [ ] Public S3 buckets or cloud storage
- [ ] No HTTPS enforcement
- [ ] Root/admin running application processes
**Tier 2 — High (fix this week):**
- [ ] Dependencies with known CVEs (CVSS ≥ 7.0)
- [ ] No rate limiting on authentication endpoints
- [ ] Missing CSRF protection on state-changing operations
- [ ] Verbose error messages leaking stack traces
- [ ] No input validation on API endpoints
- [ ] Weak password policy (< 12 chars, no complexity)
- [ ] Session tokens in URL parameters
- [ ] No logging of authentication events
**Tier 3 — Medium (fix this sprint):**
- [ ] Missing security headers (CSP, HSTS, X-Frame-Options)
- [ ] No automated dependency scanning in CI
- [ ] Overprivileged service accounts
- [ ] No secret rotation policy
- [ ] Missing account lockout after failed attempts
- [ ] No security.txt or responsible disclosure policy
- [ ] Cookies without Secure/HttpOnly/SameSite flags
**Score:** Count failures. 0-2 = solid. 3-5 = needs work. 6+ = stop shipping features, fix security.
### Full Assessment Brief
```yaml
assessment:
name: "[Project/Org Name] Security Assessment"
date: "YYYY-MM-DD"
assessor: "[Agent/Person]"
scope:
applications:
- name: "[App Name]"
type: "web|api|mobile|desktop|iot"
tech_stack: "[languages, frameworks, DBs]"
hosting: "cloud|on-prem|hybrid"
cloud_provider: "aws|gcp|azure|other"
internet_facing: true|false
handles_pii: true|false
handles_payments: true|false
handles_phi: true|false # health data
infrastructure:
- servers: "[count, OS types]"
containers: true|false
orchestration: "k8s|ecs|nomad|none"
cdn: "[provider or none]"
dns: "[provider]"
third_parties:
- name: "[service]"
data_shared: "[what data]"
criticality: "high|medium|low"
compliance_requirements:
- "SOC 2|ISO 27001|GDPR|HIPAA|PCI DSS|SOX|none"
previous_incidents:
- date: "YYYY-MM-DD"
type: "[breach|vuln|misconfiguration]"
severity: "critical|high|medium|low"
resolution: "[what was done]"
risk_tolerance: "conservative|moderate|aggressive"
```
## Phase 2: Threat Modeling (STRIDE+)
### Step 1 — Decompose the System
For each application, draw the data flow:
```
[User] → [CDN/WAF] → [Load Balancer] → [Web Server] → [App Server] → [Database]
↘ [Cache]
↘ [Message Queue] → [Worker]
↘ [Third-party API]
↘ [Object Storage]
```
**Identify trust boundaries** — where privilege level changes:
- Internet → DMZ (public-facing services)
- DMZ → Internal network (app servers, DBs)
- App → Database (credential boundary)
- User → Admin (role boundary)
- Service → Service (API key boundary)
- Your infra → Third-party (trust boundary)
### Step 2 — STRIDE Analysis Per Component
For EACH component crossing a trust boundary:
| Threat | Question | Example Attack |
|--------|----------|----------------|
| **S**poofing | Can an attacker pretend to be someone else? | Stolen JWT, session hijacking, credential stuffing |
| **T**ampering | Can data be modified in transit or at rest? | Man-in-the-middle, SQL injection, parameter manipulation |
| **R**epudiation | Can someone deny they did something? | Missing audit logs, unsigned transactions |
| **I**nformation Disclosure | Can sensitive data leak? | Error messages, API over-fetching, side channels |
| **D**enial of Service | Can the service be overwhelmed? | DDoS, resource exhaustion, regex DoS |
| **E**levation of Privilege | Can someone gain unauthorized access? | IDOR, broken access control, privilege escalation |
### Step 3 — Threat Register
```yaml
threats:
- id: "T-001"
component: "[affected component]"
category: "S|T|R|I|D|E"
description: "[specific attack scenario]"
attacker_profile: "external-unauthenticated|external-authenticated|internal|insider"
likelihood: 1-5 # 1=rare, 5=almost certain
impact: 1-5 # 1=negligible, 5=catastrophic
risk_score: 0 # likelihood × impact
existing_controls: "[what's already in place]"
residual_risk: "accept|mitigate|transfer|avoid"
mitigation: "[specific fix]"
priority: "P0|P1|P2|P3"
owner: "[person/team]"
status: "open|in-progress|mitigated|accepted"
```
### Priority Rules
- **P0** (risk ≥ 20): Fix immediately, stop other work
- **P1** (risk 12-19): Fix within 1 week
- **P2** (risk 6-11): Fix within 1 sprint
- **P3** (risk ≤ 5): Track, fix when convenient
## Phase 3: Application Security (OWASP Top 10 + Beyond)
### A01: Broken Access Control
**Test checklist:**
- [ ] Can user A access user B's resources by changing ID? (IDOR)
- [ ] Can non-admin access admin endpoints?
- [ ] Do API endpoints enforce authorization, not just authentication?
- [ ] Are directory listings disabled?
- [ ] Is CORS properly configured (not `*` with credentials)?
- [ ] Can JWT be tampered with (alg=none, key confusion)?
- [ ] Is rate limiting applied to sensitive endpoints?
- [ ] Do file uploads validate type server-side?
**Fix patterns:**
```
# Authorization check pattern (every endpoint)
1. Authenticate → verify identity
2. Authorize → verify permission for THIS resource
3. Validate → verify input is within allowed bounds
4. Execute → perform the action
5. Audit → log who did what
# IDOR prevention
- NEVER use sequential IDs in URLs — use UUIDs
- ALWAYS verify resource ownership server-side
- Use middleware that auto-checks resource.owner === request.user
```
### A02: Cryptographic Failures
**Decision tree:**
```
Need to store passwords?
→ bcrypt (cost 12+) or Argon2id
→ NEVER: MD5, SHA1, SHA256 without salt
Need to encrypt data at rest?
→ AES-256-GCM (authenticated encryption)
→ NEVER: ECB mode, DES, RC4
Need to encrypt in transit?
→ TLS 1.2+ (prefer 1.3)
→ HSTS with includeSubDomains
→ Certificate pinning for mobile apps
Need to generate random values?
→ crypto.randomBytes() / secrets.token_bytes()
→ NEVER: Math.random(), random.random()
Need to sign/verify?
→ HMAC-SHA256 for symmetric
→ Ed25519 or RSA-PSS (2048+ bits) for asymmetric
→ NEVER: RSA PKCS#1 v1.5 for new systems
```
### A03: Injection
**SQL Injection prevention:**
```
# ALWAYS use parameterized queries
✅ db.query("SELECT * FROM users WHERE id = $1", [userId])
❌ db.query("SELECT * FROM users WHERE id = " + userId)
# Test payloads (for YOUR code, during testing):
' OR '1'='1
'; DROP TABLE users;--
' UNION SELECT password FROM users--
1; WAITFOR DELAY '0:0:5'--
```
**XSS prevention:**
```
# Output encoding rules:
HTML body → HTML entity encode (< > & " ')
HTML attr → Attribute encode + always quote attributes
JavaScript → JavaScript encode (\\xHH)
URL → Percent encode (%HH)
CSS → CSS encode (\\HHHHHH)
# CSP header (strong baseline):
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://api.yourdomain.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'
```
**Command injection prevention:**
```
# NEVER pass user input to shell
✅ execFile('convert', ['-resize', size, inputFile, outputFile])
❌ exec('convert -resize ' + size + ' ' + inputFile + ' ' + outputFile)
# If you MUST use shell:
- Whitelist allowed characters (alphanumeric only)
- Use library wrappers, never string concatenation
```
### A04: Insecure Design
**Secure design checklist:**
- [ ] Business logic abuse scenarios documented
- [ ] Rate limiting on expensive operations
- [ ] Fail-safe defaults (deny by default)
- [ ] Separation of duties for critical operations
- [ ] Multi-step transactions use CSRF tokens
- [ ] API pagination has max limit
- [ ] File uploads have size limits AND type validation (magic bytes, not extension)
- [ ] Background job payloads are signed/validated
### A05: Security Misconfiguration
**Server hardening checklist:**
```yaml
web_server:
- remove_default_pages: true
- disable_directory_listing: true
- remove_server_version_header: true
- disable_TRACE_method: true
- custom_error_pages: true # no stack traces
application:
- debug_mode: false # NEVER in production
- verbose_errors: false
- default_accounts_removed: true
- unnecessary_features_disabled: true
- admin_panel_ip_restricted: true
cloud:
- public_buckets: none
- security_groups_least_privilege: true
- imds_v2_enforced: true # AWS
- logging_enabled: true
- mfa_on_root: true
- billing_alerts: true
```
### A06-A10 Quick Checks
| Vuln | Test | Fix |
|------|------|-----|
| A06: Vulnerable Components | `npm audit`, `pip-audit`, `trivy fs .` | Update, pin versions, automate scanning in CI |
| A07: Auth Failures | Brute force test, password policy audit, MFA coverage | Rate limit + lockout, enforce MFA, bcrypt/Argon2 |
| A08: Data Integrity | Can unsigned data modify app behavior? | Sign all serialized data, verify checksums, SRI for CDN |
| A09: Logging Gaps | Do you log auth events, access changes, failures? | Structured logging, SIEM integration, alert on anomalies |
| A10: SSRF | Can user input trigger server-side requests? | Allowlist URLs, block internal IPs, no redirects to internal |
## Phase 4: Infrastructure Security
### Network Security Baseline
```yaml
network_hardening:
firewall:
default_policy: "deny-all"
allowed_inbound:
- port: 443
source: "0.0.0.0/0"
service: "HTTPS"
- port: 22
source: "[admin_ip_range]"
service: "SSH"
rules:
- "No direct database access from internet"
- "Internal services communicate on private subnet"
- "Egress filtering — block unnecessary outbound"
ssh:
password_auth: false
root_login: false
key_type: "ed25519"
port: "[non-standard recommended]"
fail2ban: true
max_auth_tries: 3
dns:
dnssec: true
caa_records: true # restrict who can issue TLS certs
no_zone_transfer: true
tls:
min_version: "1.2"
preferred: "1.3"
cipher_suites: "ECDHE+AESGCM:ECDHE+CHACHA20"
hsts: "max-age=31536000; includeSubDomains; preload"
certificate_monitoring: true
auto_renewal: true
```
### Container Security
```yaml
container_hardening:
image:
- base: "distroless or alpine (minimal)"
- user: "non-root (USER 1000:1000)"
- scan: "trivy image before push"
- sign: "cosign or Notary"
- pins: "use SHA256 digests, not :latest"
- secrets: "NEVER in Dockerfile or image layers"
- layers: "multi-stage builds, minimal final image"
runtime:
- read_only_rootfs: true
- no_new_privileges: true
- drop_all_capabilities: true
- add_only: ["NET_BIND_SERVICE"] # if needed
- resource_limits: true
- seccomp_profile: "default"
- network_policy: "deny by default"
registry:
- private: true
- vulnerability_scanning: true
- image_signing: true
- tag_immutability: true
```
### Cloud Security (AWS/GCP/Azure Universal)
```yaml
cloud_security_baseline:
identity:
- root_account_mfa: true
- no_root_access_keys: true
- least_privilege_iam: true
- service_accounts_scoped: true
- temporary_credentials: true # assume role, not long-lived keys
- sso_enforced: true
data:
- encryption_at_rest: "default on all storage"
- encryption_in_transit: "TLS everywhere"
- backup_encryption: true
- key_management: "cloud KMS, not self-managed"
- data_classification: true
network:
- vpc_flow_logs: true
- private_subnets_for_databases: true
- nat_gateway_for_outbound: true
- waf_on_public_endpoints: true
- ddos_protection: true
monitoring:
- cloudtrail_enabled: true # or equivalent
- config_rules: true
- guardduty_enabled: true # or equivalent
- cost_alerts: true
- unused_resource_alerts: true
storage:
- no_public_buckets: true
- versioning_on_critical: true
- lifecycle_policies: true
- access_logging: true
```
## Phase 5: Vulnerability Management Program
### Vulnerability Lifecycle
```
Discovery → Triage → Prioritize → Remediate → Verify → Close
↓ ↓ ↓ ↓ ↓
Scan/ Confirm CVSS + Fix or Retest
Report real? context compensate
```
### Severity SLA
| Severity | CVSS | Remediation SLA | Escalation |
|----------|------|-----------------|------------|
Auf GitHub ansehen