Senior Security Engineer — Threat Modeling + Security Router This skill does exactly one job itself — STRIDE/DREAD threat modeling (plus a quick secret scan) — and routes every other security request to the specialist skill that owns that lane. Do not duplicate sibling content here; route instead. Routing Table (read this first) | The user wants... | Route to | Why that skill owns it | |---|---|---| | Vulnerability assessment, pen-test methodology, OWASP Top 10 testing | | Ships + with exit-code contracts | | Incident triage, SEV classification, forensics, containment | | SEV1–SEV4 taxonomy,…

)\n password: constr(min_length=12, max_length=128)\n\n @validator('email')\n def validate_email(cls, v):\n email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}

Senior Security Engineer — Threat Modeling + Security Router This skill does exactly one job itself — STRIDE/DREAD threat modeling (plus a quick secret scan) — and routes every other security request to the specialist skill that owns that lane. Do not duplicate sibling content here; route instead. Routing Table (read this first) | The user wants... | Route to | Why that skill owns it | |---|---|---| | Vulnerability assessment, pen-test methodology, OWASP Top 10 testing | | Ships + with exit-code contracts | | Incident triage, SEV classification, forensics, containment | | SEV1–SEV4 taxonomy,…

\n if not re.match(email_regex, v):\n raise ValueError('Invalid email format')\n return v.lower()\n\n @validator('password')\n def validate_password_strength(cls, v):\n if not re.search(r'[A-Z]', v):\n raise ValueError('Password must contain uppercase letter')\n if not re.search(r'[a-z]', v):\n raise ValueError('Password must contain lowercase letter')\n if not re.search(r'\\d', v):\n raise ValueError('Password must contain digit')\n if not re.search(r'[!@#$%^&*(),.?\":{}|\u003c>]', v):\n raise ValueError('Password must contain special character')\n return v\n```\n\n### Rate Limiting\n\n```python\nfrom redis import Redis\nfrom functools import wraps\nimport time\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter with Redis backend.\"\"\"\n\n def __init__(self, redis_client):\n self.redis = redis_client\n\n def is_allowed(self, key, limit, window_seconds):\n \"\"\"Check if request is within rate limit.\"\"\"\n pipe = self.redis.pipeline()\n now = time.time()\n window_start = now - window_seconds\n\n # Remove old entries\n pipe.zremrangebyscore(key, 0, window_start)\n # Count current entries\n pipe.zcard(key)\n # Add new entry\n pipe.zadd(key, {str(now): now})\n # Set expiry\n pipe.expire(key, window_seconds)\n\n results = pipe.execute()\n current_count = results[1]\n\n return current_count \u003c limit\n\ndef rate_limit(limit=100, window=3600, key_func=None):\n \"\"\"Rate limiting decorator.\"\"\"\n def decorator(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n if key_func:\n key = f\"rate_limit:{key_func()}\"\n else:\n key = f\"rate_limit:{request.remote_addr}:{f.__name__}\"\n\n if not rate_limiter.is_allowed(key, limit, window):\n return {\n 'error': 'Rate limit exceeded',\n 'retry_after': window\n }, 429\n\n return f(*args, **kwargs)\n return decorated\n return decorator\n```\n\n### SQL Injection Prevention\n\n```python\n# NEVER: String concatenation\n# query = f\"SELECT * FROM users WHERE id = {user_id}\"\n\n# ALWAYS: Parameterized queries\nfrom sqlalchemy import text\n\ndef get_user_secure(user_id):\n \"\"\"Safe parameterized query.\"\"\"\n query = text(\"SELECT * FROM users WHERE id = :user_id\")\n result = db.execute(query, {'user_id': user_id})\n return result.fetchone()\n\n# For dynamic queries, use ORM\ndef search_users(filters):\n \"\"\"Safe dynamic query with ORM.\"\"\"\n query = User.query\n\n if 'name' in filters:\n # ORM handles escaping\n query = query.filter(User.name.ilike(f\"%{filters['name']}%\"))\n\n if 'role' in filters:\n query = query.filter(User.role == filters['role'])\n\n return query.all()\n```\n\n---\n\n## Data Protection Patterns\n\n### Encryption at Rest\n\n```python\nfrom cryptography.fernet import Fernet\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC\nimport base64\nimport os\n\nclass FieldEncryption:\n \"\"\"Encrypt sensitive database fields.\"\"\"\n\n def __init__(self, master_key):\n self.fernet = Fernet(master_key)\n\n @staticmethod\n def derive_key(password, salt):\n \"\"\"Derive encryption key from password.\"\"\"\n kdf = PBKDF2HMAC(\n algorithm=hashes.SHA256(),\n length=32,\n salt=salt,\n iterations=480000,\n )\n key = base64.urlsafe_b64encode(kdf.derive(password.encode()))\n return key\n\n def encrypt(self, plaintext):\n \"\"\"Encrypt a field value.\"\"\"\n if isinstance(plaintext, str):\n plaintext = plaintext.encode()\n return self.fernet.encrypt(plaintext).decode()\n\n def decrypt(self, ciphertext):\n \"\"\"Decrypt a field value.\"\"\"\n if isinstance(ciphertext, str):\n ciphertext = ciphertext.encode()\n return self.fernet.decrypt(ciphertext).decode()\n\n# Usage in ORM\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(255)) # Not sensitive\n _ssn = db.Column('ssn', db.String(500)) # Encrypted\n\n @property\n def ssn(self):\n if self._ssn:\n return field_encryption.decrypt(self._ssn)\n return None\n\n @ssn.setter\n def ssn(self, value):\n if value:\n self._ssn = field_encryption.encrypt(value)\n else:\n self._ssn = None\n```\n\n### Secret Management\n\n| Storage Type | Use Case | Example |\n|--------------|----------|---------|\n| Environment variables | Container config | `DATABASE_URL` |\n| Secret manager | Application secrets | AWS Secrets Manager, HashiCorp Vault |\n| Hardware Security Module | Cryptographic keys | AWS CloudHSM |\n\n```python\n# HashiCorp Vault integration\nimport hvac\n\nclass VaultClient:\n def __init__(self, url, token):\n self.client = hvac.Client(url=url, token=token)\n\n def get_secret(self, path):\n \"\"\"Retrieve secret from Vault.\"\"\"\n secret = self.client.secrets.kv.v2.read_secret_version(path=path)\n return secret['data']['data']\n\n def get_database_credentials(self, role):\n \"\"\"Get dynamic database credentials.\"\"\"\n creds = self.client.secrets.database.generate_credentials(role)\n return {\n 'username': creds['data']['username'],\n 'password': creds['data']['password'],\n 'ttl': creds['lease_duration']\n }\n```\n\n---\n\n## Security Anti-Patterns\n\n### Anti-Pattern: Security Through Obscurity\n\n| Bad Practice | Why It's Wrong | Correct Approach |\n|--------------|----------------|------------------|\n| Custom encryption algorithm | Untested, likely breakable | Use AES-256-GCM, ChaCha20-Poly1305 |\n| Hidden admin URLs | Discovery via fuzzing | Proper authentication + authorization |\n| Encoded (not encrypted) secrets | Base64 is reversible | Use proper encryption |\n\n### Anti-Pattern: Trusting Client Input\n\n```python\n# BAD: Trusting client-provided data\[email protected]('/admin')\ndef admin_panel():\n # Client can forge this header!\n if request.headers.get('X-Is-Admin') == 'true':\n return render_admin()\n\n# GOOD: Server-side verification\[email protected]('/admin')\n@login_required\ndef admin_panel():\n if not current_user.has_role('admin'):\n abort(403)\n return render_admin()\n```\n\n### Anti-Pattern: Hardcoded Secrets\n\n```python\n# BAD: Hardcoded credentials\nDATABASE_URL = \"postgresql://admin:SuperSecret123@localhost/db\"\nAPI_KEY = \"sk-1234567890abcdef\"\n\n# GOOD: Environment variables + secret management\nimport os\nDATABASE_URL = os.environ['DATABASE_URL']\nAPI_KEY = vault_client.get_secret('api/keys')['api_key']\n```\n\n### Anti-Pattern: Verbose Error Messages\n\n```python\n# BAD: Reveals internal information\nexcept Exception as e:\n return {'error': str(e), 'stack_trace': traceback.format_exc()}, 500\n\n# GOOD: Generic message, detailed logging\nexcept Exception as e:\n logger.exception(f\"Internal error: {e}\")\n return {'error': 'An internal error occurred', 'request_id': request_id}, 500\n```\n\n---\n\n## Security Tools Reference\n\n| Category | Tools |\n|----------|-------|\n| SAST (Static Analysis) | Semgrep, SonarQube, Bandit (Python), ESLint security plugins |\n| DAST (Dynamic Analysis) | OWASP ZAP, Burp Suite, Nikto |\n| Dependency Scanning | Snyk, Dependabot, npm audit, pip-audit |\n| Secret Detection | GitLeaks, TruffleHog, detect-secrets |\n| Container Security | Trivy, Clair, Anchore |\n| Infrastructure | Terraform Sentinel, Checkov, tfsec |\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":22198,"content_sha256":"58afe30843a9363f20dc7908b456b37e2027504336dc627d2ab952789c34f32b"},{"filename":"references/threat-modeling-guide.md","content":"# Threat Modeling Guide\n\nSystematic approaches for identifying, analyzing, and mitigating security threats.\n\n---\n\n## Table of Contents\n\n- [Threat Modeling Process](#threat-modeling-process)\n- [STRIDE Framework](#stride-framework)\n- [Attack Trees](#attack-trees)\n- [DREAD Risk Scoring](#dread-risk-scoring)\n- [Data Flow Diagrams](#data-flow-diagrams)\n- [Common Attack Patterns](#common-attack-patterns)\n\n---\n\n## Threat Modeling Process\n\n### Workflow: Conduct Threat Model\n\n1. Define the scope and objectives:\n - System boundaries\n - Assets to protect\n - Trust levels\n2. Create data flow diagram:\n - External entities\n - Processes\n - Data stores\n - Data flows\n - Trust boundaries\n3. Identify threats using STRIDE:\n - Apply STRIDE to each DFD element\n - Document threat scenarios\n4. Analyze and prioritize risks:\n - Score using DREAD\n - Rank by severity\n5. Define mitigations:\n - Map controls to threats\n - Identify gaps\n6. Validate and iterate:\n - Review with team\n - Update as system evolves\n7. Document in threat model report\n8. **Validation:** All DFD elements analyzed; threats documented; mitigations mapped; residual risks accepted\n\n### Threat Model Template\n\n```\nTHREAT MODEL REPORT\n\nSystem: [System Name]\nVersion: [Version]\nDate: [Date]\nAuthor: [Name]\n\n1. SYSTEM OVERVIEW\n - Purpose: [Description]\n - Users: [User types]\n - Data: [Data classification]\n\n2. SCOPE\n - In Scope: [Components included]\n - Out of Scope: [Components excluded]\n - Assumptions: [Security assumptions]\n\n3. DATA FLOW DIAGRAM\n [DFD image or ASCII representation]\n\n4. THREATS IDENTIFIED\n | ID | Element | STRIDE | Threat | DREAD | Mitigation |\n |----|---------|--------|--------|-------|------------|\n\n5. RESIDUAL RISKS\n [Accepted risks with justification]\n\n6. RECOMMENDATIONS\n [Prioritized security improvements]\n```\n\n---\n\n## STRIDE Framework\n\nCategorization model for identifying threats.\n\n### STRIDE Categories\n\n| Category | Description | Violated Property |\n|----------|-------------|-------------------|\n| **S**poofing | Pretending to be someone/something else | Authentication |\n| **T**ampering | Modifying data or code | Integrity |\n| **R**epudiation | Denying actions occurred | Non-repudiation |\n| **I**nformation Disclosure | Exposing data to unauthorized parties | Confidentiality |\n| **D**enial of Service | Making system unavailable | Availability |\n| **E**levation of Privilege | Gaining unauthorized access | Authorization |\n\n### STRIDE per Element\n\n| DFD Element | Applicable Threats |\n|-------------|-------------------|\n| External Entity | S, R |\n| Process | S, T, R, I, D, E |\n| Data Store | T, R, I, D |\n| Data Flow | T, I, D |\n\n### STRIDE Analysis Template\n\n```\nSTRIDE ANALYSIS\n\nElement: User Authentication Service\nType: Process\n\n┌─────────────────────────────────────────────────────────────────┐\n│ SPOOFING │\n├─────────────────────────────────────────────────────────────────┤\n│ Threat: Attacker uses stolen credentials to impersonate user │\n│ Attack Vector: Phishing, credential stuffing, session hijack │\n│ Likelihood: High │\n│ Impact: High - Full account access │\n│ Mitigation: MFA, session binding, anomaly detection │\n└─────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────┐\n│ TAMPERING │\n├─────────────────────────────────────────────────────────────────┤\n│ Threat: Attacker modifies authentication request in transit │\n│ Attack Vector: Man-in-the-middle, request manipulation │\n│ Likelihood: Medium │\n│ Impact: High - Bypass authentication │\n│ Mitigation: TLS 1.3, request signing, HSTS │\n└─────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────┐\n│ REPUDIATION │\n├─────────────────────────────────────────────────────────────────┤\n│ Threat: User denies performing privileged action │\n│ Attack Vector: Claim account was compromised │\n│ Likelihood: Medium │\n│ Impact: Medium - Dispute resolution difficulty │\n│ Mitigation: Comprehensive audit logging, log integrity │\n└─────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────┐\n│ INFORMATION DISCLOSURE │\n├─────────────────────────────────────────────────────────────────┤\n│ Threat: Password hashes exposed via SQL injection │\n│ Attack Vector: SQLi, backup exposure, error messages │\n│ Likelihood: Medium │\n│ Impact: Critical - Mass credential compromise │\n│ Mitigation: Parameterized queries, encryption, error handling │\n└─────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────┐\n│ DENIAL OF SERVICE │\n├─────────────────────────────────────────────────────────────────┤\n│ Threat: Brute force attacks overwhelm authentication service │\n│ Attack Vector: Credential stuffing, distributed attacks │\n│ Likelihood: High │\n│ Impact: High - Users cannot authenticate │\n│ Mitigation: Rate limiting, CAPTCHA, account lockout │\n└─────────────────────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────────────────────┐\n│ ELEVATION OF PRIVILEGE │\n├─────────────────────────────────────────────────────────────────┤\n│ Threat: Regular user gains admin privileges │\n│ Attack Vector: JWT manipulation, IDOR, role confusion │\n│ Likelihood: Medium │\n│ Impact: Critical - Full system compromise │\n│ Mitigation: Server-side authorization, signed tokens, RBAC │\n└─────────────────────────────────────────────────────────────────┘\n```\n\n### Threat Mitigation Matrix\n\n| STRIDE Category | Standard Mitigations |\n|-----------------|---------------------|\n| Spoofing | Authentication (passwords, MFA, certificates) |\n| Tampering | Integrity controls (signing, hashing, checksums) |\n| Repudiation | Audit logging, digital signatures, timestamps |\n| Information Disclosure | Encryption, access controls, data masking |\n| Denial of Service | Rate limiting, redundancy, filtering |\n| Elevation of Privilege | Authorization, least privilege, input validation |\n\n---\n\n## Attack Trees\n\nVisual representation of attack paths to a specific goal.\n\n### Attack Tree Structure\n\n```\nATTACK TREE: Compromise User Account\n\n ┌─────────────────────┐\n │ GOAL: Access User │\n │ Account │\n └──────────┬──────────┘\n │\n ┌───────────────────┼───────────────────┐\n │ │ │\n ┌──────┴──────┐ ┌──────┴──────┐ ┌──────┴──────┐\n │ Obtain │ │ Bypass │ │ Exploit │\n │ Credentials │ │ Auth │ │ Session │\n │ [OR] │ │ [OR] │ │ [OR] │\n └──────┬──────┘ └──────┬──────┘ └──────┬──────┘\n │ │ │\n ┌─────┼─────┐ ┌─────┼─────┐ ┌─────┼─────┐\n │ │ │ │ │ │ │ │ │\n ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐\n │Phi│ │Crd│ │Key│ │SQL│ │JWT│ │Pwd│ │XSS│ │Fix│ │Sid│\n │sh │ │Stf│ │Log│ │ i │ │Frg│ │Rst│ │ │ │tn │ │Hj │\n └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘\n\nLegend:\n- Phi: Phishing\n- CrdStf: Credential Stuffing\n- KeyLog: Keylogger\n- SQLi: SQL Injection\n- JWTFrg: JWT Forgery\n- PwdRst: Password Reset Flaw\n- XSS: Cross-Site Scripting\n- Fixtn: Session Fixation\n- SidHj: Session Hijacking\n```\n\n### Attack Tree Analysis\n\n| Attack Path | Difficulty | Detection | Priority |\n|-------------|------------|-----------|----------|\n| Phishing → Credential theft | Low | Medium | High |\n| SQL Injection → Auth bypass | Medium | High | Critical |\n| XSS → Session steal | Medium | Medium | High |\n| JWT forgery → Privilege escalation | High | Low | Critical |\n\n### Calculating Attack Probability\n\n```python\ndef calculate_attack_probability(attack_tree_node):\n \"\"\"\n Calculate cumulative probability of attack success.\n\n For OR nodes: P = 1 - (1-P1)(1-P2)...(1-Pn)\n For AND nodes: P = P1 * P2 * ... * Pn\n \"\"\"\n if node.is_leaf:\n return node.probability\n\n child_probs = [calculate_attack_probability(c) for c in node.children]\n\n if node.operator == 'OR':\n # At least one path succeeds\n prob_all_fail = 1\n for p in child_probs:\n prob_all_fail *= (1 - p)\n return 1 - prob_all_fail\n\n elif node.operator == 'AND':\n # All paths must succeed\n prob_all_succeed = 1\n for p in child_probs:\n prob_all_succeed *= p\n return prob_all_succeed\n```\n\n---\n\n## DREAD Risk Scoring\n\nQuantitative risk assessment for prioritizing threats.\n\n### DREAD Components\n\n| Factor | Description | Scale |\n|--------|-------------|-------|\n| **D**amage | How bad is the impact? | 1-10 |\n| **R**eproducibility | How easy to reproduce? | 1-10 |\n| **E**xploitability | How easy to exploit? | 1-10 |\n| **A**ffected Users | How many users impacted? | 1-10 |\n| **D**iscoverability | How easy to find? | 1-10 |\n\n### DREAD Scoring Guide\n\n**Damage Potential:**\n| Score | Description |\n|-------|-------------|\n| 10 | Complete system compromise, data destruction |\n| 7-9 | Large data breach, significant financial loss |\n| 4-6 | Partial data exposure, service degradation |\n| 1-3 | Minor information disclosure, low impact |\n\n**Reproducibility:**\n| Score | Description |\n|-------|-------------|\n| 10 | Always reproducible, automated |\n| 7-9 | Reproducible most of the time |\n| 4-6 | Reproducible with some effort |\n| 1-3 | Difficult to reproduce, timing dependent |\n\n**Exploitability:**\n| Score | Description |\n|-------|-------------|\n| 10 | No skills required, exploit exists |\n| 7-9 | Basic skills, tools available |\n| 4-6 | Moderate skills required |\n| 1-3 | Advanced skills, custom exploit needed |\n\n**Affected Users:**\n| Score | Description |\n|-------|-------------|\n| 10 | All users |\n| 7-9 | Large subset of users |\n| 4-6 | Some users |\n| 1-3 | Few or individual users |\n\n**Discoverability:**\n| Score | Description |\n|-------|-------------|\n| 10 | Publicly documented, obvious |\n| 7-9 | Easy to find via scanning |\n| 4-6 | Requires investigation |\n| 1-3 | Obscure, requires insider knowledge |\n\n### DREAD Calculation\n\n```python\ndef calculate_dread_score(damage, reproducibility, exploitability,\n affected_users, discoverability):\n \"\"\"\n Calculate DREAD risk score.\n\n Returns: Float between 1-10\n Risk Levels:\n 8-10: Critical\n 6-7.9: High\n 4-5.9: Medium\n 1-3.9: Low\n \"\"\"\n score = (damage + reproducibility + exploitability +\n affected_users + discoverability) / 5\n return round(score, 1)\n\ndef get_risk_level(dread_score):\n if dread_score >= 8:\n return 'Critical'\n elif dread_score >= 6:\n return 'High'\n elif dread_score >= 4:\n return 'Medium'\n else:\n return 'Low'\n```\n\n### DREAD Assessment Example\n\n```\nTHREAT: SQL Injection in Login Form\n\n| Factor | Score | Justification |\n|--------|-------|---------------|\n| Damage | 9 | Full database access, credential theft |\n| Reproducibility | 9 | Consistent, automated tools exist |\n| Exploitability | 8 | Well-documented attack, easy tools |\n| Affected Users | 10 | All users with accounts |\n| Discoverability | 7 | Scanners detect easily |\n\nDREAD Score: (9+9+8+10+7)/5 = 8.6\nRisk Level: CRITICAL\nPriority: Immediate remediation required\n```\n\n---\n\n## Data Flow Diagrams\n\nVisual representation of system data movement for security analysis.\n\n### DFD Elements\n\n| Symbol | Element | Security Considerations |\n|--------|---------|------------------------|\n| Rectangle | External Entity | Trust boundary crossing |\n| Circle/Oval | Process | All STRIDE threats apply |\n| Parallel Lines | Data Store | Tampering, disclosure, DoS |\n| Arrow | Data Flow | Tampering, disclosure, DoS |\n| Dashed Line | Trust Boundary | Authentication required |\n\n### DFD Levels\n\n| Level | Description | Use Case |\n|-------|-------------|----------|\n| Level 0 (Context) | Single process, external entities | Executive overview |\n| Level 1 | Major processes expanded | Architecture review |\n| Level 2 | Detailed subprocesses | Detailed threat modeling |\n\n### Example: E-Commerce DFD\n\n```\nLEVEL 0: CONTEXT DIAGRAM\n\n ┌──────────────────┐\n │ │\n ┌────────────┐ │ E-Commerce │ ┌────────────┐\n │ │ Orders │ System │ Payment │ │\n │ Customer │──────────▶│ │──────────▶│ Payment │\n │ │◀──────────│ │◀──────────│ Gateway │\n └────────────┘ Status │ │ Result └────────────┘\n │ │\n └──────────────────┘\n │\n │ Fulfillment\n ▼\n ┌────────────────┐\n │ Warehouse │\n │ System │\n └────────────────┘\n\n\nLEVEL 1: EXPANDED VIEW\n\n┌─────────────────────────────────────────────────────────────────────┐\n│ TRUST BOUNDARY │\n│ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - │\n│ │\n│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │\n│ │ │ │ Web │ │ Order │ │ Payment │ │\n│ │ CDN │──────▶│ Server │──────▶│ Service │──────▶│ Service │ │\n│ │ │ │ │ │ │ │ │ │\n│ └─────────┘ └────┬────┘ └────┬────┘ └────┬────┘ │\n│ │ │ │ │\n│ │ │ │ │\n│ ▼ ▼ ▼ │\n│ ╔═══════════╗ ╔═══════════╗ ╔═══════════╗ │\n│ ║ Session ║ ║ Orders ║ ║ Payment ║ │\n│ ║ Store ║ ║ DB ║ ║ DB ║ │\n│ ╚═══════════╝ ╚═══════════╝ ╚═══════════╝ │\n│ │\n└─────────────────────────────────────────────────────────────────────┘\n │\n │ Crosses Trust Boundary\n ▼\n ┌───────────┐\n │ Payment │\n │ Gateway │\n │ (External)│\n └───────────┘\n```\n\n### Trust Boundary Analysis\n\n| Boundary Crossing | Authentication | Authorization | Encryption |\n|-------------------|----------------|---------------|------------|\n| Customer → Web Server | Session cookie | - | TLS 1.3 |\n| Web Server → Order Service | mTLS | Service account | Internal TLS |\n| Order Service → DB | Connection pool | DB user roles | TLS |\n| Payment Service → Gateway | API key + HMAC | IP whitelist | TLS 1.3 |\n\n---\n\n## Common Attack Patterns\n\n### OWASP Top 10 Mapping\n\nCodes follow the [OWASP Top 10:2025](https://owasp.org/Top10/2025/).\n\n| Rank | Vulnerability | STRIDE | Common Attack |\n|------|---------------|--------|---------------|\n| A01 | Broken Access Control (incl. SSRF) | E, I | IDOR, privilege escalation, internal service access |\n| A02 | Security Misconfiguration | I, E | Default creds, verbose errors |\n| A03 | Software Supply Chain Failures | All | Outdated libraries, CVEs, compromised builds |\n| A04 | Cryptographic Failures | I | Weak encryption, exposed keys |\n| A05 | Injection | T, E | SQLi, XSS, command injection |\n| A06 | Insecure Design | All | Logic flaws, missing controls |\n| A07 | Authentication Failures | S, E | Credential stuffing, weak passwords |\n| A08 | Software or Data Integrity Failures | T | Unsigned updates, CI/CD attacks |\n| A09 | Security Logging and Alerting Failures | R | Missing logs, log injection |\n| A10 | Mishandling of Exceptional Conditions | D, E | Fail-open checks, error leakage |\n\n### Attack Pattern Catalog\n\n```\nATTACK PATTERN: SQL Injection (A03)\n\nThreat: T (Tampering), E (Elevation of Privilege)\n\nAttack Vector:\n1. Identify input fields that construct SQL queries\n2. Test for injection: ' OR '1'='1' --\n3. Extract data: UNION SELECT password FROM users\n4. Escalate: Execute stored procedures, write files\n\nDetection:\n- WAF rules for SQL patterns\n- Prepared statement verification\n- Database query logging\n\nMitigation:\n- Parameterized queries (primary)\n- Input validation (secondary)\n- Least privilege database accounts\n- Web application firewall\n\nTest Cases:\n- Single quote injection: '\n- Boolean-based: ' OR 1=1 --\n- Time-based: '; WAITFOR DELAY '0:0:5' --\n- UNION-based: ' UNION SELECT NULL, username, password FROM users --\n```\n\n### Threat Intelligence Integration\n\n| Source | Purpose | Update Frequency |\n|--------|---------|------------------|\n| CVE/NVD | Known vulnerabilities | Daily |\n| MITRE ATT&CK | Attack techniques | Quarterly |\n| OWASP | Web application threats | Annual |\n| Industry ISACs | Sector-specific threats | Real-time |\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":22874,"content_sha256":"b8e8c6d7597ab13e1d4146d89f72c805309c396f3d92ddec438550318bad3789"},{"filename":"scripts/secret_scanner.py","content":"#!/usr/bin/env python3\n\"\"\"\nSecret Scanner\n\nDetects hardcoded secrets, API keys, and credentials in source code.\nIdentifies exposed secrets before they reach version control.\n\nUsage:\n python secret_scanner.py /path/to/project\n python secret_scanner.py /path/to/file.py\n python secret_scanner.py /path/to/project --format json\n python secret_scanner.py --list-patterns\n\"\"\"\n\nimport argparse\nimport json\nfrom datetime import datetime\nimport os\nimport re\nimport sys\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Dict, List, Optional\nfrom enum import Enum\n\n\nclass Severity(Enum):\n CRITICAL = \"critical\"\n HIGH = \"high\"\n MEDIUM = \"medium\"\n LOW = \"low\"\n\n\n@dataclass\nclass SecretPattern:\n pattern_id: str\n name: str\n description: str\n regex: str\n severity: Severity\n file_extensions: List[str]\n recommendation: str\n\n\n@dataclass\nclass SecretFinding:\n pattern_id: str\n name: str\n severity: Severity\n file_path: str\n line_number: int\n matched_text: str\n recommendation: str\n\n\n# Secret patterns database\nSECRET_PATTERNS = [\n # Cloud Provider Keys\n SecretPattern(\n pattern_id=\"AWS001\",\n name=\"AWS Access Key ID\",\n description=\"AWS access key identifier\",\n regex=r'AKIA[0-9A-Z]{16}',\n severity=Severity.CRITICAL,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".env\", \".yml\", \".yaml\", \".json\", \".xml\", \".conf\"],\n recommendation=\"Use IAM roles or AWS Secrets Manager instead of hardcoded keys\"\n ),\n SecretPattern(\n pattern_id=\"AWS002\",\n name=\"AWS Secret Access Key\",\n description=\"AWS secret access key\",\n regex=r'(?:aws_secret_access_key|AWS_SECRET_ACCESS_KEY)\\s*[:=]\\s*[\"\\']?[A-Za-z0-9/+=]{40}[\"\\']?',\n severity=Severity.CRITICAL,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".env\", \".yml\", \".yaml\", \".json\", \".conf\"],\n recommendation=\"Use IAM roles or AWS Secrets Manager instead of hardcoded secrets\"\n ),\n SecretPattern(\n pattern_id=\"GCP001\",\n name=\"Google Cloud API Key\",\n description=\"Google Cloud Platform API key\",\n regex=r'AIza[0-9A-Za-z\\-_]{35}',\n severity=Severity.CRITICAL,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".env\", \".yml\", \".yaml\", \".json\"],\n recommendation=\"Use service accounts or Google Secret Manager\"\n ),\n SecretPattern(\n pattern_id=\"AZURE001\",\n name=\"Azure Storage Key\",\n description=\"Azure storage account key\",\n regex=r'(?:AccountKey|account_key)\\s*[:=]\\s*[\"\\']?[A-Za-z0-9+/=]{88}[\"\\']?',\n severity=Severity.CRITICAL,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".cs\", \".env\", \".yml\", \".yaml\", \".json\"],\n recommendation=\"Use Azure Key Vault or managed identities\"\n ),\n\n # Authentication Tokens\n SecretPattern(\n pattern_id=\"JWT001\",\n name=\"JSON Web Token\",\n description=\"Hardcoded JWT token\",\n regex=r'eyJ[A-Za-z0-9-_=]+\\.eyJ[A-Za-z0-9-_=]+\\.[A-Za-z0-9-_.+/=]*',\n severity=Severity.HIGH,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".env\", \".json\"],\n recommendation=\"Generate tokens dynamically, never hardcode\"\n ),\n SecretPattern(\n pattern_id=\"GITHUB001\",\n name=\"GitHub Token\",\n description=\"GitHub personal access token or OAuth token\",\n regex=r'(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,255}',\n severity=Severity.CRITICAL,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".env\", \".yml\", \".yaml\", \".json\"],\n recommendation=\"Use GitHub App authentication or environment variables\"\n ),\n SecretPattern(\n pattern_id=\"GITLAB001\",\n name=\"GitLab Token\",\n description=\"GitLab personal access or pipeline token\",\n regex=r'glpat-[A-Za-z0-9\\-_]{20,}',\n severity=Severity.CRITICAL,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".env\", \".yml\", \".yaml\"],\n recommendation=\"Use CI/CD variables or environment variables\"\n ),\n SecretPattern(\n pattern_id=\"SLACK001\",\n name=\"Slack Token\",\n description=\"Slack API token\",\n regex=r'xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*',\n severity=Severity.HIGH,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".env\", \".yml\", \".yaml\", \".json\"],\n recommendation=\"Use environment variables or secrets manager\"\n ),\n SecretPattern(\n pattern_id=\"STRIPE001\",\n name=\"Stripe API Key\",\n description=\"Stripe secret or publishable key\",\n regex=r'(?:sk|pk)_(?:test|live)_[0-9a-zA-Z]{24,}',\n severity=Severity.CRITICAL,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".env\", \".yml\", \".yaml\", \".json\"],\n recommendation=\"Use environment variables, never commit API keys\"\n ),\n SecretPattern(\n pattern_id=\"TWILIO001\",\n name=\"Twilio API Key\",\n description=\"Twilio account SID or auth token\",\n regex=r'(?:AC[a-z0-9]{32}|SK[a-z0-9]{32})',\n severity=Severity.HIGH,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".env\", \".yml\", \".yaml\", \".json\"],\n recommendation=\"Use environment variables for Twilio credentials\"\n ),\n SecretPattern(\n pattern_id=\"SENDGRID001\",\n name=\"SendGrid API Key\",\n description=\"SendGrid API key\",\n regex=r'SG\\.[A-Za-z0-9_-]{22}\\.[A-Za-z0-9_-]{43}',\n severity=Severity.HIGH,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".env\", \".yml\", \".yaml\", \".json\"],\n recommendation=\"Use environment variables for email service credentials\"\n ),\n\n # Cryptographic Keys\n SecretPattern(\n pattern_id=\"CRYPTO001\",\n name=\"RSA Private Key\",\n description=\"RSA private key in PEM format\",\n regex=r'-----BEGIN RSA PRIVATE KEY-----',\n severity=Severity.CRITICAL,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".pem\", \".key\", \".txt\"],\n recommendation=\"Store private keys in secure key management systems\"\n ),\n SecretPattern(\n pattern_id=\"CRYPTO002\",\n name=\"EC Private Key\",\n description=\"Elliptic curve private key\",\n regex=r'-----BEGIN EC PRIVATE KEY-----',\n severity=Severity.CRITICAL,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".pem\", \".key\"],\n recommendation=\"Use hardware security modules or key management services\"\n ),\n SecretPattern(\n pattern_id=\"CRYPTO003\",\n name=\"OpenSSH Private Key\",\n description=\"OpenSSH private key\",\n regex=r'-----BEGIN OPENSSH PRIVATE KEY-----',\n severity=Severity.CRITICAL,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".pem\", \".key\", \".txt\"],\n recommendation=\"Never commit SSH keys to repositories\"\n ),\n SecretPattern(\n pattern_id=\"CRYPTO004\",\n name=\"PGP Private Key\",\n description=\"PGP/GPG private key block\",\n regex=r'-----BEGIN PGP PRIVATE KEY BLOCK-----',\n severity=Severity.CRITICAL,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".asc\", \".gpg\", \".txt\"],\n recommendation=\"Store PGP keys in secure key rings, not source code\"\n ),\n\n # Generic Patterns\n SecretPattern(\n pattern_id=\"GEN001\",\n name=\"Generic API Key\",\n description=\"Generic API key or secret pattern\",\n regex=r'(?:api[_-]?key|apikey|api[_-]?secret)\\s*[:=]\\s*[\"\\'][a-zA-Z0-9_\\-]{20,}[\"\\']',\n severity=Severity.HIGH,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".env\", \".yml\", \".yaml\", \".json\", \".xml\"],\n recommendation=\"Use environment variables or secrets manager\"\n ),\n SecretPattern(\n pattern_id=\"GEN002\",\n name=\"Generic Secret\",\n description=\"Generic secret or token pattern\",\n regex=r'(?:secret|token|auth[_-]?token)\\s*[:=]\\s*[\"\\'][a-zA-Z0-9_\\-]{20,}[\"\\']',\n severity=Severity.HIGH,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".env\", \".yml\", \".yaml\", \".json\"],\n recommendation=\"Store secrets in environment variables or secret managers\"\n ),\n SecretPattern(\n pattern_id=\"GEN003\",\n name=\"Password in Config\",\n description=\"Password in configuration file\",\n regex=r'(?:password|passwd|pwd)\\s*[:=]\\s*[\"\\'][^\"\\']{8,}[\"\\']',\n severity=Severity.CRITICAL,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".env\", \".yml\", \".yaml\", \".json\", \".xml\", \".conf\", \".ini\"],\n recommendation=\"Never hardcode passwords. Use secret managers\"\n ),\n SecretPattern(\n pattern_id=\"GEN004\",\n name=\"Database Connection String\",\n description=\"Database connection string with credentials\",\n regex=r'(?:mongodb|postgres|mysql|redis|amqp)://[^:]+:[^@]+@[^/]+',\n severity=Severity.CRITICAL,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\", \".env\", \".yml\", \".yaml\", \".json\"],\n recommendation=\"Use environment variables for database credentials\"\n ),\n\n # Low Severity Patterns\n SecretPattern(\n pattern_id=\"LOW001\",\n name=\"TODO with Secret\",\n description=\"TODO comment mentioning secrets or credentials\",\n regex=r'(?:#|//|/\\*)\\s*(?:TODO|FIXME|XXX).*(?:secret|password|credential|key)',\n severity=Severity.LOW,\n file_extensions=[\".py\", \".js\", \".ts\", \".java\", \".go\", \".rb\", \".php\"],\n recommendation=\"Address security TODOs before deployment\"\n ),\n]\n\n\ndef scan_file(file_path: Path, patterns: List[SecretPattern]) -> List[SecretFinding]:\n \"\"\"Scan a single file for secrets.\"\"\"\n findings = []\n extension = file_path.suffix.lower()\n\n try:\n content = file_path.read_text(encoding='utf-8', errors='ignore')\n lines = content.split('\\n')\n except Exception:\n return findings\n\n for pattern in patterns:\n if extension not in pattern.file_extensions:\n continue\n\n try:\n regex = re.compile(pattern.regex, re.IGNORECASE)\n\n for i, line in enumerate(lines, 1):\n # Skip comments that explain patterns (like in this file)\n if 'regex' in line.lower() or 'pattern' in line.lower():\n continue\n\n match = regex.search(line)\n if match:\n # Mask the actual secret for safety\n matched = match.group(0)\n if len(matched) > 20:\n masked = matched[:10] + \"...\" + matched[-5:]\n else:\n masked = matched[:5] + \"...\"\n\n findings.append(SecretFinding(\n pattern_id=pattern.pattern_id,\n name=pattern.name,\n severity=pattern.severity,\n file_path=str(file_path),\n line_number=i,\n matched_text=masked,\n recommendation=pattern.recommendation\n ))\n except re.error:\n continue\n\n return findings\n\n\ndef scan_directory(dir_path: Path, patterns: List[SecretPattern],\n exclude_dirs: List[str] = None) -> List[SecretFinding]:\n \"\"\"Scan all files in a directory for secrets.\"\"\"\n if exclude_dirs is None:\n exclude_dirs = [\n \"node_modules\", \".git\", \"__pycache__\", \"venv\", \".venv\",\n \"dist\", \"build\", \".next\", \"vendor\", \".idea\", \".vscode\"\n ]\n\n findings = []\n extensions = set()\n for pattern in patterns:\n extensions.update(pattern.file_extensions)\n\n for file_path in dir_path.rglob(\"*\"):\n if file_path.is_file():\n # Check exclusions\n if any(excluded in file_path.parts for excluded in exclude_dirs):\n continue\n\n # Skip binary files and large files\n if file_path.stat().st_size > 1_000_000: # 1MB limit\n continue\n\n if file_path.suffix.lower() in extensions or file_path.name in ['.env', '.env.local', '.env.production']:\n findings.extend(scan_file(file_path, patterns))\n\n return sorted(findings, key=lambda f: (\n 0 if f.severity == Severity.CRITICAL else\n 1 if f.severity == Severity.HIGH else\n 2 if f.severity == Severity.MEDIUM else 3\n ))\n\n\ndef format_text_report(findings: List[SecretFinding], path: str) -> str:\n \"\"\"Format findings as text report.\"\"\"\n lines = []\n lines.append(\"=\" * 70)\n lines.append(\"SECRET SCAN REPORT\")\n lines.append(\"=\" * 70)\n lines.append(f\"Target: {path}\")\n lines.append(\"\")\n\n # Summary\n by_severity = {}\n for finding in findings:\n sev = finding.severity.value\n by_severity[sev] = by_severity.get(sev, 0) + 1\n\n lines.append(\"SUMMARY:\")\n lines.append(f\" Total Secrets Found: {len(findings)}\")\n for sev in [\"critical\", \"high\", \"medium\", \"low\"]:\n count = by_severity.get(sev, 0)\n if count > 0:\n lines.append(f\" {sev.upper()}: {count}\")\n lines.append(\"\")\n\n if not findings:\n lines.append(\"No secrets found!\")\n lines.append(\"=\" * 70)\n return \"\\n\".join(lines)\n\n # Group by severity\n current_severity = None\n for finding in findings:\n if finding.severity != current_severity:\n current_severity = finding.severity\n lines.append(\"-\" * 70)\n lines.append(f\"[{current_severity.value.upper()}]\")\n lines.append(\"-\" * 70)\n\n lines.append(\"\")\n lines.append(f\" [{finding.pattern_id}] {finding.name}\")\n lines.append(f\" File: {finding.file_path}:{finding.line_number}\")\n lines.append(f\" Match: {finding.matched_text}\")\n lines.append(f\" Fix: {finding.recommendation}\")\n\n lines.append(\"\")\n lines.append(\"=\" * 70)\n lines.append(\"IMPORTANT: Review all findings and rotate exposed credentials!\")\n lines.append(\"=\" * 70)\n return \"\\n\".join(lines)\n\n\ndef format_json_report(findings: List[SecretFinding], path: str) -> Dict:\n \"\"\"Format findings as JSON.\"\"\"\n return {\n \"target\": path,\n \"scan_date\": datetime.now().isoformat(),\n \"summary\": {\n \"total\": len(findings),\n \"by_severity\": {\n sev.value: sum(1 for f in findings if f.severity == sev)\n for sev in Severity\n }\n },\n \"findings\": [\n {\n \"pattern_id\": f.pattern_id,\n \"name\": f.name,\n \"severity\": f.severity.value,\n \"file_path\": f.file_path,\n \"line_number\": f.line_number,\n \"matched_text\": f.matched_text,\n \"recommendation\": f.recommendation\n }\n for f in findings\n ]\n }\n\n\ndef list_patterns():\n \"\"\"List all secret patterns.\"\"\"\n print(\"\\n\" + \"=\" * 60)\n print(\"SECRET DETECTION PATTERNS\")\n print(\"=\" * 60)\n\n for pattern in sorted(SECRET_PATTERNS, key=lambda p: p.pattern_id):\n print(f\"\\n[{pattern.pattern_id}] {pattern.name}\")\n print(f\" Severity: {pattern.severity.value.upper()}\")\n print(f\" Description: {pattern.description}\")\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Secret Scanner - Detect hardcoded secrets in code\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"\nExamples:\n # Scan a project directory\n python secret_scanner.py /path/to/project\n\n # Scan a single file\n python secret_scanner.py /path/to/config.py\n\n # Output as JSON\n python secret_scanner.py /path/to/project --format json\n\n # List all detection patterns\n python secret_scanner.py --list-patterns\n\n # Save report to file\n python secret_scanner.py /path/to/project --output report.txt\n \"\"\"\n )\n\n parser.add_argument(\n \"path\",\n nargs=\"?\",\n help=\"Path to scan (file or directory)\"\n )\n parser.add_argument(\n \"--format\", \"-f\",\n choices=[\"text\", \"json\"],\n default=\"text\",\n help=\"Output format (default: text)\"\n )\n parser.add_argument(\n \"--output\", \"-o\",\n help=\"Output file path\"\n )\n parser.add_argument(\n \"--list-patterns\", \"-l\",\n action=\"store_true\",\n help=\"List all detection patterns\"\n )\n parser.add_argument(\n \"--severity\", \"-s\",\n choices=[\"critical\", \"high\", \"medium\", \"low\"],\n help=\"Minimum severity to report\"\n )\n\n args = parser.parse_args()\n\n if args.list_patterns:\n list_patterns()\n return\n\n if not args.path:\n parser.error(\"path is required (or use --list-patterns)\")\n\n path = Path(args.path)\n if not path.exists():\n print(f\"Error: Path does not exist: {path}\")\n sys.exit(1)\n\n # Filter patterns by severity\n patterns = SECRET_PATTERNS\n if args.severity:\n severity_order = [\"critical\", \"high\", \"medium\", \"low\"]\n min_index = severity_order.index(args.severity)\n allowed = set(Severity(s) for s in severity_order[:min_index + 1])\n patterns = [p for p in patterns if p.severity in allowed]\n\n # Scan\n if path.is_file():\n findings = scan_file(path, patterns)\n else:\n findings = scan_directory(path, patterns)\n\n # Format output\n if args.format == \"json\":\n output = json.dumps(format_json_report(findings, str(path)), indent=2)\n else:\n output = format_text_report(findings, str(path))\n\n # Write output\n if args.output:\n with open(args.output, 'w') as f:\n f.write(output)\n print(f\"Report written to {args.output}\")\n else:\n print(output)\n\n # Exit code based on findings\n if any(f.severity in (Severity.CRITICAL, Severity.HIGH) for f in findings):\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","content_type":"text/x-python; charset=utf-8","language":"python","size":18127,"content_sha256":"066fe3d2d53e72648c113474a20cdc72c5892bbddb19139eaa03fd0d4122c1ec"},{"filename":"scripts/threat_modeler.py","content":"#!/usr/bin/env python3\n\"\"\"\nThreat Modeler\n\nPerforms STRIDE threat analysis on system components.\nGenerates threat model documentation with risk scores.\n\nUsage:\n python threat_modeler.py --component \"User Authentication\"\n python threat_modeler.py --component \"API Gateway\" --assets \"user_data,sessions\"\n python threat_modeler.py --interactive\n python threat_modeler.py --list-threats\n\"\"\"\n\nimport argparse\nimport json\nfrom datetime import datetime\nimport sys\nfrom typing import Dict, List, Optional\nfrom dataclasses import dataclass, asdict\nfrom enum import Enum\n\n\nclass STRIDECategory(Enum):\n SPOOFING = \"Spoofing\"\n TAMPERING = \"Tampering\"\n REPUDIATION = \"Repudiation\"\n INFORMATION_DISCLOSURE = \"Information Disclosure\"\n DENIAL_OF_SERVICE = \"Denial of Service\"\n ELEVATION_OF_PRIVILEGE = \"Elevation of Privilege\"\n\n\n@dataclass\nclass Threat:\n category: str\n name: str\n description: str\n attack_vector: str\n impact: str\n likelihood: int # 1-5\n severity: int # 1-5\n mitigations: List[str]\n\n @property\n def risk_score(self) -> int:\n return self.likelihood * self.severity\n\n @property\n def risk_level(self) -> str:\n score = self.risk_score\n if score >= 20:\n return \"Critical\"\n elif score >= 12:\n return \"High\"\n elif score >= 6:\n return \"Medium\"\n else:\n return \"Low\"\n\n\n# Comprehensive threat database\nTHREAT_DATABASE = {\n \"authentication\": [\n Threat(\n category=\"Spoofing\",\n name=\"Credential Theft\",\n description=\"Attacker obtains valid credentials through phishing or theft\",\n attack_vector=\"Phishing emails, keyloggers, credential stuffing\",\n impact=\"Full account compromise, data access\",\n likelihood=4,\n severity=5,\n mitigations=[\n \"Implement multi-factor authentication (MFA)\",\n \"Use phishing-resistant authentication (FIDO2/WebAuthn)\",\n \"Deploy credential monitoring and breach detection\",\n \"Enforce strong password policies with complexity requirements\"\n ]\n ),\n Threat(\n category=\"Spoofing\",\n name=\"Session Hijacking\",\n description=\"Attacker steals or predicts session tokens\",\n attack_vector=\"XSS, network sniffing, session fixation\",\n impact=\"Unauthorized access to user session\",\n likelihood=3,\n severity=4,\n mitigations=[\n \"Use secure, HttpOnly, SameSite cookies\",\n \"Implement session binding (IP, user agent)\",\n \"Rotate session tokens after authentication\",\n \"Use short session timeouts for sensitive operations\"\n ]\n ),\n Threat(\n category=\"Tampering\",\n name=\"JWT Token Manipulation\",\n description=\"Attacker modifies JWT claims or signature\",\n attack_vector=\"Algorithm confusion, weak secrets, none algorithm\",\n impact=\"Privilege escalation, identity spoofing\",\n likelihood=3,\n severity=5,\n mitigations=[\n \"Use asymmetric algorithms (RS256, ES256)\",\n \"Validate algorithm in code, not from token\",\n \"Implement proper key management\",\n \"Add expiration and audience validation\"\n ]\n ),\n Threat(\n category=\"Repudiation\",\n name=\"Authentication Event Denial\",\n description=\"User denies performing authentication actions\",\n attack_vector=\"Claim of compromised credentials\",\n impact=\"Dispute resolution difficulty, fraud\",\n likelihood=2,\n severity=3,\n mitigations=[\n \"Log all authentication events with timestamps\",\n \"Capture device fingerprints and IP addresses\",\n \"Implement tamper-evident audit logs\",\n \"Use digital signatures for critical actions\"\n ]\n ),\n Threat(\n category=\"Information Disclosure\",\n name=\"Password Hash Exposure\",\n description=\"Password hashes leaked through breach or injection\",\n attack_vector=\"SQL injection, backup exposure, insider threat\",\n impact=\"Mass credential compromise\",\n likelihood=2,\n severity=5,\n mitigations=[\n \"Use strong password hashing (Argon2id, bcrypt)\",\n \"Implement database encryption at rest\",\n \"Apply parameterized queries everywhere\",\n \"Segment database access by function\"\n ]\n ),\n Threat(\n category=\"Denial of Service\",\n name=\"Authentication Brute Force\",\n description=\"Attacker overwhelms authentication service\",\n attack_vector=\"Distributed credential stuffing, password spraying\",\n impact=\"Service unavailability, account lockouts\",\n likelihood=4,\n severity=3,\n mitigations=[\n \"Implement progressive rate limiting\",\n \"Use CAPTCHA after failed attempts\",\n \"Deploy account lockout with notification\",\n \"Use distributed denial of service protection\"\n ]\n ),\n Threat(\n category=\"Elevation of Privilege\",\n name=\"Privilege Escalation via Auth Bypass\",\n description=\"Attacker gains admin access through auth flaws\",\n attack_vector=\"IDOR, insecure direct object references, role confusion\",\n impact=\"Full system compromise\",\n likelihood=2,\n severity=5,\n mitigations=[\n \"Implement server-side authorization checks\",\n \"Use role-based access control (RBAC)\",\n \"Validate permissions on every request\",\n \"Audit privilege changes\"\n ]\n )\n ],\n \"api\": [\n Threat(\n category=\"Spoofing\",\n name=\"API Key Impersonation\",\n description=\"Attacker uses stolen or leaked API keys\",\n attack_vector=\"GitHub exposure, client-side storage, logging\",\n impact=\"Unauthorized API access, data theft\",\n likelihood=4,\n severity=4,\n mitigations=[\n \"Implement API key rotation policies\",\n \"Use short-lived tokens where possible\",\n \"Monitor for exposed secrets in repositories\",\n \"Implement IP allowlisting for API keys\"\n ]\n ),\n Threat(\n category=\"Tampering\",\n name=\"Request Manipulation\",\n description=\"Attacker modifies API requests in transit\",\n attack_vector=\"Man-in-the-middle, proxy interception\",\n impact=\"Data corruption, unauthorized actions\",\n likelihood=2,\n severity=4,\n mitigations=[\n \"Enforce TLS 1.3 for all connections\",\n \"Implement request signing (HMAC)\",\n \"Use certificate pinning for mobile apps\",\n \"Validate request integrity on server\"\n ]\n ),\n Threat(\n category=\"Information Disclosure\",\n name=\"Excessive Data Exposure\",\n description=\"API returns more data than needed\",\n attack_vector=\"Response inspection, schema analysis\",\n impact=\"Sensitive data leakage\",\n likelihood=4,\n severity=3,\n mitigations=[\n \"Implement field-level access control\",\n \"Use GraphQL with depth limiting\",\n \"Apply response filtering based on role\",\n \"Audit API responses for sensitive fields\"\n ]\n ),\n Threat(\n category=\"Denial of Service\",\n name=\"API Rate Limit Bypass\",\n description=\"Attacker circumvents rate limiting\",\n attack_vector=\"Distributed requests, header spoofing\",\n impact=\"Service degradation, resource exhaustion\",\n likelihood=3,\n severity=3,\n mitigations=[\n \"Implement layered rate limiting\",\n \"Use token bucket or leaky bucket algorithms\",\n \"Rate limit by user, IP, and API key\",\n \"Deploy API gateway with DoS protection\"\n ]\n )\n ],\n \"database\": [\n Threat(\n category=\"Tampering\",\n name=\"SQL Injection\",\n description=\"Attacker injects malicious SQL commands\",\n attack_vector=\"Input fields, URL parameters, headers\",\n impact=\"Data theft, modification, destruction\",\n likelihood=3,\n severity=5,\n mitigations=[\n \"Use parameterized queries exclusively\",\n \"Apply input validation and sanitization\",\n \"Implement least privilege database accounts\",\n \"Deploy web application firewall (WAF)\"\n ]\n ),\n Threat(\n category=\"Information Disclosure\",\n name=\"Unencrypted Data at Rest\",\n description=\"Sensitive data stored without encryption\",\n attack_vector=\"Physical theft, backup exposure, insider threat\",\n impact=\"Mass data breach\",\n likelihood=2,\n severity=5,\n mitigations=[\n \"Implement transparent data encryption (TDE)\",\n \"Use field-level encryption for PII\",\n \"Encrypt database backups\",\n \"Manage encryption keys securely\"\n ]\n ),\n Threat(\n category=\"Repudiation\",\n name=\"Audit Log Tampering\",\n description=\"Attacker modifies or deletes database logs\",\n attack_vector=\"SQL injection, admin access, log rotation\",\n impact=\"Cannot prove what actions occurred\",\n likelihood=2,\n severity=4,\n mitigations=[\n \"Write audit logs to immutable storage\",\n \"Implement cryptographic log chaining\",\n \"Use separate audit database with restricted access\",\n \"Monitor for log gaps and anomalies\"\n ]\n )\n ],\n \"network\": [\n Threat(\n category=\"Information Disclosure\",\n name=\"Network Traffic Interception\",\n description=\"Attacker captures unencrypted traffic\",\n attack_vector=\"ARP spoofing, rogue access points, packet sniffing\",\n impact=\"Credential theft, data exposure\",\n likelihood=2,\n severity=4,\n mitigations=[\n \"Enforce TLS everywhere (no HTTP)\",\n \"Implement HSTS with preloading\",\n \"Use mutual TLS for service-to-service\",\n \"Deploy network segmentation\"\n ]\n ),\n Threat(\n category=\"Denial of Service\",\n name=\"DDoS Attack\",\n description=\"Attacker floods network with traffic\",\n attack_vector=\"Volumetric attacks, application layer attacks\",\n impact=\"Complete service unavailability\",\n likelihood=3,\n severity=4,\n mitigations=[\n \"Deploy CDN with DDoS protection\",\n \"Implement rate limiting at edge\",\n \"Use anycast DNS distribution\",\n \"Have incident response runbook ready\"\n ]\n )\n ],\n \"storage\": [\n Threat(\n category=\"Information Disclosure\",\n name=\"Insecure File Upload\",\n description=\"Attacker accesses uploaded files\",\n attack_vector=\"Direct URL access, path traversal\",\n impact=\"Data breach, malware distribution\",\n likelihood=3,\n severity=4,\n mitigations=[\n \"Generate random file names\",\n \"Store files outside web root\",\n \"Implement signed URLs with expiration\",\n \"Scan uploads for malware\"\n ]\n ),\n Threat(\n category=\"Tampering\",\n name=\"File Integrity Violation\",\n description=\"Attacker modifies stored files\",\n attack_vector=\"Write access exploit, supply chain attack\",\n impact=\"Data corruption, code execution\",\n likelihood=2,\n severity=4,\n mitigations=[\n \"Implement file integrity monitoring\",\n \"Use cryptographic hashes for verification\",\n \"Apply immutable storage for critical files\",\n \"Version control with audit trail\"\n ]\n )\n ]\n}\n\n# Component to threat category mapping\nCOMPONENT_MAPPING = {\n \"authentication\": [\"authentication\"],\n \"login\": [\"authentication\"],\n \"auth\": [\"authentication\"],\n \"api\": [\"api\"],\n \"api gateway\": [\"api\", \"network\"],\n \"rest api\": [\"api\"],\n \"graphql\": [\"api\"],\n \"database\": [\"database\"],\n \"db\": [\"database\"],\n \"postgres\": [\"database\"],\n \"mysql\": [\"database\"],\n \"mongodb\": [\"database\"],\n \"network\": [\"network\"],\n \"load balancer\": [\"network\"],\n \"cdn\": [\"network\"],\n \"storage\": [\"storage\"],\n \"s3\": [\"storage\"],\n \"file upload\": [\"storage\"],\n \"user service\": [\"authentication\", \"database\"],\n \"payment\": [\"api\", \"database\", \"authentication\"],\n \"web application\": [\"authentication\", \"api\", \"database\", \"network\"],\n \"microservice\": [\"api\", \"network\", \"authentication\"],\n}\n\n\ndef get_threats_for_component(component: str) -> List[Threat]:\n \"\"\"Get applicable threats for a component.\"\"\"\n component_lower = component.lower()\n\n # Find matching categories\n categories = []\n for key, value in COMPONENT_MAPPING.items():\n if key in component_lower:\n categories.extend(value)\n\n # If no specific match, return all threats\n if not categories:\n categories = list(THREAT_DATABASE.keys())\n\n # Collect unique threats\n threats = []\n seen = set()\n for category in set(categories):\n if category in THREAT_DATABASE:\n for threat in THREAT_DATABASE[category]:\n threat_key = (threat.category, threat.name)\n if threat_key not in seen:\n threats.append(threat)\n seen.add(threat_key)\n\n return sorted(threats, key=lambda t: t.risk_score, reverse=True)\n\n\ndef calculate_dread_score(threat: Threat) -> Dict:\n \"\"\"Calculate DREAD score for a threat.\"\"\"\n # Map threat properties to DREAD factors\n damage = threat.severity * 2\n reproducibility = 8 if threat.likelihood >= 4 else (5 if threat.likelihood >= 2 else 3)\n exploitability = threat.likelihood * 2\n affected_users = 8 if \"mass\" in threat.impact.lower() or \"full\" in threat.impact.lower() else 5\n discoverability = 7 if threat.likelihood >= 3 else 4\n\n dread = {\n \"damage\": min(damage, 10),\n \"reproducibility\": reproducibility,\n \"exploitability\": min(exploitability, 10),\n \"affected_users\": affected_users,\n \"discoverability\": discoverability\n }\n dread[\"total\"] = sum(dread.values()) / 5\n return dread\n\n\ndef format_threat_report(component: str, threats: List[Threat]) -> str:\n \"\"\"Format threats as a readable report.\"\"\"\n lines = []\n lines.append(\"=\" * 70)\n lines.append(f\"THREAT MODEL: {component.upper()}\")\n lines.append(\"=\" * 70)\n lines.append(\"\")\n\n # Summary\n critical = sum(1 for t in threats if t.risk_level == \"Critical\")\n high = sum(1 for t in threats if t.risk_level == \"High\")\n medium = sum(1 for t in threats if t.risk_level == \"Medium\")\n low = sum(1 for t in threats if t.risk_level == \"Low\")\n\n lines.append(\"SUMMARY:\")\n lines.append(f\" Total Threats: {len(threats)}\")\n lines.append(f\" Critical: {critical} | High: {high} | Medium: {medium} | Low: {low}\")\n lines.append(\"\")\n\n # Threats by STRIDE category\n for stride in STRIDECategory:\n category_threats = [t for t in threats if t.category == stride.value]\n if category_threats:\n lines.append(\"-\" * 70)\n lines.append(f\"[{stride.value.upper()}]\")\n lines.append(\"-\" * 70)\n\n for threat in category_threats:\n dread = calculate_dread_score(threat)\n lines.append(\"\")\n lines.append(f\" {threat.name}\")\n lines.append(f\" Risk: {threat.risk_level} (Score: {threat.risk_score}/25)\")\n lines.append(f\" DREAD: {dread['total']:.1f}/10\")\n lines.append(f\" Description: {threat.description}\")\n lines.append(f\" Attack Vector: {threat.attack_vector}\")\n lines.append(f\" Impact: {threat.impact}\")\n lines.append(\" Mitigations:\")\n for m in threat.mitigations:\n lines.append(f\" - {m}\")\n\n lines.append(\"\")\n lines.append(\"=\" * 70)\n return \"\\n\".join(lines)\n\n\ndef format_json_report(component: str, threats: List[Threat]) -> Dict:\n \"\"\"Format threats as JSON structure.\"\"\"\n return {\n \"component\": component,\n \"analysis_date\": datetime.now().isoformat(),\n \"summary\": {\n \"total_threats\": len(threats),\n \"by_risk_level\": {\n \"critical\": sum(1 for t in threats if t.risk_level == \"Critical\"),\n \"high\": sum(1 for t in threats if t.risk_level == \"High\"),\n \"medium\": sum(1 for t in threats if t.risk_level == \"Medium\"),\n \"low\": sum(1 for t in threats if t.risk_level == \"Low\")\n }\n },\n \"threats\": [\n {\n \"category\": t.category,\n \"name\": t.name,\n \"description\": t.description,\n \"attack_vector\": t.attack_vector,\n \"impact\": t.impact,\n \"likelihood\": t.likelihood,\n \"severity\": t.severity,\n \"risk_score\": t.risk_score,\n \"risk_level\": t.risk_level,\n \"dread\": calculate_dread_score(t),\n \"mitigations\": t.mitigations\n }\n for t in threats\n ]\n }\n\n\ndef interactive_mode():\n \"\"\"Run interactive threat modeling session.\"\"\"\n print(\"\\n\" + \"=\" * 50)\n print(\"STRIDE THREAT MODELER - Interactive Mode\")\n print(\"=\" * 50)\n\n component = input(\"\\nEnter component name (e.g., 'User Authentication'): \").strip()\n if not component:\n print(\"Component name required.\")\n return\n\n threats = get_threats_for_component(component)\n\n if not threats:\n print(f\"No threats found for component: {component}\")\n return\n\n print(format_threat_report(component, threats))\n\n\ndef list_all_threats():\n \"\"\"List all threats in the database.\"\"\"\n print(\"\\n\" + \"=\" * 50)\n print(\"THREAT DATABASE\")\n print(\"=\" * 50)\n\n for category, threats in THREAT_DATABASE.items():\n print(f\"\\n[{category.upper()}]\")\n for threat in threats:\n print(f\" - {threat.category}: {threat.name} (Risk: {threat.risk_level})\")\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"STRIDE Threat Modeler - Analyze security threats\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"\nExamples:\n # Analyze authentication component\n python threat_modeler.py --component \"User Authentication\"\n\n # Analyze with specific assets\n python threat_modeler.py --component \"API Gateway\" --assets \"user_data,tokens\"\n\n # JSON output for integration\n python threat_modeler.py --component \"Database\" --json\n\n # Interactive mode\n python threat_modeler.py --interactive\n\n # List all threats in database\n python threat_modeler.py --list-threats\n \"\"\"\n )\n\n parser.add_argument(\n \"--component\", \"-c\",\n help=\"Component to analyze (e.g., 'User Authentication', 'API Gateway')\"\n )\n parser.add_argument(\n \"--assets\", \"-a\",\n help=\"Comma-separated list of assets to protect\"\n )\n parser.add_argument(\n \"--json\",\n action=\"store_true\",\n help=\"Output as JSON\"\n )\n parser.add_argument(\n \"--interactive\", \"-i\",\n action=\"store_true\",\n help=\"Run in interactive mode\"\n )\n parser.add_argument(\n \"--list-threats\", \"-l\",\n action=\"store_true\",\n help=\"List all threats in database\"\n )\n parser.add_argument(\n \"--output\", \"-o\",\n help=\"Output file path\"\n )\n\n args = parser.parse_args()\n\n if args.interactive:\n interactive_mode()\n return\n\n if args.list_threats:\n list_all_threats()\n return\n\n if not args.component:\n parser.error(\"--component is required (or use --interactive)\")\n\n threats = get_threats_for_component(args.component)\n\n if args.json:\n output = json.dumps(format_json_report(args.component, threats), indent=2)\n else:\n output = format_threat_report(args.component, threats)\n\n if args.output:\n with open(args.output, 'w') as f:\n f.write(output)\n print(f\"Report written to {args.output}\")\n else:\n print(output)\n\n\nif __name__ == \"__main__\":\n main()\n","content_type":"text/x-python; charset=utf-8","language":"python","size":21332,"content_sha256":"46504b584797f935b1c3450caf3fc6270883693c4025b5254d699262970a1e0c"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"text":"Senior Security Engineer — Threat Modeling + Security Router","type":"text"}]},{"type":"paragraph","content":[{"text":"This skill does exactly one job itself — ","type":"text"},{"text":"STRIDE/DREAD threat modeling","type":"text","marks":[{"type":"strong"}]},{"text":" (plus a quick secret scan) — and routes every other security request to the specialist skill that owns that lane. Do not duplicate sibling content here; route instead.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Routing Table (read this first)","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"The user wants...","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Route to","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Why that skill owns it","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Vulnerability assessment, pen-test methodology, OWASP Top 10 testing","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"../security-pen-testing/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Ships ","type":"text"},{"text":"vulnerability_scanner.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" + ","type":"text"},{"text":"dependency_auditor.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" with exit-code contracts","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Incident triage, SEV classification, forensics, containment","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"../incident-response/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"SEV1–SEV4 taxonomy, NIST SP 800-61 phases, ","type":"text"},{"text":"incident_triage.py","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Production outage command (non-security incidents)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"../incident-commander/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Severity classifier + timeline + postmortem tools","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Security monitoring, CVE triage SLAs, compliance checks (SOC 2 etc.), security headers","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"../senior-secops/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"security_scanner.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" + ","type":"text"},{"text":"compliance_checker.py","type":"text","marks":[{"type":"code_inline"}]},{"text":", CVE SLA table","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Hostile/adversarial code review","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"../adversarial-reviewer/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"3-persona review with BLOCK/CONCERNS/CLEAN verdict","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Secure code review as part of general review","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"../code-reviewer/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Language dispatch + regression fixtures","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Cloud IAM escalation paths, S3 exposure, security groups","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"../cloud-security/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"cloud_posture_check.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" with per-check exit codes","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Threat hunting, IOC sweeps, anomaly detection","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"../threat-detection/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"z-score anomaly + IOC staleness tooling","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Red-team engagement planning, ATT&CK kill chains","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"../red-team/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"engagement_planner.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" with authorization gate","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"LLM/AI attack surface (prompt injection, poisoning)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"../ai-security/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"ATLAS-mapped ","type":"text"},{"text":"ai_threat_scanner.py","type":"text","marks":[{"type":"code_inline"}]}]}]}]}]},{"type":"paragraph","content":[{"text":"If the request spans lanes (e.g., \"secure this new architecture\"), do the threat model here first — its output (prioritized threats + mitigations) tells you which siblings to load next. Never bulk-load multiple security skills speculatively.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"What This Skill Owns: STRIDE Threat Modeling","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Workflow","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Scope:","type":"text","marks":[{"type":"strong"}]},{"text":" assets to protect, trust boundaries, data flows (external entities, processes, data stores, flows).","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Generate the threat model","type":"text","marks":[{"type":"strong"}]},{"text":" per component:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"python3 scripts/threat_modeler.py --component \"User Authentication\" --assets \"credentials,sessions\" --json --output threats.json","type":"text"}]},{"type":"paragraph","content":[{"text":"Output: per-threat STRIDE category, DREAD score (Damage, Reproducibility, Exploitability, Affected users, Discoverability — each 1–10), and suggested mitigations. Repeat per DFD element; ","type":"text"},{"text":"--interactive","type":"text","marks":[{"type":"code_inline"}]},{"text":" walks scoping questions; ","type":"text"},{"text":"--list-threats","type":"text","marks":[{"type":"code_inline"}]},{"text":" shows the threat database.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Consume the output:","type":"text","marks":[{"type":"strong"}]},{"text":" sort ","type":"text"},{"text":"threats.json","type":"text","marks":[{"type":"code_inline"}]},{"text":" by DREAD score descending; everything ≥ 7 average needs a named mitigation owner before the design ships. Map each mitigation to the responsible sibling lane (e.g., IAM threats → ","type":"text"},{"text":"cloud-security","type":"text","marks":[{"type":"code_inline"}]},{"text":", injection threats → ","type":"text"},{"text":"code-reviewer","type":"text","marks":[{"type":"code_inline"}]},{"text":").","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Quick secret sweep","type":"text","marks":[{"type":"strong"}]},{"text":" while you have the codebase open:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"python3 scripts/secret_scanner.py /path/to/project --format json --severity high","type":"text"}]},{"type":"paragraph","content":[{"text":"20+ patterns (AWS keys, GitHub tokens, private keys, generic credentials). Any critical/high finding blocks merge until rotated and moved to a secret manager.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Verification gate:","type":"text","marks":[{"type":"strong"}]},{"text":" every DFD element has ≥ 1 STRIDE row considered, every threat with DREAD ≥ 7 has an owner + mitigation, and the secret scan exits with zero high/critical findings. Re-run both tools after mitigations land — that re-run is the done signal, not the document.","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"STRIDE per Element Matrix","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"DFD Element","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"S","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"T","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"R","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"I","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"D","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"E","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"External Entity","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph"}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph"}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph"}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph"}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Process","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Data Store","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph"}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph"}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Data Flow","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph"}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph"}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"X","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph"}]}]}]},{"type":"paragraph","content":[{"text":"(S=Spoofing→authn, T=Tampering→integrity, R=Repudiation→audit logs, I=Info Disclosure→encryption/access control, D=DoS→rate limiting/redundancy, E=Elevation→least privilege.)","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"References (load on demand)","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Document","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Content","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"references/threat-modeling-guide.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/threat-modeling-guide.md","title":null}}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"STRIDE methodology, attack trees, DREAD scoring, DFD creation","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"references/security-architecture-patterns.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/security-architecture-patterns.md","title":null}}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"Zero Trust, defense-in-depth, authentication patterns, API security","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"references/cryptography-implementation.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/cryptography-implementation.md","title":null}}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":null},"content":[{"type":"paragraph","content":[{"text":"AES-GCM, Ed25519, password hashing (Argon2id), key management","type":"text"}]}]}]}]},{"type":"paragraph","content":[{"text":"The architecture and crypto references are kept because no sibling ships them; for ","type":"text"},{"text":"operating","type":"text","marks":[{"type":"em"}]},{"text":" those controls (scanning, compliance, monitoring) still route to ","type":"text"},{"text":"senior-secops","type":"text","marks":[{"type":"code_inline"}]},{"text":".","type":"text"}]}]},"metadata":{"date":"2026-06-05","name":"senior-security","author":"@skillopedia","source":{"stars":16818,"repo_name":"claude-skills","origin_url":"https://github.com/alirezarezvani/claude-skills/blob/HEAD/engineering-team/skills/senior-security/SKILL.md","repo_owner":"alirezarezvani","body_sha256":"4a7aa958ba22070cdaf45f19f4e3eeac4d9c5c8bfb1541abdf4deba3871858d6","cluster_key":"72a0d16f4cb4348747a0106fcafe5dc27afc795eee9d3b723eb8c9a3db047b20","refresh_tag":"upstream-refresh-2026-11","clean_bundle":{"format":"clean-skill-bundle-v1","source":"alirezarezvani/claude-skills/engineering-team/skills/senior-security/SKILL.md","bundle_sha256":"3612720ea03bebef7570b6f391942a0e76e29cae08b3a8df928d64d09c4d9928","attachment_count":5,"text_attachments":5,"attachment_storage":"skill_attachments","binary_attachments":0},"cluster_size":3,"refreshed_at":"2026-11-02T23:18:26.543Z","skill_md_path":"engineering-team/skills/senior-security/SKILL.md","import_metadata":{"date":"2026-06-05","author":"@skillopedia","version":"v1","category":"security","category_label":"Security"},"upstream_commit":"9ef0c3c213932e645cc5cbeeb3c35c3a762a2437","exact_dupes_collapsed_into_this":2},"version":"v1","category":"security","triggers":["security architecture","threat modeling","STRIDE analysis","penetration testing","vulnerability assessment","secure coding","OWASP","application security","cryptography implementation","secret scanning","security audit","zero trust"],"import_tag":"clean-skills-v1","description":"Use for STRIDE threat modeling, DREAD scoring or a quick secret scan, or to route a security request to the right specialist. Models threats with threat_modeler.py and scans with secret_scanner.py."}},"renderedAt":1794102103251}

Senior Security Engineer — Threat Modeling + Security Router This skill does exactly one job itself — STRIDE/DREAD threat modeling (plus a quick secret scan) — and routes every other security request to the specialist skill that owns that lane. Do not duplicate sibling content here; route instead. Routing Table (read this first) | The user wants... | Route to | Why that skill owns it | |---|---|---| | Vulnerability assessment, pen-test methodology, OWASP Top 10 testing | | Ships + with exit-code contracts | | Incident triage, SEV classification, forensics, containment | | SEV1–SEV4 taxonomy,…