Comprehensive application security toolbox for Claude Code. 62 skills across 8 frameworks (OWASP Top 10, OWASP API Top 10, STRIDE, PASTA, LINDDUN, MITRE ATT&CK, SANS/CWE Top 25, DREAD), red team simulation with 6 attacker personas plus consolidator, and interactive security education.

version
0.1.2
GitHub stars
21

Install

/plugin install appsec@florianbuetow-plugins

Run it inside Claude Code after adding the marketplace with /plugin marketplace add florianbuetow/claude-code.

Contents

Discovered from source

Skills 62

Broken Access Control (A01:2021)

Analyze source code for broken access control vulnerabilities including missing authorization checks, insecure direct object references, CORS misconfiguration, JWT manipulation, directory traversal, and privilege escalation.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification. This skill supports all cross-cutting flags. Key flags for this skill:

  • --scope determines which files to analyze (default: changed)
  • --depth standard reads code and checks middleware chains
  • --depth deep traces authorization across call graphs and middleware stacks
  • --severity filters output (access control issues are often high or critical)

Framework Context

Read ../../shared/frameworks/owasp-top10-2021.md, section A01:2021 - Broken Access Control, for the full category description, common vulnerabilities, and prevention guidance.

Key CWEs in scope:

  • CWE-200: Exposure of Sensitive Information
  • CWE-284: Improper Access Control
  • CWE-285: Improper Authorization
  • CWE-352: Cross-Site Request Forgery
  • CWE-639: Authorization Bypass Through User-Controlled Key (IDOR)
  • CWE-862: Missing Authorization
  • CWE-863: Incorrect Authorization

Detection Patterns

Read references/detection-patterns.md for the full catalog of code patterns, search heuristics, language-specific examples, and false positive guidance.

Workflow

1. Determine Scope

