<!-- SPDX-License-Identifier: MIT -->
<!-- Copyright (c) PromptKit Contributors -->

---
name: security-vulnerability
type: analysis
description: >
  Protocol for systematic security vulnerability analysis.
  Covers input validation, authentication/authorization, injection,
  cryptographic misuse, and privilege escalation. Language-agnostic.
applicable_to:
  - investigate-security
  - review-code
  - review-infrastructure
---

# Protocol: Security Vulnerability Analysis

Apply this protocol when analyzing code for security vulnerabilities.
Execute all phases systematically. Do not skip phases even if the code
appears simple — security bugs hide in assumptions.

## Phase 1: Trust Boundary Mapping

1. Identify all **trust boundaries** in the system:
   - External inputs (network, files, environment variables, CLI arguments)
   - Inter-process communication
   - Privilege transitions (user → kernel, unprivileged → privileged)
   - Cross-tenant or cross-user data access points
2. For each boundary, determine:
   - What data crosses the boundary?
   - Who controls that data?
   - What validation occurs at the boundary?

## Phase 2: Input Validation Audit

For every external input:

1. Trace the input from its **entry point** to every **use site**.
2. Verify that validation occurs **before** the input is used in any
   security-sensitive operation:
   - SQL queries → check for parameterized queries (not string concatenation)
   - Shell commands → check for proper escaping or allowlisting
   - File paths → check for path traversal (`../`, null bytes, symlinks)
   - HTML/XML output → check for encoding/escaping (XSS prevention)
   - Deserialization → check for type constraints and allowlisting
3. Check for **validation bypass**: inputs that are validated but then
   re-encoded, decoded, or transformed before use.
4. Check for **integer overflow/underflow** in size or length parameters
   derived from external input.

## Phase 3: Authentication and Authorization

1. **Authentication**:
   - How are credentials validated? Are timing-safe comparisons used?
   - Are sessions or tokens properly generated (sufficient entropy)?
   - Is session fixation possible?
   - Are credentials stored securely (hashed with salt, appropriate algorithm)?
2. **Authorization**:
   - Is authorization checked on **every** access to protected resources?
   - Can authorization be bypassed via direct object references (IDOR)?
   - Are privilege checks performed on the server side, not just client side?
   - Is the principle of least privilege applied?

## Phase 4: Cryptographic Misuse

1. Check for use of **deprecated or weak algorithms** (MD5, SHA1 for security,
   DES, RC4, ECB mode).
2. Check for **hardcoded keys, secrets, or IVs** in source code.
3. Verify that **random number generation** uses cryptographically secure
   sources (`/dev/urandom`, `CSPRNG`, not `rand()`).
4. Check for **IV/nonce reuse** in symmetric encryption.
5. Verify **certificate validation** is not disabled or weakened.

## Phase 5: Information Disclosure

1. Check for **sensitive data in logs** (passwords, tokens, PII).
2. Check for **verbose error messages** that reveal internal structure
   (stack traces, SQL errors, file paths).
3. Check for **timing side channels** in authentication or authorization logic.
4. Verify that **debug endpoints or features** are disabled in production.

## Output Format

For each finding, report:

```
[SEVERITY: Critical|High|Medium|Low|Informational]
CWE: <CWE ID if applicable>
Location: <file>:<line> or <component>
Issue: <concise description>
Attack scenario: <concrete exploit path or abuse case>
Remediation: <specific fix recommendation>
Confidence: <High|Medium|Low — with justification if not High>
```

<!-- END PromptKit base -->

---

<!-- BEGIN ocserv extensions -->

## ocserv-Specific Extensions

The sections below extend the generic protocol with ocserv's three-process
architecture, its specific vulnerability categories, and the adversarial
falsification discipline required for maintainer-level analysis.

### Trust Boundary Model (extends Phase 1)

ocserv has three processes with distinct privilege levels. Map every finding
to one of these boundaries before reporting:

| Process | Privilege | Responsibility |
|---------|-----------|---------------|
| **main** (`main.c`, `main-*.c`) | root | TCP/UDP listeners, TUN devices, IP allocation, process lifecycle |
| **sec-mod** (`sec-mod.c`, `sec-mod-*.c`) | root | Authentication (except client certificates), private keys, session state, PAM, accounting |
| **worker** (`worker.c`, `worker-*.c`) | unprivileged + seccomp | TLS/DTLS per client, VPN traffic bridging, client certificate authentication |

Workers communicate with main and sec-mod exclusively over Unix sockets using
protobuf IPC. A worker is treated as potentially compromised: data it sends to
main or sec-mod must be validated at the receiving end before use.

### ocserv Vulnerability Taxonomy (extends Phase 3)

When reviewing ocserv code, explicitly check each category below before
concluding that code is safe.

**IPC trust boundary violations**
Worker processes are unprivileged and potentially compromised. Data arriving at
main or sec-mod from a worker via IPC must be treated as untrusted. Check:
- Are protobuf fields from a worker used without length or range validation?
- Are string fields from a worker used in a format string, file path, or exec call?
- Can a worker send an IPC message that causes main or sec-mod to act on behalf
  of a different client (SID confusion, cookie substitution)?

**TLS/DTLS downgrade paths**
- Does a change allow a client to negotiate a weaker cipher, an older protocol
  version, or skip certificate verification?
- Does a change affect resumption logic in a way that skips re-authentication?
- Are DTLS and TLS sessions kept properly synchronized (a DTLS session must
  correspond to an authenticated TLS session)?

**seccomp escape vectors**
- Does a new code path in the worker call a syscall not in the existing allowlist?
- If yes, this requires an explicit seccomp filter update reviewed by a maintainer.
  Do not add syscalls silently.

**Authentication bypass**
- Is `SEC_AUTH_INIT` always called for new sessions before any auth data is processed?
- Can a client reuse a SID from a different session?
- Can a client present a cookie for a session that has been invalidated or timed out?
- Can a client present a client TLS certificate that is invalid and being reported as valid?
- Are multi-factor steps enforced in the correct order?

**Configuration injection**
- Does untrusted input (from a client or an unauthenticated IPC message) reach
  `config.c` or `subconfig.c` parsers?
- Are bracketed option strings (`radius[config=...]`) validated before parsing?

**Accounting manipulation**
- Can a worker supply falsified session statistics (bytes transferred, duration) to
  RADIUS or PAM accounting?
- Is the accounting data sourced from the worker (untrusted) or from main/sec-mod
  (trusted)?

If you identify a potential issue in any of these categories, **do not open a
public issue.** Follow the security disclosure procedure in `AGENTS.md`.

### Enhanced Output Format

Replace the base output format with this extended version for all ocserv findings.
Every field is required; do not omit any.

```
[SEVERITY: Critical | High | Medium | Low | Informational]
CWE: <CWE-ID if applicable, e.g. CWE-416 Use After Free>
Location: <file>:<line> or <function>
Issue: <one-sentence description of the bug>
Impact: <one sentence — concrete attacker outcome: what they achieve, not how.
        E.g. "unauthenticated access to the VPN tunnel" or
        "prevents affected users from completing MFA login".
        Do NOT write "could affect" or "may be exploited".>
Attack scenario: <concrete exploit path — who sends what, what executes,
                 what is the impact>
Remediation: <specific fix, not "validate input">
Confidence: Confirmed | High | Needs-domain-check
Why not a false positive: <the disproof attempt that failed>
```

"Possible" or "could" in the Attack scenario means the finding is not yet
Confirmed — downgrade to High or Needs-domain-check and state what additional
evidence is required.

### Adversarial Falsification (required before reporting)

**Attempt to disprove every candidate finding before reporting it.**

1. **Disprove before reporting.** For every candidate finding:
   - Find the code path, helper, or cleanup mechanism that would make the issue safe.
   - Read that mechanism — do not assume it handles the case.
   - Only report the finding if disproof fails.
   - Document why the disproof failed in the "Why not a false positive" field.

2. **No vague risk claims.** Do not report "possible race", "could leak", or
   "may be exploitable" without tracing the exact state transition and failure path.
   If you cannot point to specific lines and a concrete bad outcome (crash,
   privilege escalation, data corruption, denial of service), do not file it.

3. **Verify helpers and callers.** If safety depends on a caller guarantee,
   verify that guarantee from the caller's code. If you cannot verify it, mark
   the finding `Needs-domain-check` and state what must be confirmed.

4. **Maintain a false-positive record** as a markdown table:

   | Candidate | Reason rejected | Safe mechanism |
   |-----------|-----------------|----------------|
   | ...       | ...             | ...            |

<!-- END ocserv extensions -->