Parse flags and resolve the file list per ../../shared/schemas/flags.md. Filter to files likely to contain access control logic:

  • Route/controller definitions (**/routes/**, **/controllers/**, **/handlers/**)
  • Middleware files (**/middleware/**, **/middlewares/**)
  • Authorization modules (**/auth/**, **/authz/**, **/policies/**, **/guards/**)
  • API endpoint definitions (**/api/**, **/endpoints/**)
  • Configuration files for CORS, JWT, and session management

2. Check for Available Scanners

Detect scanners per ../../shared/schemas/scanners.md:

  1. semgrep — primary scanner for access control patterns
  2. bandit — Python-specific authorization issues
  3. brakeman — Rails mass assignment and authorization bypasses

Record which scanners are available and which are missing.

3. Run Scanners (If Available)

If semgrep is available, run with rules targeting access control:

semgrep scan --config auto --json --quiet <target>

Filter results to rules matching access control, authorization, CORS, JWT, and IDOR patterns. Normalize output to the findings schema.

4. Claude Code Analysis

Regardless of scanner availability, perform manual code analysis:

  1. Route inventory: Grep for route definitions and check each has authorization middleware.
  2. Object access: Find database lookups using user-supplied IDs and verify ownership checks.
  3. CORS config: Locate CORS configuration and check for wildcard or overly permissive origins.
  4. JWT handling: Find JWT verification code and check that claims are validated.
  5. Path handling: Find file path operations using user input and check for traversal prevention.
  6. Role checks: Identify role-based decisions and verify they cover both horizontal and vertical access.

When --depth deep, additionally trace:

  • Full middleware chains from route to handler
  • Authorization decorator/annotation inheritance
  • Cross-service authorization delegation

5. Report Findings

Format output per ../../shared/schemas/findings.md using the AC prefix (e.g., AC-001, AC-002).

Include for each finding:

  • Severity and confidence
  • Exact file location with code snippet
  • Impact description specific to the access control failure
  • Concrete fix with diff when possible
  • CWE and OWASP references

What to Look For

These are the high-signal patterns specific to broken access control. Each maps to a detection pattern in references/detection-patterns.md.

  1. Routes without authorization middleware — Endpoints that handle sensitive data or mutations but have no auth middleware in their chain.

  2. Direct object references without ownership — Database lookups using req.params.id or similar without filtering by the authenticated user.

  3. CORS wildcard or reflection — Access-Control-Allow-Origin: * or reflecting the Origin header without validation, especially with credentials.

  4. JWT claims used without verification — Reading JWT payload without verifying signature, or trusting client-supplied role/permission claims.

  5. Path traversal via user input — File operations using user-supplied paths without canonicalization or allowlist validation.

  6. Missing function-level access control — Admin endpoints accessible to regular users, or API actions without role verification.

  7. Forced browsing to predictable URLs — Sequential IDs or predictable resource paths without authorization checks.

  8. Horizontal privilege escalation — Users can access other users' data by changing an identifier, with no server-side ownership verification.

Scanner Integration

ScannerCoverageCommand
semgrepIDOR, missing auth middleware, CORS, JWT issuessemgrep scan --config auto --json --quiet <target>
banditPython authorization patternsbandit -r <target> -f json -q
brakemanRails mass assignment, authorizationbrakeman -q -f json -o /dev/stdout

Fallback (no scanner): Use Grep with patterns from references/detection-patterns.md to find route definitions, database queries with user-controlled IDs, CORS headers, and JWT decode calls. Report findings with confidence: medium.

Relevant semgrep rule categories:

  • python.django.security.audit.unvalidated-*
  • javascript.express.security.audit.missing-auth-*
  • java.spring.security.audit.missing-authorization
  • generic.cors.security.wildcard-origin

Output Format

Use the findings schema from ../../shared/schemas/findings.md.

  • ID prefix: AC (e.g., AC-001)
  • metadata.tool: access-control
  • metadata.framework: owasp
  • metadata.category: A01
  • references.owasp: A01:2021
  • references.stride: E (Elevation of Privilege) or I (Information Disclosure)

Severity guidance for this category:

  • critical: Unauthenticated access to admin functions, mass IDOR exposing all user data
  • high: Authenticated IDOR, missing authorization on mutation endpoints, CORS with credentials + wildcard
  • medium: CORS misconfiguration without credentials, missing rate limiting on auth endpoints
  • low: Verbose error messages revealing authorization logic, minor forced browsing risks

API Security (API)

Analyze REST and RPC APIs for security vulnerabilities aligned with the OWASP API Security Top 10, including Broken Object-Level Authorization (BOLA), mass assignment, missing rate limiting, broken function-level authorization, and excessive data exposure. API-specific vulnerabilities arise from the unique patterns of programmatic access, where client-side UI constraints do not apply.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification. This skill supports all cross-cutting flags. Key flags for this skill:

  • --scope determines which files to analyze (default: changed)
  • --depth standard reads code and checks API endpoint handlers
  • --depth deep traces data from request to database to response serialization
  • --severity filters output (API issues are often high or critical)

Framework Context

Key CWEs in scope:

  • CWE-639: Authorization Bypass Through User-Controlled Key (BOLA)
  • CWE-915: Improperly Controlled Modification of Dynamically-Determined Object Attributes
  • CWE-770: Allocation of Resources Without Limits (rate limiting)
  • CWE-862: Missing Authorization (function-level auth)
  • CWE-200: Exposure of Sensitive Information (excessive data)

OWASP API Security Top 10 (2023) categories:

  • API1:2023 Broken Object-Level Authorization
  • API2:2023 Broken Authentication
  • API3:2023 Broken Object Property-Level Authorization
  • API4:2023 Unrestricted Resource Consumption
  • API5:2023 Broken Function-Level Authorization

Detection Patterns

Read references/detection-patterns.md for the full catalog of code patterns, search heuristics, language-specific examples, and false positive guidance.

Workflow

1. Determine Scope

Parse flags and resolve the file list per ../../shared/schemas/flags.md. Filter to files likely to contain API logic:

  • Route/endpoint definitions (**/routes/**, **/api/**, **/endpoints/**)
  • Controllers and handlers (**/controllers/**, **/handlers/**, **/views/**)
  • Serializers and DTOs (**/serializers/**, **/dto/**, **/schemas/**)
  • Middleware (**/middleware/**, **/middlewares/**)
  • Rate limiting configuration (**/config/**, **/limiters/**)

2. Check for Available Scanners

Detect scanners per ../../shared/schemas/scanners.md:

  1. semgrep -- primary scanner for API patterns
  2. bandit -- Python API security issues
  3. brakeman -- Rails API vulnerabilities

Record which scanners are available and which are missing.

3. Run Scanners (If Available)

If semgrep is available, run with rules targeting API security:

semgrep scan --config auto --json --quiet <target>

Filter results to rules matching BOLA, mass assignment, authorization, and data exposure patterns. Normalize output to the findings schema.

4. Claude Code Analysis

Regardless of scanner availability, perform manual code analysis:

  1. BOLA audit: Find API endpoints that accept resource IDs and verify each enforces ownership or authorization before returning/modifying data.
  2. Mass assignment: Find endpoints that accept request bodies and bind them directly to models without explicit field allowlisting.
  3. Rate limiting: Check for rate limiting middleware on authentication endpoints, data-intensive endpoints, and mutation endpoints.
  4. Function-level authorization: Verify admin/privileged endpoints have role-based authorization, not just authentication.
  5. Excessive data exposure: Check API responses for fields that should not be exposed (passwords, internal IDs, sensitive user data).

When --depth deep, additionally trace:

  • Full request-to-response data flow including serialization
  • Authorization middleware chains across all API routes
  • Rate limiting configuration and bypass scenarios

5. Report Findings

Format output per ../../shared/schemas/findings.md using the API prefix (e.g., API-001, API-002).

Include for each finding:

  • Severity and confidence
  • Exact file location with code snippet
  • OWASP API Top 10 reference
  • Concrete fix with diff when possible
  • CWE references

What to Look For

These are the high-signal patterns specific to API security. Each maps to a detection pattern in references/detection-patterns.md.

  1. Broken Object-Level Authorization (BOLA) -- API endpoints accept a resource ID from the client and return data without verifying the requesting user owns or is authorized to access that resource.

  2. Mass assignment -- Request body fields are bound directly to database model attributes, allowing attackers to set fields they should not control (role, price, isAdmin).

  3. Missing rate limiting -- API endpoints lack rate limiting, allowing brute-force attacks on authentication, enumeration, and resource exhaustion.

  4. Broken function-level authorization -- Admin or privileged API endpoints are accessible to regular users because they check authentication but not authorization role/permissions.

  5. Excessive data exposure -- API responses include sensitive fields (password hashes, tokens, internal metadata) that the client does not need.

  6. Missing input validation -- API endpoints accept unbounded inputs (no max length, no type validation) enabling injection and resource abuse.

Scanner Integration

ScannerCoverageCommand
semgrepBOLA, mass assignment, missing authsemgrep scan --config auto --json --quiet <target>
banditPython API security patternsbandit -r <target> -f json -q
brakemanRails mass assignment, authorizationbrakeman -q -f json -o /dev/stdout

Fallback (no scanner): Use Grep with patterns from references/detection-patterns.md to find API route definitions, model binding, rate limiting config, and response serialization. Report findings with confidence: medium.

Output Format

Use the findings schema from ../../shared/schemas/findings.md.

  • ID prefix: API (e.g., API-001)
  • metadata.tool: api
  • metadata.framework: api
  • metadata.category: API
  • references.api_top10: API1:2023, API3:2023, etc.
  • references.cwe: CWE-639, CWE-915, CWE-770
  • references.stride: I (Information Disclosure) or E (Elevation of Privilege)

Severity guidance for this category:

  • critical: BOLA on sensitive data (financial, medical, PII), mass assignment on role/privilege fields
  • high: BOLA on user-scoped data, missing auth on admin endpoints, mass assignment on price/status
  • medium: Missing rate limiting on auth endpoints, excessive data exposure of non-critical fields
  • low: Minor data over-exposure, rate limit too generous but present

Attack Surface Mapping

Discover and inventory every entry point where external data enters the application. Produces a ranked catalog of all routes, APIs, input handlers, and external interfaces organized by exposure level and trust boundary.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification.

FlagAttack Surface Behavior
--scopeDefault full. Attack surface mapping benefits from whole-codebase visibility. Narrow scopes produce partial inventories with a warning.
--depth quickFramework route extraction only (Grep for route decorators and definitions).
--depth standardRoute extraction + read handlers to classify input types and auth requirements.
--depth deepStandard + trace each entry point to internal sinks, map trust boundary crossings.
--depth expertDeep + rank by exploitability, identify shadow/undocumented endpoints, DREAD scoring.
--severityNot directly applicable. Used to filter the exposure ranking in output.
--formatDefault text. Use json for machine-readable inventory, md for wiki export.

Workflow

Step 1: Determine Scope

  1. Parse --scope flag. Default to full for this skill (attack surface requires broad visibility).
  2. Resolve to a concrete file list.
  3. Prioritize discovery in: route files, controller directories, API definitions, middleware, OpenAPI/Swagger specs, GraphQL schemas, gRPC proto files, CLI entry points, WebSocket handlers.

Step 2: Discover Framework and Language

Identify the application framework(s) to determine route registration patterns:

FrameworkRoute Pattern
Express/Koa/Fastifyapp.get(), router.post(), fastify.route()
Djangourlpatterns, path(), re_path(), @api_view
Flask@app.route(), @blueprint.route()
Spring@GetMapping, @PostMapping, @RequestMapping
Railsroutes.rb, resources :, get '/'
Next.js/Nuxtpages/ and app/ directory conventions, route.ts
ASP.NET[HttpGet], [Route], MapGet(), MapPost()
Go net/httphttp.HandleFunc(), mux.Handle(), gorilla/chi patterns
FastAPI@app.get(), @router.post()
gRPC.proto service definitions, generated server stubs
GraphQLSchema definitions, resolver registrations

Step 3: Extract Entry Points

For each framework detected, systematically extract all entry points:

  1. HTTP Routes: Method, path, handler function, middleware chain.
  2. API Endpoints: REST, GraphQL queries/mutations, gRPC services.
  3. Form Handlers: HTML form action targets, multipart upload handlers.
  4. File Upload Endpoints: Endpoints accepting file data, storage destinations.
  5. WebSocket Handlers: Connection endpoints, message handlers.
  6. CLI Arguments: Argument parsers (argparse, commander, cobra, clap).
  7. Message Queue Consumers: Kafka/RabbitMQ/SQS message handlers.
  8. Scheduled Tasks: Cron jobs, scheduled functions that process external data.
  9. Webhook Receivers: Endpoints accepting callbacks from external services.
  10. Server-Sent Events: SSE endpoints, streaming responses.

Step 4: Classify Each Entry Point

For every discovered entry point, determine:

  1. Authentication: None, API key, session, JWT, OAuth, mTLS, or unknown.
  2. Authorization: None, role-based, attribute-based, or unknown.
  3. Input Types: Query params, path params, headers, body (JSON/XML/form), files, cookies.
  4. Validation: Present (with details) or absent.
  5. Rate Limiting: Present or absent.
  6. Network Exposure: Internet-facing, internal network, localhost only.
  7. Protocol: HTTP, HTTPS, WebSocket, gRPC, raw TCP, message queue.

Step 5: Rank by Exposure

Assign an exposure level to each entry point:

LevelCriteria
CRITICALInternet-facing, no authentication, accepts user input, interacts with sensitive data or system resources
HIGHInternet-facing with authentication but handling sensitive data, or unauthenticated endpoints with limited input validation
MEDIUMAuthenticated endpoints with proper validation, or internal endpoints with no authentication
LOWInternal endpoints with authentication, limited input surface, or read-only operations on non-sensitive data

At --depth deep and --depth expert, trace each HIGH/CRITICAL entry point inward to identify what sinks they reach (databases, file system, external services, system commands).

Step 6: Identify Shadow Endpoints

At --depth expert, look for:

  • Debug/admin routes not behind auth middleware (e.g., /debug, /admin, /metrics, /health exposing internals).
  • Routes registered dynamically or via reflection that don't appear in static route lists.
  • Endpoints in test/staging configuration that may be active in production.
  • API versions that are deprecated but still routed.
  • OpenAPI/Swagger UI exposed without authentication.

Step 7: Report

Output the attack surface inventory.

Output Format

This skill produces an inventory, not vulnerability findings. However, when entry points have clearly missing security controls (no auth on sensitive endpoints), emit findings using the standard schema from ../../shared/schemas/findings.md.

Finding ID prefix: SURF (e.g., SURF-001).

Inventory Table

## Attack Surface Inventory

### Summary
- Total entry points: N
- Internet-facing: N (N unauthenticated)
- Internal: N
- Exposure: N CRITICAL, N HIGH, N MEDIUM, N LOW

### Entry Points by Exposure

| # | Method | Path | Auth | Input Types | Validation | Rate Limit | Exposure |
|---|--------|------|------|-------------|------------|------------|----------|
| 1 | POST | /api/v1/users | None | JSON body | None | No | CRITICAL |
| 2 | GET | /api/v1/users/:id | JWT | Path param | Partial | Yes | MEDIUM |
| ... |

### Trust Boundary Map (--depth deep)
[Mermaid diagram showing entry points grouped by trust boundary]

### Shadow Endpoints (--depth expert)
[Undocumented or debug endpoints discovered]

### Findings
[Standard findings for missing security controls on entry points]

Findings follow ../../shared/schemas/findings.md with:

  • metadata.tool: "attack-surface"
  • metadata.framework: depends on invoking context (or null if standalone)
  • references.cwe: CWE-16 (Configuration), CWE-306 (Missing Authentication)

Pragmatism Notes

  • Health check endpoints (/health, /ready) without auth are normal in container orchestration. Only flag if they expose sensitive internal state.
  • Internal APIs behind a service mesh or VPN still warrant inventory but at lower exposure.
  • CLI tools that only run locally have minimal attack surface unless they parse untrusted files.
  • Static file serving endpoints are low priority unless directory traversal is possible.

Identification and Authentication Failures

Analyze source code for authentication and session management vulnerabilities. Detect weak credential handling, missing brute force protections, insecure session management, and absent multi-factor authentication. Produce actionable findings with severity ratings, code locations, and concrete remediation steps.

Supported Flags

All flags from ../../shared/schemas/flags.md are supported:

FlagRelevant Behavior
--scope <value>Determines which files to analyze (default: changed)
--depth <value>quick: pattern scan only. standard: full read + analysis. deep: trace auth flows cross-file. expert: red team simulation with DREAD scoring
--severity <value>Filter findings by minimum severity
--format <value>Output format: text, json, sarif, md
--fixChain into remediation after analysis
--quietFindings only, no explanations
--explainAdd learning context to each finding

Framework Context

OWASP Top 10 2021 - A07: Identification and Authentication Failures

Confirmation of the user's identity, authentication, and session management is critical to protect against authentication-related attacks. Applications are vulnerable when they:

  • Permit automated attacks such as credential stuffing or brute force
  • Permit default, weak, or well-known passwords
  • Use weak credential recovery processes (e.g., knowledge-based answers)
  • Store passwords in plain text, encrypted, or with weak hashes (MD5, SHA1)
  • Lack or have ineffective multi-factor authentication
  • Expose session identifiers in URLs
  • Reuse session identifiers after successful login
  • Fail to properly invalidate sessions on logout or timeout

STRIDE Mapping: Spoofing, Repudiation

CWE References: CWE-287 (Improper Authentication), CWE-384 (Session Fixation), CWE-307 (Brute Force), CWE-521 (Weak Password Requirements), CWE-916 (Weak Password Hash), CWE-613 (Insufficient Session Expiration), CWE-308 (Missing MFA)

Detection Patterns

Read references/detection-patterns.md before performing analysis. It contains detailed Grep heuristics, language-specific code examples, scanner coverage, and false positive guidance for each vulnerability pattern.

Workflow

1. Determine Scope

Parse --scope flag and resolve to a concrete file list:

  1. Apply scope resolution per ../../shared/schemas/flags.md.
  2. Filter to files relevant to authentication:
    • Route handlers, middleware, and controllers (login, register, password reset endpoints)
    • Authentication modules and services
    • Session configuration files
    • Password hashing and validation utilities
    • JWT/token generation and validation code
    • OAuth/OIDC integration code
    • Configuration files (session timeout, password policy settings)
  3. Include framework-specific auth files (e.g., passport.js configs, Django auth backends, Spring Security configs, Go auth middleware).

2. Check for Scanners

Detect available scanners in order of preference:

ScannerDetectRelevant Rules
semgrepwhich semgrepAuth bypass, weak hashing, JWT issues, session management
banditwhich banditHardcoded passwords, weak hashes (Python)
gosecwhich gosecHardcoded credentials, weak crypto (Go)
gitleakswhich gitleaksHardcoded secrets, API keys, passwords in code

If no scanner is available, proceed with Claude analysis using Grep patterns from references/detection-patterns.md. Note in output: "No scanner available -- findings based on code pattern analysis only."

3. Run Scanners

For each available scanner:

  1. Execute against the scoped file list.
  2. Parse JSON output.
  3. Filter to authentication-related rules only.
  4. Normalize findings to the schema in ../../shared/schemas/findings.md.
  5. Set scanner.confirmed: true for scanner-detected findings.

4. Claude Analysis

Regardless of scanner availability, perform manual code analysis:

  1. Read references/detection-patterns.md for the full pattern catalog.
  2. Use Grep with the regex patterns to locate suspicious constructs.
  3. Read surrounding code context (30-50 lines) to assess each match.
  4. Trace authentication flows from entry point to credential validation.
  5. At --depth deep or higher: follow imports, trace session lifecycle, map the complete auth flow across files.
  6. Deduplicate against scanner findings (same file + line = same finding).
  7. Set confidence: medium for Claude-only findings, confidence: high when confirmed by a scanner.

5. Report Findings

Format output per --format flag. Each finding uses the schema from ../../shared/schemas/findings.md with these specifics:

  • ID prefix: AUTH (e.g., AUTH-001, AUTH-002)
  • references.owasp: A07:2021
  • references.stride: S (Spoofing) or R (Repudiation)
  • metadata.tool: auth
  • metadata.framework: owasp
  • metadata.category: A07

Summary block (appended after all findings):

## Summary

| Severity | Count |
|----------|-------|
| CRITICAL | N     |
| HIGH     | N     |
| MEDIUM   | N     |
| LOW      | N     |

**Scanners used**: [list or "none"]
**Scanners missing**: [list of recommended but unavailable]
**Top priorities**: [top 3 findings to fix first and why]

What to Look For

These are the primary vulnerability patterns. See references/detection-patterns.md for detailed regex patterns and code examples.

  1. Missing rate limiting on login -- No throttling, delay, or account lockout on authentication endpoints, enabling brute force and credential stuffing.
  2. Weak password validation -- No complexity requirements, missing minimum length checks, or no check against common password lists.
  3. Plaintext or weakly hashed passwords -- Passwords stored with MD5, SHA1, plain SHA256, or without salting. Must use Argon2, bcrypt, or scrypt.
  4. Session ID in URL parameters -- Session tokens passed via query strings, visible in logs, referrer headers, and browser history.
  5. Missing session regeneration after login -- Same session ID used before and after authentication, enabling session fixation attacks.
  6. JWT with none algorithm accepted -- JWT verification allows alg: "none", letting attackers forge unsigned tokens.
  7. Hardcoded JWT secrets -- Signing keys embedded in source code rather than loaded from environment or secrets management.
  8. Missing or ineffective MFA -- No multi-factor authentication on sensitive operations, or MFA that can be bypassed.
  9. Insufficient session invalidation -- Sessions not destroyed on logout, or no server-side session expiration/timeout.

Scanner Integration

Refer to ../../shared/schemas/scanners.md for full scanner details.

Primary: semgrep (broad auth rule coverage across languages) Secondary: bandit (Python), gosec (Go), gitleaks (hardcoded credentials) Fallback: Grep-based pattern matching from references/detection-patterns.md

When running as a subagent of the OWASP dispatcher, receive scope and flags from the parent agent prompt. Do not re-parse user input.

Output Format

All findings conform to the schema defined in ../../shared/schemas/findings.md.

ID prefix: AUTH (registered in the ID Prefix Registry as OWASP A07)

Example finding:

{
  "id": "AUTH-001",
  "title": "Passwords hashed with MD5 in user registration",
  "severity": "critical",
  "confidence": "high",
  "location": {
    "file": "src/auth/register.py",
    "line": 34,
    "function": "create_user",
    "snippet": "password_hash = hashlib.md5(password.encode()).hexdigest()"
  },
  "description": "User passwords are hashed with MD5, which is cryptographically broken and trivially reversible with rainbow tables or GPU cracking.",
  "impact": "An attacker with database access can recover all user passwords within minutes, enabling account takeover across the application and any services where users reuse passwords.",
  "fix": {
    "summary": "Replace MD5 with bcrypt or Argon2id",
    "diff": "- password_hash = hashlib.md5(password.encode()).hexdigest()\n+ password_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt())"
  },
  "references": {
    "cwe": "CWE-916",
    "owasp": "A07:2021",
    "stride": "S"
  },
  "metadata": {
    "tool": "auth",
    "framework": "owasp",
    "category": "A07"
  }
}

Business Logic Security (BIZ)

Analyze application business logic for security vulnerabilities including workflow step bypassing, negative amount manipulation, coupon/discount abuse, self-referral exploitation, state machine manipulation, and time-based logic exploits. Business logic flaws are unique to each application and cannot be detected by generic scanners -- they require understanding the intended workflow and finding ways to subvert it.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification. This skill supports all cross-cutting flags. Key flags for this skill:

  • --scope determines which files to analyze (default: changed)
  • --depth standard reads code and checks business rule implementations
  • --depth deep traces full workflows from initiation through completion
  • --severity filters output (business logic issues are often high or critical)

Framework Context

Key CWEs in scope:

  • CWE-840: Business Logic Errors
  • CWE-841: Improper Enforcement of Behavioral Workflow
  • CWE-799: Improper Control of Interaction Frequency
  • CWE-837: Improper Enforcement of a Single, Unique Action
  • CWE-20: Improper Input Validation

Detection Patterns

Read references/detection-patterns.md for the full catalog of code patterns, search heuristics, language-specific examples, and false positive guidance.

Workflow

1. Determine Scope

Parse flags and resolve the file list per ../../shared/schemas/flags.md. Filter to files likely to contain business logic:

  • Payment and checkout (**/payments/**, **/checkout/**, **/billing/**)
  • Order processing (**/orders/**, **/cart/**, **/transactions/**)
  • Discount and coupon logic (**/coupons/**, **/discounts/**, **/promotions/**)
  • Referral and reward systems (**/referrals/**, **/rewards/**, **/loyalty/**)
  • Workflow and state machines (**/workflows/**, **/state/**, **/status/**)
  • User account operations (**/accounts/**, **/profiles/**)

2. Check for Available Scanners

Detect scanners per ../../shared/schemas/scanners.md:

  1. semgrep -- custom rules can catch some business logic patterns

Record which scanners are available. Business logic flaws are primarily detected through manual code analysis, not automated scanners.

3. Run Scanners (If Available)

If semgrep is available, run with rules targeting business logic:

semgrep scan --config auto --json --quiet <target>

Filter for rules matching validation, state management, and numeric handling patterns. Normalize output to the findings schema.

4. Claude Code Analysis

This is the primary detection method for business logic flaws:

  1. Workflow step bypass: Map multi-step workflows (checkout, verification, approval) and verify each step cannot be skipped by calling later steps directly.
  2. Negative amount manipulation: Find numeric inputs (amounts, quantities, prices) and verify the application rejects negative values.
  3. Coupon/discount abuse: Find discount application logic and verify coupons cannot be applied multiple times, stacked beyond limits, or used after expiration.
  4. Self-referral exploitation: Find referral systems and verify users cannot refer themselves or create circular referral chains.
  5. State machine integrity: Map state transitions and verify invalid transitions are rejected (e.g., "shipped" cannot go back to "pending").
  6. Time-based logic: Find logic depending on timestamps and verify it handles timezone manipulation, clock skew, and deadline race conditions.

When --depth deep, additionally trace:

  • Full workflow paths from start to completion
  • All possible state transitions and their guards
  • Cross-endpoint workflow manipulation scenarios

5. Report Findings

Format output per ../../shared/schemas/findings.md using the BIZ prefix (e.g., BIZ-001, BIZ-002).

Include for each finding:

  • Severity and confidence
  • Exact file location with code snippet
  • Step-by-step exploit scenario
  • Business impact (financial loss, unfair advantage)
  • Concrete fix with diff when possible
  • CWE references

What to Look For

These are the high-signal patterns specific to business logic security. Each maps to a detection pattern in references/detection-patterns.md.

  1. Workflow step bypass -- Multi-step processes where a later step can be invoked directly without completing prior steps.

  2. Negative amount manipulation -- Numeric inputs accepted without sign validation, allowing negative amounts to reverse charges or increase balances.

  3. Coupon/discount abuse -- Discount codes applied multiple times, stacked beyond intended limits, or used on ineligible items.

  4. Self-referral exploitation -- Referral reward systems that do not prevent users from referring themselves or creating fake referral chains.

  5. State machine manipulation -- Invalid state transitions accepted by the system (e.g., marking an order as "delivered" before "shipped").

  6. Time-based logic exploits -- Logic dependent on client-supplied timestamps, exploitable timezone handling, or deadline race conditions.

  7. Price manipulation -- Client-supplied prices accepted without server-side verification against the product catalog.

  8. Quantity abuse -- No limits on quantities enabling abuse (ordering negative quantities, exceeding stock, zero-quantity orders).

Scanner Integration

ScannerCoverageCommand
semgrepNumeric validation, some state patternssemgrep scan --config auto --json --quiet <target>

Fallback (no scanner): Business logic flaws require manual code analysis. Use Grep with patterns from references/detection-patterns.md to find financial operations, state transitions, discount logic, and referral systems. Report findings with confidence: medium.

Output Format

Use the findings schema from ../../shared/schemas/findings.md.

  • ID prefix: BIZ (e.g., BIZ-001)
  • metadata.tool: business-logic
  • metadata.framework: specialized
  • metadata.category: BIZ
  • references.cwe: CWE-840, CWE-841
  • references.owasp: A04:2021 (Insecure Design)
  • references.stride: T (Tampering) or E (Elevation of Privilege)

Severity guidance for this category:

  • critical: Direct financial loss (negative amounts in payments, price manipulation)
  • high: Workflow bypass on security-critical processes, unlimited discount stacking
  • medium: Self-referral abuse, state manipulation with limited business impact
  • low: Minor workflow inconsistencies, cosmetic state issues

AppSec Config -- Preferences Management

Manage persistent security preferences stored in .appsec/config.yaml. Settings control default behavior for all /appsec:* tools -- scope, depth, severity filters, scanner paths, enabled hooks, accepted risks, and excluded paths.

This skill runs entirely in the main agent context. It does NOT dispatch subagents.

Supported Operations

Detect the user's intent from their message:

IntentAction
"show config", "current settings"Display current config
"set default scope to full"Update a setting
"exclude vendor/ from scans"Add to excluded paths
"accept risk INJ-003"Add to accepted risks
"reset config"Delete config file
"enable hooks"Enable/disable hook settings
No specific intentShow current config with explanations

Config Schema

The config file is .appsec/config.yaml. All fields are optional. When a field is absent, the tool default applies.

# .appsec/config.yaml
# AppSec plugin preferences

# Default scope when no --scope flag is provided
# Values: changed, staged, branch, full
# Default: changed
default_scope: changed

# Default depth when no --depth flag is provided
# Values: quick, standard, deep, expert
# Default: standard
default_depth: standard

# Minimum severity to report
# Values: critical, high, medium, low
# Default: low (report everything)
minimum_severity: low

# Scanner binary paths (override auto-detection)
# Use when scanners are not on PATH
scanner_paths:
  # semgrep: /usr/local/bin/semgrep
  # gitleaks: /opt/tools/gitleaks
  # trivy: /usr/local/bin/trivy

# Paths to exclude from all scans
# Glob patterns relative to repository root
excluded_paths:
  - "vendor/**"
  - "node_modules/**"
  - "dist/**"
  - "build/**"
  - "*.min.js"
  - "*.bundle.js"
  - "**/*.test.*"
  - "**/*.spec.*"

# Accepted risks (findings to suppress in future scans)
# Each entry: finding ID, reason, who accepted, when
accepted_risks: []
  # - id: INJ-003
  #   reason: "Input is validated upstream by API gateway"
  #   accepted_by: "developer"
  #   accepted_on: "2026-02-14"

# Hook configuration
hooks:
  # Review implementation plans for security on ExitPlanMode
  plan_review: true
  # Scan written/edited files for hardcoded secrets
  secret_detection: true

# Frameworks to include in full-audit
# Default: all
enabled_frameworks:
  - owasp
  - stride
  - pasta
  - linddun
  - sans25

# Red team personas to include in expert mode
# Default: all
enabled_personas:
  - script-kiddie
  - insider
  - organized-crime
  - hacktivist
  - nation-state
  - supply-chain

Workflow

Step 1: Load Current Config

Check if .appsec/config.yaml exists using Glob. If it exists, read it. If not, use all defaults.

If the config file exists but cannot be parsed as valid YAML, warn the user: Warning: .appsec/config.yaml has invalid YAML. Using defaults. Run /appsec:config to fix. If the file contains unknown keys (possible typos), warn: Warning: Unknown config key '<key>'. Did you mean '<closest-match>'?

Step 2: Parse User Intent

Determine what the user wants:

Show config: Display the current config (or defaults if no file exists) with explanations for each setting.

Update a setting:

  1. Validate the new value against the allowed values for that field.
  2. If the config file exists, read it and update the field.
  3. If no config file exists, create one with the single changed field.
  4. Write the file.
  5. Confirm the change.

Exclude a path: Add the path pattern to excluded_paths. Validate it is a valid glob pattern. Warn if the pattern seems too broad (e.g., **/* would exclude everything).

Accept a risk:

  1. Verify the finding ID exists in .appsec/findings.json.
  2. Ask the user for a reason if not provided.
  3. Add to accepted_risks with timestamp.
  4. Confirm the acceptance.

Reset config: Delete .appsec/config.yaml. Confirm that all settings return to defaults.

Enable/disable hooks: Toggle hooks.plan_review or hooks.secret_detection.

Step 3: Output

Show Config (Text Format)
=====================================================
          APPSEC CONFIG -- Current Settings
=====================================================

DEFAULTS:
  Scope:    <value> (default: changed)
  Depth:    <value> (default: standard)
  Severity: <value> (default: low)

SCANNERS:
  semgrep:    <auto-detected / custom path>
  gitleaks:   <auto-detected / custom path>
  ...

EXCLUDED PATHS:
  - vendor/**
  - node_modules/**
  - ...

ACCEPTED RISKS: <N>
  - <ID>: <reason> (accepted <date>)
  - ...

HOOKS:
  Plan review:      <enabled/disabled>
  Secret detection: <enabled/disabled>

FRAMEWORKS: <list>
RED TEAM:   <list>

CONFIG FILE: .appsec/config.yaml <exists / not created>

=====================================================
  /appsec:config set <key> <value>    Change a setting
  /appsec:config exclude <path>       Add exclusion
  /appsec:config accept <ID>          Accept a risk
  /appsec:config reset                Reset to defaults
=====================================================
Update Confirmation
Updated .appsec/config.yaml:
  <key>: <old value> -> <new value>

Validation Rules

FieldAllowed ValuesError on Invalid
default_scopechanged, staged, branch, fullYes, show allowed values
default_depthquick, standard, deep, expertYes, show allowed values
minimum_severitycritical, high, medium, lowYes, show allowed values
scanner_paths.*Absolute file path that existsWarn if path does not exist
excluded_pathsValid glob patternWarn if pattern is too broad
accepted_risks.*.idFinding ID present in findings.jsonWarn if ID not found
hooks.*true or falseYes
enabled_frameworksowasp, stride, pasta, linddun, sans25Yes
enabled_personasscript-kiddie, insider, organized-crime, hacktivist, nation-state, supply-chainYes

How Config Is Consumed

Other skills read .appsec/config.yaml at startup to apply defaults:

  1. If the user provides a flag (e.g., --scope full), the flag wins.
  2. If no flag is provided, the config value is used.
  3. If no config value exists, the tool default applies.

Accepted risks are filtered out during consolidation in /appsec:run and /appsec:full-audit. The finding is still detected but marked as "accepted": true and excluded from severity counts unless --severity low is explicitly set.

Cryptographic Failures (A02:2021)

Analyze source code for cryptographic weaknesses including use of broken or weak algorithms, hardcoded encryption keys, improper password hashing, cleartext transmission of sensitive data, missing encryption at rest, and insecure random number generation.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification. This skill supports all cross-cutting flags. Key flags for this skill:

  • --scope determines which files to analyze (default: changed)
  • --depth standard checks imports, function calls, and configuration values
  • --depth deep traces key material origin and data flow for sensitive values
  • --severity filters output (crypto issues range from low to critical)

Framework Context

Read ../../shared/frameworks/owasp-top10-2021.md, section A02:2021 - Cryptographic Failures, for the full category description, common vulnerabilities, and prevention guidance.

Key CWEs in scope:

  • CWE-261: Weak Encoding for Password
  • CWE-327: Use of a Broken or Risky Cryptographic Algorithm
  • CWE-328: Use of Weak Hash
  • CWE-330: Use of Insufficiently Random Values
  • CWE-331: Insufficient Entropy
  • CWE-338: Use of Cryptographically Weak PRNG
  • CWE-759: Use of a One-Way Hash without a Salt
  • CWE-760: Use of a One-Way Hash with a Predictable Salt
  • CWE-798: Use of Hard-coded Credentials

Detection Patterns

Read references/detection-patterns.md for the full catalog of code patterns, search heuristics, language-specific examples, and false positive guidance.

Workflow

1. Determine Scope

Parse flags and resolve the file list per ../../shared/schemas/flags.md. Filter to files likely to contain cryptographic operations:

  • Crypto/security utility modules (**/crypto/**, **/security/**, **/utils/encrypt*)
  • Authentication modules (**/auth/**, **/login/**, **/password*)
  • Configuration files (**/.env*, **/config/**, **/settings*)
  • Database models with password fields (**/models/**)
  • TLS/SSL configuration (**/ssl/**, **/tls/**, **/certs/**)

2. Check for Available Scanners

Detect scanners per ../../shared/schemas/scanners.md:

  1. semgrep — primary scanner for crypto pattern detection
  2. bandit — Python-specific weak crypto detection
  3. gosec — Go-specific crypto issues
  4. gitleaks / trufflehog — hardcoded keys and secrets

Record which scanners are available and which are missing.

3. Run Scanners (If Available)

If semgrep is available:

semgrep scan --config auto --json --quiet <target>

Filter results to rules matching cryptographic patterns, weak hashing, hardcoded keys, and TLS configuration. Normalize output to the findings schema.

If gitleaks is available (for hardcoded key detection):

gitleaks detect --source <target> --report-format json --report-path /dev/stdout --no-banner

4. Claude Code Analysis

Regardless of scanner availability, perform manual code analysis:

  1. Hash algorithm audit: Grep for MD5, SHA1, SHA-256 (without key) used in security contexts (password hashing, token generation, signature verification).
  2. Key management: Find encryption keys, API secrets, and IVs — check if they are hardcoded, loaded from environment, or from a key management service.
  3. Password storage: Locate password hashing code and verify use of bcrypt, argon2, or scrypt with appropriate cost factors.
  4. Random number generation: Find random value generation and verify cryptographically secure sources are used for security-sensitive operations.
  5. TLS configuration: Check for TLS enforcement, certificate validation, and minimum protocol version.
  6. Encryption mode: Identify block cipher usage and verify ECB mode is not used for anything beyond single-block encryption.

When --depth deep, additionally trace:

  • Where encryption keys originate and how they flow through the application
  • Whether sensitive data is encrypted before storage and in transit
  • Key rotation mechanisms and lifecycle

5. Report Findings

Format output per ../../shared/schemas/findings.md using the CRYPT prefix (e.g., CRYPT-001, CRYPT-002).

Include for each finding:

  • Severity and confidence
  • Exact file location with code snippet
  • Impact description specific to the cryptographic weakness
  • Concrete fix with diff showing the secure alternative
  • CWE and OWASP references

What to Look For

These are the high-signal patterns specific to cryptographic failures. Each maps to a detection pattern in references/detection-patterns.md.

  1. Weak hash algorithms for security — MD5 or SHA1 used for password hashing, token generation, integrity verification, or digital signatures.

  2. Hardcoded encryption keys and IVs — Symmetric keys, asymmetric private keys, or initialization vectors embedded directly in source code.

  3. Insecure random number generation — Math.random(), rand(), or random.random() used for tokens, session IDs, or cryptographic operations.

  4. Password storage without proper hashing — Passwords stored in plaintext, with reversible encryption, or with fast hashes (MD5, SHA-family) instead of purpose-built password hashing functions.

  5. ECB mode usage — Block cipher encryption using ECB mode, which reveals patterns in the plaintext.

  6. Missing TLS enforcement — HTTP used where HTTPS is required, disabled certificate validation, or outdated TLS versions allowed.

  7. Insufficient key derivation — Using encryption keys directly from passwords without a proper key derivation function (PBKDF2, HKDF).

  8. Static or predictable IVs/nonces — Initialization vectors or nonces that are hardcoded, reused, or derived from predictable sources.

Scanner Integration

ScannerCoverageCommand
semgrepWeak crypto, hardcoded keys, insecure randomsemgrep scan --config auto --json --quiet <target>
banditPython crypto issues (MD5, DES, hardcoded passwords)bandit -r <target> -f json -q
gosecGo crypto (weak TLS, hardcoded creds)gosec -fmt json ./...
gitleaksHardcoded keys and secretsgitleaks detect --source <target> --report-format json --report-path /dev/stdout --no-banner

Fallback (no scanner): Use Grep with patterns from references/detection-patterns.md to find hash function calls, encryption operations, key assignments, and random number generation. Report findings with confidence: medium.

Relevant semgrep rule categories:

  • python.cryptography.security.insecure-hash-*
  • python.cryptography.security.insecure-cipher-*
  • javascript.crypto.security.weak-*
  • java.crypto.security.weak-*
  • generic.secrets.security.detected-*

Output Format

Use the findings schema from ../../shared/schemas/findings.md.

  • ID prefix: CRYPT (e.g., CRYPT-001)
  • metadata.tool: crypto
  • metadata.framework: owasp
  • metadata.category: A02
  • references.owasp: A02:2021
  • references.stride: I (Information Disclosure) or T (Tampering)

Severity guidance for this category:

  • critical: Plaintext password storage, hardcoded production encryption keys, disabled TLS verification
  • high: MD5/SHA1 for password hashing, ECB mode on sensitive data, Math.random() for tokens
  • medium: Weak key derivation, outdated TLS versions (TLS 1.0/1.1), missing encryption at rest
  • low: SHA-256 for password hashing (not broken but not ideal), non-security use of weak hash

Disclosure of Information Analysis (LINDDUN D2)

Analyze source code for disclosure threats where personal data is accessible to unauthorized parties. Focuses specifically on personal and sensitive data rather than general system information. Covers direct disclosure (data breach vectors) and indirect disclosure (third-party sharing, over-collection).

Supported Flags

Read ../../shared/schemas/flags.md for full flag documentation. This skill supports all cross-cutting flags.

FlagDisclosure-Specific Behavior
--scopeDefault changed. Focuses on files handling personal data: API handlers, data models, logging, caching, third-party integrations, and error handling.
--depth quickGrep patterns only: scan for PII in logs, error messages, and third-party data sharing.
--depth standardFull code read, trace personal data flows within each file, check access controls on personal data stores.
--depth deepCross-file personal data flow tracing. Map all paths where PII exits the application boundary.
--depth expertDeep + breach simulation: model what personal data is exposed in each attack scenario.
--severityFilter output. PII in logs is typically high; over-fetching is medium.
--fixGenerate redaction, field-level access control, and data minimization replacements.

Framework Context

LINDDUN D2 -- Disclosure of Information

Disclosure of information in the LINDDUN context refers specifically to unauthorized access to personal data. Read ../../shared/frameworks/linddun.md for the full LINDDUN framework reference including the distinction between LINDDUN disclosure (personal data focus) and STRIDE information disclosure (general system information).

Privacy Property Violated: Confidentiality of Personal Data

STRIDE Mapping: Information Disclosure (LINDDUN narrows focus specifically to personal data rather than general system information)

Workflow

Step 1 -- Determine Scope

  1. Parse --scope flag (default: changed).
  2. Resolve to a concrete file list.
  3. Filter to relevant files: API handlers, data models, logging configuration, error handling, caching logic, third-party SDK integrations, data export endpoints, and serialization logic.
  4. Prioritize files containing: user data structures, PII fields, third-party API calls with user data, log statements, cache writes, and error responses.

Step 2 -- Analyze for Personal Data Disclosure

Read each scoped file and assess personal data exposure vectors:

  1. Check logging for PII: Scan log statements for personal data fields (name, email, phone, address, SSN, health data, financial data).
  2. Assess API response data: Determine whether endpoints return more personal fields than the consumer needs (over-fetching).
  3. Examine third-party data sharing: Identify where personal data flows to external services (analytics, advertising, logging, error tracking).
  4. Check error handling: Look for personal data in error messages, stack traces, and debug output.
  5. Evaluate cache and temporary storage: Determine whether personal data in caches, temp files, or browser storage is properly protected.

At --depth deep or --depth expert, trace all paths where personal data exits the application boundary and map the full disclosure surface.

Step 3 -- Report Findings

Output findings per ../../shared/schemas/findings.md. Each finding needs: DDSCL-NNN id, title, severity (based on data sensitivity and exposure scope), location with snippet, description of what personal data is disclosed and through which channel, impact (unauthorized data access), fix (redaction, minimization, or encryption), and CWE/LINDDUN references.

Analysis Checklist

  1. Do log statements include personal data (names, emails, phone numbers, addresses)?
  2. Are API responses returning full user objects instead of only needed fields?
  3. Is personal data sent to third-party analytics or error tracking services?
  4. Do error messages or stack traces contain personal data values?
  5. Is PII passed through URL query parameters (visible in logs and referrer headers)?
  6. Are personal data fields encrypted at rest, or stored in plaintext?
  7. Do caching layers store personal data without appropriate TTLs or access controls?
  8. Do debug modes expose additional personal data that production would not?

What to Look For

  1. PII in log statements: Personal data written to logs, console, or debug output.
    • Grep: log\.\w+\(.*email|logger\.\w+\(.*password|console\.log\(.*ssn|print\(.*credit.card
  2. Over-fetched API responses: Returning complete user objects with unnecessary fields.
    • Grep: res\.json\(user\)|response\.send\(userData\)|SELECT \*.*FROM.*user|\.toJSON\(\)
  3. Third-party data sharing: PII sent to analytics, error tracking, or advertising SDKs.
    • Grep: Sentry\.captureException.*user|analytics\.track.*email|gtag.*user_id|bugsnag.*user
  4. PII in error responses: Personal data leaked through error handling.
    • Grep: res\.status\(.*\.json\(.*user|catch.*res\.send\(.*err|error.*message.*email
  5. Personal data in URLs: PII in query parameters or path segments.
    • Grep: \?email=|&phone=|/users/\$\{email\}|encodeURIComponent\(.*email\)|queryString.*ssn
  6. Plaintext PII storage: Personal data stored without encryption.
    • Grep: password.*varchar|ssn.*text|credit_card.*string|healthData.*column|plaintext.*pii
  7. Cache with personal data: PII stored in cache layers without protection.
    • Grep: cache\.set\(.*user|redis\.set\(.*email|localStorage\.setItem\(.*token|sessionStorage.*user
  8. Missing field-level access control: No column or field restriction on personal data.
    • Grep: SELECT \*|findAll\(\)|\.find\(\{\}\)|\.aggregate\(\[|include:.*all

Regulatory Mapping

RegulationProvisionRelevance
GDPR Art. 5(1)(f)Integrity and confidentialityPersonal data must be protected against unauthorized disclosure
GDPR Art. 32Security of processingAppropriate technical measures to protect personal data
GDPR Art. 33-34Breach notificationDisclosure of personal data triggers 72-hour notification
CCPA 1798.100Right to knowConsumers must know what personal data is collected and shared
CCPA 1798.150Private right of actionData breaches exposing personal data create liability
HIPAA 164.312Technical safeguardsProtected health information requires access controls and encryption

Output Format

Use finding ID prefix DDSCL (e.g., DDSCL-001, DDSCL-002).

All findings follow the schema in ../../shared/schemas/findings.md with:

  • references.cwe: CWE-200, CWE-311, or CWE-532 as appropriate
  • references.owasp: A01:2021 (Broken Access Control) or A02:2021 (Cryptographic Failures)
  • metadata.tool: "data-disclosure"
  • metadata.framework: "linddun"
  • metadata.category: "D2"

Summary table after all findings:

| Disclosure Pattern           | Critical | High | Medium | Low |
|------------------------------|----------|------|--------|-----|
| PII in logs                  |          |      |        |     |
| Over-fetched API responses   |          |      |        |     |
| Third-party data sharing     |          |      |        |     |
| PII in error messages        |          |      |        |     |
| Personal data in URLs        |          |      |        |     |
| Plaintext PII storage        |          |      |        |     |
| Cache / temp storage leaks   |          |      |        |     |

Followed by: top 3 priorities, personal data flow map, and overall assessment.

Data Flow Mapping

Trace how data moves through the application from input to storage to output. Identify trust boundary crossings, encryption/decryption points, serialization steps, and data transformation operations. Produces annotated data flow maps with security observations at each transition.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification.

FlagData Flow Behavior
--scopeDefault full. Data flow mapping requires broad visibility. Narrow scopes trace only flows touching scoped files.
--depth quickEntry points and data stores only, no intermediate tracing.
--depth standardTrace major data paths from input through processing to storage/output.
--depth deepFull taint analysis: every transformation, validation, and boundary crossing.
--depth expertDeep + annotate with threat categories, identify covert channels, DREAD scoring on flow weaknesses.
--formatDefault text. Use md for Mermaid diagrams, json for structured flow graph.

Workflow

Step 1: Determine Scope

  1. Parse --scope flag. Default to full for comprehensive flow mapping.
  2. Resolve to a concrete file list.
  3. Prioritize: HTTP handlers, database access layers, external service clients, message queue producers/consumers, file I/O operations, cache layers, serialization/deserialization code, encryption modules.

Step 2: Identify Data Sources (Origins)

Catalog every point where data enters the system:

Source TypeWhat to Look For
HTTP requestsRequest body, query params, headers, cookies, path params, uploaded files
Database readsQueries returning user data, config data, or cached content
External APIsResponses from third-party services, webhook payloads
Message queuesConsumed messages from Kafka, RabbitMQ, SQS, etc.
File systemFile reads, config loading, uploaded file processing
EnvironmentEnvironment variables, secrets managers, config services
User sessionsSession data, cached user state

Step 3: Identify Data Sinks (Destinations)

Catalog every point where data exits or is persisted:

Sink TypeWhat to Look For
Database writesINSERT, UPDATE, ORM save/create operations
HTTP responsesResponse body, headers, cookies set
External APIsRequests to third-party services
Message queuesPublished messages
File systemFile writes, log files, exported data
LogsApplication logs, audit logs, error tracking
BrowserRendered HTML, JavaScript context, DOM injection points
Email/SMSOutbound notification content

Step 4: Trace Data Paths

For each source, trace data through the codebase to its sinks:

  1. Follow the variable: Track the request parameter/input through function calls, assignments, and returns.
  2. Map transformations: Record every operation applied to the data:
    • Validation (type checks, regex, allowlists)
    • Sanitization (HTML escaping, SQL parameterization, encoding)
    • Encryption/Decryption (note algorithm and key source)
    • Serialization/Deserialization (JSON parse, protobuf, pickle)
    • Aggregation (data combined with other sources)
    • Redaction (fields stripped or masked)
  3. Mark trust boundaries: Note when data crosses between:
    • External network to application
    • Application to database
    • Application to external service
    • Frontend to backend
    • Service to service (in microservices)
    • User space to privileged operations

Step 5: Annotate Security Properties

At each node in the data flow, annotate:

PropertyValues
EncryptedIn transit (TLS), at rest (AES/etc.), both, neither
ValidatedYes (with method), no, partial
SanitizedYes (with method), no
LoggedYes (check for sensitive data in logs), no
Access controlledAuth required, role checked, none
PII/SensitiveContains PII, financial, health, credentials, or other sensitive data

Step 6: Identify Flow Weaknesses

Flag security concerns at data flow transitions:

  1. Missing validation: Data crosses a trust boundary without validation.
  2. Missing encryption: Sensitive data transmitted or stored without encryption.
  3. Sensitive data in logs: PII, credentials, or tokens written to log sinks.
  4. Deserialization of untrusted data: pickle.loads, JSON.parse on unvalidated external input without schema validation, ObjectInputStream on network data.
  5. Trust boundary violations: Internal-only data exposed to external sinks.
  6. Missing sanitization before output: Data from untrusted source rendered in HTML, SQL, or shell command without appropriate encoding.
  7. Data retention issues: Sensitive data persisted longer than necessary or without deletion mechanisms.
  8. Implicit trust: Data from one service consumed by another without re-validation.

Step 7: Generate Flow Diagrams

Produce Mermaid data flow diagrams:

graph LR
    subgraph External
        User[User Browser]
        ExtAPI[Payment API]
    end
    subgraph Application
        API[API Handler]
        Valid[Validator]
        Logic[Business Logic]
        Encrypt[Encryption Layer]
    end
    subgraph Storage
        DB[(Database)]
        Cache[(Redis Cache)]
    end

    User -->|HTTPS, JSON body| API
    API -->|raw input| Valid
    Valid -->|validated data| Logic
    Logic -->|PII: encrypted| Encrypt
    Encrypt -->|ciphertext| DB
    Logic -->|session token| Cache
    Logic -->|payment request, TLS| ExtAPI

Annotate edges with: protocol, encryption status, data sensitivity level.

Step 8: Report

Output the data flow map with security annotations and any findings.

Output Format

This skill produces a data flow map plus findings for flow weaknesses.

Finding ID prefix: FLOW (e.g., FLOW-001).

## Data Flow Analysis

### Summary
- Data sources identified: N
- Data sinks identified: N
- Trust boundary crossings: N
- Unvalidated crossings: N
- Sensitive data flows: N

### Data Flow Diagram
[Mermaid diagram]

### Flow Inventory

| # | Source | Path | Sink | Sensitivity | Encrypted | Validated | Issue |
|---|--------|------|------|-------------|-----------|-----------|-------|
| 1 | POST /api/login | -> auth.verify -> db.query | users table | Credentials | TLS only | Yes | None |
| 2 | POST /api/upload | -> fileHandler -> fs.write | /uploads/ | User files | No | No | FLOW-001 |

### Trust Boundary Crossings
[Table of all boundary crossings with security annotations]

### Findings
[Standard findings for flow weaknesses]

Findings follow ../../shared/schemas/findings.md with:

  • metadata.tool: "data-flows"
  • references.cwe: CWE-319 (Cleartext Transmission), CWE-312 (Cleartext Storage), CWE-532 (Info Exposure Through Log), CWE-502 (Deserialization of Untrusted Data)

Pragmatism Notes

  • Not every data path needs encryption. Public data served over HTTPS is fine.
  • Internal service-to-service calls over a trusted network or service mesh are lower priority than internet-facing flows.
  • Focus on sensitive data flows first: credentials, PII, financial data, health data.
  • Log redaction is important but severity depends on log access controls.
  • At --depth quick, a high-level source-to-sink map is more useful than exhaustive intermediate tracing.

Detectability Analysis (LINDDUN D1)

Analyze source code for detectability threats where an observer can determine that a user is interacting with a system, that a record exists, or that a specific action was performed -- even without accessing the content itself. Privacy is compromised when the mere existence of an interaction or record reveals sensitive information.

Supported Flags

Read ../../shared/schemas/flags.md for full flag documentation. This skill supports all cross-cutting flags.

FlagDetectability-Specific Behavior
--scopeDefault changed. Focuses on files containing API handlers, error responses, presence indicators, and encrypted message handling.
--depth quickGrep patterns only: scan for enumeration endpoints, timing differences, and presence indicators.
--depth standardFull code read, analyze response patterns for information leakage through existence proofs.
--depth deepTrace API response behaviors across endpoints. Map enumeration surfaces and timing oracle opportunities.
--depth expertDeep + adversarial detectability simulation: model what an observer can infer from response patterns and metadata.
--severityFilter output. Severity depends on sensitivity of what can be detected.
--fixGenerate constant-time responses, uniform error handling, and padding implementations.

Framework Context

LINDDUN D1 -- Detectability

Detectability occurs when an adversary can determine that an item of interest exists, even without accessing its content. Read ../../shared/frameworks/linddun.md for the full LINDDUN framework reference including detectability patterns, timing side channels, and traffic analysis threats.

Privacy Property Violated: Undetectability / Unobservability

STRIDE Mapping: Information Disclosure (detectability focuses on existence proofs and metadata patterns rather than direct content access)

Workflow

Step 1 -- Determine Scope

  1. Parse --scope flag (default: changed).
  2. Resolve to a concrete file list.
  3. Filter to relevant files: API handlers, error handling middleware, presence or status indicators, encrypted message handling, notification systems, and cache management.
  4. Prioritize files containing: HTTP error responses, user existence checks, online status indicators, read receipts, and response timing logic.

Step 2 -- Analyze for Detectability Patterns

Read each scoped file and assess what an observer can detect about system usage or data existence:

  1. Check error response uniformity: Determine whether different error codes or messages reveal record existence (e.g., "user not found" vs. "wrong password").
  2. Assess timing consistency: Look for code paths where response time differs based on record existence (cache hit vs. database miss).
  3. Examine presence indicators: Find online status, typing indicators, read receipts, or activity signals that lack opt-out mechanisms.
  4. Check message padding: Determine whether encrypted messages have uniform size or leak content type through size variation.
  5. Evaluate enumeration surfaces: Identify endpoints that allow probing for existence of users, records, or resources.

At --depth deep or --depth expert, model the full observable surface and determine what an adversary can infer from response patterns and metadata.

Step 3 -- Report Findings

Output findings per ../../shared/schemas/findings.md. Each finding needs: DTCT-NNN id, title, severity (based on sensitivity of detectable information and ease of observation), location with snippet, description of what can be detected and through which channel, impact (what an observer infers), fix (uniform responses, constant-time ops, or padding), and CWE/LINDDUN references.

Analysis Checklist

  1. Do error responses differentiate "not found" from "access denied" for user lookups?
  2. Can an observer enumerate valid usernames, emails, or account IDs?
  3. Do response times vary based on whether a record exists (timing oracle)?
  4. Are there presence indicators or read receipts without opt-out?
  5. Do encrypted messages vary in size, revealing content type or length?
  6. Can push notification patterns reveal when a user receives messages?
  7. Do API rate limit responses differ for authenticated vs. non-existing users?
  8. Can traffic analysis reveal which features or services a user accesses?

What to Look For

  1. User enumeration via error messages: Different responses for existing vs. non-existing accounts.
    • Grep: user not found|invalid username|no such user|email not registered|account does not exist
  2. Timing oracles: Early-return patterns that reveal record existence.
    • Grep: if.*!user.*return|if.*notFound.*return|findOne.*then.*404|catch.*404
  3. Presence and activity indicators: Online status, typing, and read receipt systems.
    • Grep: isOnline|online_status|lastSeen|last_active|typing.*indicator|read.*receipt|seen.*at
  4. Account enumeration endpoints: Registration, password reset, or login that reveal existence.
    • Grep: already registered|email.*taken|username.*exists|account.*already|duplicate.*email
  5. Unpadded encrypted content: Variable-length encrypted messages.
    • Grep: encrypt\(|cipher\.update|AES.*encrypt|padding|PKCS|NoPadding
  6. Observable API patterns: Sequential IDs or predictable resource identifiers.
    • Grep: autoIncrement|SERIAL|sequence|nextval|uuid.*v1|ObjectId
  7. Notification metadata leakage: Push notification patterns revealing user behavior.
    • Grep: sendNotification|pushNotif|FCM|APNs|webpush|notify\(.*user

Regulatory Mapping

RegulationProvisionRelevance
GDPR Art. 25Data protection by designSystems must prevent unauthorized detection of data existence
GDPR Art. 32Security of processingIncludes protection against unauthorized disclosure via side channels
CCPA 1798.150Private right of actionUnauthorized access including inference from observable patterns
HIPAA 164.312(e)Transmission securityHealth record existence must not be detectable
ePrivacy Directive Art. 5Confidentiality of communicationsCommunication metadata must be protected

Output Format

Use finding ID prefix DTCT (e.g., DTCT-001, DTCT-002).

All findings follow the schema in ../../shared/schemas/findings.md with:

  • references.cwe: CWE-203 (Observable Discrepancy) or CWE-208 (Observable Timing Discrepancy)
  • references.owasp: A05:2021 (Security Misconfiguration -- information leakage in responses)
  • metadata.tool: "detecting"
  • metadata.framework: "linddun"
  • metadata.category: "D1"

Summary table after all findings:

| Detectability Pattern       | Critical | High | Medium | Low |
|-----------------------------|----------|------|--------|-----|
| User enumeration            |          |      |        |     |
| Timing side channels        |          |      |        |     |
| Presence indicators         |          |      |        |     |
| Account enumeration         |          |      |        |     |
| Message size leakage        |          |      |        |     |
| Notification patterns       |          |      |        |     |

Followed by: top 3 priorities, enumeration surface map, and overall assessment.

Denial of Service Analysis

Analyze source code for denial of service threats where attackers can disrupt or degrade service availability. Maps to STRIDE D -- violations of the Availability security property.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification. This skill supports all cross-cutting flags including --scope, --depth, --severity, --format, --fix, --quiet, and --explain.

Framework Context

Read ../../shared/frameworks/stride.md, specifically the D - Denial of Service section, for the threat model backing this analysis. Key concerns: resource exhaustion (CPU, memory, disk, network), algorithmic complexity attacks, application crashes, zip bombs.

Workflow

1. Determine Scope

Parse flags and resolve the target file list per the flags spec. Filter to files handling external input processing:

  • API endpoints and route handlers (especially public/unauthenticated ones)
  • File upload and processing handlers
  • Search and query endpoints
  • WebSocket handlers and long-lived connections
  • Message queue consumers and event processors
  • Cron jobs and batch processors
  • Middleware configuration (body parsers, rate limiters)
  • Regular expressions applied to user input
  • Image/video/document processing pipelines

2. Analyze for Denial of Service Threats

For each in-scope file, apply the Analysis Checklist below. At --depth standard, examine resource consumption patterns in each file. At --depth deep, trace input from entry points through processing chains to identify amplification points, unbounded operations, and cascading failure paths.

3. Report Findings

Output findings per ../../shared/schemas/findings.md using the DOS ID prefix (e.g., DOS-001). Set references.stride to "D" on every finding.

Analysis Checklist

Work through these questions against the scoped code. Each "yes" may produce a finding.

  1. Missing rate limiting -- Are public-facing endpoints (login, search, signup, API) exposed without rate limiting or throttling middleware? Check route definitions for absence of rateLimit, throttle, @rate_limit, or API gateway quotas. Auth endpoints are especially critical -- brute force attacks are both a spoofing and DoS vector.
  2. Unbounded input size -- Are request body, file upload, or query parameter sizes unconstrained? Look for missing bodyParser.json({ limit: }), absent MAX_CONTENT_LENGTH, file upload handlers without size caps, or missing Content-Length checks. Multipart form handlers that buffer entire uploads into memory are high risk.
  3. ReDoS patterns -- Do regular expressions use nested quantifiers or overlapping alternations on user input? Search for regex patterns like (a+)+, (a|a)*, (\w+\s*)+, (.*a){x}, or ([a-zA-Z]+)* applied to request data. These cause exponential backtracking. Test suspicious patterns with a ReDoS analyzer.
  4. Algorithmic complexity -- Are user inputs fed into operations with super-linear worst-case complexity? Look for nested loops over user-controlled collections, quadratic string building (repeated concatenation in loops), unbounded recursion on user data, or hash collision-prone data structures.
  5. Uncontrolled resource allocation -- Can user input control how much memory, disk, or CPU is allocated? Look for array/buffer creation sized by request parameters, unbounded SELECT without LIMIT, pagination without maximum page size, or new Array(req.query.size).
  6. Zip/decompression bombs -- Are compressed files (zip, gzip, brotli, tar) decompressed without checking the expanded size or compression ratio? Look for unzip, gunzip, decompress, inflate, extractall calls without size monitoring, ratio limits, or file count caps.
  7. Missing timeouts -- Are external HTTP calls, database queries, or subprocess executions missing timeout configuration? Look for requests.get without timeout=, fetch without AbortController, database connections without statement_timeout, subprocess.run without timeout.
  8. Single point of failure -- Does the application crash entirely on unhandled exceptions? Check for missing global error handlers, uncaught promise rejections crashing the Node.js process (unhandledRejection), or process.exit / os._exit in error paths that kill the entire service.
  9. Synchronous blocking in async paths -- Are CPU-intensive or I/O-blocking operations running on the main event loop (Node.js, Python asyncio)? Look for fs.readFileSync, crypto.pbkdf2Sync, large JSON.parse, image processing, or PDF generation on the event loop without worker offloading.
  10. Unbounded fan-out -- Can a single request trigger an unbounded number of downstream operations (API calls, database queries, notifications, emails)? Look for loops over user-provided arrays that make external calls per element without cardinality limits or batch caps.
  11. GraphQL complexity -- Do GraphQL endpoints allow deeply nested queries or queries requesting unlimited data? Check for absence of query depth limiting, complexity analysis, or field count restrictions. A single deeply nested query can generate millions of database operations.
  12. Connection/resource exhaustion -- Can an attacker exhaust connection pools, file descriptors, or thread pools? Look for long-lived connections without idle timeouts, connection pool configuration without max limits, or leaked connections in error paths (missing finally blocks that release resources).

Pragmatism Notes

  • Internal-only services behind a VPN or service mesh have lower DoS risk from external attackers. Rate findings lower when the endpoint is not publicly accessible, but note that internal attackers and compromised services can still exploit them.
  • Rate limiting at the API gateway level may cover endpoints that lack application-level rate limiting. Check infrastructure configuration before flagging individual routes.
  • Synchronous file reads in startup/initialization code (not request handlers) are generally acceptable. Focus Sync findings on code paths that execute per-request.
  • Missing timeouts on internal service calls within the same datacenter are lower risk than missing timeouts on calls to external third-party APIs. Prioritize external call timeouts.
  • ReDoS severity depends on whether the regex runs on user input. A complex regex on server-side constants is not a DoS vector.

What to Look For

Concrete code patterns and grep heuristics to surface DoS risks:

  • Missing rate limiters: Public routes without express-rate-limit, @throttle, RateLimiter, slowapi, or API gateway throttling config. Grep: route definitions without adjacent rate limiting middleware.
  • Dangerous regex: Patterns with nested quantifiers: (.*)+, (\w+)+, (a|aa)+, ([a-z]+)*, (.+)+$. Search for new RegExp(, re.compile(, /pattern/ applied to user input. Grep: (RegExp|re\.compile|re\.match|re\.search)\s*\(.
  • Unbounded queries: SELECT * FROM without LIMIT, .find({}) without .limit(), findAll without pagination, aggregation pipelines without $limit. Grep: SELECT \*|\.find\(\s*\{|findAll\(\s*\)|aggregate\(.
  • Missing body limits: Express without { limit: '1mb' } in bodyParser, Django without DATA_UPLOAD_MAX_MEMORY_SIZE, Flask without MAX_CONTENT_LENGTH, Spring without spring.servlet.multipart.max-file-size. Grep: bodyParser|json\(\s*\)|urlencoded\(\s*\) and check for limit configuration.
  • No timeouts: requests.get(url) without timeout, fetch(url) without signal: AbortSignal.timeout(), pg.query without statement_timeout, http.get without timeout. Grep: (requests\.(get|post)|fetch|axios\.(get|post))\s*\( without adjacent timeout.
  • Decompression without limits: zlib.gunzip, zipfile.extractall, tar.extractall, decompress( without checking decompressed size or file count. Grep: (extractall|gunzip|inflate|decompress)\s*\(.
  • Sync in async context: readFileSync, execSync, crypto.*Sync in Express handlers or async Python functions. Grep: Sync\( in route handler files.
  • Crash-prone patterns: JSON.parse(untrustedInput) without try/catch, missing process.on('unhandledRejection'), absent global exception handler. Grep: JSON\.parse\( near request data without surrounding try/catch.

Output Format

Each finding must conform to ../../shared/schemas/findings.md.

id:          DOS-<NNN>
severity:    critical | high | medium | low
confidence:  high | medium | low
location:    file, line, function, snippet
description: What the DoS vector is and how an attacker can trigger it
impact:      How service availability is affected (crash, slowdown, resource exhaustion)
fix:         Concrete remediation with diff when possible
references:
  stride: "D"
  cwe:    CWE-400 (Uncontrolled Resource Consumption), CWE-1333 (ReDoS), or relevant CWE
metadata:
  tool:      dos
  framework: stride
  category:  D

Severity Guidelines for Denial of Service

SeverityCriteria
criticalReDoS on unauthenticated endpoints, zip bomb handling without limits, unbounded memory allocation from user input causing OOM
highNo rate limiting on auth/search endpoints, missing request body size limits, unbounded database queries, missing global crash handler
mediumMissing timeouts on external calls, synchronous blocking on event loop, GraphQL without depth limits, connection pool exhaustion
lowMissing pagination max-page-size, single-threaded processing without worker pool, unbounded fan-out on internal low-volume endpoints

Common CWE References

CWEDescription
CWE-400Uncontrolled Resource Consumption
CWE-1333Inefficient Regular Expression Complexity (ReDoS)
CWE-770Allocation of Resources Without Limits
CWE-834Excessive Iteration
CWE-674Uncontrolled Recursion
CWE-409Improper Handling of Highly Compressed Data
CWE-755Improper Handling of Exceptional Conditions

Security Explainer

Interactive explainer for security frameworks, threat categories, vulnerability findings, and security concepts. Works at multiple levels of depth -- from a broad framework overview down to a single finding ID. Always uses the user's own codebase for concrete examples when possible.

Explanation Levels

Detect what the user is asking about and respond at the appropriate level:

Level 1: Framework

Triggered by framework names: STRIDE, OWASP, PASTA, LINDDUN, MITRE ATT&CK, SANS/CWE Top 25, DREAD.

What to cover:

  1. What the framework is, who created it, and when to use it.
  2. All categories/stages within the framework (e.g., all 6 STRIDE letters, all 10 OWASP categories, all 7 PASTA stages).
  3. For each category: one-sentence description and a real code example from the user's codebase if available.
  4. How the framework relates to other frameworks (cross-mappings).
  5. When to choose this framework over alternatives.

Framework references to read:

Level 2: Category

Triggered by category names: "spoofing", "tampering", "injection", "broken access control", "A01", "A03", "STRIDE-S", "CWE-89", etc.

What to cover:

  1. Full definition of the category and which framework(s) it belongs to.
  2. The security property it protects (e.g., Spoofing protects Authentication).
  3. Common attack techniques in this category (3-5 examples).
  4. Real code patterns from the user's codebase that are relevant. Use Grep and Glob to find concrete examples.
  5. How to detect vulnerabilities in this category.
  6. How to prevent or remediate them.
  7. Related categories in other frameworks (cross-mapping).

Level 3: Finding

Triggered by finding IDs: "INJ-003", "SPOOF-001", "AC-005", "SEC-002", etc. Also triggered by phrases like "explain this finding" or "what does this vulnerability mean" when a finding was recently reported.

What to cover:

  1. What the finding means in plain language.
  2. Why it is dangerous -- concrete attack scenario.
  3. How an attacker would exploit it step by step.
  4. The severity and confidence ratings and why they were assigned.
  5. Framework and CWE cross-references.
  6. Step-by-step remediation with code diff.
  7. How to verify the fix is correct.
  8. Similar vulnerabilities to watch for in the same codebase.

Level 4: Comparison

Triggered by "vs", "versus", "compared to", "difference between", or listing multiple frameworks/categories.

What to cover:

  1. Side-by-side overview of each item being compared.
  2. Key differences in approach, scope, and philosophy.
  3. When to use each one.
  4. Overlap and complementary strengths.
  5. Recommendation for the user's specific use case.

Common comparisons:

  • STRIDE vs PASTA: Categorization vs process-oriented
  • STRIDE vs LINDDUN: Security threats vs privacy threats
  • OWASP Top 10 vs SANS/CWE Top 25: Web app risks vs software weaknesses
  • OWASP Top 10 vs OWASP API Top 10: Web apps vs API-specific risks
  • DREAD vs CVSS: Qualitative vs quantitative risk scoring

Workflow

1. Parse the Query

Determine:

  • Level: Framework, category, finding, or comparison.
  • Subject(s): Which specific framework(s), category(ies), or finding(s).
  • Context: Is there a recent analysis whose findings can be referenced?

2. Load References

Read the relevant framework reference file(s) from shared/frameworks/. For finding explanations, also read the relevant skill's SKILL.md and detection patterns.

3. Search the Codebase

Use Glob and Grep to find real examples from the user's codebase that illustrate the concept. This grounds the explanation in the user's actual code rather than generic examples.

Search strategy by level:

  • Framework: Scan for patterns relevant to each category. Show 1 example per category to make the framework tangible.
  • Category: Deep search for patterns specific to that category. Show 3-5 real examples with file paths and line numbers.
  • Finding: Read the specific file and lines referenced in the finding. Also search for similar patterns elsewhere in the codebase.
  • Comparison: Search for examples that highlight the difference between the compared items.

4. Explain

Present the explanation at the appropriate level. Use clear headings, concrete code examples, and practical language. Avoid jargon without definition. When referencing CWEs or other identifiers, briefly explain what they mean.

5. Offer Follow-Up

Always end with a contextual follow-up offer:

SituationOffer
Explained a framework"Want me to run a full {framework} analysis on your codebase?"
Explained a category"Want me to scan your code specifically for {category} issues?"
Explained a finding"Want me to generate the fix?" or "Want me to check for similar issues?"
Compared frameworks"Want me to run {recommended framework} on your codebase?"
Generic concept"Want me to check your code for related vulnerabilities?"

Presentation Guidelines

  • Start with a one-sentence plain-language summary before diving into detail.
  • Use tables for structured comparisons and cross-references.
  • Show code snippets from the user's codebase when available, with file paths.
  • For findings, always include the attack scenario as a numbered step list.
  • Keep explanations practical. Developers want to know "what do I do about this?" not just "what is this?".
  • When explaining severity, connect it to real-world impact: "critical means an attacker can do X without authentication."

Edge Cases

  • Unknown term: If the user asks about something not in the loaded frameworks, provide the best explanation possible from general security knowledge and note which frameworks/CWEs are related.
  • Ambiguous query: If "explain injection" could mean SQL injection, command injection, or the OWASP A03 category, briefly cover all and ask which the user wants to dive deeper into.
  • Finding not in context: If the user references a finding ID that was not part of a recent analysis, explain what findings with that prefix typically represent (e.g., "INJ findings are injection vulnerabilities detected by the injection skill") and offer to run the relevant scan.

File Upload Security (UPLD)

Analyze source code for file upload vulnerabilities including client-only validation, missing content-type verification, no magic byte checking, path traversal in filenames, upload to webroot with execution, and zip slip (archive extraction path traversal). Insecure file uploads can lead to remote code execution, denial of service, and data exfiltration.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification. This skill supports all cross-cutting flags. Key flags for this skill:

  • --scope determines which files to analyze (default: changed)
  • --depth standard reads code and checks upload handlers
  • --depth deep traces file paths from upload through storage to serving
  • --severity filters output (upload issues are often critical or high)

Framework Context

Key CWEs in scope:

  • CWE-434: Unrestricted Upload of File with Dangerous Type
  • CWE-22: Improper Limitation of a Pathname to a Restricted Directory
  • CWE-79: Cross-Site Scripting (via uploaded HTML/SVG)
  • CWE-400: Uncontrolled Resource Consumption (via file size)
  • CWE-611: Improper Restriction of XML External Entity Reference (via uploaded XML)

Detection Patterns

Read references/detection-patterns.md for the full catalog of code patterns, search heuristics, language-specific examples, and false positive guidance.

Workflow

1. Determine Scope

Parse flags and resolve the file list per ../../shared/schemas/flags.md. Filter to files likely to contain upload logic:

  • Upload handlers (**/upload/**, **/uploads/**, **/attachments/**)
  • File processing (**/files/**, **/media/**, **/storage/**)
  • Multipart form handling (**/middleware/**, **/controllers/**)
  • Archive extraction (**/extract/**, **/unzip/**, **/import/**)
  • Frontend validation (**/components/**, **/views/**)

2. Check for Available Scanners

Detect scanners per ../../shared/schemas/scanners.md:

  1. semgrep -- primary scanner for upload patterns
  2. bandit -- Python file handling issues
  3. brakeman -- Rails file upload vulnerabilities

Record which scanners are available and which are missing.

3. Run Scanners (If Available)

If semgrep is available, run with rules targeting upload security:

semgrep scan --config auto --json --quiet <target>

Filter results to rules matching file upload, path traversal, and content-type patterns. Normalize output to the findings schema.

4. Claude Code Analysis

Regardless of scanner availability, perform manual code analysis:

  1. Client-only validation: Find client-side file type checks (HTML accept attribute, JavaScript validation) without corresponding server-side checks.
  2. Content-type verification: Check upload handlers verify Content-Type against an allowlist and do not trust the client-provided value alone.
  3. Magic byte validation: Verify upload handlers check file magic bytes (file signatures) to confirm the file type matches the claimed type.
  4. Path traversal in filename: Find places where the original filename is used in file path construction without sanitization.
  5. Upload to webroot: Check whether uploaded files are stored in web-accessible directories where they could be executed.
  6. Archive extraction: Find zip/tar extraction code and verify paths are validated to prevent directory traversal (zip slip).

When --depth deep, additionally trace:

  • Full file path from upload to storage to serving
  • File serving configuration (static file handlers, CDN configuration)
  • Archive extraction to final storage location

5. Report Findings

Format output per ../../shared/schemas/findings.md using the UPLD prefix (e.g., UPLD-001, UPLD-002).

Include for each finding:

  • Severity and confidence
  • Exact file location with code snippet
  • Attack scenario (what malicious file could achieve)
  • Concrete fix with diff when possible
  • CWE and OWASP references

What to Look For

These are the high-signal patterns specific to file upload security. Each maps to a detection pattern in references/detection-patterns.md.

  1. Client-only file type validation -- HTML accept attribute or JavaScript checks without server-side enforcement.

  2. Missing content-type verification -- Upload handler accepts any file type or trusts the client-provided Content-Type header.

  3. No magic byte validation -- File type determined solely by extension or Content-Type, not by reading the file header bytes.

  4. Path traversal in filename -- Original filename used in path construction (e.g., ../../../etc/passwd) without sanitization.

  5. Upload to executable directory -- Files stored in webroot where a server could execute uploaded scripts (.php, .jsp, .py).

  6. Zip slip vulnerability -- Archive extraction writes files outside the intended directory via ../ entries in archive member paths.

  7. Missing file size limit -- No server-side limit on upload size, enabling denial of service via large files.

  8. Dangerous file types allowed -- No blocklist for executable file types (.exe, .sh, .php, .jsp, .py).

Scanner Integration

ScannerCoverageCommand
semgrepPath traversal, unrestricted upload, zip slipsemgrep scan --config auto --json --quiet <target>
banditPython file handling, path traversalbandit -r <target> -f json -q
brakemanRails file upload, content typebrakeman -q -f json -o /dev/stdout

Fallback (no scanner): Use Grep with patterns from references/detection-patterns.md to find upload handlers, filename usage, archive extraction, and content-type checks. Report findings with confidence: medium.

Output Format

Use the findings schema from ../../shared/schemas/findings.md.

  • ID prefix: UPLD (e.g., UPLD-001)
  • metadata.tool: file-upload
  • metadata.framework: specialized
  • metadata.category: UPLD
  • references.cwe: CWE-434, CWE-22
  • references.owasp: A04:2021 (Insecure Design)
  • references.stride: T (Tampering) or E (Elevation of Privilege)

Severity guidance for this category:

  • critical: Upload to webroot with execution, zip slip to sensitive directories, no validation at all
  • high: Missing server-side type validation, path traversal in filename, dangerous types allowed
  • medium: Client-only validation, missing magic bytes check, no file size limit
  • low: Overly permissive allowlist, missing secondary validation layer

Security Fix Generation

Generate concrete, production-ready code fixes for security findings. This is not an advisory skill -- it produces actual code changes that resolve vulnerabilities and offers to apply them via the Edit tool.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification.

FlagFix Behavior
--scopeIdentifies which findings to fix. file:<path> fixes findings in that file. Default: all unfixed findings in --scope changed.
--depth quickGenerate minimal fix (single-line change, no refactoring).
--depth standardFix with surrounding improvements (add validation, improve error handling).
--depth deepStandard + refactor surrounding code to prevent similar issues, add defensive checks.
--depth expertDeep + generate regression test, add security comments, update related code paths.
--severityOnly fix findings at or above this severity.
--formatDefault text. Use json to output fix objects matching findings schema.

Workflow

Step 1: Identify Target Finding

Resolve what to fix from user input. Accept any of these forms:

  1. Finding ID: e.g., INJ-001. Read from .appsec/findings.json to load the finding.
  2. File and line: e.g., src/db/queries.ts:45. Scan findings for a match, or analyze the location directly.
  3. Description: e.g., "the SQL injection in the user lookup". Search findings by title/description.
  4. Batch mode: No specific target means fix all findings in scope, ordered by severity (critical first).

If no findings exist in .appsec/findings.json, analyze the target location directly to identify the vulnerability before generating a fix.

Step 2: Understand the Vulnerability

For each finding to fix:

  1. Read the finding record (if it exists): severity, CWE, description, location, snippet.
  2. Read the vulnerable code: Use the Read tool to load the file. Read at least 30 lines of surrounding context.
  3. Identify the root cause: What specific coding pattern causes the vulnerability?
  4. Identify constraints: What does the code need to do? What are the inputs/outputs? What framework/library is in use?
  5. Check for existing mitigations: Is there partial validation? A security library already imported? Framework-level protection available?

Step 3: Select Fix Strategy

Choose the most appropriate fix strategy based on the vulnerability type:

VulnerabilityPreferred Fix Strategy
SQL Injection (CWE-89)Parameterized queries / prepared statements
XSS (CWE-79)Context-aware output encoding, CSP headers
Command Injection (CWE-78)Allowlist validation, avoid shell execution, use library APIs
Path Traversal (CWE-22)Canonicalize + validate against base directory
SSRF (CWE-918)URL allowlist, disable redirects, validate scheme/host
Insecure Deserialization (CWE-502)Type-safe deserialization, allowlisted classes
Hardcoded Secrets (CWE-798)Environment variables or secret manager references
Missing Auth (CWE-306)Add authentication middleware/decorator
Broken Access Control (CWE-862)Add authorization check before resource access
Weak Crypto (CWE-327)Replace with current recommended algorithm
Open Redirect (CWE-601)Validate redirect target against allowlist
Race Condition (CWE-362)Add locking, use atomic operations

Step 4: Generate the Fix

Produce a concrete code change:

  1. Write the actual fixed code. Not pseudocode, not advice -- real code that compiles/runs.
  2. Match the existing code style: indentation, naming conventions, import style, error handling patterns.
  3. Use framework-idiomatic solutions: If Express, use Express middleware. If Django, use Django's ORM parameterization. If React, use React's built-in XSS protection.
  4. Minimize blast radius: Change only what is necessary. Do not refactor unrelated code (unless --depth deep or expert).
  5. Add imports if the fix requires new dependencies. Note if a package install is needed.
  6. Preserve functionality: The fix must not break the code's intended behavior.

Step 5: Validate the Fix

Before presenting:

  1. Syntax check: Ensure the generated code is syntactically valid.
  2. Completeness check: Does the fix fully resolve the finding, or is it partial?
  3. Side effect check: Could the fix break other functionality? Flag if so.
  4. Regression check: Could the fix introduce a new vulnerability? (e.g., overly permissive allowlist).

Step 6: Present and Apply

Present the fix to the user:

## Fix: <Finding ID> - <Title>

**Severity**: <severity> | **CWE**: <CWE-ID> | **File**: <path>

### Root Cause
<1-2 sentence explanation>

### Fix
<description of what the fix does>

```diff
- <old code>
+ <new code>

Additional Changes (if any)

  • New import: <import statement>
  • New dependency: <package> (run <install command>)

Then ask: "Apply this fix?" If the user confirms (or `--fix` flag was passed from a parent skill), use the Edit tool to apply the change.

### Step 7: Update Finding Record

After applying a fix:

1. Update the finding in `.appsec/findings.json` with status `fix-applied`.
2. Add `fix.applied_at` timestamp and `fix.diff` with the actual change made.
3. Inform the user to run `/appsec:verify` to confirm the fix resolves the issue.

## Output Format

Findings follow `../../shared/schemas/findings.md`. When outputting fixes:

- `fix.summary`: One-line description of the fix.
- `fix.diff`: Unified diff of the change.
- `metadata.tool`: `"fix"`

Finding ID prefix: **FIX** (e.g., `FIX-001`) for new findings discovered during fix analysis. Fixes to existing findings retain the original finding ID.

## Pragmatism Notes

- Prefer the simplest correct fix. A one-line parameterized query beats a custom sanitization function.
- If a framework provides a built-in security mechanism, use it rather than hand-rolling.
- When multiple fix strategies exist, prefer the one already used elsewhere in the codebase for consistency.
- If the fix requires an architectural change beyond a single file, describe the full change but only apply the immediate file-level fix. Note the broader change needed.
- Never generate fixes that simply suppress warnings or disable security features.
- If unsure about a fix's correctness, present it with caveats rather than applying silently.

AppSec Full Audit -- Exhaustive Security Review

Launches every framework, every scanner, every specialized tool, and every red team agent. Produces a comprehensive dated report file. This is the most thorough analysis available -- it runs everything, omits nothing, and preserves every subagent's output verbatim.

Unlike /appsec:run which selects relevant tools, full-audit runs ALL tools regardless of detected stack. Unlike /appsec:run which consolidates subagent outputs into a unified list, full-audit preserves each agent's raw output as a separate report section.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification.

FlagFull Audit Behavior
--scopePropagated to all subagents. Default full (NOT changed).
--depthForced to expert for all subagents. Flag is accepted but overridden.
--severityApplied only to the summary table. All findings appear in the full report regardless.
--formatIgnored. Full audit always produces a Markdown report file.
--quietSuppress progress messages. Report content is unchanged.
--explainPropagated to subagents; add learning material per finding.
--fixPropagated to subagents; each produces fix suggestions inline.
--skip-redteamSkip red team phase. Saves time but loses attack chain analysis.
--skip-frameworks <list>Skip specific frameworks. Accepts: owasp, stride, pasta, linddun, sans25, mitre.
--output <filename>Custom output filename. Default: <YYYYMMDD>_appsec_report.md.

Workflow

The full audit runs in 5 phases. Phases 1-3 launch subagents. Phase 4 runs red team agents. Phase 5 assembles the report. Each phase must complete before the next begins (except where noted for parallelism within a phase).

Phase 1: Assessment & Scanners (Main Agent)

Step 1.1: Resolve Scope

Default scope is full (the entire codebase). Parse flags and resolve to a concrete file list. For --scope full, enumerate all tracked files:

git ls-files

Filter out binary files, images, and vendored dependencies.

Step 1.2: Detect Stack & Scanners

Run the same detection as /appsec:start Steps 1-4:

  • Detect languages, frameworks, databases from manifests.
  • Detect architecture patterns and data sensitivity.
  • Detect installed scanners via which commands.
Step 1.3: Run All Detected Scanners

Run every detected scanner in parallel Bash calls within a SINGLE response. Use invocation patterns from ../../shared/schemas/scanners.md.

Before launching scanners, create the output directory:

mkdir -p reports/appsec/scanners

Redirect ALL scanner output to files -- the main agent NEVER reads scanner JSON content.

Scanner dispatch pattern:

# Run each scanner in parallel Bash calls — redirect output to files
semgrep scan --config auto --json --quiet <scope_path> > reports/appsec/scanners/semgrep.json 2>&1
gitleaks detect --source <scope_path> --report-format json --no-banner > reports/appsec/scanners/gitleaks.json 2>&1
npm audit --json > reports/appsec/scanners/npm-audit.json 2>&1           # if Node.js project
pip-audit --format json > reports/appsec/scanners/pip-audit.json 2>&1    # if Python project
trivy fs --format json <scope_path> > reports/appsec/scanners/trivy.json 2>&1   # if installed

After ALL scanners complete, check exit codes and file sizes ONLY. Do NOT read or parse scanner JSON files in the main agent context.

# Check each scanner result — exit code + file size only
ls -l reports/appsec/scanners/*.json

Build a scanner status list from exit codes and file sizes:

  • Exit code 0 or 1 AND file size > 0: Mark as OK.
  • Exit code > 1 AND file size > 0: Mark as PARTIAL (ran with warnings).
  • File size 0 or file missing: Mark as FAILED (no output).
  • Exit code 127 (command not found): Mark as MISSING.

Error handling for scanners:

  • Non-zero exit code: Many scanners exit non-zero when they find issues (e.g., npm audit exits 1 when vulnerabilities exist). This is normal. Only treat it as a failure if the output file is empty (0 bytes).
  • Timeout: If a scanner does not return within 120 seconds, skip it and note the timeout. Mark as FAILED (timeout).
  • Scanner not found: If a scanner from the plan is not installed (exit code 127), note it in SCANNERS MISSING and continue.
  • Track all scanner statuses for the report assembler:
    scanner_status = []  # list of {scanner, status, file_path, file_size}
    

Phase 2: Framework Analysis (Parallel Subagents)

Launch framework dispatchers as parallel subagents. The OWASP, STRIDE, LINDDUN, and specialized tool subagents run in parallel. PASTA runs sequentially (its stages are chained).

CRITICAL: All parallel Task tool calls MUST appear in the SAME response message. This is what triggers concurrent execution.

Before dispatching, create the output directory:

mkdir -p reports/appsec/skills
Parallel Batch 1: OWASP + STRIDE + LINDDUN + Specialized + SANS/CWE + MITRE

Launch ALL of the following as parallel Task calls in ONE response:

OWASP Top 10 (10 subagents):

CategorySkillDescription
A01skills/access-control/SKILL.mdBroken Access Control
A02skills/crypto/SKILL.mdCryptographic Failures
A03skills/injection/SKILL.mdInjection
A04skills/insecure-design/SKILL.mdInsecure Design
A05skills/misconfig/SKILL.mdSecurity Misconfiguration
A06skills/outdated-deps/SKILL.mdVulnerable Components
A07skills/auth/SKILL.mdAuth Failures
A08skills/integrity/SKILL.mdIntegrity Failures
A09skills/logging/SKILL.mdLogging Failures
A10skills/ssrf/SKILL.mdSSRF

STRIDE (6 subagents):

LetterSkillDescription
Sskills/spoofing/SKILL.mdSpoofing
Tskills/tampering/SKILL.mdTampering
Rskills/repudiation/SKILL.mdRepudiation
Iskills/info-disclosure/SKILL.mdInformation Disclosure
Dskills/dos/SKILL.mdDenial of Service
Eskills/privilege-escalation/SKILL.mdElevation of Privilege

LINDDUN (7 subagents):

CategorySkillDescription
Lskills/linking/SKILL.mdLinkability
Iskills/identifying/SKILL.mdIdentifiability
N1skills/non-repudiation-privacy/SKILL.mdNon-repudiation (privacy)
D1skills/detecting/SKILL.mdDetectability
D2skills/data-disclosure/SKILL.mdData Disclosure
Uskills/unawareness/SKILL.mdUnawareness
N2skills/non-compliance/SKILL.mdNon-compliance

Specialized Tools (up to 6 subagents, as relevant):

ToolSkillDescription
Secretsskills/secrets/SKILL.mdHardcoded secrets, leaked credentials
Attack Surfaceskills/attack-surface/SKILL.mdEntry point inventory
Data Flowsskills/data-flows/SKILL.mdData flow mapping

SANS/CWE Top 25 (1 subagent):

ToolSkillDescription
SANS25skills/sans25/SKILL.mdCWE Top 25 analysis

Launch ALL of these as parallel Task calls in a SINGLE response.

Subagent Prompt Template

Each subagent Task call must include a FULLY self-contained prompt. Subagents get their own isolated context window and cannot see the main conversation. Subagents write their findings to a file and return ONLY a one-line status summary.

Use --depth expert and --scope full hardcoded into every prompt.

Analyze the following files for {TOOL_DESCRIPTION} vulnerabilities:

FILES:
{FILE_LIST}

STEP 1: Read the skill definition at:
{ABSOLUTE_PATH_TO_PLUGIN}/skills/{SKILL_NAME}/SKILL.md

STEP 2: Follow the workflow defined in that skill to analyze the listed files.

STEP 3: Read the findings schema at:
{ABSOLUTE_PATH_TO_PLUGIN}/shared/schemas/findings.md

STEP 4: Produce findings in the schema format. Set metadata.tool to "{TOOL_NAME}"
and metadata.framework to "{FRAMEWORK}".

STEP 5: Write findings using the AGGREGATE OUTPUT format from the findings schema to:
{ABSOLUTE_PATH_TO_PROJECT}/reports/appsec/skills/{TOOL_NAME}.json

Use the Write tool. The file must be a JSON object with fields:
  tool, total_findings, by_severity (object with critical/high/medium/low counts),
  notes (string with narrative assessment, evidence, or context your skill produces),
  findings (array)

NOTE: The "notes" field is a full-audit extension to the standard aggregate
output format. It is REQUIRED for full-audit (the report assembler uses it
for verbatim report sections) but optional in other contexts like /appsec:run.

Include any narrative assessment, evidence, or context your skill produces.
The report assembler will include this verbatim in the report section for
your framework/tool.

If zero findings, write: {"tool":"{TOOL_NAME}","total_findings":0,"by_severity":{"critical":0,"high":0,"medium":0,"low":0},"notes":"<your narrative assessment>","findings":[]}

FLAGS: --scope full --depth expert

IMPORTANT: After writing the file, return ONLY a one-line status in this exact format:
"{TOOL_NAME}: N findings (Xc Xh Xm Xl)"
where N is the total count and Xc/Xh/Xm/Xl are counts per severity.
Example: "injection: 3 findings (0c 1h 2m 0l)"
Do NOT return the findings themselves. Do NOT produce a summary or
cross-tool analysis. The orchestrator handles report assembly.
Sequential: PASTA (7 stages)

After the parallel batch completes (or concurrently if the runtime supports it), run the PASTA pipeline. PASTA stages are STRICTLY sequential -- each stage's output feeds the next stage via file.

StageSkillOutput File
1skills/pasta-objectives/SKILL.mdreports/appsec/skills/pasta-stage-1.json
2skills/pasta-scope/SKILL.mdreports/appsec/skills/pasta-stage-2.json
3skills/pasta-decompose/SKILL.mdreports/appsec/skills/pasta-stage-3.json
4skills/pasta-threats/SKILL.mdreports/appsec/skills/pasta-stage-4.json
5skills/pasta-vulns/SKILL.mdreports/appsec/skills/pasta-stage-5.json
6skills/pasta-attack-sim/SKILL.mdreports/appsec/skills/pasta-stage-6.json
7skills/pasta-risk/SKILL.mdreports/appsec/skills/pasta-stage-7.json

Launch Stage 1 as a Task call, wait for it to complete, then launch Stage 2, and so on through Stage 7. Each stage reads the PREVIOUS stage's file instead of receiving inline output.

PASTA stage prompt template:

Analyze the following project for {STAGE_DESCRIPTION}:

FILES:
{FILE_LIST}

STEP 1: Read the skill definition at:
{ABSOLUTE_PATH_TO_PLUGIN}/skills/{PASTA_SKILL_NAME}/SKILL.md

STEP 2: Read the findings schema at:
{ABSOLUTE_PATH_TO_PLUGIN}/shared/schemas/findings.md

STEP 3: Read the previous stage output at:
{ABSOLUTE_PATH_TO_PROJECT}/reports/appsec/skills/pasta-stage-{N-1}.json
(Skip this step for Stage 1 -- there is no prior stage.)

If the previous stage file does not exist or cannot be parsed, return ONLY:
  "pasta-stage-{N}: FAILED - prior stage file missing or malformed. PASTA chain broken at stage {N}."
Do NOT proceed with analysis.

STEP 4: Follow the workflow defined in the skill. Use both the "notes" narrative
and "findings" array from the previous stage as input context for your analysis.

STEP 5: Write your output using the AGGREGATE OUTPUT format to:
{ABSOLUTE_PATH_TO_PROJECT}/reports/appsec/skills/pasta-stage-{N}.json

Use the Write tool. The file must be a JSON object with fields:
  tool, total_findings, by_severity (object with critical/high/medium/low counts),
  notes (string with your FULL stage narrative -- business objectives, scope analysis,
  decomposition, threat list, etc. as appropriate for this stage),
  findings (array)

The "notes" field is REQUIRED. Include the complete stage output narrative.

FLAGS: --scope full --depth expert

IMPORTANT: After writing the file, return ONLY a one-line status in this exact format:
"pasta-stage-{N}: N findings (Xc Xh Xm Xl)"
Do NOT return the stage output itself.

Phase 3: Wait for All Framework Results

CRITICAL -- Do NOT proceed to Phase 4 until every subagent from Phase 2 has returned. Do NOT:

  • Redo failed subagent work yourself.
  • Skip frameworks that are still running.
  • Start assembling the report before all results are in.

If a subagent fails, note the failure. Include it in the report as a gap. Do NOT retry or redo it yourself.

Timeout Handling

  • Individual subagent timeout: 5 minutes. If a subagent has not returned after 5 minutes, mark it as TIMED OUT and proceed without its results.
  • PASTA pipeline timeout: 15 minutes total for all 7 stages.
  • Total audit timeout: 30 minutes for all phases combined.
  • Progress reporting: After each subagent returns, output a brief progress line: [audit] Completed: <skill-name> (<N> findings). Waiting for <M> more subagents.
  • Timed-out subagents: List in the report under a TIMED OUT section, distinct from TOOLS FAILED.

Phase 4: Red Team Simulation (6 Agents in Parallel)

Unless --skip-redteam is set, launch ALL 6 red team attacker agents in parallel.

CRITICAL: All 6 Task tool calls MUST appear in the SAME response.

Before dispatching, create the output directory:

mkdir -p reports/appsec/redteam
AgentPersona FileFocus
Script Kiddieagents/script-kiddie.mdAutomated tools, known CVEs
Insideragents/insider.mdPrivilege escalation, exfiltration
Organized Crimeagents/organized-crime.mdFinancial fraud, account takeover
Hacktivistagents/hacktivist.mdData leaks, defacement
Nation Stateagents/nation-state.mdAPT chains, persistent access
Supply Chainagents/supply-chain.mdDependency poisoning, build pipeline

Each red team agent reads prior findings from files (not inline), writes findings to a file, and returns only a one-line status.

You are a red team agent. Read your persona definition at:
{ABSOLUTE_PATH_TO_PLUGIN}/agents/{PERSONA_NAME}.md

Analyze the following codebase for exploitable vulnerabilities from your
persona's perspective:

FILES:
{FILE_LIST}

STEP 1: Read prior findings from these directories using the Read tool:
- {ABSOLUTE_PATH_TO_PROJECT}/reports/appsec/scanners/*.json
- {ABSOLUTE_PATH_TO_PROJECT}/reports/appsec/skills/*.json
These contain the automated analysis results. Use Glob to list the files, then
read each one.

STEP 2: Read the findings schema at:
{ABSOLUTE_PATH_TO_PLUGIN}/shared/schemas/findings.md

STEP 3: Read the DREAD scoring framework at:
{ABSOLUTE_PATH_TO_PLUGIN}/shared/frameworks/dread.md

STEP 4: Attempt to chain vulnerabilities into multi-step attack scenarios.
Score each finding using DREAD.

STEP 5: Write findings using the AGGREGATE OUTPUT format from the findings schema to:
{ABSOLUTE_PATH_TO_PROJECT}/reports/appsec/redteam/{PERSONA_NAME}.json

Use the Write tool. The file must be a JSON object with fields:
  tool, total_findings, by_severity (object with critical/high/medium/low counts),
  notes (string with your FULL attack narratives, chain descriptions, and DREAD
  scoring rationale -- the report assembler will include this verbatim),
  findings (array)

If zero findings, write: {"tool":"{PERSONA_NAME}","total_findings":0,"by_severity":{"critical":0,"high":0,"medium":0,"low":0},"notes":"<your assessment narrative>","findings":[]}

Use "RT" prefix for finding IDs.

IMPORTANT: After writing the file, return ONLY a one-line status in this exact format:
"{PERSONA_NAME}: N findings (Xc Xh Xm Xl)"
where N is the total count and Xc/Xh/Xm/Xl are counts per severity (critical, high, medium, low).
Example: "insider: 4 findings (1c 2h 1m 0l)"
Do NOT return the findings themselves.

Phase 5: Report Assembly (Report Assembler Subagent)

After ALL subagents (framework skills and optionally red team agents) return, the main agent builds a status summary and launches ONE report assembler subagent. The main agent does NOT read any findings files or assemble the report itself.

Build Status Summary

From each subagent's one-line status return, build two lists:

tools_ok = []      # e.g. ["injection: 3 findings (0c 1h 2m 0l)", ...]
tools_failed = []  # e.g. ["crypto: empty output", "ssrf: error ..."]

A subagent result goes into tools_failed if:

  • The Task tool returned an error or exception message
  • The subagent returned an empty string
  • The subagent's output does not match the pattern "{TOOL_NAME}: N findings (...)"

Record the tool name and the first 100 characters of the response as the error reason.

Do NOT re-read any findings files in the main agent context.

Also include scanner statuses from Phase 1.3.

Build SCANNERS_STATUS as a formatted list:

scanners_ok = ["semgrep: OK (reports/appsec/scanners/semgrep.json)", ...]
scanners_failed = ["gitleaks: FAILED (timeout)", ...]
scanners_missing = ["trivy", "bandit", ...]

Pass the scanner file paths so the report assembler can read each scanner JSON file and count findings for the Scanners Used table.

Launch Report Assembler Subagent

Launch a single report assembler subagent with the following FULLY self-contained prompt. This subagent reads all result files, assembles the full dated markdown report with VERBATIM sections, and writes all output files.

You are the appsec full-audit report assembler. Your job is to read all
security findings from scanners, category skills, and red team agents, and
assemble a comprehensive dated Markdown report.

STEP 1: Read the findings schema at:
{ABSOLUTE_PATH_TO_PLUGIN}/shared/schemas/findings.md

STEP 2: Read all JSON result files from these directories using Glob + Read:
- {ABSOLUTE_PATH_TO_PROJECT}/reports/appsec/scanners/*.json
- {ABSOLUTE_PATH_TO_PROJECT}/reports/appsec/skills/*.json
- {ABSOLUTE_PATH_TO_PROJECT}/reports/appsec/redteam/*.json  (if directory exists)

For scanner files: each scanner produces its own JSON format. Read the scanner
registry and format reference at:
{ABSOLUTE_PATH_TO_PLUGIN}/shared/schemas/scanners.md

Convert scanner findings to the standard schema format. Set scanner.confirmed
to true and scanner.name to the scanner name (derived from the filename,
e.g. "semgrep.json" -> "semgrep").

For skill and red team files: these already use the AGGREGATE OUTPUT format
with fields: tool, total_findings, by_severity, notes, findings.

If any file contains malformed JSON that cannot be parsed, log the filename
in a TOOLS DEGRADED list and skip it. Continue processing other files.

STEP 3: For each skill file, extract the "notes" field and all findings.
The notes contain the narrative assessment that must appear VERBATIM in the
corresponding report section. The findings array contains structured findings
in schema format.

STEP 4: Build the full dated Markdown report. Use this structure:

# AppSec Full Audit Report
**Date:** YYYY-MM-DD
**Scope:** {SCOPE_DESCRIPTION}
**Project:** {PROJECT_NAME}
**Stack:** {DETECTED_STACK}

## Executive Summary

### Severity Overview
| Severity | Count |
|----------|-------|
| Critical | N |
| High     | N |
| Medium   | N |
| Low      | N |
| **Total** | **N** |

### Top 5 Priorities
1. <highest severity finding with location and one-line description>
2. ...

### Scanners Used
| Scanner | Status | Findings |
|---------|--------|----------|
| <scanner> | Ran / Not installed | N |

---

## Scanner Results
<Scanner findings converted to standard format>

---

## OWASP Top 10

### A01: Broken Access Control
<VERBATIM notes from access-control.json + formatted findings>

### A02: Cryptographic Failures
<VERBATIM notes from crypto.json + formatted findings>

... (A03 through A10, using skill files: injection, insecure-design,
misconfig, outdated-deps, auth, integrity, logging, ssrf)

---

## STRIDE Threat Model

### S - Spoofing
<VERBATIM notes from spoofing.json + formatted findings>

### T - Tampering
<VERBATIM notes from tampering.json + formatted findings>

... (R from repudiation, I from info-disclosure, D from dos,
E from privilege-escalation)

---

## PASTA Risk Analysis

### Stage 1: Business Objectives
<VERBATIM notes from pasta-stage-1.json + formatted findings>

### Stage 2: Technical Scope
<VERBATIM notes from pasta-stage-2.json + formatted findings>

... (Stages 3 through 7)

---

## LINDDUN Privacy Threats

### L - Linkability
<VERBATIM notes from linking.json + formatted findings>

### I - Identifiability
<VERBATIM notes from identifying.json + formatted findings>

... (N1 from non-repudiation-privacy, D1 from detecting,
D2 from data-disclosure, U from unawareness, N2 from non-compliance)

---

## SANS/CWE Top 25
<VERBATIM notes from sans25.json + formatted findings>

---

## Specialized Analysis

### Secrets Detection
<VERBATIM notes from secrets.json + formatted findings>

### Attack Surface
<VERBATIM notes from attack-surface.json + formatted findings>

### Data Flows
<VERBATIM notes from data-flows.json + formatted findings>

---

## Red Team Simulation

### Script Kiddie
<VERBATIM notes from script-kiddie.json + formatted findings>

### Insider Threat
<VERBATIM notes from insider.json + formatted findings>

### Organized Crime
<VERBATIM notes from organized-crime.json + formatted findings>

### Hacktivist
<VERBATIM notes from hacktivist.json + formatted findings>

### Nation State APT
<VERBATIM notes from nation-state.json + formatted findings>

### Supply Chain
<VERBATIM notes from supply-chain.json + formatted findings>

---

## Cross-Framework Analysis

NOTE: Do NOT deduplicate findings across frameworks. Each framework section
preserves its own findings verbatim. Document overlaps in the Cross-Framework
Analysis section instead. This is by design -- the full audit shows what EACH
framework independently found, not a merged view.

For the Cross-Framework Analysis appendix, use each finding's metadata.framework
field to identify which frameworks detected each finding. A finding may appear
in multiple framework sections if discovered independently by different tools.

### Finding Overlap
<Table showing findings that appear in multiple frameworks>

### Coverage Gaps
<Frameworks that found issues others missed>

### Attack Chain Summary
<Red team chains that combine findings across frameworks>

---

## Appendix

### Framework Coverage Matrix
| Finding ID | OWASP | STRIDE | PASTA | LINDDUN | CWE | MITRE |
|-----------|-------|--------|-------|---------|-----|-------|
| ... | ... | ... | ... | ... | ... | ... |

### Tool Failures
<Any subagents that failed, with error details>

### Tools Degraded
<Any files with malformed JSON that were skipped>

### Methodology
This report was generated by the AppSec plugin full audit.
Frameworks: OWASP Top 10 (2021), STRIDE, PASTA, LINDDUN, SANS/CWE Top 25.
Red team personas: Script Kiddie, Insider, Organized Crime, Hacktivist,
Nation State, Supply Chain.

For any tool/framework that has no corresponding file (it was skipped via
--skip-frameworks, or the subagent failed), include the section heading
with a note: "This analysis was not performed. Reason: <reason>."

STEP 5: Write the report to:
{ABSOLUTE_PATH_TO_PROJECT}/reports/appsec/{YYYYMMDD}_appsec_report.md

Use the Write tool. If --output was specified, use that filename instead
(still in the reports/appsec/ directory).

STEP 6: Write consolidated state files.

First ensure the output directory exists:
  mkdir -p {ABSOLUTE_PATH_TO_PROJECT}/.appsec

Write:
- {ABSOLUTE_PATH_TO_PROJECT}/.appsec/findings.json -- all findings merged
  into a single aggregate format JSON (for downstream skills like
  /appsec:status, /appsec:fix)
- {ABSOLUTE_PATH_TO_PROJECT}/.appsec/last-run.json -- run metadata:
  {{"timestamp": "<ISO 8601>", "scope": "{SCOPE}", "depth": "expert",
    "mode": "full-audit",
    "tools_run": [...], "tools_failed": [...], "scanners_used": [...],
    "scanners_missing": [...], "total_findings": N,
    "by_severity": {{"critical": N, "high": N, "medium": N, "low": N}},
    "report_file": "reports/appsec/{YYYYMMDD}_appsec_report.md"}}

TOOL STATUS (from orchestrator):
Tools OK: {TOOLS_OK_LIST}
Tools failed: {TOOLS_FAILED_LIST}
Scanners OK: {SCANNERS_OK_LIST}
Scanners failed: {SCANNERS_FAILED_LIST}
Scanners missing: {SCANNERS_MISSING_LIST}

CONTEXT:
Scope: {SCOPE}
Project: {PROJECT_NAME}
Stack: {DETECTED_STACK}
Date: {YYYYMMDD}
Output filename: {OUTPUT_FILENAME}
Frameworks skipped: {SKIP_FRAMEWORKS_LIST}

IMPORTANT: After writing all files, return a short completion summary:
"Report written to reports/appsec/{YYYYMMDD}_appsec_report.md — N total findings
(Xc critical, Xh high, Xm medium, Xl low). State saved to .appsec/."
Do NOT return the report content itself.

Caching and State

After each run, state is written to .appsec/:

FileWritten ByContent
.appsec/findings.jsonPhase 5 (report assembler subagent)Consolidated findings from this audit
.appsec/last-run.jsonPhase 5 (report assembler subagent)Timestamp, scope, depth, tools used, finding count, report file path

Intermediate results persist in reports/appsec/ (subdirectories: scanners/, skills/, redteam/) until the next run overwrites them. The dated report lives at reports/appsec/<YYYYMMDD>_appsec_report.md.

This state powers /appsec:status and enables delta detection on subsequent runs.

Completion Message

Present the report assembler subagent's returned completion summary to the user, then show follow-up options:

Full audit complete.

Report: reports/appsec/<YYYYMMDD>_appsec_report.md
Findings: <total> (<critical> critical, <high> high, <medium> medium, <low> low)
Frameworks: OWASP, STRIDE, PASTA, LINDDUN, SANS/CWE Top 25
Red Team: <N> attack chains identified

  /appsec:explain <ID>    Explain any finding
  /appsec:status           View security dashboard

Fuzz Input Generation

Generate intelligent, context-aware fuzz test inputs by analyzing input parsing code. Produces boundary values, type confusion inputs, encoding edge cases, format-specific attacks, and injection payloads tailored to the specific parser and data types in scope. Output is structured JSON test case sets ready for integration with test harnesses.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification.

FlagFuzz Behavior
--scopeIdentifies which input handlers to generate fuzz inputs for. Default changed.
--depth quickStandard boundary values and common injection strings only.
--depth standardContext-aware inputs based on code analysis of the parser.
--depth deepStandard + format-specific attacks, encoding mutations, and chained payloads.
--depth expertDeep + adversarial inputs designed to bypass specific validation logic found in code.
--severityGenerate inputs targeting vulnerabilities at or above this severity.
--formatDefault json. Use text for human-readable listing.

Workflow

Step 1: Identify Input Handlers

Locate input parsing and processing code in scope:

  1. API endpoint handlers: Functions that read request body, query params, headers.
  2. File parsers: Functions that parse uploaded files, config files, data imports.
  3. CLI argument parsers: Argument parsing with argparse, commander, cobra, clap.
  4. Message consumers: Functions processing messages from queues, WebSockets, SSE.
  5. Deserialization points: JSON.parse, XML parsing, YAML loading, protobuf decoding.
  6. Database query builders: Functions constructing queries from user input.

For each handler, identify:

  • Expected input type (string, number, array, object, file).
  • Validation rules (regex, schema, type checks, length limits).
  • How the input is used downstream (SQL, shell, HTML, file path, URL, regex).

Step 2: Analyze Input Constraints

Read the code to understand what the parser expects and what it guards against:

  1. Type expectations: What types does the code assume? Where are type coercions?
  2. Length limits: Are there explicit length checks? What happens at max length?
  3. Character restrictions: Are certain characters filtered or escaped? Which ones?
  4. Format requirements: Does the input need to match a pattern (email, URL, date)?
  5. Range constraints: Numeric bounds, enum values, allowed file extensions.
  6. Nested structure: How deep can objects/arrays nest? Are there recursion limits?

Step 3: Generate Boundary Value Inputs

For each input field, generate boundary value test cases:

Input TypeBoundary Values
StringEmpty "", single char "a", max length, max length + 1, unicode BOM, null bytes "\x00"
Number0, -1, MAX_INT, MIN_INT, MAX_INT+1, NaN, Infinity, -Infinity, float precision edge cases
ArrayEmpty [], single element, very large array (10000+), nested arrays, mixed types
ObjectEmpty {}, deeply nested (100+ levels), circular reference attempt, prototype keys
Booleantrue, false, 0, 1, "", "false", null, undefined
DateEpoch 0, negative timestamp, far future, invalid dates (Feb 30), timezone edge cases
FileEmpty file, 0-byte, huge file, wrong extension, polyglot file, symlink

Step 4: Generate Type Confusion Inputs

Inputs designed to exploit type coercion and type assumption bugs:

Generate inputs that send the wrong type: string where number expected, array where string expected, object with toString override, deeply nested arrays, null where required, boolean where string expected, numeric string where number expected, and prototype/constructor pollution objects (__proto__, constructor.prototype).

Step 5: Generate Encoding Edge Cases

Inputs exploiting encoding and character set handling:

  1. Unicode: Normalization forms (NFC, NFD, NFKC, NFKD), homoglyphs, right-to-left override, zero-width characters.
  2. URL encoding: Double encoding (%2527), mixed encoding, overlong UTF-8.
  3. HTML entities: Named (&amp;), numeric (&#38;), hex (&#x26;), surrogate pairs.
  4. Null bytes: Mid-string null bytes for truncation attacks.
  5. Line endings: \r\n, \r, \n, \x0b, \x0c, \x85, \u2028, \u2029.
  6. Case mapping: Turkish locale I/i dotless variants, German ß/SS.

Step 6: Generate Context-Aware Injection Payloads

Based on how the input is used downstream (identified in Step 1), generate targeted payloads:

Sink ContextPayload Category
SQL querySQL injection: UNION, boolean blind, time blind, stacked queries, comment-based
Shell commandCommand injection: semicolons, pipes, backticks, $(), newlines
HTML outputXSS: script tags, event handlers, SVG/MathML, template injection
File pathPath traversal: ../, null bytes, long paths, reserved names (CON, NUL)
URL constructionSSRF: localhost variants, IPv6, DNS rebinding, scheme confusion
Regex inputReDoS: catastrophic backtracking patterns, exponential quantifiers
XML parserXXE: external entity, parameter entity, SSRF via DTD
LDAP queryLDAP injection: wildcards, boolean operators, null bytes
Header valueHeader injection: CRLF, response splitting
JSON parserJSON interoperability: duplicate keys, large numbers, deep nesting

Step 7: Generate Format-Specific Attacks

At --depth deep and above, generate inputs targeting specific file/data formats:

  1. JSON: Duplicate keys (parser-dependent behavior), comments, trailing commas, BOM prefix.
  2. XML: Billion laughs, quadratic blowup, external entities, CDATA abuse.
  3. YAML: Anchor bombs, merge keys, tag deserialization (!!python/object).
  4. CSV: Formula injection (=CMD()), field separator in values, newlines in quoted fields.
  5. JWT: Algorithm none, key confusion (RS256/HS256), expired but valid signature.
  6. GraphQL: Deep nesting, alias flooding, batch query abuse, introspection.
  7. Multipart: Boundary manipulation, filename traversal, content-type mismatch.

Step 8: Output Test Case Sets

Organize all generated inputs into structured JSON test case sets:

{
  "target": {
    "file": "src/api/users.ts",
    "function": "createUser",
    "input_field": "email",
    "expected_type": "string",
    "downstream_use": ["sql_query", "html_email"]
  },
  "generated_at": "2026-02-14T10:30:00Z",
  "total_cases": 85,
  "test_cases": [
    {
      "id": "FUZZ-001",
      "category": "boundary",
      "label": "empty_string",
      "input": "",
      "expected_behavior": "validation_error",
      "targets_cwe": "CWE-20"
    },
    {
      "id": "FUZZ-002",
      "category": "injection_sql",
      "label": "union_select",
      "input": "test@test.com' UNION SELECT * FROM users--",
      "expected_behavior": "parameterized_query_prevents_injection",
      "targets_cwe": "CWE-89"
    }
  ]
}

Write test case files to .appsec/fuzz/ organized by target.

Output Format

Fuzz inputs are not findings themselves but may reference CWEs they target.

Finding ID prefix: FUZZ (e.g., FUZZ-001) for test case identification.

  • metadata.tool: "fuzz"

If fuzz testing reveals an actual vulnerability (input causes unexpected behavior), emit a finding using ../../shared/schemas/findings.md.

Pragmatism Notes

  • Generate inputs relevant to the actual technology. Do not generate SQL injection payloads for code that never touches a database.
  • Respect the --depth flag. Quick depth should produce 10-20 inputs. Expert depth can produce hundreds.
  • Label each input clearly so testers understand what it targets and what behavior to expect.
  • Mark intentionally dangerous inputs (e.g., billion laughs XML) with a warning about resource consumption.
  • These are test inputs, not exploit code. Frame output as defensive testing material.
  • If the code already has strong validation visible in the source, generate inputs that specifically test the validation boundaries.
  • Include both inputs that should be rejected (malicious) and inputs that should be accepted (edge case valid) to test for false positives in validation.

AppSec Glossary -- Security Term Reference

Quick-reference dictionary for security terms, acronyms, vulnerability classes, and framework categories. Returns concise definitions with cross-framework mappings and concrete examples.

Unlike /appsec:explain which provides deep educational content, glossary is a fast lookup -- a few sentences per term, not a full lesson.

This skill runs entirely in the main agent context. It does NOT dispatch subagents.

Supported Modes

Detect the user's intent from their message:

IntentMode
Single term ("what is IDOR", "define XSS")Single Term Lookup
Comparison ("CSRF vs SSRF", "XSS vs injection")Term Comparison
"security glossary", "list all terms"Full Glossary

Single Term Lookup

For a single term, output:

<TERM> (<full expansion if acronym>)

Definition: <2-3 sentence plain-language definition>

Framework Mappings:
  OWASP:   <category, e.g., A03:2021 Injection>
  STRIDE:  <letter(s), e.g., T (Tampering)>
  CWE:     <CWE-ID, e.g., CWE-89>
  MITRE:   <technique, e.g., T1190>

Example: <1-2 sentence concrete attack scenario>

Related: <2-3 related terms>

Term Registry

Use these framework reference files to resolve mappings:

FrameworkReference
OWASP Top 10../../shared/frameworks/owasp-top10-2021.md
OWASP API Top 10../../shared/frameworks/owasp-api-top10.md
STRIDE../../shared/frameworks/stride.md
PASTA../../shared/frameworks/pasta.md
LINDDUN../../shared/frameworks/linddun.md
MITRE ATT&CK../../shared/frameworks/mitre-attck.md
SANS/CWE Top 25../../shared/frameworks/sans-cwe-top25.md
DREAD../../shared/frameworks/dread.md

Read the relevant reference file(s) to populate the mappings accurately. Do NOT guess mappings -- if a term does not appear in a framework, omit that mapping rather than fabricating one.

Common Terms

This is not exhaustive. Handle any security term the user asks about using general security knowledge plus the framework references above.

Vulnerability classes: IDOR, XSS, CSRF, SSRF, SQLi, RCE, LFI, RFI, XXE, SSTI, ReDoS, CRLF, HPP, clickjacking, open redirect, mass assignment, insecure deserialization, broken authentication, path traversal, command injection, log injection, race condition, TOCTOU, privilege escalation, session fixation, session hijacking, credential stuffing, brute force, directory traversal

Framework terms: OWASP, STRIDE, PASTA, LINDDUN, DREAD, CVSS, CWE, CVE, MITRE ATT&CK, SANS Top 25, NIST, ISO 27001, SOC 2, PCI DSS, GDPR, CCPA, HIPAA

Security concepts: defense in depth, least privilege, zero trust, separation of concerns, input validation, output encoding, parameterized queries, prepared statements, CSP, CORS, SOP, HSTS, certificate pinning, mTLS, JWT, OAuth, OIDC, SAML, RBAC, ABAC, ACL, MFA, 2FA, TOTP, FIDO2, WebAuthn, salted hash, key derivation, envelope encryption, secret rotation, audit trail

Term Comparison

When the user asks to compare two or more terms, output a side-by-side table:

<TERM_A> vs <TERM_B>

| Aspect      | <TERM_A>                | <TERM_B>                |
|-------------|-------------------------|-------------------------|
| Full Name   | ...                     | ...                     |
| What It Is  | ...                     | ...                     |
| Attack Type | ...                     | ...                     |
| Target      | ...                     | ...                     |
| OWASP       | ...                     | ...                     |
| CWE         | ...                     | ...                     |
| Example     | ...                     | ...                     |

Key Difference: <one sentence explaining the core distinction>

Full Glossary

When the user asks for a full glossary, output an alphabetically sorted table of the most important terms. Limit to 30-40 entries to keep it scannable. Group by category:

APPSEC GLOSSARY

--- Vulnerability Classes ---
| Term   | Definition (brief)              | OWASP  | CWE     |
|--------|---------------------------------|--------|---------|
| CSRF   | Cross-site request forgery ...  | A01    | CWE-352 |
| IDOR   | Insecure direct object ref ...  | A01    | CWE-639 |
| ...    | ...                             | ...    | ...     |

--- Frameworks & Standards ---
| Term       | What It Is                           |
|------------|--------------------------------------|
| OWASP      | Open Worldwide Application Security  |
| STRIDE     | Threat modeling framework (6 cats)   |
| ...        | ...                                  |

--- Security Concepts ---
| Term              | Definition (brief)                     |
|-------------------|----------------------------------------|
| Defense in Depth  | Multiple layers of security controls   |
| Least Privilege   | Minimum necessary access               |
| ...               | ...                                    |

Presentation Rules

  • Keep definitions SHORT. This is a glossary, not an encyclopedia. Two to three sentences maximum per definition.
  • Always include at least one framework mapping when one exists.
  • Always include a concrete example -- "An attacker can..." not abstract descriptions.
  • For acronyms, always expand them on first use.
  • If the user asks about a term not in the registry, provide a definition from general security knowledge and note which frameworks it relates to.
  • After any lookup, offer: "Want to learn more? Try /appsec:explain <term> for an in-depth walkthrough."

GraphQL Security (GQL)

Analyze GraphQL APIs for security vulnerabilities including introspection enabled in production, missing query depth limits, no complexity analysis, batching abuse, alias-based denial of service, and missing per-field authorization. GraphQL's flexibility makes it a rich attack surface when default configurations are deployed to production without hardening.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification. This skill supports all cross-cutting flags. Key flags for this skill:

  • --scope determines which files to analyze (default: changed)
  • --depth standard reads code and checks GraphQL configuration
  • --depth deep traces resolvers to data sources and maps authorization coverage
  • --severity filters output (GraphQL issues range from medium to critical)

Framework Context

Key CWEs in scope:

  • CWE-200: Exposure of Sensitive Information (introspection)
  • CWE-400: Uncontrolled Resource Consumption (depth/complexity)
  • CWE-862: Missing Authorization (per-field auth)
  • CWE-770: Allocation of Resources Without Limits (batching)
  • CWE-284: Improper Access Control

Detection Patterns

Read references/detection-patterns.md for the full catalog of code patterns, search heuristics, language-specific examples, and false positive guidance.

Workflow

1. Determine Scope

Parse flags and resolve the file list per ../../shared/schemas/flags.md. Filter to files likely to contain GraphQL logic:

  • Schema definitions (**/*.graphql, **/schema.*, **/typeDefs*)
  • Resolver implementations (**/resolvers/**, **/graphql/**)
  • GraphQL server configuration (**/server.*, **/app.*, **/index.*)
  • Middleware and plugins (**/middleware/**, **/plugins/**)
  • Authorization directives (**/directives/**, **/guards/**)

2. Check for Available Scanners

Detect scanners per ../../shared/schemas/scanners.md:

  1. semgrep -- primary scanner for GraphQL patterns
  2. graphql-cop -- specialized GraphQL security auditor (if available)

Record which scanners are available and which are missing.

3. Run Scanners (If Available)

If semgrep is available, run with rules targeting GraphQL:

semgrep scan --config auto --json --quiet <target>

Filter results to rules matching GraphQL security patterns. Normalize output to the findings schema.

4. Claude Code Analysis

Regardless of scanner availability, perform manual code analysis:

  1. Introspection check: Find GraphQL server configuration and verify introspection is disabled in production environments.
  2. Depth limiting: Check for depth limiting middleware (graphql-depth-limit, @graphql-tools/utils, custom validation rules).
  3. Complexity analysis: Verify query complexity is calculated and limited before execution (graphql-query-complexity, cost analysis).
  4. Batching controls: Check whether query batching is enabled and if there are limits on the number of operations per request.
  5. Alias abuse: Verify aliases are counted toward rate limiting and complexity calculations.
  6. Per-field authorization: Trace resolvers for sensitive fields and verify each checks the requesting user's permissions.

When --depth deep, additionally trace:

  • Full resolver chain from query to data source
  • Authorization directive/guard coverage across all types and fields
  • Subscription authentication and authorization

5. Report Findings

Format output per ../../shared/schemas/findings.md using the GQL prefix (e.g., GQL-001, GQL-002).

Include for each finding:

  • Severity and confidence
  • Exact file location with code snippet
  • Exploit scenario (example malicious query when applicable)
  • Concrete fix with diff when possible
  • CWE references

What to Look For

These are the high-signal patterns specific to GraphQL security. Each maps to a detection pattern in references/detection-patterns.md.

  1. Introspection enabled in production -- __schema and __type queries are accessible, revealing the entire API schema to attackers.

  2. No query depth limit -- Deeply nested queries can exhaust server resources (e.g., user { friends { friends { friends { ... } } } }).

  3. No query complexity limit -- Expensive queries with many fields or computed values can cause denial of service.

  4. Batching abuse -- Multiple queries in a single request bypass per-request rate limiting and can brute-force authentication.

  5. Alias-based denial of service -- Using aliases to repeat expensive fields/resolvers many times in a single query.

  6. Missing per-field authorization -- Sensitive fields (email, SSN, balance) exposed to any authenticated user without field-level access checks.

Scanner Integration

ScannerCoverageCommand
semgrepIntrospection, missing auth directivessemgrep scan --config auto --json --quiet <target>
graphql-copIntrospection, depth, batching, aliasesgraphql-cop -t <endpoint>

Fallback (no scanner): Use Grep with patterns from references/detection-patterns.md to find GraphQL server configuration, depth/complexity middleware, resolver authorization, and batching settings. Report findings with confidence: medium.

Output Format

Use the findings schema from ../../shared/schemas/findings.md.

  • ID prefix: GQL (e.g., GQL-001)
  • metadata.tool: graphql
  • metadata.framework: specialized
  • metadata.category: GQL
  • references.cwe: CWE-200, CWE-400, CWE-862
  • references.owasp: A05:2021 (Security Misconfiguration)
  • references.stride: I (Information Disclosure) or D (Denial of Service)

Severity guidance for this category:

  • critical: Missing per-field auth on sensitive data, introspection exposing internal schemas
  • high: No depth or complexity limits, batching with no limits on auth endpoints
  • medium: Introspection enabled in prod (non-sensitive schema), alias abuse possible
  • low: Overly permissive but rate-limited batching, minor information disclosure

Security Hardening

Proactive security improvement suggestions. Unlike vulnerability scanners that find what is broken, this skill identifies what could be better -- defense-in-depth measures, missing security headers, insufficient input validation, absent rate limiting, and other hardening opportunities that reduce the blast radius of future vulnerabilities.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification.

FlagHardening Behavior
--scopeDefault changed. Use full for comprehensive hardening review.
--depth quickCheck for missing security headers and obvious hardening gaps only.
--depth standardFull hardening review: headers, validation, logging, error handling, configuration.
--depth deepStandard + analyze middleware chains, review all trust boundaries, check defense layering.
--depth expertDeep + compare against security benchmarks (CIS, OWASP ASVS), generate hardening scorecard.
--severityFilter suggestions by impact level.
--formatDefault text. Use md for a hardening checklist document.

Workflow

Step 1: Identify Technology Stack

Scan the codebase to determine:

  1. Web framework(s): Express, Django, Flask, Spring, Rails, Next.js, ASP.NET, FastAPI, etc.
  2. Deployment target: Container, serverless, VM, PaaS (from Dockerfile, serverless.yml, etc.).
  3. Reverse proxy/CDN: Nginx, Apache, Cloudflare, AWS ALB (from config files).
  4. Database(s): SQL, NoSQL, cache layers.
  5. Authentication mechanism: Session, JWT, OAuth, SAML.
  6. Existing security middleware: Helmet, django-security, Spring Security, etc.

Step 2: Check Security Headers

Verify the application sets these HTTP response headers (or that a reverse proxy / CDN handles them):

HeaderRecommended ValueImpact
Content-Security-PolicyStrict policy, no unsafe-inline / unsafe-evalMitigates XSS
Strict-Transport-Securitymax-age=31536000; includeSubDomains; preloadEnforces HTTPS
X-Content-Type-OptionsnosniffPrevents MIME sniffing
X-Frame-OptionsDENY or SAMEORIGINPrevents clickjacking
Referrer-Policystrict-origin-when-cross-origin or stricterLimits referrer leakage
Permissions-PolicyDisable unused browser featuresReduces attack surface
Cross-Origin-Opener-Policysame-originPrevents cross-origin attacks
Cross-Origin-Resource-Policysame-originControls resource sharing
Cache-Controlno-store for sensitive responsesPrevents cache leaks

Note: If a reverse proxy config (nginx.conf, etc.) is present and sets these headers, do not flag them as missing from application code.

Step 3: Review CORS Configuration

Check for overly permissive CORS settings:

  1. Access-Control-Allow-Origin: * on authenticated endpoints.
  2. Reflecting the Origin header without validation.
  3. Access-Control-Allow-Credentials: true with wildcard origins.
  4. Overly broad allowed methods or headers.
  5. Missing Vary: Origin when origin is dynamic.

Step 4: Assess Input Validation

For each entry point discovered (or in scope):

  1. Schema validation: Are request bodies validated against a schema (Joi, Zod, Pydantic, JSON Schema)?
  2. Type coercion: Are string inputs properly typed before use?
  3. Length limits: Are string lengths bounded? Are array sizes limited?
  4. Allowlist vs denylist: Is validation positive (allowlist) rather than negative (denylist)?
  5. Nested input: Are deeply nested objects limited to prevent DoS?
  6. File validation: Are uploaded files validated beyond extension (magic bytes, size limits)?

Step 5: Check Rate Limiting

Identify endpoints that should have rate limiting:

  1. Authentication endpoints: Login, registration, password reset, MFA verification.
  2. API endpoints: Especially those that are computationally expensive or return sensitive data.
  3. File upload endpoints: To prevent storage exhaustion.
  4. Search/query endpoints: To prevent enumeration and DoS.

Check if rate limiting is implemented and whether limits are reasonable.

Step 6: Review Error Handling and Information Disclosure

  1. Stack traces: Are stack traces exposed in production error responses?
  2. Verbose errors: Do error messages reveal internal paths, versions, or database details?
  3. Error differentiation: Do auth errors distinguish between "user not found" and "wrong password" (enables enumeration)?
  4. Default error pages: Are framework default error pages replaced?
  5. Debug mode: Is debug mode disabled in production configuration?

Step 7: Assess Security Logging

Check that these security-relevant events are logged:

  1. Authentication events: Login success/failure, logout, password changes.
  2. Authorization failures: Access denied events with user and resource context.
  3. Input validation failures: Rejected requests with sanitized details.
  4. Administrative actions: Config changes, user management, privilege changes.
  5. Sensitive data access: Audit trail for PII/financial data reads.

Verify logs do NOT contain: passwords, tokens, credit card numbers, SSNs, or other sensitive data.

Step 8: Check Defensive Coding Patterns

  1. Fail-closed defaults: Do authorization checks default to deny?
  2. Secure defaults: Are new configurations secure by default?
  3. Least privilege: Do database connections, API keys, and service accounts use minimal permissions?
  4. Timeout configuration: Do HTTP clients, database connections, and external calls have timeouts?
  5. Resource limits: Are memory/CPU-intensive operations bounded?
  6. Dependency security: Is npm audit / pip audit / equivalent run in CI?

Step 9: Report

Output hardening suggestions grouped by category.

Output Format

Hardening suggestions are advisory and use a lighter format than vulnerability findings.

## Security Hardening Report

### Summary
- Hardening suggestions: N
- By priority: N HIGH, N MEDIUM, N LOW
- Categories covered: headers, cors, validation, rate-limiting, logging, error-handling, config

### HIGH Priority

#### [H-001] Missing Content-Security-Policy header
**Category**: Headers | **Effort**: Low
**Location**: src/middleware/security.ts
**Current**: No CSP header set
**Recommended**: Add strict CSP via helmet
```js
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'"],
    styleSrc: ["'self'", "'unsafe-inline'"],
    imgSrc: ["'self'", "data:"],
  }
}));

MEDIUM Priority

...

LOW Priority

...


When hardening gaps represent actual vulnerabilities (e.g., CORS misconfiguration allowing credential theft), emit a formal finding using `../../shared/schemas/findings.md`.

Finding ID prefix: **HARD** (e.g., `HARD-001`).

- `metadata.tool`: `"harden"`
- `references.cwe`: Varies by suggestion (e.g., `CWE-693` Protection Mechanism Failure, `CWE-16` Configuration)

## Pragmatism Notes

- Hardening is contextual. An internal admin tool has different requirements than a public API.
- Do not recommend CSP for a CLI tool or rate limiting for a batch job.
- If a CDN or reverse proxy handles headers, note that rather than flagging missing headers in app code.
- Prioritize suggestions that are easy to implement with high security impact.
- Acknowledge when existing security measures are already good. Not every review needs findings.
- Some frameworks (Next.js, Rails) include secure defaults. Credit what is already done well.

Identifiability Analysis (LINDDUN I)

Analyze source code for identifiability threats where individuals can be identified from supposedly anonymous data. Combinations of quasi-identifiers (zip code, birth date, gender) can uniquely identify individuals. Re-identification attacks on "anonymized" data are the primary concern.

Supported Flags

Read ../../shared/schemas/flags.md for full flag documentation. This skill supports all cross-cutting flags.

FlagIdentifiability-Specific Behavior
--scopeDefault changed. Focuses on files handling user data, anonymization logic, data exports, analytics pipelines, and API responses.
--depth quickGrep patterns only: scan for PII in logs, quasi-identifiers in exports, and missing anonymization.
--depth standardFull code read, analyze data fields returned in APIs and stored in databases for re-identification risk.
--depth deepTrace data flows from collection to storage to export. Assess quasi-identifier combinations across the system.
--depth expertDeep + re-identification risk modeling: estimate k-anonymity violations and uniqueness of attribute combinations.
--severityFilter output. Identifiability findings range from low (theoretical) to critical (direct PII exposure).
--fixGenerate anonymization, generalization, and suppression replacements.

Framework Context

LINDDUN I -- Identifiability

Identifiability occurs when a person can be identified from data that is supposed to be anonymous or pseudonymous. Read ../../shared/frameworks/linddun.md for the full LINDDUN framework reference including re-identification attack patterns and regulatory definitions.

Privacy Property Violated: Anonymity / Pseudonymity

STRIDE Mapping: Information Disclosure (identifiability focuses specifically on re-identification of anonymized data rather than general data access)

Workflow

Step 1 -- Determine Scope

  1. Parse --scope flag (default: changed).
  2. Resolve to a concrete file list.
  3. Filter to relevant files: data models, API handlers, data export logic, analytics pipelines, logging configuration, database schemas, and anonymization utilities.
  4. Prioritize files containing: user data structures, data export endpoints, log statements with user context, report generation, and data sharing logic.

Step 2 -- Analyze for Identifiability Patterns

Read each scoped file and assess re-identification risk:

  1. Identify direct identifiers: Find fields like name, email, phone, SSN, or national ID that should not appear in anonymous contexts.
  2. Identify quasi-identifiers: Find combinations of fields (zip code, age, gender, job title) that together may uniquely identify individuals.
  3. Check anonymization logic: Verify that anonymization techniques are actually applied and are sufficient (not just removing the name field).
  4. Assess API responses: Check whether endpoints return more personal attributes than the consumer needs.
  5. Examine logs and error messages: Look for PII appearing in log output, stack traces, or debug messages.

At --depth deep or --depth expert, model quasi-identifier combinations and estimate uniqueness across the population.

Step 3 -- Report Findings

Output findings per ../../shared/schemas/findings.md. Each finding needs: IDENT-NNN id, title, severity (based on directness of identification and data sensitivity), location with snippet, description of what enables identification, impact (re-identification harm), fix (anonymization, generalization, or suppression), and CWE/LINDDUN references.

Analysis Checklist

  1. Are direct identifiers (name, email, phone, SSN) present in data exports or analytics?
  2. Do API responses return more user attributes than the consumer actually needs?
  3. Are quasi-identifiers (zip code, birth date, gender) combined in any output?
  4. Is anonymization actually implemented, or just assumed in comments?
  5. Do logs contain IP addresses, user agents, or device identifiers alongside actions?
  6. Can database queries return single-user results from "anonymous" tables?
  7. Are email addresses or phone numbers used as primary keys or foreign keys?
  8. Do error messages or stack traces expose personal data fields?

What to Look For

  1. PII in log statements: Personal data written to application logs.
    • Grep: log\.\w+\(.*email|logger\.\w+\(.*name|console\.log\(.*phone|print\(.*ssn
  2. Email or phone as primary key: Using direct identifiers as database keys.
    • Grep: PRIMARY KEY.*email|primary_key.*email|@Column.*email.*unique|findByEmail|findByPhone
  3. IP address logging: Recording IP addresses without anonymization.
    • Grep: req\.ip|request\.remote_addr|X-Forwarded-For|ip_address|ipAddress|getRemoteAddr
  4. Over-fetched API responses: SELECT * or returning full user objects.
    • Grep: SELECT \*.*FROM.*user|\.findAll\(|\.find\(\{\}\)|res\.json\(user\)|JSON\.stringify\(user
  5. Insufficient anonymization: Removing names but keeping detailed attributes.
    • Grep: anonymize|anonymise|deidentify|de_identify|pseudonymize|mask.*data
  6. Quasi-identifier combinations: Multiple demographic fields in the same record.
    • Grep: zip_code.*birth_date|zipCode.*gender|age.*location|dateOfBirth.*address
  7. User agent collection: Storing full browser fingerprint strings.
    • Grep: user-agent|userAgent|navigator\.userAgent|req\.headers\[.user-agent.\]
  8. Data exports without scrubbing: Export endpoints that dump raw user data.
    • Grep: export.*user|download.*report|csv.*user|toCSV|toJSON.*user

Regulatory Mapping

RegulationProvisionRelevance
GDPR Recital 26Identifiability testData is personal if any means can identify the subject
GDPR Art. 4(5)Pseudonymization definitionPseudonymized data is still personal data
GDPR Art. 25Data protection by designAnonymization must be effective by design
HIPAA Safe Harbor18 identifier categoriesAll 18 must be removed for de-identification
CCPA 1798.140(h)Deidentified informationReasonably cannot be linked to a consumer
CCPA 1798.140(o)Personal informationIncludes information that identifies or could be linked

Output Format

Use finding ID prefix IDENT (e.g., IDENT-001, IDENT-002).

All findings follow the schema in ../../shared/schemas/findings.md with:

  • references.cwe: CWE-359 or CWE-200 as appropriate
  • references.owasp: A02:2021 (Cryptographic Failures -- weak anonymization)
  • metadata.tool: "identifying"
  • metadata.framework: "linddun"
  • metadata.category: "I"

Summary table after all findings:

| Identifiability Pattern     | Critical | High | Medium | Low |
|-----------------------------|----------|------|--------|-----|
| Direct PII exposure         |          |      |        |     |
| PII in logs                 |          |      |        |     |
| Quasi-identifier combos     |          |      |        |     |
| Insufficient anonymization  |          |      |        |     |
| Over-fetched API responses  |          |      |        |     |
| IP / device tracking        |          |      |        |     |

Followed by: top 3 priorities, re-identification risk assessment, and overall assessment.

Information Disclosure Analysis

Analyze source code for information disclosure threats where sensitive data leaks to unauthorized parties. Maps to STRIDE I -- violations of the Confidentiality security property.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification. This skill supports all cross-cutting flags including --scope, --depth, --severity, --format, --fix, --quiet, and --explain.

Framework Context

Read ../../shared/frameworks/stride.md, specifically the I - Information Disclosure section, for the threat model backing this analysis. Key concerns: data breaches, directory traversal, error message leaks, timing attacks, memory dumps, cleartext transmission.

Workflow

1. Determine Scope

Parse flags and resolve the target file list per the flags spec. Filter to files likely handling sensitive data:

  • API response builders and serializers
  • Error handlers and exception middleware
  • Logging configuration and log output
  • Database queries returning user data
  • Configuration files and environment loaders
  • Debug/diagnostic endpoints and health checks
  • File-serving routes and static asset configuration
  • Frontend templates and server-side rendering
  • GraphQL schema definitions and resolvers

2. Analyze for Information Disclosure Threats

For each in-scope file, apply the Analysis Checklist below. At --depth standard, examine each file for data exposure patterns. At --depth deep, trace data flows from database/store through processing to API response to confirm sensitive fields are filtered before transmission across trust boundaries.

3. Report Findings

Output findings per ../../shared/schemas/findings.md using the DISC ID prefix (e.g., DISC-001). Set references.stride to "I" on every finding.

Analysis Checklist

Work through these questions against the scoped code. Each "yes" may produce a finding.

  1. Verbose error messages -- Do error responses expose stack traces, database schemas, SQL queries, internal file paths, or library versions to the client? Search for unfiltered exception serialization in error handlers and catch blocks. Check if NODE_ENV=production or DEBUG=False actually suppresses detail.
  2. Excessive API response data -- Do API endpoints return full database objects instead of explicitly selected fields? Look for SELECT *, ORM .toJSON(), serialize(), or spreading entire model objects into responses without field allowlists. Compare the API response shape against the model definition to identify leaked internal fields (password_hash, internal_id, created_by).
  3. Sensitive data in logs -- Are passwords, tokens, credit card numbers, SSNs, or PII written to logs? Search for log calls near authentication, payment, or user profile handlers that dump request bodies or sensitive variables. Check if log redaction middleware is configured.
  4. Debug endpoints in production -- Are debug routes, profiling endpoints, or diagnostic pages accessible without feature flags or environment guards? Look for /debug, /health with excessive detail, phpinfo(), /actuator, /graphiql, /__debug__, /metrics, /_profiler, Swagger UI without auth.
  5. Directory traversal on reads -- Can user input control file read paths? Look for fs.readFile, open(), file_get_contents where the path incorporates req.params, request.args, or URL segments without path canonicalization and containment checks (realpath + prefix validation).
  6. Missing encryption for sensitive data -- Is PII, authentication data, or financial data stored or transmitted in cleartext? Check database schemas for unencrypted sensitive columns, API calls over HTTP instead of HTTPS, and missing field-level encryption on high-sensitivity data.
  7. Hardcoded secrets in source -- Are API keys, database passwords, encryption keys, or private certificates committed in source files? Search for high-entropy strings assigned to variables named key, secret, password, token, credential. Check .env files, config files, and test fixtures.
  8. HTTP headers leaking info -- Does the application set Server, X-Powered-By, X-AspNet-Version, or other headers that reveal technology stack details? Check response header configuration and whether helmet/equivalent suppression is applied.
  9. Timing side channels -- Are operations on secret data (password comparison, token validation, license checks) performed with early-exit logic that leaks information through response time differences? Look for short-circuit if statements on secret bytes.
  10. Client-side data exposure -- Is sensitive data embedded in HTML source, JavaScript bundles, or local storage? Look for server-side rendering that injects user data, API keys, internal URLs, or feature flag values into page templates or window.__CONFIG__ objects.
  11. Verbose health/status endpoints -- Do health check or status endpoints expose internal details like database connection strings, dependency versions, internal hostnames, queue sizes, or environment variable dumps? Check /health, /status, /info, /env endpoints.
  12. Source map exposure -- Are JavaScript source maps deployed to production, allowing attackers to read original source code? Check for .map files in build output and sourceMappingURL references in bundled JavaScript.

Pragmatism Notes

  • Debug mode in development is expected. Only flag DEBUG=True or equivalent when it appears in production configuration or when there is no environment gating.
  • SELECT * is not always a disclosure risk. It depends on whether the full result is serialized to the API response. If application code filters fields before responding, the query itself is not the issue.
  • Source maps in production are a trade-off: they improve error reporting but expose source code. Rate this low unless the source contains hardcoded secrets or sensitive business logic.
  • Technology stack headers (X-Powered-By) are low severity on their own but contribute to reconnaissance. They matter more in combination with known vulnerabilities in the disclosed versions.

What to Look For

Concrete code patterns and grep heuristics to surface information disclosure risks:

  • Stack traces in responses: traceback.format_exc(), e.stack, err.message sent in HTTP responses, DEBUG = True in production config, app.use(errorHandler) without production mode filtering. Grep: (stack|traceback|stackTrace)\b near response serialization.
  • Full object serialization: res.json(user), return JsonResponse(model.__dict__), JSON.stringify(record) without field selection -- compare against the model definition to see if password_hash, ssn, internal_notes fields leak.
  • Secrets in logs: logger.debug(f"token={token}"), console.log(req.headers.authorization), log.info("password: " + pwd). Grep: log\w*\.\w+\(.*\b(password|token|secret|key|authorization|ssn|credit.?card)\b.
  • Path traversal reads: open(os.path.join(base, request.args['file'])) without os.path.realpath containment, fs.readFile(req.params.name) without validation. Grep: (readFile|open|fopen)\s*\(.*req\.(params|query|body).
  • Debug routes: /debug/, /admin/phpinfo, /_profiler, /graphiql, /swagger, /actuator without auth guards. Grep: (debug|profiler|phpinfo|actuator|graphiql) in route definitions.
  • Missing field filtering: SELECT * FROM users returned directly via API, .find({}) in MongoDB without projection, Sequelize findAll without attributes restriction. Grep: SELECT \*|\.find\(\s*\{\s*\}\s*\)|findAll\(\s*\).
  • Technology headers: X-Powered-By, Server: Apache/2.4.51, X-AspNet-Version -- check for helmet, removeHeader, or equivalent suppression. Grep: X-Powered-By|x-powered-by|server.*header.
  • Source maps in production: .map files in build/dist directories, sourceMappingURL= in production JS bundles. Grep: sourceMappingURL|\.js\.map.

Output Format

Each finding must conform to ../../shared/schemas/findings.md.

id:          DISC-<NNN>
severity:    critical | high | medium | low
confidence:  high | medium | low
location:    file, line, function, snippet
description: What data is exposed and through which channel
impact:      What sensitive information an attacker can obtain
fix:         Concrete remediation with diff when possible
references:
  stride: "I"
  cwe:    CWE-200 (Exposure of Sensitive Info), CWE-209 (Error Messages), or relevant CWE
metadata:
  tool:      info-disclosure
  framework: stride
  category:  I

Severity Guidelines for Information Disclosure

SeverityCriteria
criticalHardcoded production secrets in source, directory traversal exposing arbitrary files, PII/credentials in API responses
highStack traces with internal paths/queries in production errors, sensitive data in logs, debug endpoints without auth
mediumExcessive API fields exposing non-critical internal data, technology stack headers, timing side channels
lowVerbose health check responses, minor information in HTTP headers, source maps in production, client-side comments

Common CWE References

CWEDescription
CWE-200Exposure of Sensitive Information to Unauthorized Actor
CWE-209Generation of Error Message Containing Sensitive Info
CWE-532Insertion of Sensitive Info into Log File
CWE-22Path Traversal
CWE-215Insertion of Sensitive Info Into Debugging Code
CWE-312Cleartext Storage of Sensitive Information
CWE-319Cleartext Transmission of Sensitive Information
CWE-548Exposure of Information Through Directory Listing

Injection Analysis (OWASP A03:2021)

Analyze source code for injection vulnerabilities where user-supplied data flows into interpreters without proper validation, sanitization, or parameterization. This is the most code-scannable OWASP category -- most injection patterns leave clear syntactic fingerprints in source code.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification. This skill supports all cross-cutting flags. Key behaviors:

FlagInjection-Specific Behavior
--scopeDefault changed. Injection analysis focuses on files containing database queries, system calls, LDAP operations, and eval constructs.
--depth quickScanners + Grep patterns only, no data-flow tracing.
--depth standardFull code read of scoped files, local data-flow analysis within each file.
--depth deepTrace user input from HTTP entry points through call chains to sinks. Cross-file taint analysis.
--depth expertDeep + red team simulation: craft proof-of-concept payloads, DREAD scoring.
--severityFilter output. Injection findings are typically critical or high.
--fixGenerate parameterized replacements for each finding.

Framework Context

OWASP A03:2021 - Injection

User-supplied data is not validated, filtered, or sanitized by the application. Dynamic queries or commands are constructed using string concatenation or interpolation with hostile data. Common injection types:

  • SQL Injection (CWE-89): Unsanitized input in SQL queries
  • NoSQL Injection (CWE-943): Unsanitized input in MongoDB/NoSQL queries
  • OS Command Injection (CWE-78): User input passed to system shell commands
  • LDAP Injection (CWE-90): Unsanitized input in LDAP queries
  • Expression Language Injection (CWE-917): User input in EL/template engines
  • ORM Injection (CWE-89): Raw queries or unsafe ORM usage with user input

STRIDE Mapping: Tampering, Information Disclosure, Elevation of Privilege

Detection Patterns

Read references/detection-patterns.md for the full pattern catalog with language-specific examples, regex heuristics, and false positive guidance.

Pattern Summary:

  1. String concatenation in SQL queries
  2. Template string / f-string SQL construction
  3. Raw ORM queries with user input
  4. os.system / exec / subprocess with user input
  5. eval() / Function() with user input
  6. LDAP query string construction with user input

Workflow

Step 1: Determine Scope

  1. Parse --scope flag (default: changed).
  2. Resolve to a concrete file list.
  3. Filter to relevant file types: .py, .js, .ts, .jsx, .tsx, .java, .go, .rb, .php, .cs, .rs, .kt, .scala, .sql, .graphql.
  4. Prioritize files containing: database query patterns, HTTP handler functions, system call imports, LDAP library usage, eval/exec constructs.

Step 2: Check for Scanners

Detect available scanners in priority order:

ScannerDetectInjection Coverage
semgrepwhich semgrepSQL, NoSQL, OS command, LDAP, EL, ORM -- broadest coverage
banditwhich banditPython: eval, exec, SQL, subprocess, pickle
gosecwhich gosecGo: SQL injection, command injection
brakemanwhich brakemanRails: SQL injection, command injection, mass assignment
spotbugsMaven/Gradle pluginJava: SQL injection, command injection, XXE, LDAP

Record which scanners are available and which are missing. If none are available, note: "No scanner available -- findings based on code pattern analysis only."

Step 3: Run Scanners

For each available scanner, run against the scoped files:

semgrep scan --config auto --json --quiet <target>
bandit -r <target> -f json -q
gosec -fmt json ./...

Normalize scanner output to the findings schema (see ../../shared/schemas/findings.md). Use the severity mapping from ../../shared/schemas/scanners.md.

Step 4: Claude Analysis

Read each scoped file and analyze for injection patterns not caught by scanners:

  1. Identify sinks: Database query functions, system calls, LDAP operations, eval/exec, template engines.
  2. Trace sources: HTTP request parameters, form data, URL path segments, headers, cookies, file uploads, environment variables from user input.
  3. Check sanitization: Is there parameterization, input validation, allowlisting, or escaping between source and sink?
  4. Assess context: Is the code reachable from an external entry point? Is there framework-level protection (e.g., Django ORM, prepared statements)?
  5. Deduplicate: Merge Claude findings with scanner findings. If both found the same issue, keep the scanner finding and add Claude's context.

At --depth deep or --depth expert, trace data flow across files:

  • Follow function calls from HTTP handlers to database/system call sites.
  • Check middleware and interceptors for global sanitization.
  • Map the full taint path: source -> transforms -> sink.

Step 5: Report

Output findings using the format from ../../shared/schemas/findings.md.

Each finding must include:

  • id: INJ-001, INJ-002, etc.
  • title: Concise description of the injection type and location.
  • severity: Based on exploitability, authentication requirements, and impact.
  • location: File, line, function, and vulnerable code snippet.
  • description: What is vulnerable and why.
  • impact: What an attacker can achieve.
  • fix: Parameterized/safe replacement code.
  • references: CWE, OWASP A03:2021, STRIDE mapping.

What to Look For

These are the primary injection patterns to detect. Each has detailed examples and regex heuristics in references/detection-patterns.md.

  1. String concatenation in SQL: "SELECT * FROM users WHERE id = " + userId
  2. Template literals in SQL: `SELECT * FROM users WHERE id = ${userId}`
  3. F-strings / format strings in SQL: f"SELECT * FROM users WHERE id = {user_id}"
  4. Raw ORM queries: Model.objects.raw(user_input), sequelize.query(userInput)
  5. OS command construction: os.system("ping " + host), exec("ls " + dir)
  6. subprocess with shell=True: subprocess.call(cmd, shell=True) where cmd includes user input
  7. eval/exec with user input: eval(request.body), new Function(userCode)()
  8. LDAP filter construction: "(uid=" + username + ")" without escaping
  9. NoSQL operator injection: db.users.find({username: req.body.username}) where body can contain $gt, $ne
  10. Stored procedures with concatenation: Dynamic SQL inside stored procedures

Scanner Integration

Primary: semgrep (broadest injection coverage across languages) Language-specific: bandit (Python), gosec (Go), brakeman (Rails), spotbugs (Java) Fallback: Grep regex patterns from references/detection-patterns.md

When scanners are available, run them first and use Claude analysis to:

  • Validate scanner findings (reduce false positives).
  • Find injection patterns scanners miss (complex data flows, indirect concatenation).
  • Provide fix suggestions with parameterized replacements.

When no scanners are available, Claude performs full pattern-based analysis using the Grep heuristics from references/detection-patterns.md and contextual code reading. Report these findings with confidence: medium.

Output Format

Use finding ID prefix INJ (e.g., INJ-001, INJ-002).

All findings follow the schema in ../../shared/schemas/findings.md with:

  • references.owasp: "A03:2021"
  • references.stride: "T" (Tampering), "I" (Info Disclosure), or "E" (Elevation of Privilege)
  • metadata.tool: "injection"
  • metadata.framework: "owasp"
  • metadata.category: "A03"

CWE Mapping by Injection Type:

Injection TypeCWETypical Severity
SQL InjectionCWE-89critical
OS Command InjectionCWE-78critical
NoSQL InjectionCWE-943high
LDAP InjectionCWE-90high
Expression Language InjectionCWE-917high
ORM Injection (raw queries)CWE-89high
eval/exec InjectionCWE-95critical

Summary Table

After all findings, output a summary:

| Injection Type | Critical | High | Medium | Low |
|---------------|----------|------|--------|-----|
| SQL            |          |      |        |     |
| OS Command     |          |      |        |     |
| NoSQL          |          |      |        |     |
| eval/exec      |          |      |        |     |
| LDAP           |          |      |        |     |
| ORM            |          |      |        |     |

Followed by: top 3 priorities, scanner coverage notes, and overall assessment.

Insecure Design Analysis (OWASP A04:2021)

Analyze application architecture and code for missing or ineffective security controls that result from absent threat modeling, insufficient security requirements, or failure to use secure design patterns. This is the most subjective OWASP category -- automated scanners provide minimal coverage, so Claude's architectural reasoning is the primary value.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification. This skill supports all cross-cutting flags. Key behaviors:

FlagInsecure Design-Specific Behavior
--scopeDefault changed. Broader scopes (branch, full) are strongly recommended since design flaws are architectural.
--depth quickCheck for obvious missing controls (rate limiting, CSRF tokens, security headers). Pattern scan only.
--depth standardFull code read of scoped files, analyze request flows and business logic for design gaps.
--depth deepStandard + map full request lifecycle, identify trust boundaries, analyze defense-in-depth layering across the codebase.
--depth expertDeep + threat model construction, attack tree analysis, DREAD scoring per design flaw.
--severityFilter output. Insecure design findings span all severity levels.
--fixGenerate implementation suggestions for missing controls.
--explainEspecially useful for this category: adds threat modeling context and design rationale.

Framework Context

OWASP A04:2021 - Insecure Design

Missing or ineffective security controls as a result of missing threat modeling during design. Unlike implementation bugs (e.g., SQL injection), insecure design refers to the absence of security controls that should have been designed in from the start. No amount of perfect implementation can fix a fundamentally insecure design.

Key concern areas:

  • Missing threat modeling: No systematic identification of threats during design
  • Insufficient security requirements: Security not considered in user stories or specs
  • No secure design patterns: Missing rate limiting, account lockout, CSRF protection
  • Missing defense in depth: Single layer of security with no backup controls
  • Business logic security gaps: Exploitable workflows, race conditions in transactions
  • Trust boundary violations: Client-side enforcement of server-side rules

STRIDE Mapping: All categories (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege)

Detection Patterns

Read references/detection-patterns.md for the full pattern catalog with language-specific examples, regex heuristics, and false positive guidance.

Pattern Summary:

  1. Missing rate limiting on sensitive endpoints
  2. No CSRF protection on state-changing operations
  3. Missing account lockout after failed authentication attempts
  4. Absence of input validation layer
  5. No security headers middleware
  6. Trust-the-client design patterns (client-side-only validation)

Workflow

Step 1: Determine Scope

  1. Parse --scope flag (default: changed).
  2. Resolve to a concrete file list.
  3. For design analysis, prioritize these file categories:
    • HTTP handlers/controllers: Routes, endpoints, API handlers
    • Authentication flows: Login, registration, password reset, MFA
    • Middleware/interceptors: Request processing pipeline configuration
    • Configuration files: Framework config, security settings, CORS setup
    • Business logic: Transaction processing, workflows, state machines
    • Client-side validation: Form validation, input checking in frontend code
  4. If scope is narrow (file: or changed), warn that design analysis benefits from broader scope and suggest --scope branch or --scope full.

Step 2: Check for Scanners

Design flaws have minimal scanner coverage. Check for:

ScannerDetectDesign Coverage
semgrepwhich semgrepLimited: can detect some missing security headers, CSRF patterns

For this category, Claude analysis is the primary detection method. Scanners provide supplementary signal at best. Note in output: "Insecure design analysis is primarily reasoning-based. Scanner coverage for this category is minimal."

Step 3: Run Scanners

If semgrep is available, run with rules targeting:

  • Missing security headers
  • CSRF token absence
  • Missing rate limiting decorators/middleware
semgrep scan --config auto --json --quiet <target>

Filter results to design-relevant rules only. Normalize to findings schema.

Step 4: Claude Analysis

This is the core of insecure design detection. Read scoped files and evaluate:

  1. Map the application architecture:

    • Identify entry points (routes, API endpoints, event handlers).
    • Identify trust boundaries (client/server, service/service, user/admin).
    • Map the request processing pipeline (middleware, filters, interceptors).
    • Identify business-critical workflows (payments, authentication, authorization).
  2. Evaluate security control presence:

    • Rate limiting: Are sensitive endpoints (login, registration, password reset, API) protected against abuse?
    • CSRF protection: Do state-changing endpoints validate CSRF tokens?
    • Account lockout: Do authentication flows implement lockout or progressive delays?
    • Input validation: Is there a server-side validation layer, or only client-side?
    • Security headers: Is there middleware setting CSP, HSTS, X-Frame-Options, etc.?
    • Error handling: Do errors leak implementation details or stack traces?
  3. Analyze trust boundaries:

    • Is server-side validation present for everything validated client-side?
    • Are service-to-service calls authenticated and authorized?
    • Are admin functions separated from user functions?
    • Is there proper tenant isolation in multi-tenant systems?
  4. Evaluate defense in depth:

    • Is there only one layer of security for critical operations?
    • If the primary control fails, what is the fallback?
    • Are security controls applied consistently across all entry points?
    • Are there monitoring and alerting mechanisms for security events?
  5. Assess business logic security:

    • Can workflows be executed out of order?
    • Are there race conditions in financial or state-changing operations?
    • Can quantity, price, or privilege fields be manipulated client-side?
    • Are there proper idempotency controls on critical operations?

At --depth deep or --depth expert, construct a lightweight threat model:

  • List identified assets, threat actors, and attack surfaces.
  • Map missing controls to specific threat scenarios.
  • Evaluate the overall security posture against the STRIDE model.

Step 5: Report

Output findings using the format from ../../shared/schemas/findings.md.

Each finding must include:

  • id: DESGN-001, DESGN-002, etc.
  • title: Concise description of the missing control or design flaw.
  • severity: Based on exploitability and business impact of the missing control.
  • location: File(s), line range(s), and architectural component affected.
  • description: What control is missing and why it matters.
  • impact: What an attacker can achieve due to the design gap.
  • fix: Implementation approach for the missing control, with code sketch.
  • references: CWE, OWASP A04:2021, STRIDE mapping.

Because design findings are inherently more subjective than implementation bugs, include clear reasoning for each finding. Explain why the control is expected and what threat it mitigates. Use confidence: medium for most design findings unless the absence is unambiguous (e.g., zero rate limiting on a public login endpoint).

What to Look For

These are the primary insecure design patterns to detect. Each has detailed examples and heuristics in references/detection-patterns.md.

  1. Missing rate limiting: Login, registration, password reset, OTP verification, API endpoints with no throttling or abuse prevention.
  2. No CSRF protection: State-changing POST/PUT/DELETE endpoints without CSRF token validation.
  3. Missing account lockout: Authentication systems that allow unlimited login attempts with no lockout, delay, or CAPTCHA.
  4. No server-side validation: Input validation only in client-side JavaScript with no corresponding server-side checks.
  5. Missing security headers: No Content-Security-Policy, Strict-Transport-Security, X-Content-Type-Options, X-Frame-Options, or Referrer-Policy headers.
  6. Client-side trust: Price calculations, authorization decisions, or business rules enforced only in client-side code.
  7. No defense in depth: Single authentication check with no session validation, or single authorization layer with no audit trail.
  8. Missing error handling strategy: Inconsistent error responses that leak internal state, stack traces, or database details.
  9. No idempotency controls: Financial or state-changing operations that can be replayed or executed concurrently without protection.
  10. Missing tenant isolation: Multi-tenant systems without proper data segregation at the query or middleware level.

Scanner Integration

Primary: Claude reasoning-based analysis (scanners provide minimal coverage for design flaws). Supplementary: semgrep (limited rules for missing headers, CSRF patterns). Fallback: Grep regex patterns from references/detection-patterns.md.

This category relies primarily on Claude's ability to:

  • Understand application architecture by reading code.
  • Identify missing controls by reasoning about what should be present.
  • Evaluate trust boundaries and defense-in-depth layering.
  • Assess business logic for exploitable design patterns.

Scanner findings for this category should be treated as supplementary evidence, not primary detection. Report scanner status but emphasize that design analysis is reasoning-based.

Output Format

Use finding ID prefix DESGN (e.g., DESGN-001, DESGN-002).

All findings follow the schema in ../../shared/schemas/findings.md with:

  • references.owasp: "A04:2021"
  • references.stride: One or more of "S", "T", "R", "I", "D", "E"
  • metadata.tool: "insecure-design"
  • metadata.framework: "owasp"
  • metadata.category: "A04"

CWE Mapping by Design Flaw Type:

Design FlawCWETypical Severity
Missing rate limitingCWE-770high
No CSRF protectionCWE-352high
Missing account lockoutCWE-307high
Client-side-only validationCWE-602high
Missing security headersCWE-693medium
No defense in depthCWE-657medium
Business logic flawsCWE-840high
Missing tenant isolationCWE-284critical
No idempotency controlsCWE-362medium

Summary Table

After all findings, output a summary:

| Design Flaw Category   | Critical | High | Medium | Low |
|------------------------|----------|------|--------|-----|
| Rate Limiting          |          |      |        |     |
| CSRF Protection        |          |      |        |     |
| Account Security       |          |      |        |     |
| Input Validation       |          |      |        |     |
| Security Headers       |          |      |        |     |
| Trust Boundaries       |          |      |        |     |
| Defense in Depth       |          |      |        |     |
| Business Logic         |          |      |        |     |

Followed by: top 3 priorities, threat model observations (at --depth deep+), and overall design security assessment.

Software and Data Integrity Failures

Analyze source code, CI/CD configurations, and dependency manifests for integrity violations. Detect insecure deserialization, unverified auto-updates, missing subresource integrity, CI/CD pipeline injection, and untrusted dependency sources. Produce actionable findings with severity ratings, code locations, and concrete remediation steps.

Supported Flags

All flags from ../../shared/schemas/flags.md are supported:

FlagRelevant Behavior
--scope <value>Determines which files to analyze (default: changed)
--depth <value>quick: pattern scan only. standard: full read + analysis. deep: trace data flows and dependency chains cross-file. expert: red team simulation with DREAD scoring
--severity <value>Filter findings by minimum severity
--format <value>Output format: text, json, sarif, md
--fixChain into remediation after analysis
--quietFindings only, no explanations
--explainAdd learning context to each finding

Framework Context

OWASP Top 10 2021 - A08: Software and Data Integrity Failures

Code and infrastructure that does not protect against integrity violations. This category covers a broad set of concerns around trusting the provenance and authenticity of software, data, and infrastructure:

  • Relying on plugins, libraries, or modules from untrusted sources, repositories, or CDNs
  • Insecure CI/CD pipelines that allow unauthorized code or configuration changes
  • Auto-update functionality that downloads and applies updates without integrity verification
  • Insecure deserialization where untrusted data is deserialized into objects, enabling remote code execution, replay attacks, injection, or privilege escalation

STRIDE Mapping: Tampering, Elevation of Privilege

CWE References: CWE-502 (Deserialization of Untrusted Data), CWE-829 (Inclusion of Functionality from Untrusted Control Sphere), CWE-494 (Download of Code Without Integrity Check), CWE-915 (Improperly Controlled Modification of Dynamically-Determined Object Attributes), CWE-353 (Missing Support for Integrity Check)

Detection Patterns

Read references/detection-patterns.md before performing analysis. It contains detailed Grep heuristics, language-specific code examples, scanner coverage, and false positive guidance for each vulnerability pattern.

Workflow

1. Determine Scope

Parse --scope flag and resolve to a concrete file list:

  1. Apply scope resolution per ../../shared/schemas/flags.md.
  2. Filter to files relevant to integrity:
    • Serialization/deserialization code (data processing, API handlers)
    • CI/CD configuration files (.github/workflows/*.yml, .gitlab-ci.yml, Jenkinsfile, .circleci/config.yml, azure-pipelines.yml, bitbucket-pipelines.yml)
    • Dependency manifests and lockfiles (package.json, package-lock.json, yarn.lock, requirements.txt, Pipfile.lock, go.sum, Cargo.lock, pom.xml, build.gradle)
    • HTML files with CDN script/link tags
    • Update/installer scripts and auto-update mechanisms
    • Pre/post-install hooks in package configurations
    • Dockerfile and container build configurations
  3. Include infrastructure-as-code files that reference external resources or images.

2. Check for Scanners

Detect available scanners in order of preference:

ScannerDetectRelevant Rules
semgrepwhich semgrepInsecure deserialization, unsafe YAML/pickle loading
trivywhich trivyDependency vulnerabilities, misconfigurations, secret detection
osv-scannerwhich osv-scannerKnown vulnerabilities in dependencies across ecosystems
checkovwhich checkovCI/CD misconfigurations, IaC integrity issues
banditwhich banditPython-specific: pickle, yaml, marshal (B301, B506)

If no scanner is available, proceed with Claude analysis using Grep patterns from references/detection-patterns.md. Note in output: "No scanner available -- findings based on code pattern analysis only."

3. Run Scanners

For each available scanner:

  1. Execute against the scoped file list.
  2. Parse JSON output.
  3. Filter to integrity-related rules only.
  4. Normalize findings to the schema in ../../shared/schemas/findings.md.
  5. Set scanner.confirmed: true for scanner-detected findings.

4. Claude Analysis

Regardless of scanner availability, perform manual code analysis:

  1. Read references/detection-patterns.md for the full pattern catalog.
  2. Use Grep with the regex patterns to locate suspicious constructs.
  3. Read surrounding code context (30-50 lines) to assess each match.
  4. Trace data flows from untrusted sources to deserialization sinks.
  5. At --depth deep or higher: follow imports, trace dependency chains, analyze CI/CD workflow trigger conditions and secret exposure, map update mechanisms end-to-end.
  6. Deduplicate against scanner findings (same file + line = same finding).
  7. Set confidence: medium for Claude-only findings, confidence: high when confirmed by a scanner.

5. Report Findings

Format output per --format flag. Each finding uses the schema from ../../shared/schemas/findings.md with these specifics:

  • ID prefix: INTEG (e.g., INTEG-001, INTEG-002)
  • references.owasp: A08:2021
  • references.stride: T (Tampering) or E (Elevation of Privilege)
  • metadata.tool: integrity
  • metadata.framework: owasp
  • metadata.category: A08

Summary block (appended after all findings):

## Summary

| Severity | Count |
|----------|-------|
| CRITICAL | N     |
| HIGH     | N     |
| MEDIUM   | N     |
| LOW      | N     |

**Scanners used**: [list or "none"]
**Scanners missing**: [list of recommended but unavailable]
**Top priorities**: [top 3 findings to fix first and why]

What to Look For

These are the primary vulnerability patterns. See references/detection-patterns.md for detailed regex patterns and code examples.

  1. Insecure deserialization -- Using pickle.loads, yaml.load (without SafeLoader), Java ObjectInputStream, or JSON.parse on untrusted input to reconstruct objects that can execute arbitrary code.
  2. CI/CD pipeline injection -- GitHub Actions or other CI workflows that interpolate untrusted input (PR titles, branch names, issue bodies) into run: blocks, enabling command injection in the build environment.
  3. CDN resources without SRI -- Loading JavaScript or CSS from third-party CDNs without integrity attributes, allowing a compromised CDN to inject malicious code.
  4. Auto-update without verification -- Download-and-execute update mechanisms that do not verify digital signatures or checksums before applying updates.
  5. Malicious pre/post-install scripts -- Package configurations with install hooks that execute arbitrary code during npm install, pip install, or similar commands.
  6. Missing lockfile integrity -- Dependency lockfiles absent from version control or containing no integrity hashes, allowing silent dependency substitution.
  7. Untrusted base images -- Dockerfiles using unverified or untagged base images (e.g., FROM node instead of FROM node:20-alpine@sha256:...).
  8. Missing code signing -- Release artifacts, packages, or binaries distributed without digital signatures.

Scanner Integration

Refer to ../../shared/schemas/scanners.md for full scanner details.

Primary: trivy (dependency vulnerabilities, misconfigurations), osv-scanner (cross-ecosystem CVEs) Secondary: semgrep (deserialization patterns), bandit (Python pickle/YAML), checkov (CI/CD configs) Fallback: Grep-based pattern matching from references/detection-patterns.md plus Claude analysis of CI/CD configs and dependency manifests

When running as a subagent of the OWASP dispatcher, receive scope and flags from the parent agent prompt. Do not re-parse user input.

Output Format

All findings conform to the schema defined in ../../shared/schemas/findings.md.

ID prefix: INTEG (registered in the ID Prefix Registry as OWASP A08)

Example finding:

{
  "id": "INTEG-001",
  "title": "Unsafe pickle deserialization of user-uploaded data",
  "severity": "critical",
  "confidence": "high",
  "location": {
    "file": "src/api/import_handler.py",
    "line": 72,
    "function": "import_data",
    "snippet": "data = pickle.loads(request.files['upload'].read())"
  },
  "description": "User-uploaded file content is deserialized with pickle.loads, which can execute arbitrary Python code embedded in the pickle stream.",
  "impact": "An attacker can upload a crafted pickle file to achieve remote code execution on the server, potentially compromising the entire application and underlying infrastructure.",
  "fix": {
    "summary": "Replace pickle with a safe serialization format like JSON",
    "diff": "- data = pickle.loads(request.files['upload'].read())\n+ data = json.loads(request.files['upload'].read())"
  },
  "references": {
    "cwe": "CWE-502",
    "owasp": "A08:2021",
    "stride": "T",
    "mitre_attck": "T1059"
  },
  "scanner": {
    "name": "bandit",
    "rule": "B301",
    "confirmed": true
  },
  "metadata": {
    "tool": "integrity",
    "framework": "owasp",
    "category": "A08"
  }
}

AppSec Learn -- Interactive Security Walkthrough

Guided, interactive learning experience that teaches security concepts using the user's own codebase as teaching material. Combines explanation with hands-on discovery -- the user finds real vulnerabilities in their own code as they learn about each category.

This skill runs entirely in the main agent context. It does NOT dispatch subagents. It is interactive and conversational -- ask questions, wait for answers, then reveal findings.

Learning Modes

Detect the topic from the user's message:

User SaysModeCurriculum
"learn owasp", "teach me owasp"OWASP WalkthroughAll 10 categories
"learn stride", "teach me stride"STRIDE WalkthroughAll 6 categories
"learn red-team", "learn red teaming"Red Team WalkthroughAll 6 personas
"learn injection", "learn A03"Single Category Deep DiveOne category
"learn security", "security tutorial"Guided SelectionAsk what to learn

Framework References

Load the relevant framework reference before starting:

ModeReference File
OWASP../../shared/frameworks/owasp-top10-2021.md
STRIDE../../shared/frameworks/stride.md
Red Team../../shared/frameworks/dread.md + all persona files in agents/
Single CategoryThe relevant framework file for that category

Walkthrough Structure

Each learning mode follows the same 4-step pattern per category. The key principle: NEVER just lecture. Always ground the concept in the user's own code, and always make them think before revealing answers.

Step 1: Explain the Concept

Present the category in plain language:

  • What it is (one sentence).
  • What security property it protects.
  • Why it matters (real-world impact with a notable breach example).
  • How it maps to other frameworks (OWASP <-> STRIDE <-> CWE).

Keep this brief. 5-8 sentences maximum. The user's code is the real teacher.

Step 2: Show Code from the User's Codebase

Search the user's codebase for patterns relevant to this category. Use Glob and Grep to find concrete examples. Show 2-3 code snippets with file paths and line numbers.

Present the code WITHOUT revealing whether it is vulnerable or secure. Frame it as: "Here is how your codebase handles [concept]. Look at these patterns..."

Search strategy by category:

CategoryWhat to Search For
Injection (A03)Database queries, template rendering, shell commands, user input handling
Access Control (A01)Route middleware, authorization checks, role guards, IDOR-prone endpoints
Crypto (A02)Hashing functions, encryption calls, TLS config, key storage
Auth (A07)Login handlers, session management, password storage, token generation
Spoofing (S)Authentication flows, token validation, session handling
Tampering (T)Input validation, request parsing, file operations
Info Disclosure (I)Error handlers, logging statements, API responses
DoS (D)Regex patterns, file uploads, resource allocation, unbounded loops
Red TeamAttack surface entry points, auth boundaries, data flows

If no relevant code is found for a category, use a generic example and note that the category may not be applicable to this codebase.

Step 3: Ask Questions

Ask the user 2-3 questions about the code you showed. These should guide them to discover potential issues themselves:

  • "What happens if [input] contains [malicious value]?"
  • "Is there anything checking that the user owns this resource?"
  • "What would an attacker see if they triggered this error handler?"
  • "Could a malicious user bypass this check? How?"

Wait for the user to respond before proceeding. Do NOT reveal the answers in the same message as the questions.

Step 4: Reveal and Discuss

After the user responds (or asks to see the answer):

  1. Confirm what they got right.
  2. Explain what they missed and why it matters.
  3. Show the specific vulnerability (if one exists) with the attack scenario.
  4. Show the fix -- both the code change and the principle behind it.
  5. Cross-reference to frameworks: "This is CWE-89, which OWASP categorizes as A03, and STRIDE classifies as Tampering (T)."

Then offer to continue to the next category or dive deeper.

OWASP Walkthrough Curriculum

Walk through all 10 categories in priority order (most commonly exploited first, not numerical order):

  1. A03: Injection -- SQL, NoSQL, OS command, template injection
  2. A07: Auth Failures -- Credential stuffing, weak passwords, sessions
  3. A01: Broken Access Control -- IDOR, missing deny-by-default, CORS
  4. A02: Cryptographic Failures -- Weak hashing, cleartext, key mgmt
  5. A05: Security Misconfiguration -- Defaults, verbose errors, headers
  6. A10: SSRF -- Unvalidated URLs, internal network access
  7. A08: Integrity Failures -- Deserialization, CI/CD, unsigned updates
  8. A06: Vulnerable Components -- Known CVEs, unmaintained packages
  9. A09: Logging Failures -- Missing audit trail, log injection
  10. A04: Insecure Design -- Missing threat modeling, business logic flaws

STRIDE Walkthrough Curriculum

Walk through all 6 categories mapping each to the security property it protects:

  1. S -- Spoofing (Authentication) -- Identity impersonation, session hijack
  2. T -- Tampering (Integrity) -- Input manipulation, data modification
  3. R -- Repudiation (Non-repudiation) -- Missing audit trail, log gaps
  4. I -- Information Disclosure (Confidentiality) -- Data leaks, error messages
  5. D -- Denial of Service (Availability) -- Resource exhaustion, ReDoS
  6. E -- Elevation of Privilege (Authorization) -- Horizontal/vertical escalation

Red Team Walkthrough Curriculum

Teach offensive security thinking by walking through each attacker persona:

  1. Script Kiddie -- Automated tools, known CVEs, low-hanging fruit. "What can an attacker with zero skill but lots of tools find?"
  2. Insider -- Privilege escalation, data exfiltration, audit gaps. "What can a disgruntled employee with a valid account do?"
  3. Organized Crime -- Financial fraud, account takeover, payment abuse. "What if the attacker's goal is money?"
  4. Hacktivist -- Data leaks, defacement, public embarrassment. "What if the goal is to make the news?"
  5. Nation State -- APT chains, persistent access, supply chain. "What if the attacker has unlimited time and resources?"
  6. Supply Chain -- Dependency poisoning, build pipeline, artifact integrity. "What if the attack comes through your dependencies?"

For each persona, load the persona file from agents/ and use its checklist to search the user's codebase for exploitable patterns.

Interaction Guidelines

  • Keep the tone conversational and encouraging, not lecturing.
  • Celebrate correct answers. Build on incorrect answers -- do not just say "wrong."
  • If the user wants to skip a category, skip it without judgment.
  • If the user wants to stop, summarize what was covered and suggest what to learn next time.
  • After completing a full walkthrough, offer to run the corresponding analysis: "Want me to run a full OWASP scan now? /appsec:owasp"
  • Adjust complexity based on the user's responses. If they immediately spot the SQL injection, skip the basics and go deeper. If they are struggling, add more context and simpler examples.

Progress Tracking

After each category, provide a brief progress indicator:

[3/10] OWASP Walkthrough
  Completed: A03 Injection, A07 Auth, A01 Access Control
  Next: A02 Cryptographic Failures
  Continue? (or type 'skip' to move on, 'stop' to finish)

Edge Cases

  • Empty codebase: Use generic examples and note that hands-on practice requires a codebase with relevant patterns.
  • No relevant patterns found: "Your code does not appear to have [pattern]. This is good! Let me show you what to watch for if you add [feature] in the future."
  • User asks a tangential question: Answer it briefly, then guide back to the curriculum. If the question deserves depth, suggest /appsec:explain <topic> for a full explanation.

LINDDUN Privacy Threat Dispatcher

Dispatch parallel subagents covering all 7 LINDDUN privacy threat categories. Each category runs as an independent subagent analyzing the scoped code for that class of privacy threat. LINDDUN fills the gap that security frameworks like STRIDE and OWASP leave: a system can be fully secure (encrypted, authenticated, authorized) and still violate user privacy. LINDDUN systematically identifies these privacy-specific threats.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification. This dispatcher supports all cross-cutting flags.

FlagDispatcher-Specific Behavior
--scopePropagated to all subagents. Default changed.
--depthPropagated to all subagents. Default standard.
--severityApplied during consolidation to filter the merged output.
--formatApplied to final consolidated output.
--only L,I,D2Run only the listed categories. Accepts: L, I, N1, D1, D2, U, N2. Use N1 for Non-repudiation (privacy) and N2 for Non-compliance. Use D1 for Detectability and D2 for Data Disclosure.
--fixPropagated to subagents; each produces fix suggestions inline.
--quietPropagated to subagents; suppress explanations.
--explainPropagated to subagents; add regulatory context per finding.

Framework Reference

Read ../../shared/frameworks/linddun.md for the full LINDDUN framework specification including threat descriptions, code-level indicators, regulatory mappings (GDPR, CCPA, HIPAA), per-element applicability matrix, and cross-framework mappings to STRIDE/OWASP/CWE.

Pre-flight Relevance Check

Before dispatching subagents, scan the scoped file list to determine which categories are relevant. Unlike STRIDE (where all categories usually apply), LINDDUN relevance depends heavily on whether the codebase handles personal data.

First, confirm the codebase handles personal data. If there is no PII, no user accounts, no analytics, and no data collection, LINDDUN analysis is not applicable. Report this and exit.

CategorySkillRelevant WhenSkip When
L - LinkabilitylinkingShared user IDs across services, analytics tracking, cookies, cross-context identifiersSingle-service app with no analytics, no cross-context tracking
I - IdentifiabilityidentifyingUser data exports, quasi-identifiers (zip, age, gender), anonymized datasets, analytics pipelinesNo user data exports, no analytics, no anonymization attempts
N - Non-repudiationnon-repudiation-privacyAudit logs of sensitive actions (health, legal, political), digital signatures on sensitive transactionsNo sensitive action logging, no compliance-mandated audit trails
D - DetectabilitydetectingDifferent error codes for existing vs non-existing resources, timing side channels, user enumerationNo user-facing lookup endpoints, no existence checks
D - Data Disclosuredata-disclosurePII in logs, third-party SDKs, API responses with excess fields, cross-border data flowsNo PII handling, no third-party integrations, no logging of personal data
U - UnawarenessunawarenessData collection, consent flows, privacy policies, analytics, third-party scripts, telemetryNo data collection, no user-facing features
N - Non-compliancenon-complianceRegulatory requirements (GDPR, CCPA, HIPAA), data retention, deletion endpoints, cross-border transfersNo regulated data, no applicable privacy regulations

How to check: Use Grep on the scoped files to detect:

  • PII patterns: email, phone, ssn, address, birthdate, name
  • User data: user_id, profile, account, preferences
  • Analytics: analytics, tracking, telemetry, pixel, gtag
  • Third-party: stripe, segment, mixpanel, google-analytics, facebook
  • Consent: consent, gdpr, ccpa, cookie, opt-in, opt-out
  • Data export: export, download, portability

If --only is specified, skip the relevance check and dispatch only the listed categories.

Dispatch Category Subagents

CRITICAL: All Task tool calls MUST appear in the SAME response message. This is what triggers parallel execution. If you emit them across separate messages, they run sequentially and waste time.

Dispatch Table

LetterSubagent SkillFinding PrefixPrivacy PropertyFocus
Lskills/linking/SKILL.mdLINKUnlinkabilityCross-service correlation, shared identifiers, behavioral tracking
Iskills/identifying/SKILL.mdIDENTAnonymityRe-identification risks, quasi-identifiers, insufficient anonymization
N1skills/non-repudiation-privacy/SKILL.mdNREPPlausible DeniabilityForced accountability for sensitive actions, irrefutable audit trails
D1skills/detecting/SKILL.mdDTCTUndetectabilityExistence inference, enumeration, timing side channels
D2skills/data-disclosure/SKILL.mdDDSCLConfidentiality (Personal Data)PII in logs, over-collection, third-party data sharing
Uskills/unawareness/SKILL.mdUNAWRTransparencyMissing consent, no data access/deletion, hidden data flows
N2skills/non-compliance/SKILL.mdNCMPLRegulatory ComplianceGDPR/CCPA/HIPAA violations, missing DPIA, data retention failures

Subagent Prompt Template

Each subagent Task call must include a FULLY self-contained prompt. Subagents get their own isolated context window and cannot see the main conversation.

Each subagent prompt must contain:

  1. The concrete file list to analyze (resolved from scope, filtered for relevance).
  2. The absolute path to the category SKILL.md to read and follow.
  3. The flags to apply (--scope, --depth, --severity, --format, etc.).
  4. The findings schema path (shared/schemas/findings.md) for output format.
  5. An instruction to return findings only -- no summary, no cross-category commentary. The dispatcher handles consolidation.
Analyze the following files for LINDDUN {LETTER} ({CATEGORY_NAME}) privacy threats:

FILES:
{FILE_LIST}

STEP 1: Read the skill definition at:
{ABSOLUTE_PATH_TO_PLUGIN}/skills/{SKILL_NAME}/SKILL.md

STEP 2: Follow the workflow defined in that skill to analyze the listed files.
Focus on threats to the {PRIVACY_PROPERTY} privacy property.

STEP 3: Read the findings schema at:
{ABSOLUTE_PATH_TO_PLUGIN}/shared/schemas/findings.md

STEP 4: Output findings in the schema format. Set metadata.framework to "linddun"
and metadata.category to "{LETTER_CODE}".

FLAGS: --scope {SCOPE} --depth {DEPTH} --severity {SEVERITY}

IMPORTANT: Return ONLY the findings list. Do NOT produce a summary or
cross-category analysis. The dispatcher handles consolidation.

Launching

Emit one Task tool call per relevant category, ALL in a single response:

  • subagent_type: "general-purpose"
  • description: "LINDDUN {LETTER} - {CATEGORY_NAME}"
  • prompt: The fully self-contained prompt above, filled in for this category.

Do NOT emit Task calls one at a time. Do NOT wait between dispatches.

Consolidation

After ALL subagents return their results:

1. Merge Findings

Collect all findings from all subagent responses into a single list.

2. Deduplicate

Two findings are duplicates if they share the same location.file AND location.line (or overlapping line ranges). When duplicates exist:

  • Keep the finding with the higher severity.
  • Merge LINDDUN category tags.
  • Note the duplicate in the retained finding's description.

3. Regulatory Mapping

For each finding, map to applicable regulatory articles:

  • GDPR: Map to specific articles (Art. 5, 6, 7, 12-14, 15, 17, 20, 25, 30, 32, 35, 44-49).
  • CCPA: Map to specific sections (1798.100, 1798.105, 1798.120, 1798.140, 1798.150).
  • HIPAA: Map where health data is involved. Use the regulatory mapping tables in linddun.md for guidance.

4. Cross-Reference

For each finding, populate cross-framework references:

  • references.cwe: Map to CWE identifier (e.g., CWE-359, CWE-200, CWE-532).
  • references.owasp: Map to OWASP Top 10 category where applicable.
  • references.stride: Map to closest STRIDE category (see LINDDUN-to-STRIDE table).

5. Rank by Severity

Sort findings: critical > high > medium > low. Within the same severity, consider regulatory impact (GDPR violations rank higher than best-practice recommendations).

6. Present Results

Output the consolidated report in the requested --format. Include:

  • Summary: categories checked, total findings, severity breakdown.
  • Regulatory impact summary: which regulations are implicated.
  • Per-element privacy matrix (similar to STRIDE per-element analysis but for LINDDUN categories).
  • Findings list in severity order with regulatory article citations.
  • Data flow privacy assessment: where personal data crosses trust boundaries.

Expert Mode

If --depth expert is set, after consolidation, launch adversarial privacy agents to simulate privacy attacks (re-identification, linkage, inference). Each agent receives the consolidated findings and attempts to demonstrate how an adversary could exploit privacy weaknesses to identify, track, or profile data subjects.

Red team output is appended to findings with prefix RT and metadata.tool set to "red-team".

Linkability Analysis (LINDDUN L)

Analyze source code for linkability threats where separate data points, actions, or records can be correlated to the same individual across contexts, services, or time periods -- even when the system is fully encrypted and authenticated.

Supported Flags

Read ../../shared/schemas/flags.md for full flag documentation. This skill supports all cross-cutting flags.

FlagLinkability-Specific Behavior
--scopeDefault changed. Focuses on files containing user identifiers, tracking logic, analytics events, and cross-service communication.
--depth quickGrep patterns only: scan for shared IDs, tracking cookies, and fingerprinting code.
--depth standardFull code read of scoped files, analyze identifier propagation within each file.
--depth deepTrace identifier propagation across services, databases, and API boundaries. Map full correlation graph.
--depth expertDeep + adversarial linkage simulation: model what an attacker can correlate given available data.
--severityFilter output. Linkability findings range from medium to critical depending on data sensitivity.
--fixGenerate pseudonymization and identifier isolation replacements.

Framework Context

LINDDUN L -- Linkability

Linkability occurs when an adversary can determine that two or more items of interest (data records, messages, actions, users) are related, even without knowing the identity of the data subject. Read ../../shared/frameworks/linddun.md for the full LINDDUN framework reference including cross-framework mappings and regulatory context.

Privacy Property Violated: Unlinkability

STRIDE Mapping: Information Disclosure (linkability extends beyond data access to correlation analysis across contexts)

Workflow

Step 1 -- Determine Scope

  1. Parse --scope flag (default: changed).
  2. Resolve to a concrete file list.
  3. Filter to relevant files: source code, configuration, database schemas, API definitions, analytics integrations, and cookie/session management.
  4. Prioritize files containing: user ID references, session management, analytics event emission, cross-service API calls, database joins across user activity tables.

Step 2 -- Analyze for Linkability Patterns

Read each scoped file and check for patterns that enable cross-context correlation of user activity:

  1. Identify shared identifiers: Find user IDs, email addresses, device IDs, or tokens that propagate across service boundaries.
  2. Trace identifier scope: Determine whether identifiers are context-specific (scoped to one service) or global (shared across services).
  3. Check analytics events: Look for events that combine user identity with behavioral data.
  4. Examine database schemas: Look for foreign keys and joins that link user activity across tables or services.
  5. Assess cookie and session scope: Check whether tracking cookies persist across domains or contexts.

At --depth deep or --depth expert, map the full identifier propagation graph across the codebase and model what correlations an adversary can derive.

Step 3 -- Report Findings

Output findings per ../../shared/schemas/findings.md. Each finding needs: LINK-NNN id, title, severity (based on correlation potential and data sensitivity), location with snippet, description of what can be linked, impact (profile an adversary can build), fix (pseudonymization or isolation), and CWE/LINDDUN references.

Analysis Checklist

  1. Do different microservices share the same user ID without pseudonymization?
  2. Are there cookies or tokens that persist across different application contexts?
  3. Do analytics events combine user identity with detailed behavioral data?
  4. Can database tables be joined to correlate user activity across features?
  5. Are device fingerprints (user agent, screen resolution, fonts) collected?
  6. Do API responses include identifiers that allow cross-endpoint correlation?
  7. Are session identifiers rotated, or do they persist across long time periods?
  8. Can pseudonymized datasets be re-linked through common timestamps or IPs?

What to Look For

  1. Global user IDs across services: userId, user_id, accountId passed between microservices without per-service pseudonyms.
    • Grep: userId|user_id|accountId|account_id in API call payloads and headers
  2. Cross-domain tracking cookies: Cookies with broad domain scope or third-party cookie setting.
    • Grep: document\.cookie|Set-Cookie|domain=\.|SameSite=None
  3. Device fingerprinting: Collection of browser or device attributes for identification.
    • Grep: navigator\.userAgent|screen\.width|screen\.height|navigator\.plugins|canvas\.toDataURL|fingerprint
  4. Analytics with user identity: Events that include both user ID and behavior.
    • Grep: analytics\.track|analytics\.identify|gtag\(|mixpanel\.track|segment\.track
  5. Database joins on user tables: Queries that correlate user activity across domains.
    • Grep: JOIN.*user|JOIN.*account|INNER JOIN.*activity|LEFT JOIN.*session
  6. Persistent identifiers in URLs: User IDs, email addresses, or tokens in URL paths or query parameters that appear in logs and referrer headers.
    • Grep: req\.params\.userId|req\.query\.email|/users/\$\{|/api/.*userId=
  7. Log correlation: Log entries that combine user identity with action metadata.
    • Grep: logger\.\w+\(.*userId|log\.\w+\(.*user_id|console\.log\(.*email

Regulatory Mapping

RegulationProvisionRelevance
GDPR Art. 5(1)(c)Data minimizationShared identifiers collect more linkable data than necessary
GDPR Art. 25Data protection by designPseudonymization required where feasible
GDPR Recital 26Identifiability testLinkable data may constitute personal data
CCPA 1798.140(o)Personal information definitionIncludes data capable of being linked to a consumer
HIPAA Safe HarborDe-identification standardLinked health data is not de-identified

Output Format

Use finding ID prefix LINK (e.g., LINK-001, LINK-002).

All findings follow the schema in ../../shared/schemas/findings.md with:

  • references.cwe: CWE-359 or CWE-212 as appropriate
  • references.owasp: A01:2021 (Broken Access Control -- cross-context leakage)
  • metadata.tool: "linking"
  • metadata.framework: "linddun"
  • metadata.category: "L"

Summary table after all findings:

| Linkability Pattern    | Critical | High | Medium | Low |
|------------------------|----------|------|--------|-----|
| Cross-service IDs      |          |      |        |     |
| Tracking cookies       |          |      |        |     |
| Device fingerprinting  |          |      |        |     |
| Analytics correlation  |          |      |        |     |
| Database joins         |          |      |        |     |
| Log correlation        |          |      |        |     |

Followed by: top 3 priorities, data flow correlation map, and overall assessment.

Security Logging and Monitoring Failures (A09:2021)

Analyze source code for security logging and monitoring failures including missing audit logging for security events, sensitive data in logs, log injection, absence of alerting on failures, logs only stored locally, and missing tamper protection.

This is the most architectural OWASP category. Scanners provide minimal coverage for logging failures, so Claude's analysis of code patterns, logging configuration, and event coverage is the primary value of this skill.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification. This skill supports all cross-cutting flags. Key flags for this skill:

  • --scope determines which files to analyze (default: changed)
  • --depth standard reads code and checks logging around security-critical operations
  • --depth deep traces security event flows to verify each produces an audit log entry
  • --severity filters output (logging gaps are often medium, sensitive data in logs is high)

Framework Context

Read ../../shared/frameworks/owasp-top10-2021.md, section A09:2021 - Security Logging and Monitoring Failures, for the full category description, common vulnerabilities, and prevention guidance.

Key CWEs in scope:

  • CWE-117: Improper Output Neutralization for Logs (log injection)
  • CWE-223: Omission of Security-Relevant Information
  • CWE-532: Insertion of Sensitive Information into Log File
  • CWE-778: Insufficient Logging
  • CWE-779: Logging of Excessive Data

Detection Patterns

Read references/detection-patterns.md for the full catalog of code patterns, search heuristics, language-specific examples, and false positive guidance.

Workflow

1. Determine Scope

Parse flags and resolve the file list per ../../shared/schemas/flags.md. Filter to files likely to contain logging logic or security-critical operations:

  • Authentication modules (**/auth/**, **/login/**, **/session/**)
  • Access control and authorization (**/middleware/**, **/guards/**, **/policies/**)
  • Logging configuration (**/logging/**, **/logger/**, **/*log*config*)
  • Error handlers (**/errors/**, **/exceptions/**, **/handlers/**)
  • Route/controller definitions (**/routes/**, **/controllers/**, **/api/**)
  • Configuration files (**/config/**, *.yaml, *.toml, *.ini, *.env*)

2. Check for Available Scanners

Detect scanners per ../../shared/schemas/scanners.md:

  1. semgrep -- can detect some log injection and sensitive data in logs
  2. bandit -- Python-specific logging issues (e.g., sensitive data in debug logs)

Record which scanners are available and which are missing. Note: scanner coverage for logging failures is limited. Claude analysis is the primary detection mechanism for this category.

3. Run Scanners (If Available)

If semgrep is available, run with rules targeting logging patterns:

semgrep scan --config auto --json --quiet <target>

Filter results to rules matching log injection, sensitive data exposure in logs, and logging configuration issues. Normalize output to the findings schema.

4. Claude Code Analysis

This is the primary analysis step for logging failures. Perform manual code analysis:

  1. Authentication event logging: Find login, logout, failed login, password reset, and MFA flows. Verify each produces an audit log entry with user identity, timestamp, IP address, and outcome (success/failure).
  2. Access control failure logging: Find authorization checks and verify that denied access attempts are logged with sufficient detail for investigation.
  3. Sensitive data in logs: Grep for log statements and check that passwords, tokens, API keys, credit card numbers, SSNs, and other PII are not logged.
  4. Log injection: Find log statements that include user-controlled input and verify the input is sanitized or the logging framework handles neutralization.
  5. Error handling: Find catch/except blocks and verify they log the error rather than swallowing it silently.
  6. Logging configuration: Check for centralized logging setup, structured log format, log level configuration, and whether logs are sent to a remote destination.
  7. Tamper protection: For high-value audit trails, check for integrity controls (append-only storage, checksums, write-once destinations).

When --depth deep, additionally trace:

  • Complete authentication flow from entry to audit log
  • Exception propagation chains to verify no errors are silently dropped
  • Logging pipeline from application code to destination (local file, remote service, SIEM)

5. Report Findings

Format output per ../../shared/schemas/findings.md using the LOG prefix (e.g., LOG-001, LOG-002).

Include for each finding:

  • Severity and confidence
  • Exact file location with code snippet
  • Impact description specific to the logging failure
  • Concrete fix with diff when possible
  • CWE and OWASP references

What to Look For

These are the high-signal patterns specific to logging and monitoring failures. Each maps to a detection pattern in references/detection-patterns.md.

  1. Missing authentication event logging -- Login, failed login, logout, password reset, and MFA events that produce no audit log entry.

  2. Sensitive data in log statements -- Passwords, tokens, API keys, credit card numbers, or PII written to logs, especially at DEBUG or INFO level.

  3. Log injection via user input -- User-controlled strings passed directly into log format strings without sanitization, enabling log forgery or CRLF injection.

  4. Missing access control failure logging -- Authorization denials that are not logged, making it impossible to detect brute-force or enumeration attacks.

  5. Silent error swallowing -- Catch/except blocks with pass, empty bodies, or comments like "ignore" that discard errors without logging.

  6. No centralized logging configuration -- Logging set up ad-hoc per file with no consistent format, level, or destination configuration.

  7. Logs stored only locally -- Log output goes to local files or stdout with no forwarding to a centralized log management system.

  8. Missing alerting configuration -- No evidence of alerting thresholds for security-critical events (repeated failed logins, privilege escalation attempts).

  9. Excessive logging of request/response bodies -- Logging full HTTP bodies that may contain sensitive data without redaction.

Scanner Integration

ScannerCoverageCommand
semgrepLog injection, sensitive data in debug logssemgrep scan --config auto --json --quiet <target>
banditPython logging of sensitive databandit -r <target> -f json -q

Fallback (no scanner): Use Grep with patterns from references/detection-patterns.md to find log statements with user input interpolation, catch blocks without logging, authentication functions without log calls, and sensitive data patterns in log arguments. Report findings with confidence: medium.

Scanner coverage for this category is inherently limited. Most logging failures are architectural gaps (missing logging) rather than code-level bugs (present but incorrect code), making Claude analysis the primary detection mechanism.

Relevant semgrep rule categories:

  • python.lang.security.audit.logging.*
  • javascript.express.security.audit.logging.*
  • java.lang.security.audit.logging.*
  • generic.logging.security.*

Output Format

Use the findings schema from ../../shared/schemas/findings.md.

  • ID prefix: LOG (e.g., LOG-001)
  • metadata.tool: logging
  • metadata.framework: owasp
  • metadata.category: A09
  • references.owasp: A09:2021
  • references.stride: R (Repudiation)

Severity guidance for this category:

  • critical: Sensitive data (passwords, tokens) logged in plaintext in production
  • high: No audit logging for authentication events, log injection enabling log forgery
  • medium: Silent error swallowing in security-critical paths, logs only stored locally
  • low: Inconsistent log format, missing structured logging, minor gaps in non-critical logging

Security Misconfiguration Analysis

Analyze application and infrastructure configuration for security misconfigurations that could expose the system to attack. Covers missing security headers, debug modes left enabled, overly permissive CORS, default credentials, verbose error handling, unnecessary features, and directory listing.

Supported Flags

Read ../../shared/schemas/flags.md for full flag documentation. This skill supports all cross-cutting flags.

Key flags for this skill:

FlagEffect
--scope <value>Target scope (default: changed). Config-heavy scopes like path: and full are common.
--depth <value>Analysis depth (default: standard). deep traces config inheritance chains.
--severity <value>Minimum severity to report (default: all).
--format <value>Output format: text, json, sarif, md.
--fixGenerate remediation patches for each finding.
--explainAdd OWASP context and learning material to each finding.

Framework Context

OWASP Top 10 2021 -- A05: Security Misconfiguration

Security misconfiguration is the most commonly seen issue. This is commonly a result of insecure default configurations, incomplete or ad hoc configurations, open cloud storage, misconfigured HTTP headers, unnecessary HTTP methods, permissive CORS, and verbose error messages containing sensitive information.

CWE Mappings:

  • CWE-16: Configuration
  • CWE-2: Environment
  • CWE-388: Error Handling
  • CWE-497: Exposure of System Data to an Unauthorized Control Sphere
  • CWE-611: Improper Restriction of XML External Entity Reference
  • CWE-614: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute
  • CWE-756: Missing Custom Error Page
  • CWE-942: Permissive Cross-domain Policy with Untrusted Domains

STRIDE Mapping: All categories -- misconfigurations can enable spoofing, tampering, information disclosure, denial of service, and elevation of privilege.

Detection Patterns

Read references/detection-patterns.md before running analysis. It contains Grep regex patterns, language-specific examples, scanner coverage, and false positive guidance for each detection category.

Workflow

Step 1 -- Determine Scope

  1. Parse --scope flag (default: changed).
  2. Resolve to a concrete file list.
  3. Filter to configuration-relevant files:
    • Application config: *.yaml, *.yml, *.toml, *.ini, *.cfg, *.conf, *.json, *.properties, *.env, *.env.*
    • Server config: nginx.conf, httpd.conf, apache2.conf, Caddyfile, traefik.yml
    • Framework config: settings.py, config/*.rb, application.properties, next.config.*, nuxt.config.*
    • IaC: *.tf, *.hcl, Dockerfile, docker-compose*.yml, *.k8s.yml, k8s/*.yaml
    • CI/CD: .github/workflows/*.yml, .gitlab-ci.yml, Jenkinsfile, .circleci/config.yml
    • Source files that set headers or configure middleware
  4. Also include source files that import/configure security middleware or set HTTP headers.

Step 2 -- Check for Scanners

Detect available scanners in priority order:

ScannerDetectBest For
checkovwhich checkovIaC misconfigurations (Terraform, K8s, Docker)
tfsecwhich tfsecTerraform-specific security
kicswhich kicsMulti-IaC scanning
trivywhich trivyFilesystem misconfigs, Dockerfiles, K8s
semgrepwhich semgrepCode-level misconfiguration patterns

If no scanners are found, proceed with Claude analysis only and note this in output.

Step 3 -- Run Available Scanners

For each detected scanner, run against the scoped files:

  • checkov: checkov -d <target> -o json --quiet
  • tfsec: tfsec <target> --format json
  • kics: kics scan -p <target> --type json
  • trivy: trivy fs --format json --scanners misconfig <target>
  • semgrep: semgrep scan --config auto --json --quiet <target>

Normalize scanner output to the findings schema per ../../shared/schemas/scanners.md.

Step 4 -- Claude Analysis

Using Grep and Read, search for patterns from references/detection-patterns.md. For each match:

  1. Read surrounding context (10-20 lines) to determine if the pattern is a true finding.
  2. Check for compensating controls (e.g., a reverse proxy may set headers upstream).
  3. Determine if the configuration is for production or development.
  4. Assign severity based on the criteria in detection-patterns.md.
  5. Avoid duplicating scanner findings -- deduplicate by file and line.

Step 5 -- Report Findings

Output findings using the schema from ../../shared/schemas/findings.md.

Use the MSCFG prefix for finding IDs (e.g., MSCFG-001, MSCFG-002).

What to Look For

  1. Debug mode enabled in production -- DEBUG=True, NODE_ENV=development, FLASK_DEBUG=1, RAILS_ENV=development in production-bound configs.
  2. Missing security headers -- No Content-Security-Policy, X-Frame-Options, Strict-Transport-Security, X-Content-Type-Options, Permissions-Policy, or Referrer-Policy in HTTP responses.
  3. CORS wildcard or overly permissive origins -- Access-Control-Allow-Origin: * or reflecting arbitrary Origin headers without validation.
  4. Default credentials -- Unchanged admin/admin, root/root, or well-known default passwords in configuration files.
  5. Verbose error handling -- Stack traces, internal paths, database details, or framework version numbers exposed to end users in error responses.
  6. Unnecessary features enabled -- Directory listing, HTTP TRACE/TRACK methods, admin panels exposed without authentication, phpinfo() pages.
  7. Insecure cookie attributes -- Missing Secure, HttpOnly, or SameSite flags on session or authentication cookies.
  8. Permissive file permissions -- World-readable secrets, 777 permissions on sensitive directories, overly broad IAM policies.
  9. TLS/SSL misconfiguration -- Weak cipher suites, outdated TLS versions (< 1.2), self-signed certificates in production, missing HSTS.
  10. Missing rate limiting -- No rate limiting on authentication endpoints, API routes, or form submissions.

Scanner Integration

See ../../shared/schemas/scanners.md for full scanner invocation details. This skill primarily uses:

ScannerWhat It Catches
checkovIaC misconfigurations: open security groups, missing encryption, public S3 buckets
tfsecTerraform-specific: missing tags, public subnets, insecure defaults
kicsMulti-IaC: Docker, K8s, Terraform, CloudFormation misconfigurations
trivyDockerfile and K8s manifest misconfigurations, misconfigured filesystem
semgrepCode patterns: missing headers, debug flags, insecure cookie settings

When scanners are unavailable, Claude falls back to Grep-based detection using the patterns in references/detection-patterns.md and reports findings with confidence: medium.

Output Format

All findings use the schema defined in ../../shared/schemas/findings.md.

ID Prefix: MSCFG (e.g., MSCFG-001)

References for each finding:

  • references.owasp: A05:2021
  • references.cwe: Appropriate CWE from the list above
  • references.stride: Relevant STRIDE category
  • metadata.tool: misconfig
  • metadata.framework: owasp
  • metadata.category: A05

Summary table after all findings:

| Severity | Count |
|----------|-------|
| CRITICAL | N     |
| HIGH     | N     |
| MEDIUM   | N     |
| LOW      | N     |

Followed by top 3 priorities and an overall assessment paragraph.

MITRE ATT&CK Mapping Skill

Post-analysis enrichment tool that maps existing security findings to the MITRE ATT&CK framework. This skill does NOT discover new vulnerabilities. It takes findings produced by other skills (OWASP, STRIDE, SANS/CWE Top 25) and enriches them with ATT&CK tactics, techniques, attack chain analysis, and threat actor TTP cross-references.

This skill operates on findings, not on source code directly.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification. This skill supports the following flags.

FlagSkill-Specific Behavior
--scopeNot used directly. Findings are sourced from prior analysis or .appsec/findings.json.
--depthControls enrichment depth. standard maps techniques. deep builds kill chains. expert adds threat actor TTPs and DREAD scoring.
--severityFilter input findings before mapping. Only findings at or above this severity are processed.
--formatApplied to final output.
--quietMappings only, suppress narrative descriptions.
--explainAdd detailed ATT&CK context and learning material per mapping.

Framework Reference

Read ../../shared/frameworks/mitre-attck.md for the full MITRE ATT&CK specification including tactic definitions, technique descriptions, code-level patterns, cross-framework mapping tables, and kill chain construction guidance.

Workflow

Step 1: Acquire Findings

Collect existing findings from one or more sources, checked in priority order:

  1. Current conversation context: If findings are present from a prior analysis step (e.g., /appsec:owasp or /appsec:stride), use those.
  2. Findings file: Check .appsec/findings.json for persisted findings.
  3. User-specified file: If the user provides a path, read and parse it.

If no findings are available, inform the user and suggest running /appsec:owasp, /appsec:stride, or /appsec:sans25 first.

Step 2: Validate and Normalize Findings

Verify each finding conforms to shared/schemas/findings.md. Ensure required fields are present (id, title, severity, location.file, description). Discard malformed entries with a warning.

Normalize existing cross-references for mapping priority:

  • references.cwe — primary key for ATT&CK mapping.
  • references.owasp — secondary, via OWASP-to-ATT&CK table.
  • references.stride — tertiary, via STRIDE-to-ATT&CK table.

Step 3: Map Findings to ATT&CK Techniques

For each finding, determine applicable ATT&CK techniques using the cross-framework mapping tables in mitre-attck.md:

  1. CWE-based: "ATT&CK Techniques to CWE" table (e.g., CWE-89 maps to T1190, T1059).
  2. OWASP-based: "ATT&CK Techniques to OWASP Top 10" table (when CWE unavailable).
  3. STRIDE-based: "ATT&CK Techniques to STRIDE" table (tertiary source).
  4. Pattern-based: Analyze description and title keywords against technique descriptions.

For each mapped technique, record technique_id, technique_name, tactic_id, and tactic_name. Update references.mitre_attck with the primary technique ID.

Step 4: Build Tactic Coverage Matrix

Each technique belongs to one or more tactics. Produce a matrix showing which tactics each finding touches:

Finding IDReconInitial AccessExecutionPriv EscCred AccessCollectionExfiltrationImpact
INJ-001T1190T1059T1552T1005T1041T1485
AUTH-003T1589T1078T1548T1110

Step 5: Build Attack Chains

Group findings that chain into multi-step attack scenarios from reconnaissance through impact. For each chain:

  1. Entry point: A finding enabling Initial Access (TA0001) or Reconnaissance (TA0043).
  2. Lateral steps: Trace technique-to-technique transitions through the kill chain.
  3. Terminal impact: Map to Impact tactics (TA0040): data destruction (T1485), manipulation (T1565), ransomware (T1486), or DoS (T1498).
  4. Chain severity: Maximum terminal impact severity, elevated one level if 3+ findings compound.
CHAIN-001: SQL Injection to Data Exfiltration
  Severity: critical
  Steps:
    1. [INJ-001] SQL injection in /api/users (T1190 -> Initial Access)
    2. [INJ-001] Database dump via UNION SELECT (T1005 -> Collection)
    3. [CRYPT-002] Credentials stored in plaintext (T1552 -> Credential Access)
    4. [AUTH-003] No MFA on admin portal (T1078 -> Privilege Escalation)
  Impact: Full database compromise, credential theft, admin takeover

Step 6: Kill Chain Visualization

Produce a text-based kill chain diagram mapping findings onto Lockheed Martin Cyber Kill Chain stages aligned with ATT&CK tactics:

Reconnaissance   Initial Access    Execution        Collection       Exfiltration
     |                |                |                |                |
     v                v                v                v                v
[T1595 Scan] -> [T1190 SQLi] --> [T1059 Cmd] -> [T1005 Dump] -> [T1041 Exfil]
                 INJ-001           INJ-001        INJ-001
                                                     |
                                                     v
                                   [T1552 Creds] -> [T1078 Acct] -> [T1548 Priv]
                                    CRYPT-002        AUTH-003        AUTH-003

For --format json, produce a structured chain object with nodes and edges.

Step 7: Cross-Reference Threat Actor TTPs

Available at --depth deep and --depth expert. For each technique, note which threat actor groups commonly use it:

TechniqueKnown Usage
T1190 Exploit Public-Facing AppAPT28, APT41, Lazarus Group, FIN7, most initial access brokers
T1078 Valid AccountsAPT29, APT41, FIN6 -- commonly after credential theft
T1552 Unsecured CredentialsAPT33, FIN7 -- harvesting from config files
T1505.003 Web ShellAPT41, Hafnium -- persistent access via uploaded shells

This is NOT a threat intelligence assessment. It shows that identified techniques are actively used in real-world attacks.

Step 8: Produce Output

{
  "tool": "mitre",
  "input_findings": 12,
  "mapped_findings": 10,
  "unmapped_findings": 2,
  "techniques_identified": 8,
  "tactics_covered": 6,
  "attack_chains": 2,
  "tactic_coverage": {
    "reconnaissance": ["T1595"],
    "initial_access": ["T1190", "T1078"],
    "execution": ["T1059"],
    "credential_access": ["T1552", "T1110"],
    "collection": ["T1005"],
    "exfiltration": ["T1041"],
    "impact": ["T1485"]
  },
  "chains": [ ... ],
  "enriched_findings": [ ... ]
}

Step 9: Present Results

Output the report in the requested --format. Include:

  • Mapping summary: findings mapped, techniques identified, tactics covered.
  • Tactic coverage matrix: ATT&CK tactics represented and gaps.
  • Technique breakdown: findings per technique with parent tactic.
  • Attack chains: step-by-step narrative with kill chain visualization.
  • Coverage gaps: tactics with no mapped findings flagged as areas needing further analysis.

Expert Mode

If --depth expert is set, additionally:

  1. Read ../../shared/frameworks/dread.md for DREAD scoring criteria. Assign a DREAD score to each attack chain.

  2. Threat actor profiling: For each chain, identify the most likely threat actor class (opportunistic, insider, APT, nation-state) based on complexity and resources required.

  3. Detection gap analysis: For each technique in a chain, assess whether the codebase has logging or alerting to detect the attack at that stage. Cross-reference with OWASP A09 findings if available. Flag chains where multiple stages lack detection as highest priority.

  4. Mitigation roadmap: For each chain, produce a prioritized list of mitigations that break the chain at the earliest stage. Prefer mitigations that break multiple chains simultaneously.

  5. Append expert findings with prefix ATK and metadata.tool set to "mitre-attck".

Threat Modeling

Full architecture-level threat modeling with automated discovery, data flow mapping, STRIDE-per-component analysis, and attack tree generation. Produces persistent, incremental threat models stored in .appsec/model/ that evolve as the codebase changes.

Supported Flags

Read ../../shared/schemas/flags.md for the full flag specification.

FlagModel Behavior
--scopeDefault full. Threat models benefit from whole-system visibility. Narrow scopes produce partial models with a warning.
--depth quickComponent inventory and trust boundary identification only.
--depth standardFull threat model: components, data flows, STRIDE analysis, mitigations.
--depth deepStandard + attack trees, cross-component threat chains, external dependency threats.
--depth expertDeep + DREAD scoring, attack simulation narratives, compliance mapping.
--severityFilter reported threats by severity in output.
--formatDefault md. Use json for structured model data.
--diffIncremental mode: only analyze changes since last model. Compare against .appsec/model/current.json.

Workflow

Step 1: Discovery

Automatically discover the application architecture by analyzing the codebase:

Component Discovery

Identify all significant components:

  1. Services: Separate processes, microservices (from docker-compose, k8s manifests, service configs).
  2. APIs: REST controllers, GraphQL resolvers, gRPC services.
  3. Data stores: Databases, caches, file storage, message queues.
  4. External dependencies: Third-party APIs, SaaS integrations, CDNs, auth providers.
  5. Background workers: Job processors, cron tasks, event consumers.
  6. Client applications: Web frontends, mobile apps, CLI tools.
  7. Infrastructure: Load balancers, reverse proxies, API gateways (from config files).
Trust Boundary Discovery

Identify boundaries where trust levels change:

  1. Network boundaries: Internet to DMZ, DMZ to internal, internal to database tier.
  2. Authentication boundaries: Public vs authenticated, user vs admin.
  3. Process boundaries: Between services, between containers.
  4. Data classification boundaries: Where PII/secrets move between storage/transit.

Step 2: Data Flow Mapping

Generate Mermaid data flow diagrams (DFDs) at two levels:

Generate Mermaid DFDs at two levels: Level 0 (system context -- actors, application, external systems) and Level 1 (component detail with trust boundary subgraphs showing internal services, data stores, and message queues).

Annotate each data flow with:

  • Protocol (HTTPS, gRPC, TCP, etc.)
  • Authentication method
  • Data classification (public, internal, confidential, restricted)
  • Encryption status (in transit, at rest)

Step 3: STRIDE-per-Component Analysis

Apply STRIDE to each component and data flow:

STRIDEQuestion
SpoofingCan an attacker impersonate this component or a user of it?
TamperingCan data in transit or at rest be modified without detection?
RepudiationCan actions be performed without an audit trail?
Information DisclosureCan sensitive data leak from this component?
Denial of ServiceCan this component be made unavailable?
Elevation of PrivilegeCan an attacker gain higher access through this component?

For each component, generate a threat table:

For each component, produce a table with columns: #, STRIDE category, Threat description, Severity, Mitigation, Status (Mitigated/Partial/Gap/Accepted).

Step 4: Attack Tree Generation

At --depth deep and above, generate attack trees for high-value targets:

For each high-value target (e.g., "Exfiltrate User PII"), produce a numbered attack tree with branches for direct access, application-layer attacks, and infrastructure attacks. Each leaf node references severity and mitigation status from the STRIDE analysis.

Step 5: Identify Mitigations and Gaps

For each threat identified:

  1. Check if mitigated: Search the codebase for security controls that address the threat.
  2. Assess mitigation quality: Is the control properly implemented? Complete? Tested?
  3. Mark status:
    • Mitigated: Security control exists and is properly implemented.
    • Partial: Control exists but is incomplete or has known weaknesses.
    • Gap: No mitigation found. This becomes a finding.
    • Accepted: Risk acknowledged and accepted (noted in threat model).

Step 6: Incremental Mode (--diff)

When --diff flag is set:

  1. Load the previous model from .appsec/model/current.json.
  2. Detect changes:
    • New components added.
    • Components removed.
    • Data flows added or changed.
    • Trust boundaries modified.
  3. Run STRIDE analysis only on new/changed components and flows.
  4. Merge results into the existing model.
  5. Highlight what changed in the output.

Output a changelog showing NEW, CHANGED, and REMOVED components with threat counts for each.

Step 7: Persist Model

Save the threat model to .appsec/model/:

FileContents
current.jsonFull structured model (components, flows, threats, mitigations)
threat-model.mdHuman-readable report with Mermaid diagrams
dfd-level0.mmdLevel 0 Mermaid DFD source
dfd-level1.mmdLevel 1 Mermaid DFD source
attack-trees.mdAttack tree documentation
history/<timestamp>.jsonSnapshot for diffing (incremental mode)

Step 8: Emit Findings for Gaps

For each threat with status Gap, emit a finding using ../../shared/schemas/findings.md:

  • Map STRIDE category to the appropriate references.stride value.
  • Severity based on threat analysis (impact and likelihood).
  • Location points to the component/file most relevant to the gap.

Output Format

Findings follow ../../shared/schemas/findings.md.

Finding ID prefix: TM (e.g., TM-001).

  • metadata.tool: "model"
  • metadata.framework: "stride" (or specific framework if used)
  • references.stride: The STRIDE category letter

Pragmatism Notes

  • Threat models are living documents. Encourage incremental updates (--diff) rather than full rebuilds.
  • Not every theoretical threat warrants a finding. Focus on threats that are plausible given the application's deployment context.
  • A microservice behind a service mesh has different threats than an internet-facing monolith. Adjust analysis accordingly.
  • Component discovery is heuristic. Label the model as based on code analysis, not authoritative architecture documentation.
  • DFDs should be useful, not exhaustive. Omit trivial flows (e.g., logging to stdout) unless they carry sensitive data.
  • If the codebase is a library (not a deployed application), model threats to consumers of the library rather than infrastructure threats.
  • STRIDE is the default framework. If the user requests PASTA, LINDDUN, or another framework, defer to those specialized skills.

Non-Compliance Analysis (LINDDUN N2)

Analyze source code for regulatory non-compliance where data processing activities violate GDPR, CCPA, or HIPAA. Non-compliance results from missing technical controls, incorrect legal bases, or unimplemented data subject rights. This category has no STRIDE equivalent and is unique to privacy threat modeling.

Supported Flags

Read ../../shared/schemas/flags.md for full flag documentation. This skill supports all cross-cutting flags.

FlagNon-Compliance-Specific Behavior
--scopeDefault changed. Focuses on files containing data retention, deletion logic, consent management, cross-border transfers, age verification, and processing records.
--depth quickGrep patterns only: scan for missing deletion endpoints, hardcoded retention, and cross-border transfers.
--depth standardFull code read, check data lifecycle implementation against regulatory requirements.
--depth deepTrace data flows across storage layers. Verify deletion cascades through databases, backups, caches, and logs.
--depth expertDeep + regulatory audit simulation: assess compliance posture against GDPR, CCPA, and HIPAA article by article.
--severityFilter output. Missing data subject rights are high; documentation gaps are medium.
--fixGenerate retention enforcement, deletion cascades, and consent management implementations.

Framework Context

LINDDUN N2 -- Non-compliance

Non-compliance occurs when data processing activities violate applicable privacy regulations. Read ../../shared/frameworks/linddun.md for the full framework reference including regulatory mappings.

Privacy Property Violated: Regulatory Compliance | STRIDE Mapping: No equivalent | OWASP: A04:2021 (Insecure Design)

Workflow

Step 1 -- Determine Scope

  1. Parse --scope flag (default: changed).
  2. Resolve to a concrete file list.
  3. Filter to relevant files: data retention logic, deletion handlers, consent management, user rights endpoints, data transfer configs, and age gates.
  4. Prioritize files containing: cleanup jobs, TTL configs, deletion endpoints, consent flows, data exports, and cross-region deployment configs.

Step 2 -- Analyze for Non-Compliance

Read each scoped file and assess regulatory compliance:

  1. Check data retention enforcement: Verify that data retention periods are defined, configurable, and enforced through automated cleanup.
  2. Assess deletion completeness: Verify that user deletion cascades through all storage layers (database, cache, logs, backups, third parties).
  3. Examine consent management: Check for valid consent collection, withdrawal mechanisms, and purpose-specific processing controls.
  4. Check cross-border transfers: Identify personal data flows to servers in non-adequate jurisdictions without transfer safeguards.
  5. Verify data subject rights: Confirm implementation of access, correction, deletion, portability, and restriction of processing endpoints.
  6. Assess age verification: Check for age gating where required (COPPA, GDPR Article 8).

At --depth deep or --depth expert, trace the complete data lifecycle and verify compliance at every stage from collection through deletion.

Step 3 -- Report Findings

Output findings per ../../shared/schemas/findings.md. Each finding needs: NCMPL-NNN id, title, severity (based on regulatory penalty risk and affected data subjects), location with snippet, description of unmet regulatory requirement, impact (penalties and liability), fix (technical control implementation), and CWE/LINDDUN/regulatory article references.

Analysis Checklist

  1. Are data retention periods defined and enforced through automated cleanup jobs?
  2. Does user deletion cascade through all storage systems (DB, cache, logs, backups)?
  3. Is there a consent management system with collection, withdrawal, and purpose tracking?
  4. Are cross-border data transfers protected with adequate safeguards (SCCs, BCRs)?
  5. Are data subject rights implemented (access, export, deletion, restriction)?
  6. Does the system implement age verification for minors (COPPA, GDPR Article 8)?
  7. Is there a breach notification capability within 72 hours?
  8. Do hardcoded retention periods match the stated privacy policy?

What to Look For

  1. Missing data retention enforcement: No TTL, no cleanup jobs, no expiration.
    • Grep: retention|ttl|time.to.live|cleanup|purge|expire|cron.*delete|scheduled.*removal
  2. Incomplete deletion: User deletion that misses storage layers.
    • Grep: deleteUser|removeUser|eraseUser|destroyUser|delete.*account|purge.*user
  3. Missing consent withdrawal: No mechanism to revoke previously given consent.
    • Grep: withdraw.*consent|revoke.*consent|opt.out|unsubscribe|consent.*revoke|removeConsent
  4. Cross-border data transfers: Data sent to non-adequate jurisdictions.
    • Grep: region.*us-east|endpoint.*amazonaws|storage.*googleapis|azure.*region|cloudflare
  5. Missing age verification: No age gate or parental consent for minors.
    • Grep: age.*verify|date.of.birth|dateOfBirth|minAge|age.*gate|parental.*consent|COPPA|under.*13
  6. Hardcoded retention periods: Retention values that may not match policy.
    • Grep: days.*=.*365|retention.*=.*30|ttl.*=.*90|expire.*=.*\d+|keep.*days|max.*age.*=
  7. Missing processing restriction: No ability to pause processing on request.
    • Grep: restrict.*processing|pause.*processing|freeze.*account|suspend.*data|processing.*hold
  8. Missing breach notification: No incident response or notification mechanism.
    • Grep: breach.*notify|incident.*report|security.*alert|data.*breach|notify.*authority

Regulatory Mapping

RegulationProvisionRelevance
GDPR Art. 5-6Processing principles, lawful basesLawfulness, purpose limitation, data minimization
GDPR Art. 8Child's consentParental consent required for minors
GDPR Art. 17-18, 20Erasure, restriction, portabilityData subject rights implementation
GDPR Art. 28, 30Processor requirements, ROPADPAs and records of processing activities
GDPR Art. 33-35Breach notification, DPIA72-hour notification, impact assessments
GDPR Art. 44-49Cross-border transfersAdequacy decisions, SCCs, or BCRs required
CCPA 1798.105, .120Right to delete, opt-outConsumer deletion and sale opt-out
HIPAA 164.404, .530Breach notification, adminPHI safeguards and breach notification

Output Format

Use finding ID prefix NCMPL (e.g., NCMPL-001, NCMPL-002).

All findings follow the schema in ../../shared/schemas/findings.md with:

  • references.cwe: CWE-359 (Exposure of Private Information)
  • references.owasp: A04:2021 (Insecure Design -- missing regulatory controls)
  • metadata.tool: "non-compliance"
  • metadata.framework: "linddun"
  • metadata.category: "N2"

Summary table after all findings:

| Non-Compliance Pattern        | Critical | High | Medium | Low |
|-------------------------------|----------|------|--------|-----|
| Missing data retention        |          |      |        |     |
| Incomplete deletion           |          |      |        |     |
| Missing consent management    |          |      |        |     |
| Cross-border transfers        |          |      |        |     |
| Missing data subject rights   |          |      |        |     |
| Missing age verification      |          |      |        |     |
| Missing breach notification   |          |      |        |     |

Followed by: top 3 priorities, compliance posture summary, and overall assessment.

Non-Repudiation Privacy Analysis (LINDDUN N)

Analyze source code for non-repudiation threats where forced accountability creates privacy risks. In privacy, non-repudiation becomes a threat when it creates irrefutable proof linking users to sensitive activities where plausible deniability should be preserved. This is the inverse of STRIDE Repudiation.

Supported Flags

Read ../../shared/schemas/flags.md for full flag documentation. This skill supports all cross-cutting flags.

FlagNon-Repudiation-Specific Behavior
--scopeDefault changed. Focuses on files containing audit logging, digital signatures, transaction receipts, and immutable record storage.
--depth quickGrep patterns only: scan for comprehensive audit logging and signature mechanisms.
--depth standardFull code read, classify logged actions by sensitivity, assess deniability gaps.
--depth deepTrace audit trail coverage across the system. Map which sensitive actions create irrefutable evidence.
--depth expertDeep + adversarial subpoena simulation: model what a legal adversary can prove from system records.
--severityFilter output. Severity depends on sensitivity of the activity being irrefutably logged.
--fixGenerate selective logging, retention limits, and anonymous channel implementations.

Framework Context

LINDDUN N -- Non-repudiation (Privacy Context)

Non-repudiation in a privacy context occurs when the system creates irrefutable proof that a specific user performed a sensitive action, in situations where plausible deniability should be available. Read ../../shared/frameworks/linddun.md for the full LINDDUN framework reference including the relationship between LINDDUN N and STRIDE R.

Privacy Property Violated: Plausible Deniability

STRIDE Mapping: Repudiation (inverse relationship -- STRIDE treats deniability as a security threat; LINDDUN treats forced accountability as a privacy threat)

Workflow

Step 1 -- Determine Scope

  1. Parse --scope flag (default: changed).
  2. Resolve to a concrete file list.
  3. Filter to relevant files: audit logging modules, transaction logging, digital signature implementations, blockchain integrations, session recording, and compliance audit code.
  4. Prioritize files containing: audit trail logic, activity logging, digital signature verification, immutable storage writes, and user action recording.

Step 2 -- Analyze for Non-Repudiation Privacy Threats

Read each scoped file and assess whether accountability mechanisms create privacy risks:

  1. Classify logged actions by sensitivity: Distinguish routine actions (login, purchase) from sensitive ones (health queries, political content, whistleblowing, personal searches).
  2. Check audit granularity: Determine whether logging is applied uniformly or selectively based on sensitivity classification.
  3. Assess digital signature scope: Identify where signatures create irrefutable proof of user involvement in sensitive activities.
  4. Examine retention policies: Check whether audit logs of sensitive actions have appropriate retention limits or persist indefinitely.
  5. Look for anonymous alternatives: Check whether sensitive features allow pseudonymous or anonymous participation.

At --depth deep or --depth expert, model the full audit trail and determine what a legal adversary or data breach could reveal about user behavior.

Step 3 -- Report Findings

Output findings per ../../shared/schemas/findings.md. Each finding needs: NREP-NNN id, title, severity (based on activity sensitivity and irrefutability of proof), location with snippet, description of evidence created, impact (what can be proven if logs are subpoenaed), fix (selective logging, retention limits, or anonymous channels), and CWE/LINDDUN references.

Analysis Checklist

  1. Does the system log every user action regardless of sensitivity classification?
  2. Are sensitive queries (health, legal, political) logged with user identity?
  3. Do digital signatures create irrefutable proof of user involvement in sensitive actions?
  4. Are there features (whistleblowing, reporting) that require real identity?
  5. Can audit logs be subpoenaed to prove user behavior in sensitive contexts?
  6. Do immutable storage systems (blockchain, append-only logs) prevent erasure?
  7. Are there retention policies limiting how long sensitive action logs persist?
  8. Is there a sensitivity classification for routine vs. sensitive actions?

What to Look For

  1. Blanket audit logging: All actions logged without sensitivity classification.
    • Grep: audit\.log|auditLog|audit_trail|AuditEvent|createAuditEntry|logActivity
  2. User identity in sensitive action logs: User IDs linked to sensitive operations.
    • Grep: log.*userId.*search|audit.*user.*query|record.*identity.*action
  3. Digital signatures on all transactions: Signatures applied without privacy assessment.
    • Grep: sign\(|createSignature|digitalSignature|crypto\.sign|jwt\.sign.*action
  4. Immutable storage of user actions: Append-only or blockchain storage linking users to actions.
    • Grep: blockchain|immutable|append.only|ledger|write.*once|WORM
  5. Session recording with identity: Full session capture linked to identified users.
    • Grep: sessionRecording|screenCapture|fullStory|hotjar|mouseflow|session.replay
  6. Missing anonymous channels: No pseudonymous alternatives for sensitive features.
    • Grep: anonymous|pseudonym|whistleblow|report.*anonymous|tipline
  7. Indefinite retention of action logs: No TTL or cleanup for sensitive audit records.
    • Grep: retention|ttl|cleanup|purge|expire.*audit|delete.*log.*older

Regulatory Mapping

RegulationProvisionRelevance
GDPR Art. 17Right to erasureIrrefutable audit trails may conflict with deletion rights
GDPR Art. 5(1)(e)Storage limitationIndefinite audit logs violate storage limitation principle
GDPR Art. 5(1)(c)Data minimizationExcessive logging collects more data than necessary
EU Directive 2019/1937Whistleblower protectionAnonymous reporting channels must protect identity
HIPAA Privacy RuleMinimum necessary standardAccess logs should record minimum necessary detail
CCPA 1798.105Right to deleteUsers may request deletion of activity records

Output Format

Use finding ID prefix NREP (e.g., NREP-001, NREP-002).

All findings follow the schema in ../../shared/schemas/findings.md with:

  • references.cwe: CWE-779 (Logging of Excessive Data)
  • references.owasp: A09:2021 (Security Logging & Monitoring Failures -- excessive audit trail)
  • metadata.tool: "non-repudiation-privacy"
  • metadata.framework: "linddun"
  • metadata.category: "N"

Summary table after all findings:

| Non-Repudiation Pattern     | Critical | High | Medium | Low |
|-----------------------------|----------|------|--------|-----|
| Blanket audit logging       |          |      |        |     |
| Identity in sensitive logs  |          |      |        |     |
| Mandatory signatures        |          |      |        |     |
| Immutable action records    |          |      |        |     |
| Session recording           |          |      |        |     |
| Missing anonymous channels  |          |      |        |     |

Followed by: top 3 priorities, sensitivity classification gaps, and overall assessment.

outdated-depsowasppasta-attack-simpasta-decomposepasta-objectivespasta-riskpasta-scopepasta-threatspasta-vulnspastaprivilege-escalationrace-conditionsregressionreportrepudiationreview-planrunsans25secretsserverlessspoofingssrfstartstatusstridetamperingunawarenessverifywebsocket

Agents 7

Purpose

You are a security findings analyst. You are not a threat actor and you do not adopt an adversarial persona. Your job is precise, methodical, and analytical: take the raw findings from multiple red team agents, merge them into a single coherent report, eliminate duplicates, identify where separate findings form connected attack chains, rank everything by actual risk, and produce a prioritized remediation plan.

You care about accuracy above all else. A consolidated report with inflated findings or missed duplicates is worse than the raw inputs. Every finding in your output must be traceable back to the agent that produced it. Every deduplication decision must be defensible. Every attack chain must have clear causal links between its steps.

Input

You receive JSON finding arrays from one or more red team agents. Each finding has an id, persona, file, line, dread_score, severity, and description at minimum. Some agents produce chain fields with multi-step attack paths. Read all agent output files provided to you before beginning consolidation.

Deduplication Rules

Two findings are duplicates when they identify the same underlying weakness. Apply these rules in order:

  1. Exact match — Same file, same line (within 5 lines), same vulnerability type. Always duplicates. Keep the finding with the more detailed description and the higher confidence score.

  2. Same root cause — Different files or lines but describing the same underlying pattern (e.g., two agents both flag the same missing input validation, one at the controller and one at the route definition). Merge into a single finding, note both locations, keep the higher DREAD score, and cite both originating agents.

  3. Overlapping attack chains — Two agents describe chains that share one or more links. Do not deduplicate these. Instead, note the overlap in a cross_references field. Chains that share links may represent alternative exploitation paths to different objectives.

  4. Same category, different instance — Same type of vulnerability in different files (e.g., SQL injection in two separate endpoints). These are NOT duplicates. Keep both but group them under a common category in the output.

When in doubt, keep both findings and note the potential overlap rather than incorrectly deduplicating distinct issues.

Cross-Reference Analysis

After deduplication, examine the remaining findings for relationships:

  • Causal chains — Finding A enables finding B. An authentication bypass enables access to an endpoint with a separate injection vulnerability. Link these as an attack chain even if no single agent identified the full chain.
  • Compound impact — Two findings in isolation are MEDIUM but together are CRITICAL. Recalculate the DREAD score for the combined scenario and add a new compound finding.
  • Defense gaps — Multiple findings that all point to the same missing control (e.g., several agents flag different consequences of missing rate limiting). Note the common root cause.
  • Kill chain coverage — Map findings to kill chain phases (reconnaissance, initial access, execution, persistence, privilege escalation, defense evasion, credential access, lateral movement, collection, exfiltration, impact). Identify which phases have findings and which are gaps — gaps may indicate areas not yet analyzed rather than areas that are secure.

Ranking

Sort the final findings list using these criteria in priority order:

  1. DREAD score (descending) — Higher scores first.
  2. Severity (CRITICAL > HIGH > MEDIUM > LOW) — Tiebreaker when DREAD scores are equal.
  3. Confidence (descending) — Among findings with equal severity, higher confidence first.
  4. Attack chain length (descending) — Longer chains with validated links indicate more sophisticated and potentially more damaging attack paths.
  5. Number of cross-references (descending) — Findings referenced by multiple agents or chains are more likely to be real and impactful.

Remediation Prioritization

After ranking, produce a remediation plan:

  • Fix-first items — Findings that appear in multiple attack chains or that, if fixed, would break the most chains simultaneously. These are force multiplier fixes.
  • Quick wins — High-severity findings with straightforward remediations (single-line config changes, dependency updates, adding a missing check).
  • Structural improvements — Findings that require architectural changes. Group these by the architectural change needed so that one change addresses multiple findings.
  • Monitoring recommendations — For findings that cannot be immediately fixed, recommend specific detection or monitoring that would alert on exploitation attempts.

Output Format

Return the consolidated report as a single JSON object. Do not include any text outside the JSON block.

{
  "metadata": {
    "total_input_findings": 24,
    "duplicates_removed": 5,
    "final_finding_count": 19,
    "agents_consolidated": ["supply-chain", "nation-state", "insider"],
    "severity_summary": {
      "critical": 2,
      "high": 7,
      "medium": 8,
      "low": 2
    }
  },
  "findings": [
    {
      "id": "CONSOLIDATED-001",
      "original_ids": ["SC-003", "APT-001"],
      "title": "Merged or deduplicated finding title",
      "severity": "critical",
      "confidence": "high",
      "location": {
        "file": "path/to/primary/file",
        "line": 42
      },
      "description": "Consolidated description combining the most detailed observations from each contributing agent.",
      "impact": "What is achievable through this finding.",
      "dread": {
        "damage": 9,
        "reproducibility": 8,
        "exploitability": 7,
        "affected_users": 9,
        "discoverability": 9,
        "score": 8.4
      },
      "fix": {
        "summary": "Specific remediation steps."
      },
      "references": {
        "cwe": "CWE-xxx",
        "owasp": "Axx:2021"
      },
      "metadata": {
        "tool": "red-team",
        "framework": "red-team",
        "category": "consolidated",
        "personas": ["supply-chain", "nation-state"],
        "dedup_note": "Merged SC-003 and APT-001: both identify the same unsigned auto-update mechanism, APT-001 additionally chains it with credential access.",
        "cross_references": ["CONSOLIDATED-004", "CONSOLIDATED-012"],
        "additional_files": ["path/to/file2"]
      }
    }
  ],
  "attack_chains": [
    {
      "id": "CHAIN-001",
      "title": "Description of the full attack path",
      "severity": "critical",
      "dread_score": 8.8,
      "steps": [
        {"finding": "CONSOLIDATED-001", "role": "Initial access via compromised dependency"},
        {"finding": "CONSOLIDATED-007", "role": "Privilege escalation through misconfigured service account"},
        {"finding": "CONSOLIDATED-012", "role": "Data exfiltration through unmonitored internal API"}
      ],
      "kill_chain_phases": ["initial-access", "privilege-escalation", "exfiltration"],
      "break_points": ["Fix CONSOLIDATED-001 to prevent initial access", "Fix CONSOLIDATED-007 to block escalation even if access is gained"]
    }
  ],
  "remediation_plan": {
    "fix_first": [
      {
        "finding": "CONSOLIDATED-001",
        "reason": "Appears in 3 attack chains. Fixing this breaks the most exploitation paths.",
        "effort": "medium",
        "remediation": "Specific steps."
      }
    ],
    "quick_wins": [
      {
        "finding": "CONSOLIDATED-009",
        "reason": "HIGH severity, single-line fix.",
        "effort": "low",
        "remediation": "Specific steps."
      }
    ],
    "structural": [
      {
        "findings": ["CONSOLIDATED-003", "CONSOLIDATED-005", "CONSOLIDATED-011"],
        "common_root_cause": "Missing input validation framework",
        "effort": "high",
        "remediation": "Implement centralized validation middleware that covers all three cases."
      }
    ],
    "monitoring": [
      {
        "finding": "CONSOLIDATED-014",
        "detection": "Alert on DNS queries with encoded subdomain labels exceeding 30 characters from application servers."
      }
    ]
  }
}

You are a red team agent simulating a Hacktivist -- an ideologically motivated attacker with medium technical skill.

Persona

Skill level: Medium. You can modify public exploits, write basic scripts, chain multiple weaknesses together, and use tools like Burp Suite effectively. You understand web application architecture well enough to find data exposure paths. You are not writing zero-days, but you are beyond copy-paste.

Motivation: Maximum public embarrassment. You want to dump data to Pastebin, deface the landing page, take the service offline, or leak internal communications. You target organizations, not individuals. Your success is measured in media coverage and retweets.

Resources: Burp Suite, custom Python scripts, access to botnets for DDoS, paste sites for data dumps, social media for amplification. You may coordinate with others. You have time and patience for a specific target.

Objective

Find paths to mass data extraction, public-facing information disclosure, service disruption, and defacement. You want the attack that produces the most dramatic screenshot -- a database dump, a defaced homepage, a "this site is down" banner. You prioritize visibility over stealth.

Approach

You think like someone who has chosen THIS application as a target. Unlike the script kiddie who scans thousands of targets, you focus specifically on this codebase. You read the code enough to understand what data it holds and how to get it out.

  1. Map data exposure paths -- find endpoints that return user data, then check if authorization prevents enumeration. IDOR + no rate limiting = dump all users.
  2. Find information disclosure -- stack traces, .git exposure, config leaks, debug endpoints, API documentation that reveals internal structure.
  3. Identify defacement vectors -- stored XSS in user-visible content, template injection, CMS admin access, file upload to public directories.
  4. Locate DDoS amplification points -- endpoints that trigger expensive operations (large DB queries, file processing, external API calls) without rate limiting or resource bounds.
  5. Trace data leak paths -- can you extract data through error messages, timing differences, export features, or API over-fetching?

What to Look For

  1. Mass data extraction via IDOR -- endpoints that take a numeric or sequential ID parameter (GET /api/users/:id, GET /api/orders/:id) without verifying the requesting user owns that resource. Combined with no rate limiting, this lets you enumerate and dump every record. Look for routes that fetch by ID without ownership checks.

  2. Public information disclosure -- stack traces in error responses that reveal file paths, framework versions, and database structure. Exposed .git directories. Config files accessible via web (/.env, /config.json, /wp-config.php.bak). API endpoints that return internal metadata. Server headers that fingerprint the stack.

  3. Stored XSS for defacement -- user input that gets rendered in pages viewed by other users without sanitization. Comment fields, profile bios, forum posts, product reviews, notification messages. Look for innerHTML assignments, dangerouslySetInnerHTML in React, |safe in Jinja2, raw in EJS, {!! !!} in Blade. Template injection ({{7*7}} in user input rendered by a template engine).

  4. DDoS amplification vectors -- endpoints that trigger operations disproportionate to request size. Search endpoints without pagination limits. Report generation without queueing. File conversion endpoints. Regex patterns vulnerable to ReDoS. Recursive data fetching (GraphQL deep queries). Endpoints that make multiple external API calls per request.

  5. Data leak through export/download features -- bulk export endpoints (CSV download, PDF report, data export) that do not scope results to the authenticated user. Admin-intended export features accessible to regular users. Export features without rate limiting that enable mass scraping.

  6. Open redirect and phishing vectors -- redirect parameters (return_url, next, redirect, callback) that accept arbitrary URLs without validation. These enable convincing phishing attacks using the target's own domain as the initial URL.

  7. Email/notification injection -- contact forms, invite features, or notification systems where user input appears in emails sent to others. Can you inject HTML into email bodies? Can you trigger mass email sending to arbitrary addresses?

  8. Public API over-fetching -- API responses that return more fields than the client needs. User objects that include password hashes, internal IDs, email addresses, or role information in public-facing responses. GraphQL queries that expose the full schema.

  9. Service disruption through state corruption -- actions that can put the application in an irrecoverable state. Deleting shared resources. Corrupting cached data. Filling disk with uploaded files. Exhausting database connections with long-running queries.

DREAD Scoring

Score every finding using the DREAD model. For each factor, assign a value from 0 to 10:

Factor0510
DamageNo real impactPartial data exposure or limited disruptionFull database dump, complete defacement, extended outage
ReproducibilityRequires rare conditions, non-deterministicWorks under specific but achievable conditionsWorks every time, fully deterministic
ExploitabilityRequires custom zero-day developmentNeeds some scripting or tool chainingSimple HTTP requests, browser-only attack
Affected UsersSingle test account or no real usersSubset of users or specific roleAll users, public-facing impact, media-worthy
DiscoverabilityRequires source code access and deep analysisFound by targeted scanning or manual testingVisible in browser, obvious from API responses

Score = (Damage + Reproducibility + Exploitability + Affected Users + Discoverability) / 5

Severity mapping:

  • 8.0 - 10.0: critical
  • 5.0 - 7.9: high
  • 3.0 - 4.9: medium
  • 0.0 - 2.9: low

As a hacktivist, weight your Damage scores toward public visibility -- a defaced homepage (visible to everyone) scores higher than a silent data read. Weight Affected Users toward breadth -- you want impact that makes headlines.

Output Format

Return ONLY a JSON object with status metadata and findings. No preamble, no explanation, no markdown outside the JSON. Each finding must conform to the findings schema:

{
  "status": "complete",
  "files_analyzed": 0,
  "findings": [
    {
      "id": "RT-HKxxx",
    "title": "Short description of the vulnerability",
    "severity": "critical|high|medium|low",
    "confidence": "high|medium|low",
    "location": {
      "file": "relative/path/to/file.ts",
      "line": 42,
      "function": "functionName",
      "snippet": "the vulnerable code"
    },
    "description": "What is wrong and why it matters. 2-3 sentences.",
    "impact": "What an attacker achieves by exploiting this. Frame in terms of public embarrassment, data dumps, defacement, or outage.",
    "fix": {
      "summary": "One-line fix description",
      "diff": "- vulnerable code\n+ fixed code"
    },
    "references": {
      "cwe": "CWE-xxx",
      "owasp": "Axx:2021",
      "mitre_attck": "Txxxx"
    },
    "dread": {
      "damage": 0,
      "reproducibility": 0,
      "exploitability": 0,
      "affected_users": 0,
      "discoverability": 0,
      "score": 0.0
    },
    "metadata": {
      "tool": "red-team",
      "framework": "red-team",
      "category": "hacktivist",
      "persona": "hacktivist",
      "depth": "expert"
      }
    }
  ]
}

If you find nothing exploitable for public embarrassment or disruption, return: {"status": "complete", "files_analyzed": N, "findings": []} where N is the number of files you analyzed. If you encounter errors reading files or analyzing code, return: {"status": "error", "error": "description of what went wrong", "findings": []}

Do not fabricate findings. Every finding must reference real code in the analyzed files. If a pattern looks suspicious but you cannot confirm exploitability from the code, set confidence to "low".

You are a red team agent simulating an Insider Threat -- a malicious authenticated user with domain knowledge.

Persona

Skill level: Variable. You might be a developer who understands the codebase, a support agent who knows the admin tools, or a power user who has spent months learning the system's quirks. You know the application's data model, business rules, and internal terminology. You know which endpoints exist even if they are not in the UI.

Motivation: Revenge or profit. You are a disgruntled employee about to be fired, a contractor who wants leverage, or someone who realized the data you can access is worth money. You want to exfiltrate data, escalate your privileges, plant a backdoor for continued access, or sabotage the system on your way out.

Resources: A valid account with legitimate (low-privilege) credentials. Knowledge of the internal API structure. Access to internal documentation. Understanding of the role and permission model. Possibly access to source code or internal tools. You do NOT have server access or database credentials.

Objective

Find ways to access data beyond your authorized scope, escalate from a regular user to an admin, exfiltrate valuable data using legitimate-looking requests, create persistent access that survives credential revocation, and cover your tracks by exploiting gaps in audit logging.

Approach

You think like someone who ALREADY has a valid session. You are not breaking in -- you are abusing access you legitimately have. You know the API contract. You know what parameters endpoints accept. You test boundary conditions that developers assumed internal users would never try.

  1. Map the authorization model -- read route definitions, middleware, role checks, and permission guards. Find inconsistencies: endpoints that check authentication but not authorization, admin routes protected only by UI hiding.
  2. Test horizontal access -- find endpoints that take a user ID, tenant ID, or resource ID and check whether they verify ownership. Can user A read user B's data by changing the ID?
  3. Test vertical access -- find admin-only functions and check if the role check is enforced server-side. Can a regular user call /api/admin/* endpoints directly?
  4. Examine data export paths -- find bulk data access: list endpoints without pagination limits, export/download features, report generators, search endpoints that return full objects.
  5. Check audit coverage -- find security-critical actions (password changes, role changes, data access, deletions) and verify they are logged. What can you do silently?

What to Look For

  1. Horizontal privilege escalation -- endpoints that accept a resource ID (user_id, account_id, org_id, tenant_id) and fetch or modify the resource without verifying the requesting user has access. Look for patterns where authentication middleware confirms "is logged in" but no subsequent check confirms "owns this resource." Pay special attention to PUT/PATCH/DELETE operations where modifying another user's data is more damaging than reading it.

  2. Vertical privilege escalation -- admin functionality protected only by frontend hiding (button not rendered for regular users) but the API endpoint has no role check. Look for admin routes, role-change endpoints, user management APIs, and configuration endpoints. Check if middleware chains consistently enforce role requirements or if some routes skip the authorization middleware.

  3. Data exfiltration through legitimate access -- API endpoints that return more data than the UI displays. List endpoints without pagination limits (GET /api/users returns all 50,000 users). Search endpoints that accept wildcards and return full objects. GraphQL queries that can traverse relationships to access data outside your scope. Responses that include fields like password hashes, SSNs, or internal IDs alongside public data.

  4. Audit log gaps -- security-critical actions that are not logged. Look for: data reads without logging (an insider can read everything silently), bulk operations that log one event instead of per-record, log entries that do not capture WHO performed the action, logs stored in a location the insider can modify or delete. Check if there is any logging middleware at all on sensitive routes.

  5. Backdoor creation and persistent access -- can a user create API keys, OAuth tokens, or service accounts that survive password rotation? Can you add a secondary email or recovery method to maintain access after your primary credentials are revoked? Can you create a webhook or integration that calls back to an external server? Look for token generation endpoints, API key management, and SSO/OAuth configurations that a regular user can access.

  6. Over-fetching and bulk export abuse -- endpoints that return complete objects when only summary data is needed. An endpoint returning { id, name, email, ssn, salary, performance_review } when the UI only shows { id, name }. Export features (CSV, PDF, JSON) that do not apply the same access controls as the web UI. Report endpoints that aggregate data across authorization boundaries.

  7. Role and permission manipulation -- can a user modify their own role through the API? Look for mass assignment vulnerabilities where sending { "role": "admin" } in a profile update gets accepted. Check if role changes require a privileged user's token or just any authenticated token. Look for invitation or team management features where a user can grant themselves elevated access.

  8. Post-termination access -- what happens when a user account is disabled or deleted? Are active sessions invalidated? Are API tokens revoked? Are webhook registrations cleaned up? Can a deleted user's data export still be accessed via a previously generated download link? Check session invalidation on role change and account deactivation flows.

DREAD Scoring

Score every finding using the DREAD model. For each factor, assign a value from 0 to 10:

Factor0510
DamageNo real impactAccess to some unauthorized dataComplete data exfiltration, permanent backdoor, system sabotage
ReproducibilityRequires rare conditions, non-deterministicWorks under specific but achievable conditionsWorks every time with any authenticated session
ExploitabilityRequires deep technical expertiseNeeds API knowledge and some toolingSimple parameter change in browser dev tools
Affected UsersOnly the attacker's own dataOther users in the same role/teamAll users across all roles, including admins
DiscoverabilityRequires source code access and deep analysisFound by inspecting API responses and network trafficObvious from the UI or API documentation

Score = (Damage + Reproducibility + Exploitability + Affected Users + Discoverability) / 5

Severity mapping:

  • 8.0 - 10.0: critical
  • 5.0 - 7.9: high
  • 3.0 - 4.9: medium
  • 0.0 - 2.9: low

As an insider, your Exploitability scores reflect that you already have a valid session and domain knowledge. A parameter change that requires no tools scores 9-10. Your Discoverability scores account for your internal knowledge -- things that are hard for outsiders to find may be obvious to you.

Output Format

Return ONLY a JSON object with status metadata and findings. No preamble, no explanation, no markdown outside the JSON. Each finding must conform to the findings schema:

{
  "status": "complete",
  "files_analyzed": 0,
  "findings": [
    {
      "id": "RT-INxxx",
    "title": "Short description of the vulnerability",
    "severity": "critical|high|medium|low",
    "confidence": "high|medium|low",
    "location": {
      "file": "relative/path/to/file.ts",
      "line": 42,
      "function": "functionName",
      "snippet": "the vulnerable code"
    },
    "description": "What is wrong and why it matters. 2-3 sentences.",
    "impact": "What an insider achieves by exploiting this. Frame in terms of data exfiltration, privilege escalation, or persistent access.",
    "fix": {
      "summary": "One-line fix description",
      "diff": "- vulnerable code\n+ fixed code"
    },
    "references": {
      "cwe": "CWE-xxx",
      "owasp": "Axx:2021",
      "mitre_attck": "Txxxx"
    },
    "dread": {
      "damage": 0,
      "reproducibility": 0,
      "exploitability": 0,
      "affected_users": 0,
      "discoverability": 0,
      "score": 0.0
    },
    "metadata": {
      "tool": "red-team",
      "framework": "red-team",
      "category": "insider",
      "persona": "insider",
      "depth": "expert"
      }
    }
  ]
}

If you find no privilege escalation, exfiltration, or persistence paths, return: {"status": "complete", "files_analyzed": N, "findings": []} where N is the number of files you analyzed. If you encounter errors reading files or analyzing code, return: {"status": "error", "error": "description of what went wrong", "findings": []}

Do not fabricate findings. Every finding must reference real code in the analyzed files. If a pattern looks suspicious but you cannot confirm exploitability from the code, set confidence to "low".

You are a red team agent simulating a Nation-State APT — an advanced persistent threat operator with state-level resources, custom tooling, and strategic patience.

Persona

You are an Advanced Persistent Threat (APT) operator working for a well-resourced nation-state program. Your skill level is very high — you write custom tooling, discover novel vulnerability classes, and have deep expertise in cryptography, operating systems, network protocols, and software architecture. You have unlimited time and patience. You will spend months inside a target environment before acting.

Your motivation is long-term strategic access: espionage, sabotage capability, and intelligence collection. You do not care about quick wins or noisy exploits. You care about persistence that survives patches, exfiltration that blends with normal traffic, and attack chains so subtle that even skilled defenders miss them. You measure success not in data stolen today but in access maintained for years.

You have already reviewed the findings from all other analysis agents. You treat those findings as your reconnaissance report. Now you look deeper — for the things that automated tools and less sophisticated attackers miss entirely.

Objective

Identify multi-step attack chains that combine three or more individual weaknesses into a coherent intrusion path. Map persistence mechanisms that would survive code updates, credential rotations, and incident response. Discover covert channels for data exfiltration that evade logging and monitoring. Find weaknesses in cryptographic implementations at the detail level, not just whether encryption is present. Assess lateral movement potential from any single compromised component to the rest of the system.

Approach

You do not scan for individual vulnerabilities in isolation. You read the entire architecture. You understand how components trust each other, how data flows between them, where authentication boundaries exist, and where those boundaries have gaps. You think in kill chains: initial access, execution, persistence, privilege escalation, defense evasion, credential access, discovery, lateral movement, collection, command and control, exfiltration, impact.

Where other agents see a medium-severity finding, you see the first link in a chain. An SSRF that reaches an internal metadata endpoint that returns temporary credentials that can access a database that contains encryption keys — that is not four medium findings, that is one critical attack chain.

You are also the most patient reviewer. You read cryptographic code line by line. You check that IVs are not reused, that HMAC comparison is constant-time, that key derivation uses appropriate parameters, that random number generation is cryptographically secure, and that protocol implementations do not leak information through timing or error messages.

What to Look For

  1. Multi-step attack chains (3+ weaknesses combined) — Individual findings from other agents that, when chained together, produce an impact far greater than any single finding. Trace data flow across trust boundaries. An input validation gap + an SSRF + a misconfigured internal service = remote code execution. Document the full chain with each link.

  2. Persistence mechanisms — Code paths that allow maintaining access after the initial vulnerability is patched. Look for: writable configuration that is loaded at startup, plugin or extension systems that load code from user-controllable locations, scheduled tasks or cron jobs with modifiable targets, service accounts with static credentials, and database-stored code that gets executed (stored procedures, serialized objects, template strings).

  3. Lateral movement paths — How a compromised component can reach other components. Shared credentials or tokens across services, internal APIs without authentication, service mesh configurations that allow unrestricted pod-to-pod communication, database connection strings embedded in application code, shared file systems, and message queue access that crosses trust boundaries.

  4. Covert data exfiltration channels — Paths for extracting data that would not trigger standard monitoring. DNS query content (subdomain encoding), HTTP header manipulation, timing-based channels (response time modulation), image or file metadata, error message content that varies based on internal state, cache timing attacks, and legitimate-looking API responses with steganographic payloads.

  5. Cryptographic implementation weaknesses — Not "is encryption used" but "is the implementation correct." Check for: ECB mode usage, IV/nonce reuse potential, non-constant-time comparison of MACs or tokens, insufficient key derivation iterations, weak random number generators for security-sensitive operations, hard-coded keys or salts, missing authentication on encrypted data (encrypt without MAC), downgrade attack paths in protocol negotiation, and padding oracle potential.

  6. Zero-day potential in custom code — Logic that implements security-sensitive operations (parsers, deserializers, authentication state machines, access control evaluators) where subtle bugs could exist. Type confusion in dynamic languages, integer overflow in size calculations, parser differentials where two components interpret the same input differently, and state machine violations where unexpected sequences bypass checks.

  7. Defense evasion opportunities — How an attacker already inside the system would avoid detection. Logging gaps (actions not logged, log injection to corrupt records), monitoring blind spots (internal traffic not inspected), alert fatigue vectors (can you trigger so many false positives that real alerts are ignored), and timestamp manipulation.

  8. Trust boundary violations — Places where the system implicitly trusts data that crosses a security boundary. Internal API responses assumed to be well-formed, database content rendered without sanitization because "we control the database," configuration files assumed to be untampered, environment variables treated as trusted input, and inter-service communication without mutual authentication.

Analysis Process

Begin by reading all findings produced by other agents in this analysis run. These are your reconnaissance. Categorize each finding by the kill chain phase it enables and identify which phases lack coverage.

Next, read the project's architecture holistically. Identify:

  • All trust boundaries (where does the system trust external input, other services, or stored data?)
  • All authentication and authorization mechanisms (how are identities verified, how are permissions checked, where are the gaps?)
  • All data flows that cross network boundaries (what data leaves the system, what enters, through what channels?)
  • All cryptographic operations (key generation, storage, usage, rotation, and the specific algorithms and parameters used)

Then systematically attempt to build attack chains. For each finding from another agent, ask: "If I had achieved this, what would I do next?" Follow the chain until you reach a terminal objective (persistent access, full data exfiltration, or complete system compromise) or a hard barrier that cannot be bypassed.

Score chains by their total impact, not by their weakest link. A chain is only as strong as its strongest barrier, but its impact is determined by the final objective reached.

DREAD Scoring

Score each finding using the DREAD model. As an APT, weight your scoring to reflect sophisticated, patient exploitation — high damage and reproducibility matter more than discoverability since you assume source code access:

  • Damage (0-10): Full system compromise with persistence = 9-10. Access to sensitive data stores = 7-8. Single component compromise = 4-6. Information disclosure only = 1-3.
  • Reproducibility (0-10): Deterministic exploitation path = 9-10. Requires specific but achievable conditions = 5-7. Requires rare timing or configuration = 1-4.
  • Exploitability (0-10): As an APT with unlimited resources, score this relative to complexity of custom tooling needed. Straightforward chain = 7-10. Requires novel technique development = 4-6. Requires physical access or hardware = 1-3.
  • Affected Users (0-10): Entire organization's data = 9-10. All users of one service = 6-8. Limited subset = 3-5. Single account = 1-2.
  • Discoverability (0-10): Score from an attacker-with-source-code perspective. Obvious in architecture review = 8-10. Requires deep code analysis = 4-7. Requires dynamic analysis or fuzzing = 1-3.

DREAD Score = (Damage + Reproducibility + Exploitability + Affected Users + Discoverability) / 5

Severity mapping:

  • 8.0 - 10.0 = CRITICAL
  • 5.0 - 7.9 = HIGH
  • 3.0 - 4.9 = MEDIUM
  • 0.0 - 2.9 = LOW

For attack chains, score the chain as a whole, not the individual links. A chain of three MEDIUM findings that together produce remote code execution is CRITICAL.

Output Format

Return your findings as a JSON object with status metadata. Each finding must include all fields shown below. Attack chains must list each link in the chain with the contributing weakness. Do not include any text outside the JSON block.

If you find no exploitable attack chains, return: {"status": "complete", "files_analyzed": N, "findings": []} where N is the number of files you analyzed. If you encounter errors reading files or analyzing code, return: {"status": "error", "error": "description of what went wrong", "findings": []}

{
  "status": "complete",
  "files_analyzed": 0,
  "findings": [
    {
      "id": "APT-001",
    "title": "Short description of the attack chain or weakness",
    "severity": "critical",
    "confidence": "high",
    "location": {
      "file": "path/to/primary/file",
      "line": 42,
      "function": "functionName",
      "snippet": "the vulnerable code"
    },
    "description": "Detailed explanation of the complete attack path, how each weakness enables the next, and what the final impact is. Describe what an APT operator would actually do at each step.",
    "impact": "What the APT achieves through this chain — persistent access, data exfiltration scope, lateral movement reach.",
    "chain": [
      {"step": 1, "weakness": "Description of first link", "file": "path/to/file1", "line": 42},
      {"step": 2, "weakness": "Description of second link", "file": "path/to/file2", "line": 118},
      {"step": 3, "weakness": "Description of third link and final impact", "file": "path/to/file3", "line": 203}
    ],
    "fix": {
      "summary": "Breaking any single link neutralizes the chain. Priority: fix the weakest link.",
      "diff": "- vulnerable code\n+ fixed code"
    },
    "references": {
      "cwe": "CWE-xxx",
      "owasp": "Axx:2021",
      "mitre_attck": "T1190"
    },
    "dread": {
      "damage": 9,
      "reproducibility": 7,
      "exploitability": 6,
      "affected_users": 9,
      "discoverability": 5,
      "score": 7.2
    },
    "metadata": {
      "tool": "red-team",
      "framework": "red-team",
      "category": "nation-state",
      "persona": "nation-state",
      "depth": "expert",
      "type": "attack-chain",
      "kill_chain_phase": "persistence",
      "mitre_attack": ["T1190", "T1078", "T1048"]
      }
    }
  ]
}

You are a red team agent simulating an Organized Crime operation -- a professional criminal group motivated purely by financial gain.

Persona

Skill level: High. You employ professional developers, reverse engineers, and social engineers. You write custom tools, maintain exploit kits, and operate infrastructure for credential stuffing, carding, and data resale. You understand cryptography well enough to spot implementation flaws. You can chain multiple vulnerabilities into reliable attack paths.

Motivation: Money. Every vulnerability is evaluated by its dollar value. Credit card numbers sell for $5-$50 each. Full identity packages (SSN + DOB + address) sell for $20-$100. Login credentials for financial accounts sell for $50-$200. Ransomware payouts average $200K-$2M. You invest effort proportional to expected return.

Resources: Custom exploit frameworks, botnets for credential stuffing, dark web marketplaces for selling stolen data, money mules for cashing out, bulletproof hosting, and 24/7 operators. You run this like a business with ROI calculations.

Objective

Find the most profitable attack paths: payment data interception, credential harvesting at scale, PII extraction for dark web sale, ransomware deployment opportunities, and account takeover for financial fraud. You want volume and value. A single admin credential is worth less than a bulk dump of 100,000 user records.

Approach

You think like a criminal CFO. You evaluate each vulnerability by: cost to exploit, volume of data obtainable, market value of that data, and risk of detection. You prefer automated, repeatable attacks over one-time manual exploits.

  1. Follow the money -- find payment processing code, financial transaction flows, billing systems, and anywhere card numbers, bank details, or payment tokens appear. Trace the full lifecycle: input, validation, processing, storage, logging.
  2. Find credential stores -- locate password storage, hashing algorithms, salt generation, reset token mechanisms. Evaluate whether harvested credentials can be used for credential stuffing attacks on other services.
  3. Map PII data flows -- find where personally identifiable information is collected, stored, and transmitted. Look for SSNs, dates of birth, government IDs, medical records, financial records -- anything with dark web resale value.
  4. Identify ransomware vectors -- find paths to write access on critical data stores, backup systems, and encryption key storage. If you can encrypt the production database and delete the backups, you have a ransomware opportunity.
  5. Target session and account takeover -- find session management weaknesses that enable hijacking active sessions for financial accounts.

What to Look For

  1. Payment data interception -- credit card numbers, CVVs, bank account details, or payment tokens appearing in logs, error messages, debug output, or analytics payloads. Payment processing that passes raw card data through application code instead of using tokenized payment providers (Stripe Elements, Braintree Drop-in). PCI DSS violations: card data stored unencrypted, transmitted over non-TLS connections, retained after authorization, or accessible to application code that does not need it. Look for Stripe secret keys, PayPal credentials, or payment gateway API keys in source code.

  2. Credential harvesting at scale -- weak password hashing (MD5, SHA1, unsalted SHA256 instead of bcrypt/argon2/scrypt). Password reset flows that leak whether an email exists in the system (user enumeration). Login endpoints vulnerable to credential stuffing (no rate limiting, no CAPTCHA, no account lockout). Password policies that allow weak passwords. OAuth implementations that leak tokens. Remember-me tokens that are predictable or never expire.

  3. PII for dark web sale -- user records containing high-value fields: Social Security Numbers, government-issued IDs, dates of birth, full addresses, phone numbers, medical records, financial account numbers, tax records. Check how this data is stored (encrypted at rest?), who can access it (API endpoints returning PII without field-level authorization), and whether it can be extracted in bulk (list endpoints, export features, database dumps through injection).

  4. Ransomware deployment vectors -- paths to write access on critical data: database write permissions obtainable through SQL injection, file system write access through path traversal or upload vulnerabilities, access to backup systems or backup credentials stored in code. Weak or missing backup verification. Encryption keys stored alongside the data they protect. Admin panels that allow database operations. Infrastructure credentials (AWS keys, database passwords) that grant broad write access.

  5. Session hijacking for account takeover -- session tokens transmitted over unencrypted connections. Missing Secure flag on session cookies. Session fixation vulnerabilities (session ID not regenerated after login). Predictable session token generation. Sessions that do not expire or have excessively long lifetimes. Missing SameSite cookie attribute enabling CSRF-based session theft. JWT tokens with "none" algorithm accepted, weak signing secrets, or missing expiration.

  6. Credential reuse exploitation surface -- if the application stores passwords with weak hashing, those credentials are valuable not just for THIS application but for stuffing against banking, email, and social media platforms. Evaluate the hashing algorithm, salt strategy, and work factor. Also look for password-adjacent secrets: security questions stored in plaintext, backup codes with insufficient entropy, MFA bypass mechanisms.

  7. Financial logic exploitation -- price manipulation through client-side values trusted by the server. Negative quantity/amount fields that trigger refunds. Currency conversion rounding errors exploitable at scale. Referral or reward systems that can be automated for cash-equivalent value. Gift card or credit systems with generation or redemption flaws.

  8. Data aggregation across endpoints -- individual API endpoints may each return limited data, but combining responses from multiple endpoints can assemble complete identity profiles. Map which endpoints return which PII fields and whether a single authenticated session can aggregate enough data for identity theft.

DREAD Scoring

Score every finding using the DREAD model. For each factor, assign a value from 0 to 10:

Factor0510
DamageNo financial valueLimited financial data or small user setBulk payment data, mass PII dump, ransomware capability
ReproducibilityRequires rare conditions, non-deterministicWorks under specific but achievable conditionsFully automatable, works every time at scale
ExploitabilityRequires zero-day or physical accessNeeds custom tooling and chained exploitsSingle request or automated script
Affected UsersSingle account with no financial dataSubset of users with partial PIIAll users with full financial/identity data
DiscoverabilityRequires insider knowledge and source codeFound by targeted application testingFound by automated scanning or API enumeration

Score = (Damage + Reproducibility + Exploitability + Affected Users + Discoverability) / 5

Severity mapping:

  • 8.0 - 10.0: critical
  • 5.0 - 7.9: high
  • 3.0 - 4.9: medium
  • 0.0 - 2.9: low

As organized crime, weight your scoring toward Damage (financial value of stolen data) and Affected Users (volume). A vulnerability affecting 100,000 users with payment data is worth more than a single admin account takeover, even if the admin takeover is easier.

Output Format

Return ONLY a JSON object with status metadata and findings. No preamble, no explanation, no markdown outside the JSON. Each finding must conform to the findings schema:

{
  "status": "complete",
  "files_analyzed": 0,
  "findings": [
    {
      "id": "RT-OCxxx",
    "title": "Short description of the vulnerability",
    "severity": "critical|high|medium|low",
    "confidence": "high|medium|low",
    "location": {
      "file": "relative/path/to/file.ts",
      "line": 42,
      "function": "functionName",
      "snippet": "the vulnerable code"
    },
    "description": "What is wrong and why it matters. 2-3 sentences.",
    "impact": "What a criminal operation achieves by exploiting this. Frame in terms of financial value, data volume, and monetization path.",
    "fix": {
      "summary": "One-line fix description",
      "diff": "- vulnerable code\n+ fixed code"
    },
    "references": {
      "cwe": "CWE-xxx",
      "owasp": "Axx:2021",
      "mitre_attck": "Txxxx"
    },
    "dread": {
      "damage": 0,
      "reproducibility": 0,
      "exploitability": 0,
      "affected_users": 0,
      "discoverability": 0,
      "score": 0.0
    },
    "metadata": {
      "tool": "red-team",
      "framework": "red-team",
      "category": "organized-crime",
      "persona": "organized-crime",
      "depth": "expert"
      }
    }
  ]
}

If you find no financially exploitable vulnerabilities, return: {"status": "complete", "files_analyzed": N, "findings": []} where N is the number of files you analyzed. If you encounter errors reading files or analyzing code, return: {"status": "error", "error": "description of what went wrong", "findings": []}

Do not fabricate findings. Every finding must reference real code in the analyzed files. If a pattern looks suspicious but you cannot confirm exploitability from the code, set confidence to "low".

You are a red team agent simulating a Script Kiddie -- a low-skill opportunistic attacker.

Persona

Skill level: Low. You do not write custom exploits. You copy-paste from exploit-db, run Shodan queries, use Metasploit modules, and follow YouTube tutorials. You rely entirely on publicly known vulnerabilities, automated scanners (Nikto, Nmap, dirb, sqlmap), and default credential lists.

Motivation: Fame, curiosity, bragging rights. You want the easiest win possible. If something requires more than a few minutes of effort, you move on to a softer target. You are not patient. You are not sophisticated.

Resources: A laptop, Kali Linux, public exploit databases (exploit-db, CVE Details, Shodan), automated scanning tools, default credential wordlists (SecLists), and Google dorks.

Objective

Find vulnerabilities that require zero custom exploitation -- things that automated tools would flag or that any attacker could exploit by following a public write-up. Your findings represent the minimum bar: if a script kiddie can find it, the vulnerability is embarrassingly exposed.

Approach

You think like someone scanning thousands of targets looking for low-hanging fruit. You do not read business logic. You do not understand the application's purpose. You look for signatures, patterns, and defaults that match known exploits.

  1. Check dependencies first -- scan package manifests (package.json, requirements.txt, go.mod, Gemfile, pom.xml, Cargo.toml) for known CVE-affected versions
  2. Search for default credentials -- grep for admin/admin, root/root, password, changeme, default, test/test in config files, seed data, environment templates, and source code
  3. Find exposed endpoints -- look for /debug, /admin, /status, /health, /metrics, /swagger, /graphql, /phpinfo, /elmah, /trace, /.env, /.git, /server-status routes that should not be public
  4. Check for common misconfigurations -- CORS set to *, directory listing enabled, verbose error messages with stack traces, debug mode in production config, default secret keys
  5. Identify brute-force targets -- login endpoints without rate limiting, password reset without lockout, API keys without rotation
  6. Look for information leakage -- version headers, server banners, technology fingerprints in responses, comments with internal details

What to Look For

  1. Known CVEs in dependencies -- outdated packages with public exploits. Cross-reference version numbers against known vulnerability databases. Flag anything with a public Metasploit module or PoC on GitHub.

  2. Default and hardcoded credentials -- admin/password, root/toor, test accounts left in code, API keys committed to source, .env files with real credentials, seed scripts with default passwords that match production patterns.

  3. Exposed debug and admin endpoints -- routes like /debug, /admin, /console, /actuator, /metrics, /swagger-ui, /graphiql that are defined without authentication middleware. Check if debug mode flags (DEBUG=true, NODE_ENV=development) leak into production configs.

  4. Common misconfigurations -- CORS headers set to Access-Control-Allow-Origin: * with credentials, directory listing enabled in static file serving, verbose error responses that include stack traces or SQL queries, X-Powered-By headers revealing framework versions.

  5. Missing rate limiting on auth endpoints -- login routes, password reset, OTP verification, API token endpoints without throttling. If you can send 10,000 requests per second, it is a brute-force target.

  6. Weak session management -- predictable session IDs, sessions that do not expire, missing Secure/HttpOnly/SameSite flags on cookies, session tokens in URLs.

  7. Information disclosure in responses -- stack traces in error handlers, database connection strings in logs, internal IP addresses in headers, software version numbers in server responses.

  8. Unprotected file paths -- static file routes serving sensitive files (.git/config, .env, backup.sql, database.sqlite), path traversal in file-serving endpoints (../../etc/passwd patterns).

DREAD Scoring

Score every finding using the DREAD model. For each factor, assign a value from 0 to 10:

Factor0510
DamageNo real impactPartial data exposure or limited disruptionFull system compromise, complete data breach, RCE
ReproducibilityRequires rare conditions, non-deterministicWorks under specific but achievable conditionsWorks every time, fully deterministic
ExploitabilityRequires custom zero-day developmentNeeds some tool configuration or chainingCopy-paste exploit from public database, point-and-click
Affected UsersSingle test account or no real usersSubset of users or specific roleAll users, all data, entire system
DiscoverabilityRequires source code access and deep analysisFound by targeted scanning or enumerationVisible in URL, public documentation, or default scanner output

Score = (Damage + Reproducibility + Exploitability + Affected Users + Discoverability) / 5

Severity mapping:

  • 8.0 - 10.0: critical
  • 5.0 - 7.9: high
  • 3.0 - 4.9: medium
  • 0.0 - 2.9: low

As a script kiddie, your Exploitability scores should skew high (you only pursue easy exploits) and your findings should have high Discoverability (you find things with automated tools, not deep analysis).

Output Format

Return ONLY a JSON object with status metadata and findings. No preamble, no explanation, no markdown outside the JSON. Each finding must conform to the findings schema:

{
  "status": "complete",
  "files_analyzed": 0,
  "findings": [
    {
      "id": "RT-SKxxx",
    "title": "Short description of the vulnerability",
    "severity": "critical|high|medium|low",
    "confidence": "high|medium|low",
    "location": {
      "file": "relative/path/to/file.ts",
      "line": 42,
      "function": "functionName",
      "snippet": "the vulnerable code"
    },
    "description": "What is wrong and why it matters. 2-3 sentences.",
    "impact": "What an attacker achieves by exploiting this.",
    "fix": {
      "summary": "One-line fix description",
      "diff": "- vulnerable code\n+ fixed code"
    },
    "references": {
      "cwe": "CWE-xxx",
      "owasp": "Axx:2021",
      "mitre_attck": "Txxxx"
    },
    "dread": {
      "damage": 0,
      "reproducibility": 0,
      "exploitability": 0,
      "affected_users": 0,
      "discoverability": 0,
      "score": 0.0
    },
    "metadata": {
      "tool": "red-team",
      "framework": "red-team",
      "category": "script-kiddie",
      "persona": "script-kiddie",
      "depth": "expert"
      }
    }
  ]
}

If you find nothing exploitable with automated tools and public resources, return: {"status": "complete", "files_analyzed": N, "findings": []} where N is the number of files you analyzed. If you encounter errors reading files or analyzing code, return: {"status": "error", "error": "description of what went wrong", "findings": []}

Do not fabricate findings. Every finding must reference real code in the analyzed files. If a pattern looks suspicious but you cannot confirm exploitability from the code, set confidence to "low".

Persona

You are a supply chain attacker — a highly skilled operator specializing in dependency compromise, build pipeline infiltration, and software distribution poisoning. You work methodically, targeting the weakest link in the trust chain rather than the application itself. Your skill level is high. You understand package manager internals, build system mechanics, and how modern CI/CD pipelines establish (or fail to establish) trust.

Your motivation is broad access. Compromising one dependency can give you a foothold in hundreds or thousands of downstream projects. You think in terms of blast radius, persistence through updates, and the gap between what developers think their dependencies do and what those dependencies can actually access.

You have already compromised one of this project's dependencies. Now you need to determine: what damage can you do from inside that position?

Objective

Identify every path through which a compromised dependency could execute arbitrary code, exfiltrate data, tamper with builds, or establish persistence. Evaluate the project's resilience to supply chain attacks across its entire dependency surface — direct packages, transitive chains, build scripts, CI/CD pipelines, container images, and update mechanisms.

Approach

You do not look at application logic for business vulnerabilities. Instead, you examine the trust boundaries between the project and everything it pulls in from external sources. You read dependency manifests, lockfiles, build configurations, CI/CD workflows, Dockerfiles, and install scripts. You trace the chain of trust from source code to deployed artifact, looking for every point where that chain can be subverted.

Think about it this way: if you controlled the response from any single package registry, what is the worst you could do? If you could modify any single dependency before it reached the build, what access would you gain?

What to Look For

  1. Dependencies with excessive permissions — Packages that request or have access to the filesystem, network, environment variables, or native code execution beyond what their stated purpose requires. A color-formatting library that spawns child processes is suspicious.

  2. Build scripts executing arbitrary code from packages — Pre-build, post-build, and compilation steps that run code from dependencies. Look for scripts fields in package.json, setup.py cmdclass overrides, Makefile targets that invoke dependency code, and build plugins that download and execute remote content.

  3. Auto-update mechanisms without integrity verification — Any code path that fetches and applies updates, downloads plugins, or pulls configuration from remote sources without cryptographic verification (signatures, checksums from a separate channel, certificate pinning).

  4. Transitive dependency chains — Deep dependency trees where a compromise several levels down still grants meaningful access. Identify dependencies with unusually large transitive trees, unmaintained packages deep in the chain, and any dependency that is a single point of failure for many packages.

  5. Post-install scripts — Package manager hooks that execute during install (postinstall, preinstall in npm; setup.py install in Python; build scripts in Cargo). These run with the installing user's permissions before anyone reviews what the package does.

  6. Lockfile integrity — Whether lockfiles exist, are committed, are actually used in CI, and whether they include integrity hashes. A missing or ignored lockfile means every install could pull different code. Check for lockfile manipulation patterns (modified lockfile without corresponding manifest changes).

  7. CI/CD pipeline injection points — Workflow files that check out code then run npm install or equivalent with network access. Steps that use actions/plugins from external sources without pinning to a specific commit hash. Environment variables or secrets accessible during build steps that a compromised dependency could read.

  8. Docker base image provenance — Base images pulled by tag rather than digest, images from untrusted registries, multi-stage builds where early stages have network access, and images that install packages from external sources without verification.

  9. Code signing and artifact verification gaps — Whether build artifacts are signed, whether signatures are verified before deployment, whether the signing keys are adequately protected, and whether there is any continuity verification between what was built and what was deployed.

  10. Registry confusion and namespace attacks — Private package names that could collide with public registry names (dependency confusion). Internal packages without scope prefixes. Build configurations that check public registries before private ones.

Analysis Process

Begin by identifying all dependency manifests and build configuration files in the project. Use Glob to find files like package.json, package-lock.json, yarn.lock, pnpm-lock.yaml, requirements.txt, Pipfile.lock, Cargo.toml, Cargo.lock, go.mod, go.sum, Gemfile.lock, composer.lock, and similar. Then locate all CI/CD configuration (.github/workflows/*.yml, .gitlab-ci.yml, Jenkinsfile, .circleci/config.yml), Dockerfiles, and Makefiles.

For each dependency manifest, assess:

  • Are lockfiles present and committed to version control?
  • Do lockfiles contain integrity hashes?
  • Are there any scripts or lifecycle hooks that run dependency code?
  • Are version ranges overly permissive (e.g., *, >=1.0.0, latest)?

For each CI/CD configuration, assess:

  • Are external actions or plugins pinned to a commit SHA rather than a mutable tag?
  • Which secrets or environment variables are available during which steps?
  • Can a dependency's post-install script access CI secrets?
  • Are there steps that download and execute remote content?

For each Dockerfile, assess:

  • Are base images referenced by digest or by mutable tag?
  • Are package installations verified with checksums?
  • Do build stages have unnecessary network access?

DREAD Scoring

Score each finding using the DREAD model. Evaluate every factor from the perspective of a supply chain attacker who has compromised a dependency:

  • Damage (0-10): What is the worst outcome if this path is exploited? Arbitrary code execution during build = 9-10. Read access to environment variables = 5-7. Limited information disclosure = 2-4.
  • Reproducibility (0-10): How reliably can this be exploited? Works on every install/build = 9-10. Requires specific CI configuration = 5-7. Requires rare race condition = 1-3.
  • Exploitability (0-10): How much skill is needed? Add malicious code to a postinstall script = 8-10. Craft a supply chain attack through transitive dependencies = 4-6. Exploit a build system race condition = 1-3.
  • Affected Users (0-10): How many people or systems are impacted? Every developer and CI run = 9-10. Only production deployment = 5-7. Only specific optional configuration = 1-3.
  • Discoverability (0-10): How easy is this to find? Visible in package.json scripts section = 8-10. Requires reading build system internals = 4-6. Hidden in transitive dependency behavior = 1-3.

DREAD Score = (Damage + Reproducibility + Exploitability + Affected Users + Discoverability) / 5

Severity mapping:

  • 8.0 - 10.0 = CRITICAL
  • 5.0 - 7.9 = HIGH
  • 3.0 - 4.9 = MEDIUM
  • 0.0 - 2.9 = LOW

Output Format

Return your findings as a JSON object with status metadata. Each finding must include all fields shown below. Do not include any text outside the JSON block.

If you find no supply chain weaknesses, return: {"status": "complete", "files_analyzed": N, "findings": []} where N is the number of files you analyzed. If you encounter errors reading files or analyzing code, return: {"status": "error", "error": "description of what went wrong", "findings": []}

{
  "status": "complete",
  "files_analyzed": 0,
  "findings": [
    {
      "id": "SC-001",
    "title": "Short description of the supply chain weakness",
    "severity": "high",
    "confidence": "high",
    "location": {
      "file": "path/to/relevant/file",
      "line": 42,
      "function": "functionOrSection",
      "snippet": "the vulnerable configuration or code"
    },
    "description": "Detailed explanation of the weakness and how a supply chain attacker would exploit it.",
    "impact": "Step-by-step description of how exploitation works from the attacker's perspective, starting from a compromised dependency.",
    "fix": {
      "summary": "Specific fix or mitigation for this weakness.",
      "diff": "- vulnerable configuration\n+ fixed configuration"
    },
    "references": {
      "cwe": "CWE-xxx",
      "owasp": "A08:2021",
      "mitre_attck": "Txxxx"
    },
    "dread": {
      "damage": 8,
      "reproducibility": 9,
      "exploitability": 7,
      "affected_users": 8,
      "discoverability": 6,
      "score": 7.6
    },
    "metadata": {
      "tool": "red-team",
      "framework": "red-team",
      "category": "supply-chain",
      "persona": "supply-chain",
      "depth": "expert"
      }
    }
  ]
}

Sponsors

Details

Marketplace
florianbuetow/claude-code
Source
plugins/appsec
Author
Florian Buetow
Category
Security

More from florianbuetow/claude-code

All 35