diff --git a/.github/workflows/claude-full-security-scan.yml b/.github/workflows/claude-full-security-scan.yml index 0d1b99ee..789d1bbc 100644 --- a/.github/workflows/claude-full-security-scan.yml +++ b/.github/workflows/claude-full-security-scan.yml @@ -1,16 +1,42 @@ -name: Claude Full Codebase Security Scan +name: Claude Codebase Security Scan on: workflow_dispatch: inputs: - prompt_path: - description: "Path to the repo prompt file Claude should read" - required: true - default: "resources/specs/claude-security-scan.md" target_ref: description: "Branch, tag, or SHA to scan" required: false default: "" + common_misc: + description: "Run common/misc security scan" + required: false + type: boolean + default: true + mongoose_core: + description: "Run Mongoose core security scan" + required: false + type: boolean + default: true + web_http_auth: + description: "Run web/HTTP/auth security scan" + required: false + type: boolean + default: true + tls: + description: "Run TLS security scan" + required: false + type: boolean + default: true + net_builtin: + description: "Run built-in network security scan" + required: false + type: boolean + default: true + protocols: + description: "Run protocol security scan" + required: false + type: boolean + default: true #schedule: # Weekly scan: Sunday 02:00 UTC # - cron: "0 2 * * 0" @@ -20,53 +46,140 @@ permissions: id-token: write concurrency: - group: claude-full-codebase-security-scan-${{ github.ref }} + group: claude-security-scans cancel-in-progress: false + queue: max jobs: - scan: - name: Full codebase security scan + prepare: + name: Prepare selected scan matrix runs-on: ubuntu-latest - timeout-minutes: 60 - env: - DEFAULT_PROMPT_PATH: "resources/specs/claude-security-scan.md" + outputs: + target_ref: ${{ steps.plan.outputs.target_ref }} + matrix: ${{ steps.plan.outputs.matrix }} + has_scans: ${{ steps.plan.outputs.has_scans }} steps: - - name: Resolve scan inputs - id: vars + - name: Resolve scan inputs and build matrix + id: plan shell: bash run: | + set -euo pipefail + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then - PROMPT_PATH="${{ inputs.prompt_path }}" TARGET_REF="${{ inputs.target_ref }}" + RUN_COMMON_MISC="${{ inputs.common_misc }}" + RUN_MONGOOSE_CORE="${{ inputs.mongoose_core }}" + RUN_WEB_HTTP_AUTH="${{ inputs.web_http_auth }}" + RUN_TLS="${{ inputs.tls }}" + RUN_NET_BUILTIN="${{ inputs.net_builtin }}" + RUN_PROTOCOLS="${{ inputs.protocols }}" else - PROMPT_PATH="${DEFAULT_PROMPT_PATH}" TARGET_REF="" + RUN_COMMON_MISC="true" + RUN_MONGOOSE_CORE="true" + RUN_WEB_HTTP_AUTH="true" + RUN_TLS="true" + RUN_NET_BUILTIN="true" + RUN_PROTOCOLS="true" fi if [ -z "$TARGET_REF" ]; then TARGET_REF="${{ github.ref }}" fi - echo "prompt_path=$PROMPT_PATH" >> "$GITHUB_OUTPUT" - echo "target_ref=$TARGET_REF" >> "$GITHUB_OUTPUT" + MATRIX="$(jq -cn \ + --arg common_misc "$RUN_COMMON_MISC" \ + --arg mongoose_core "$RUN_MONGOOSE_CORE" \ + --arg web_http_auth "$RUN_WEB_HTTP_AUTH" \ + --arg tls "$RUN_TLS" \ + --arg net_builtin "$RUN_NET_BUILTIN" \ + --arg protocols "$RUN_PROTOCOLS" \ + '{ + include: ([ + { + enabled: ($common_misc == "true"), + area: "common_misc", + display_name: "Common / Misc", + area_prompt: "resources/specs/areas/common_misc.md" + }, + { + enabled: ($mongoose_core == "true"), + area: "mongoose_core", + display_name: "Mongoose Core", + area_prompt: "resources/specs/areas/mongoose_core.md" + }, + { + enabled: ($web_http_auth == "true"), + area: "web_http_auth", + display_name: "Web / HTTP / Auth", + area_prompt: "resources/specs/areas/web_http_auth.md" + }, + { + enabled: ($tls == "true"), + area: "tls", + display_name: "TLS", + area_prompt: "resources/specs/areas/tls.md" + }, + { + enabled: ($net_builtin == "true"), + area: "net_builtin", + display_name: "Built-In Network", + area_prompt: "resources/specs/areas/net_builtin.md" + }, + { + enabled: ($protocols == "true"), + area: "protocols", + display_name: "Protocols", + area_prompt: "resources/specs/areas/protocols.md" + } + ] | map(select(.enabled)) | map(del(.enabled))) + }' + )" + HAS_SCANS="$(jq -r '.include | length > 0' <<< "$MATRIX")" + + echo "target_ref=$TARGET_REF" >> "$GITHUB_OUTPUT" + echo "matrix=$MATRIX" >> "$GITHUB_OUTPUT" + echo "has_scans=$HAS_SCANS" >> "$GITHUB_OUTPUT" + + scan: + name: ${{ matrix.display_name }} security scan + needs: prepare + if: needs.prepare.outputs.has_scans == 'true' + runs-on: ubuntu-latest + timeout-minutes: 60 + + strategy: + fail-fast: false + max-parallel: 1 + matrix: ${{ fromJSON(needs.prepare.outputs.matrix) }} + + env: + MASTER_PROMPT_PATH: "resources/specs/claude-security-scan.md" + FILTERING_PROMPT_PATH: "resources/specs/claude-false-positive-filtering.md" + SCAN_AREA: ${{ matrix.area }} + AREA_PROMPT_PATH: ${{ matrix.area_prompt }} + + steps: - name: Checkout repository uses: actions/checkout@v6 with: - ref: ${{ steps.vars.outputs.target_ref }} + ref: ${{ needs.prepare.outputs.target_ref }} fetch-depth: 0 - - name: Verify prompt file exists + - name: Verify required prompt files exist shell: bash run: | - test -f "${{ steps.vars.outputs.prompt_path }}" || { - echo "Prompt file not found: ${{ steps.vars.outputs.prompt_path }}" - exit 1 - } + for prompt_file in "$MASTER_PROMPT_PATH" "$AREA_PROMPT_PATH" "$FILTERING_PROMPT_PATH"; do + test -f "$prompt_file" || { + echo "Required prompt file not found: $prompt_file" + exit 1 + } + done - - name: Run Claude full codebase security scan + - name: Run Claude ${{ matrix.display_name }} security scan id: claude_scan uses: anthropics/claude-code-action@v1 timeout-minutes: 30 @@ -75,19 +188,21 @@ jobs: prompt: | REPO: ${{ github.repository }} - REF: ${{ steps.vars.outputs.target_ref }} - PROMPT_FILE: ${{ steps.vars.outputs.prompt_path }} + REF: ${{ needs.prepare.outputs.target_ref }} + MASTER_PROMPT_FILE: ${{ env.MASTER_PROMPT_PATH }} + SCAN_AREA: ${{ matrix.area }} + AREA_PROMPT_FILE: ${{ matrix.area_prompt }} + FILTERING_PROMPT_FILE: ${{ env.FILTERING_PROMPT_PATH }} - You are running a full-codebase security scan in GitHub Actions. + You are running a focused security scan for the assigned area in GitHub Actions. - First, read the main prompt file at: - ${{ steps.vars.outputs.prompt_path }} + First, read the master prompt at ${{ env.MASTER_PROMPT_PATH }}. + Then read the assigned area prompt at ${{ matrix.area_prompt }}. + Read the false-positive filtering prompt at ${{ env.FILTERING_PROMPT_PATH }} as required by the master prompt. - Treat that file as the authoritative security-review instruction set. You will also - read and analyze additional prompt files mentioned in the main prompt file by their absolute paths in the repo, - as per the instructions found in it. + Perform the security review for the ${{ matrix.area }} area. Follow relevant supporting code when necessary, but do not independently scan unrelated areas. + Return only the JSON required by the master prompt. - Scan the checked-out repository as a whole codebase. Do not modify files. Do not create commits. Do not open pull requests. @@ -106,8 +221,8 @@ jobs: set -u mkdir -p private-scan-results TODAY="$(date -u +%Y%m%d)" - EXECUTION_OUTPUT_FILE="claude-execution-output_${TODAY}.json" - FINDINGS_FILE="security-findings_${TODAY}.json" + EXECUTION_OUTPUT_FILE="claude-execution-output_${SCAN_AREA}_${TODAY}.json" + FINDINGS_FILE="security-findings_${SCAN_AREA}_${TODAY}.json" HAS_EXECUTION_OUTPUT="false" HAS_JSON_FINDINGS="false" @@ -177,5 +292,5 @@ jobs: exit 0 fi - git commit -m "Add security scan results ${{ steps.prepare_outputs.outputs.date_suffix }}" + git commit -m "Add ${SCAN_AREA} security scan results ${{ steps.prepare_outputs.outputs.date_suffix }}" git push diff --git a/resources/specs/areas/common_misc.md b/resources/specs/areas/common_misc.md new file mode 100644 index 00000000..bbf5b1cd --- /dev/null +++ b/resources/specs/areas/common_misc.md @@ -0,0 +1,38 @@ +# Security Scan Area: common_misc + +## Target + +Area: common_misc + +This area covers common utility code, parsing/string/formatting helpers, URL handling, hash/base64 helpers, filesystem backends, little filesystem integration, and flash support. + +Primary files: +- `src/base64.c` +- `src/fmt.c` +- `src/json.c` +- `src/log.c` +- `src/md5.c` +- `src/printf.c` +- `src/sha1.c` +- `src/sha256.c` +- `src/str.c` +- `src/url.c` +- `src/util.c` +- `src/fs*.c` +- `src/lfs.c` +- `src/flash.c` + +Perform a focused security review centered on these files and this security surface. + +Supporting code outside these files may be inspected when necessary to establish reachability, data flow, state, validation, mitigation, or impact, but do not independently review unrelated areas. + +## Area-Specific Security Guidance + +**Filesystem Backends:** +- Review packed filesystem code and filesystem backends for traversal, unauthorized file read/write, overwrite, or truncation. +- Check path canonicalization across POSIX, Windows, embedded filesystems, packed filesystems, and custom `mg_fs` implementations. +- Look for trailing slash confusion, NUL byte truncation, and case sensitivity differences in backend path handling. + +**URL Parsing:** +- Review URL parsing for scheme, host, port, IPv6 literal, userinfo, percent-encoding, embedded NUL, empty host, default port, and path/query boundary confusion. +- Check for SSRF-relevant behavior only when attacker input can control the destination host, protocol, or network boundary. Path-only control is not sufficient. diff --git a/resources/specs/areas/mongoose_core.md b/resources/specs/areas/mongoose_core.md new file mode 100644 index 00000000..867d996e --- /dev/null +++ b/resources/specs/areas/mongoose_core.md @@ -0,0 +1,30 @@ +# Security Scan Area: mongoose_core + +## Target + +Area: mongoose_core + +This area covers the core event/network/connection machinery, iobuf handling, queues, socket transport, timers, and BSD abstraction. + +Primary files: +- `src/event.c` +- `src/iobuf.c` +- `src/net.c` +- `src/queue.c` +- `src/sock.c` +- `src/timer.c` +- `src/bsd.c` + +Perform a focused security review centered on these files and this security surface. + +Supporting code outside these files may be inspected when necessary to establish reachability, data flow, state, validation, mitigation, or impact, but do not independently review unrelated areas. + +## Area-Specific Security Guidance + +**Protocol State Machine and Event-Driven Lifecycle Bugs:** +- Review transitions between listening, accepted, connecting, resolving, TLS handshaking, HTTP, WebSocket, MQTT, draining, closing, and closed states. +- Check whether malformed input can cause protocol handlers to process data in the wrong state, process stale data after close, or invoke callbacks with invalid event data. +- Look for use-after-free or stale pointer use when callbacks call `mg_close_conn`, mark a connection closing, mutate iobufs, change protocol handlers, or initiate TLS/WebSocket/MQTT transitions. +- Verify that partial reads/writes, backpressure, `is_full`, draining, TLS pending states, and send-buffer mutations cannot cause duplicated sends, skipped validation, or parser confusion. +- Review timer and wakeup handling for stale user data pointers, cross-thread queue misuse, and callbacks firing after associated connections/state have been freed. +- Only report concurrency or race issues when a concrete event ordering can trigger memory corruption, unauthorized action, or reliable device/process crash. diff --git a/resources/specs/areas/net_builtin.md b/resources/specs/areas/net_builtin.md new file mode 100644 index 00000000..f849097d --- /dev/null +++ b/resources/specs/areas/net_builtin.md @@ -0,0 +1,26 @@ +# Security Scan Area: net_builtin + +## Target + +Area: net_builtin + +This area covers the built-in TCP/IP stack and its selected L2 implementations. + +Primary files: +- `src/l2_*.c` +- `src/net_builtin.c` + +Perform a focused security review centered on these files and this security surface. + +Supporting code outside these files may be inspected when necessary to establish reachability, data flow, state, validation, mitigation, or impact, but do not independently review unrelated areas. + +## Area-Specific Security Guidance + +**Built-In TCP/IP Stack, Packet Parsing, and Embedded Network Drivers:** +- Review Ethernet, ARP, IP, IPv6, ICMP, UDP, TCP, DHCP, SNTP, and driver receive/transmit paths for packet-length validation before reading protocol headers. +- Check IP/TCP/UDP header length fields, options length, fragmentation/reassembly behavior, checksum handling, and payload offset calculations for underflow, overflow, or out-of-bounds access. +- Look for malformed packets that can corrupt descriptor rings, RX/TX buffers, queue state, ARP tables, connection state, or timers. +- Review interrupt handlers and bare-metal driver code for bounded processing loops. Flag IRQ paths where attacker-controlled traffic can cause livelock, starvation, descriptor ownership loss, or repeated processing of the same malformed frame. +- Check DMA descriptor ownership transitions, memory barriers, cache coherency handling, and buffer length fields for race-like bugs that can cause memory corruption or stale packet reuse. +- Review platform-specific drivers such as STM32, NXP, TI, Microchip, Renesas, Infineon, Wiznet, Cypress WiFi, cellular, and other built-in stack integrations for inconsistent bounds checks or endian conversions. +- Treat a remotely reachable malformed Ethernet/IP/TCP/UDP packet that crashes, wedges, or corrupts an embedded target as reportable. diff --git a/resources/specs/areas/protocols.md b/resources/specs/areas/protocols.md new file mode 100644 index 00000000..8a150850 --- /dev/null +++ b/resources/specs/areas/protocols.md @@ -0,0 +1,38 @@ +# Security Scan Area: protocols + +## Target + +Area: protocols + +This area covers the smaller externally controlled protocol parsers and state machines other than HTTP, WebSocket, and TLS. + +Primary files: +- `src/modbus.c` +- `src/rpc.c` +- `src/sntp.c` +- `src/mqtt.c` +- `src/dns.c` + +Perform a focused security review centered on these files and this security surface. + +Supporting code outside these files may be inspected when necessary to establish reachability, data flow, state, validation, mitigation, or impact, but do not independently review unrelated areas. + +## Area-Specific Security Guidance + +**MQTT Parser and Broker/Client State Machine Vulnerabilities:** +- Review MQTT fixed header parsing, remaining-length decoding, variable-length integer loops, packet identifier handling, QoS transitions, topic extraction, property parsing, and MQTT 3.x vs MQTT 5 differences. +- Look for malformed MQTT packets that can trigger out-of-bounds reads/writes, stack buffer overflow, heap corruption, assertion/crash, or parser desynchronization. +- Specifically check SUBSCRIBE and UNSUBSCRIBE handling for unbounded numbers of topics, malformed topic length fields, missing QoS bytes, invalid QoS values, and writes to fixed-size response arrays. +- Verify that PUBLISH handling enforces topic length, packet length, QoS rules, retained flag handling, packet identifier requirements, and message bounds before accessing fields. +- Check broker examples and protocol handlers for authorization bypass, cross-topic data exposure, wildcard topic mishandling, `$SYS` or reserved topic confusion, and unintended publish/subscribe access. +- Review MQTT reconnect/resubscribe logic for stale connection state, packet identifier reuse bugs, and memory lifetime problems after close/reconnect. +- Treat unauthenticated single-packet broker crash, client crash from malicious broker response, or memory corruption during MQTT parsing as reportable. + +**DNS and mDNS Parsing and Name Resolution:** +- Review DNS and mDNS message parsing for label length validation, compression pointer loops, pointer bounds, recursive expansion limits, integer overflow, malformed resource records, and out-of-bounds reads. +- Check that DNS answers are matched to outstanding requests by transaction ID, question name/type/class, and source expectations where applicable. +- Look for cache poisoning, response spoofing, or name confusion if DNS response validation is weak in client or resolver code. +- Verify that DNS failures, timeouts, and retries cannot leave dangling active request state or corrupt connection state. + +**Modbus, RPC, and SNTP:** +- Review externally controlled lengths, framing, message parsing, and protocol state for malformed peer input that can cause parser desynchronization, state corruption, or a remotely triggerable crash or wedge. diff --git a/resources/specs/areas/tls.md b/resources/specs/areas/tls.md new file mode 100644 index 00000000..0a35f856 --- /dev/null +++ b/resources/specs/areas/tls.md @@ -0,0 +1,43 @@ +# Security Scan Area: tls + +## Target + +Area: tls + +This area covers the complete Mongoose TLS implementation represented by the primary files. + +Primary files: +- `src/tls_aes128.c` +- `src/tls_builtin.c` +- `src/tls_chacha20.c` +- `src/tls_dummy.c` +- `src/tls_mbed.c` +- `src/tls_openssl.c` +- `src/tls_rsa.c` +- `src/tls_uecc.c` +- `src/tls_x25519.c` + +Perform a focused security review centered on these files and this security surface. + +Supporting code outside these files may be inspected when necessary to establish reachability, data flow, state, validation, mitigation, or impact, but do not independently review unrelated areas. + +Connection, core, network, and helper code may be inspected when needed to understand the complete TLS execution path. + +## Area-Specific Security Guidance + +### Mandatory High-Risk Coverage: Built-In TLS + +The built-in TLS implementation (`MG_TLS_BUILTIN`) is a mandatory high-risk review target. Perform a substantial security analysis of all security-relevant built-in TLS code, including parsing, cryptographic processing, authentication and certificate validation, length and buffer handling, protocol state, cross-call behavior, and failure paths. + +Trace attacker-controlled TLS peer input through normal client and server execution, including traffic received before peer authentication is complete. Report any credible memory-safety, authentication, confidentiality, integrity, state-corruption, or remotely triggerable availability vulnerability. + +**TLS, Certificate, Hostname Verification, and Cryptographic Validation:** +- Review all TLS backends, including built-in TLS, mbedTLS, OpenSSL, WolfSSL, and custom TLS integration, for equivalent security behavior where possible. +- Flag certificate verification bypasses, accidental `skip_verification` use in security-sensitive examples or defaults, missing hostname verification when `name`/SNI is available, or inconsistent validation across TLS backends. +- For hostname verification, check wildcard handling carefully. A wildcard certificate identity must not match multiple DNS labels. For example, `*.example.com` must not match `a.b.example.com`. +- Verify that wildcard matching is applied only to certificate presented identifiers, not to arbitrary reference identifiers or general DNS glob matching. +- Review `mg_match` or other glob/matching helpers if used for certificate identity checks, authorization checks, filesystem paths, routing, or topic matching. Flag cases where glob semantics are broader than the security policy requires. +- Check certificate parsing for DER/PEM boundary errors, length overflows, malformed ASN.1, extension parsing mistakes, name constraints, SAN vs CN precedence, embedded NUL, and invalid string type handling. +- Review TLS record parsing, handshake transcript handling, key schedule, random generation, ECC/X25519 operations, AES-GCM nonce/tag handling, and error handling for memory safety and authentication failures. +- Flag any behavior that silently falls back from verified TLS to unverified TLS or plaintext. +- Check that TLS receive/send error paths cannot corrupt connection state, reuse freed buffers, or continue processing unauthenticated plaintext as encrypted data. diff --git a/resources/specs/areas/web_http_auth.md b/resources/specs/areas/web_http_auth.md new file mode 100644 index 00000000..855ce252 --- /dev/null +++ b/resources/specs/areas/web_http_auth.md @@ -0,0 +1,62 @@ +# Security Scan Area: web_http_auth + +## Target + +Area: web_http_auth + +This area covers HTTP parsing and framing, HTTP-facing filesystem behavior, SSI, WebSocket, authentication/token/dashboard code, and HTTP-based OTA behavior. + +Primary files: +- `src/http.c` +- `src/ssi.c` +- `src/ws.c` +- `src/jwt.c` +- `src/dash.c` +- `src/ota.c` + +Perform a focused security review centered on these files and this security surface. + +Supporting code outside these files may be inspected when necessary to establish reachability, data flow, state, validation, mitigation, or impact, but do not independently review unrelated areas. + +For OTA behavior, follow operations into TLS, flash, filesystem, JSON, URL, or other support code when necessary, while keeping the review centered on the `web_http_auth` surface. + +## Area-Specific Security Guidance + +**HTTP Parser, Request Smuggling, and Message Framing:** +- Verify that HTTP requests or responses containing both `Content-Length` and `Transfer-Encoding` are rejected or handled in a way that cannot cause front-end/back-end desynchronization. Treat CL+TE coexistence as security-relevant request smuggling risk. +- Verify that duplicate `Content-Length`, duplicate `Transfer-Encoding`, conflicting transfer codings, malformed chunk sizes, chunk extensions, premature EOF, and body length mismatches cannot cause inconsistent body parsing. +- Check whether HTTP/1.0, HTTP/1.1, and malformed protocol versions alter CL/TE handling unsafely. A message with both `Content-Length` and `Transfer-Encoding` should not be accepted merely because of version differences. +- Look for parsing paths where headers are normalized differently from later lookup paths, including case folding, whitespace around colon, obs-fold/line folding, embedded NUL, duplicate headers, or partial header names. +- Review URL decoding, query parsing, multipart parsing, upload handling, range handling, and chunked responses for bounds mistakes, truncation, or inconsistent decoded-vs-raw path decisions. +- Check static file serving and SSI handling for path traversal through percent-encoding, double decoding, backslashes on Windows, mixed separators, dot-dot segments, absolute paths, drive letters, symlinks, embedded NUL, or alias/root_dir confusion. +- Review HTTP authentication helper paths for parsing ambiguities in Basic auth, header extraction, credential truncation, empty username/password acceptance, or incorrect comparison behavior. +- Check that HTTP upgrade to WebSocket validates method, headers, key, version, and connection semantics consistently before switching protocol state. + +**WebSocket Framing and Upgrade Vulnerabilities:** +- Review WebSocket frame parsing for extended payload length handling, 16-bit/64-bit length conversion, masking rules, fragmentation, continuation frames, control-frame length limits, close/ping/pong handling, and compression-related assumptions if present. +- Check that client-to-server frames require masking and that malformed mask/payload boundaries cannot read or write out of bounds. +- Look for state-machine confusion after HTTP upgrade, especially where partial frames, fragmented messages, or mixed HTTP/WebSocket bytes can cause parser desynchronization. +- Check whether large or malformed frame lengths can cause integer overflow, memory corruption, uncontrolled allocation, connection lockup, or single-connection/device crash. +- Verify that WebSocket message APIs preserve attacker-controlled binary data length correctly and do not pass non-null-terminated payloads to C-string functions. + +**HTTP-Facing Filesystem Serving, Uploads, and SSI:** +- Review `mg_http_serve_dir`, `mg_http_serve_file`, upload APIs, and SSI expansion for traversal, unauthorized file read/write, overwrite, truncation, or unexpected executable/include behavior. +- Look for inconsistent handling of decoded and undecoded paths, double decoding, query string leakage into path, trailing slash confusion, NUL byte truncation, and case sensitivity differences. +- Review multipart upload parsing for boundary confusion, filename traversal, field length overflow, partial-write behavior, and max-size enforcement. +- Check SSI include handling for directory escape, recursive include loops, unintended disclosure of local files, and parsing of attacker-controlled SSI directives. +- Verify that range requests and static response headers cannot cause out-of-bounds reads or disclose memory. + +**OTA/Firmware Update and Device Dashboard Security:** +- Review firmware update endpoints and examples for missing authentication, authorization bypass, path confusion, arbitrary write, unsafe flash offset/length handling, and failure to verify firmware authenticity where the code claims secure update behavior. +- Check update chunk parsing for integer overflow, flash boundary crossing, rollback/downgrade exposure, incomplete image bootability, and crash/power-loss unsafe state transitions. +- Flag any code path where unauthenticated network input can write firmware, configuration, filesystem contents, flash pages, bootloader state, or device identity material. +- Review device dashboard examples for security-sensitive default routes, credentials, upload handlers, debug endpoints, config mutation endpoints, and CORS/header behavior when they are likely to be copied into production. +- Do not report ordinary insecure demo behavior unless it creates a realistic copy-paste production vulnerability or affects library code. + +**Authentication, Authorization, and Access-Control Patterns in Mongoose Integrations:** +- Review examples and helper APIs that implement HTTP auth, cookies, sessions, tokens, device dashboards, REST APIs, upload endpoints, and firmware update endpoints. +- Flag authentication bypasses caused by prefix route matching, glob matching, decoded-vs-raw URI confusion, case normalization mistakes, missing boundary checks, or default-open sensitive endpoints. +- Check for authorization decisions made in client-side JavaScript only. Client-side checks are not security boundaries. +- Review CORS and origin checks only when they protect credentialed sensitive operations and the exploit path is concrete. +- Look for credential comparison bugs, truncation of usernames/passwords, accepting empty credentials, parsing only part of an Authorization header, or treating malformed credentials as anonymous-but-authorized. +- Flag sensitive data exposure when secrets, credentials, tokens, private keys, firmware signing material, PII, or device identity values can be read by unauthorized remote clients or logged from attacker-triggered paths. diff --git a/resources/specs/claude-pr-security-review.md b/resources/specs/claude-pr-security-review.md index 09a79eac..83e75b25 100644 --- a/resources/specs/claude-pr-security-review.md +++ b/resources/specs/claude-pr-security-review.md @@ -6,19 +6,30 @@ Perform a security-focused code review to identify HIGH-CONFIDENCE security vuln This is not a general code review - focus ONLY on security implications newly added by this PR. Do not comment on existing security concerns. -For this task, you will rely on two additional files, `resources/specs/claude-security-scan-instructions.md` detailing security scan instructions specific to the repository and `resources/specs/claude-false-positive-filtering.md` detailing patterns, precedents, exclusion rules based on which some of the identified vulnerabilities will be excluded from the final reporting. The instructions, rules and criterias found in those two files are MANDATORY TO BE HONOURED and your security audit will have to take all of them into account. +For this task, you will rely on the specified shared security-review sections in `resources/specs/claude-security-scan.md`, the specified security-guidance sections in the six `resources/specs/areas/*.md` prompts listed below, and `resources/specs/claude-false-positive-filtering.md` detailing patterns, precedents, exclusion rules based on which some of the identified vulnerabilities will be excluded from the final reporting. The instructions, rules and criterias found in those referenced sections and the filtering file are MANDATORY TO BE HONOURED and your security audit will have to take all of them into account. -YOU MUST READ AND ANALYZE BOTH OF THESE FILES BEFORE COMMENCING THE SECURITY AUDIT. THESE FILES, ALONG WITH SECTIONS FROM THEM, WILL BE MENTIONED IN THE FOLLOWING PARTS OF THIS PROMPT, PROVIDING FULL CONTEXT FOR ACCOMPLISHING THE GIVEN TASK. +YOU MUST READ AND ANALYZE THE SPECIFIED SECTIONS AND THE FILTERING FILE BEFORE COMMENCING THE SECURITY AUDIT. THESE SOURCES WILL BE MENTIONED IN THE FOLLOWING PARTS OF THIS PROMPT, PROVIDING FULL CONTEXT FOR ACCOMPLISHING THE GIVEN TASK. # CRITICAL INSTRUCTIONS 1. MINIMIZE FALSE POSITIVES: Only flag issues where you're >80% confident of actual exploitability 2. AVOID NOISE: Skip theoretical issues, style concerns, or low-impact findings -3. UNDERSTANDING CONTEXT AND SCOPE OF REVIEW: In the security scan instructions file `resources/specs/claude-security-scan-instructions.md`, read the `External Attacker Threat Model` and `Mongoose-Specific Security Review Scope` subsections found in the `SECURITY SCAN CONTEXT` main section for a full understanding of the scanning model, code review context and the perspective from which the scanning is going to take place. +3. UNDERSTANDING CONTEXT AND SCOPE OF REVIEW: In `resources/specs/claude-security-scan.md`, read only the `External Attacker Threat Model` and `Mongoose-Specific Security Review Scope` subsections found in the `SECURITY SCAN CONTEXT` main section for a full understanding of the scanning model, code review context and the perspective from which the scanning is going to take place. Do not apply unrelated full-scan instructions from that file. In particular, do not inherit assigned-area scan scope, full-scan JSON output requirements, full-scan `review_completed` semantics, instructions to scan long-standing code independently of the PR, or area-selection workflow behavior. This PR prompt's scope, methodology, validation, and output rules remain authoritative. 4. TREAT EXCLUSIONS AS MANDATORY. The exclusions section below is mandatory. If a potential finding falls under an exclusion, do not report it. If a finding partially overlaps an exclusion, only report it if there is a concrete, non-excluded security impact. # SECURITY CATEGORIES TO EXAMINE -In the security scan instructions file `resources/specs/claude-security-scan-instructions.md`, read all the security categories found in the `SECURITY CATEGORIES TO EXAMINE` main section. THESE ARE THE SECURITY CATEGORIES WHICH NEED TO BE EXAMINED. +Read the general/common security categories in the `GENERAL SECURITY CATEGORIES TO EXAMINE` section of `resources/specs/claude-security-scan.md`. + +Also read the `Area-Specific Security Guidance` section from every area prompt: + +* `resources/specs/areas/common_misc.md` +* `resources/specs/areas/mongoose_core.md` +* `resources/specs/areas/web_http_auth.md` +* `resources/specs/areas/tls.md` +* `resources/specs/areas/net_builtin.md` +* `resources/specs/areas/protocols.md` + +Use only the security guidance from the area prompts and ignore their full-scan-specific `Target` sections. Consider the complete set of common and area-specific security categories regardless of which source files the PR modifies. Do not choose one area or make this PR review area-scoped. Review the PR diff and report only security vulnerabilities introduced by that PR. Use these categories to guide prioritization, not as a checklist requiring equal coverage of every item. @@ -112,4 +123,4 @@ Read the `HARD EXCLUSIONS` section found in the `resources/specs/claude-false-po Begin your analysis now. Use the repository exploration tools to understand the codebase context, then analyze the PR changes for security implications. -Your final action must be posting the PR comment. You should not reply again after posting the PR comment. \ No newline at end of file +Your final action must be posting the PR comment. You should not reply again after posting the PR comment. diff --git a/resources/specs/claude-security-scan-instructions.md b/resources/specs/claude-security-scan-instructions.md deleted file mode 100644 index 68f645f0..00000000 --- a/resources/specs/claude-security-scan-instructions.md +++ /dev/null @@ -1,130 +0,0 @@ -# SECURITY SCAN CONTEXT - -**External Attacker Threat Model:** -- Analyze vulnerabilities from the perspective of an external attacker, not from the perspective of a developer, local user, debugger, test harness, or code running inside the process. -- The attacker can provide bytes through real external interfaces exposed by Mongoose or a Mongoose-based application: TCP, UDP, HTTP, WebSocket, MQTT, DNS, mDNS, TLS handshakes/certificates, Ethernet/IP/TCP/UDP packets, uploaded files, request paths, query strings, headers, message bodies, malicious server responses, and other protocol inputs. -- The attacker cannot directly call internal C functions, pass arbitrary invalid pointers, mutate internal structs, invoke callbacks manually, edit compile-time macros, alter build flags, write to hardware registers, control DMA descriptors directly, attach a debugger, or run code inside the target process. -- For a finding to be valid, show how attacker-controlled external input reaches the vulnerable code path through normal library/application execution. -- Do not report findings that require impossible internal states unless the finding also explains how an external input can cause that state. -- Do not report “API misuse” as a library vulnerability unless the API contract makes the insecure use likely, undocumented, or unavoidable. -- For embedded networking and driver code, assume the attacker can send malformed network traffic to the device, but cannot directly manipulate hardware registers, memory-mapped I/O, DMA rings, or interrupt state except as a consequence of packets processed by the driver. - -**Mongoose-Specific Security Review Scope:** -- Treat this repository as a security-sensitive embedded C/C++ networking stack. Mongoose processes attacker-controlled bytes from TCP, UDP, HTTP, WebSocket, MQTT, DNS, mDNS, TLS, filesystem upload/download paths, and built-in TCP/IP drivers. -- In this repository, remotely triggerable denial of service is security-relevant when it is caused by a concrete implementation flaw such as memory corruption, parser abort, assertion failure, stack exhaustion, infinite loop, unbounded recursion, IRQ livelock, connection state corruption, descriptor-ring corruption, or a single unauthenticated packet causing process/device crash. -- Prioritize HIGH and MEDIUM severity findings. Include LOW only when unusually concrete, externally relevant, and useful. Do not report vague robustness concerns. Every finding must identify the attacker-controlled input, affected parser/state machine/buffer, concrete impact, and the exact code path. -- Prefer findings with a plausible packet/request/message shape. For network protocol issues, describe the relevant malformed HTTP request, MQTT packet, WebSocket frame, DNS message, TLS handshake/certificate input, Ethernet/IP/TCP/UDP packet, or filesystem request. -- Because this is C/C++, memory safety vulnerabilities are in scope. Buffer overflows, stack overflows, heap overflows, out-of-bounds reads/writes, use-after-free, double free, integer overflow leading to memory corruption, invalid pointer lifetime, and unsafe length conversions must be reviewed carefully. -- Do not dismiss issues merely because they are “only DoS” if the issue is remotely triggerable against an embedded server, broker, device dashboard, firmware-update endpoint, or network-facing parser. - -# SECURITY CATEGORIES TO EXAMINE - -## Mandatory High-Risk Coverage: Built-In TLS - -The built-in TLS implementation (`MG_TLS_BUILTIN`) is a mandatory high-risk review target. Perform a substantial security analysis of all security-relevant built-in TLS code, including parsing, cryptographic processing, authentication and certificate validation, length and buffer handling, protocol state, cross-call behavior, and failure paths. - -Trace attacker-controlled TLS peer input through normal client and server execution, including traffic received before peer authentication is complete. Report any credible memory-safety, authentication, confidentiality, integrity, state-corruption, or remotely triggerable availability vulnerability. - -Do not set `review_completed` to `true` unless the built-in TLS implementation has been meaningfully inspected as a whole. - - -**C Memory Safety and Length-Handling Vulnerabilities:** -- Look for writes to fixed-size stack or heap buffers where the loop bound is derived from attacker-controlled protocol fields, including topic counts, header counts, chunk counts, multipart parts, DNS labels, WebSocket fragments, TCP/IP options, or filesystem path components. -- Check all conversions between `size_t`, `int`, `long`, `uint16_t`, `uint32_t`, and signed protocol lengths. Flag integer truncation, wraparound, negative-to-large conversion, or off-by-one behavior that can affect allocation, parsing, copying, or bounds checks. -- Review any `memcpy`, `memmove`, `memcmp`, `snprintf`, `mg_snprintf`, `mg_xprintf`, iobuf append/delete/resize operation, and manual pointer increment where source length can originate from network input. -- Treat `struct mg_str` values as non-null-terminated unless the code proves otherwise. Flag use of `strlen`, `%s`, `strcmp`, `strstr`, or C-string APIs on attacker-controlled `mg_str.buf` unless length and termination are guaranteed. -- Check for parser code that advances pointers without proving that enough bytes remain. Flag any read of fixed-size fields, variable-length integers, DNS labels, TLS vectors, MQTT remaining length, WebSocket extended lengths, or HTTP chunks before bounds are validated. -- Look for inconsistent ownership and lifetime of buffers referenced by `mg_str`, connection receive/send iobufs, TLS buffers, filesystem buffers, and event callback data. -- Check for reentrancy hazards in event callbacks where user handlers may close a connection, mutate iobufs, start TLS, change protocol handlers, or free state while protocol code continues using stale pointers. - -**HTTP Parser, Request Smuggling, and Message Framing:** -- Verify that HTTP requests or responses containing both `Content-Length` and `Transfer-Encoding` are rejected or handled in a way that cannot cause front-end/back-end desynchronization. Treat CL+TE coexistence as security-relevant request smuggling risk. -- Verify that duplicate `Content-Length`, duplicate `Transfer-Encoding`, conflicting transfer codings, malformed chunk sizes, chunk extensions, premature EOF, and body length mismatches cannot cause inconsistent body parsing. -- Check whether HTTP/1.0, HTTP/1.1, and malformed protocol versions alter CL/TE handling unsafely. A message with both `Content-Length` and `Transfer-Encoding` should not be accepted merely because of version differences. -- Look for parsing paths where headers are normalized differently from later lookup paths, including case folding, whitespace around colon, obs-fold/line folding, embedded NUL, duplicate headers, or partial header names. -- Review URL decoding, query parsing, multipart parsing, upload handling, range handling, and chunked responses for bounds mistakes, truncation, or inconsistent decoded-vs-raw path decisions. -- Check static file serving and SSI handling for path traversal through percent-encoding, double decoding, backslashes on Windows, mixed separators, dot-dot segments, absolute paths, drive letters, symlinks, embedded NUL, or alias/root_dir confusion. -- Review HTTP authentication helper paths for parsing ambiguities in Basic auth, header extraction, credential truncation, empty username/password acceptance, or incorrect comparison behavior. -- Check that HTTP upgrade to WebSocket validates method, headers, key, version, and connection semantics consistently before switching protocol state. - -**MQTT Parser and Broker/Client State Machine Vulnerabilities:** -- Review MQTT fixed header parsing, remaining-length decoding, variable-length integer loops, packet identifier handling, QoS transitions, topic extraction, property parsing, and MQTT 3.x vs MQTT 5 differences. -- Look for malformed MQTT packets that can trigger out-of-bounds reads/writes, stack buffer overflow, heap corruption, assertion/crash, or parser desynchronization. -- Specifically check SUBSCRIBE and UNSUBSCRIBE handling for unbounded numbers of topics, malformed topic length fields, missing QoS bytes, invalid QoS values, and writes to fixed-size response arrays. -- Verify that PUBLISH handling enforces topic length, packet length, QoS rules, retained flag handling, packet identifier requirements, and message bounds before accessing fields. -- Check broker examples and protocol handlers for authorization bypass, cross-topic data exposure, wildcard topic mishandling, `$SYS` or reserved topic confusion, and unintended publish/subscribe access. -- Review MQTT reconnect/resubscribe logic for stale connection state, packet identifier reuse bugs, and memory lifetime problems after close/reconnect. -- Treat unauthenticated single-packet broker crash, client crash from malicious broker response, or memory corruption during MQTT parsing as reportable. - -**WebSocket Framing and Upgrade Vulnerabilities:** -- Review WebSocket frame parsing for extended payload length handling, 16-bit/64-bit length conversion, masking rules, fragmentation, continuation frames, control-frame length limits, close/ping/pong handling, and compression-related assumptions if present. -- Check that client-to-server frames require masking and that malformed mask/payload boundaries cannot read or write out of bounds. -- Look for state-machine confusion after HTTP upgrade, especially where partial frames, fragmented messages, or mixed HTTP/WebSocket bytes can cause parser desynchronization. -- Check whether large or malformed frame lengths can cause integer overflow, memory corruption, uncontrolled allocation, connection lockup, or single-connection/device crash. -- Verify that WebSocket message APIs preserve attacker-controlled binary data length correctly and do not pass non-null-terminated payloads to C-string functions. - -**TLS, Certificate, Hostname Verification, and Cryptographic Validation:** -- Review all TLS backends, including built-in TLS, mbedTLS, OpenSSL, WolfSSL, and custom TLS integration, for equivalent security behavior where possible. -- Flag certificate verification bypasses, accidental `skip_verification` use in security-sensitive examples or defaults, missing hostname verification when `name`/SNI is available, or inconsistent validation across TLS backends. -- For hostname verification, check wildcard handling carefully. A wildcard certificate identity must not match multiple DNS labels. For example, `*.example.com` must not match `a.b.example.com`. -- Verify that wildcard matching is applied only to certificate presented identifiers, not to arbitrary reference identifiers or general DNS glob matching. -- Review `mg_match` or other glob/matching helpers if used for certificate identity checks, authorization checks, filesystem paths, routing, or topic matching. Flag cases where glob semantics are broader than the security policy requires. -- Check certificate parsing for DER/PEM boundary errors, length overflows, malformed ASN.1, extension parsing mistakes, name constraints, SAN vs CN precedence, embedded NUL, and invalid string type handling. -- Review TLS record parsing, handshake transcript handling, key schedule, random generation, ECC/X25519 operations, AES-GCM nonce/tag handling, and error handling for memory safety and authentication failures. -- Flag any behavior that silently falls back from verified TLS to unverified TLS or plaintext. -- Check that TLS receive/send error paths cannot corrupt connection state, reuse freed buffers, or continue processing unauthenticated plaintext as encrypted data. - -**DNS, mDNS, URL Parsing, and Name Resolution:** -- Review DNS and mDNS message parsing for label length validation, compression pointer loops, pointer bounds, recursive expansion limits, integer overflow, malformed resource records, and out-of-bounds reads. -- Check that DNS answers are matched to outstanding requests by transaction ID, question name/type/class, and source expectations where applicable. -- Look for cache poisoning, response spoofing, or name confusion if DNS response validation is weak in client or resolver code. -- Review URL parsing for scheme, host, port, IPv6 literal, userinfo, percent-encoding, embedded NUL, empty host, default port, and path/query boundary confusion. -- Check for SSRF-relevant behavior only when attacker input can control the destination host, protocol, or network boundary. Path-only control is not sufficient. -- Verify that DNS failures, timeouts, and retries cannot leave dangling active request state or corrupt connection state. - -**Built-In TCP/IP Stack, Packet Parsing, and Embedded Network Drivers:** -- Review Ethernet, ARP, IP, IPv6, ICMP, UDP, TCP, DHCP, SNTP, and driver receive/transmit paths for packet-length validation before reading protocol headers. -- Check IP/TCP/UDP header length fields, options length, fragmentation/reassembly behavior, checksum handling, and payload offset calculations for underflow, overflow, or out-of-bounds access. -- Look for malformed packets that can corrupt descriptor rings, RX/TX buffers, queue state, ARP tables, connection state, or timers. -- Review interrupt handlers and bare-metal driver code for bounded processing loops. Flag IRQ paths where attacker-controlled traffic can cause livelock, starvation, descriptor ownership loss, or repeated processing of the same malformed frame. -- Check DMA descriptor ownership transitions, memory barriers, cache coherency handling, and buffer length fields for race-like bugs that can cause memory corruption or stale packet reuse. -- Review platform-specific drivers such as STM32, NXP, TI, Microchip, Renesas, Infineon, Wiznet, Cypress WiFi, cellular, and other built-in stack integrations for inconsistent bounds checks or endian conversions. -- Treat a remotely reachable malformed Ethernet/IP/TCP/UDP packet that crashes, wedges, or corrupts an embedded target as reportable. - -**Filesystem Serving, Uploads, Packed Filesystems, and SSI:** -- Review `mg_http_serve_dir`, `mg_http_serve_file`, upload APIs, packed filesystem code, and SSI expansion for traversal, unauthorized file read/write, overwrite, truncation, or unexpected executable/include behavior. -- Check path canonicalization across POSIX, Windows, embedded filesystems, packed filesystems, and custom `mg_fs` implementations. -- Look for inconsistent handling of decoded and undecoded paths, double decoding, query string leakage into path, trailing slash confusion, NUL byte truncation, and case sensitivity differences. -- Review multipart upload parsing for boundary confusion, filename traversal, field length overflow, partial-write behavior, and max-size enforcement. -- Check SSI include handling for directory escape, recursive include loops, unintended disclosure of local files, and parsing of attacker-controlled SSI directives. -- Verify that range requests and static response headers cannot cause out-of-bounds reads or disclose memory. - -**OTA/Firmware Update and Device Dashboard Security:** -- Review firmware update endpoints and examples for missing authentication, authorization bypass, path confusion, arbitrary write, unsafe flash offset/length handling, and failure to verify firmware authenticity where the code claims secure update behavior. -- Check update chunk parsing for integer overflow, flash boundary crossing, rollback/downgrade exposure, incomplete image bootability, and crash/power-loss unsafe state transitions. -- Flag any code path where unauthenticated network input can write firmware, configuration, filesystem contents, flash pages, bootloader state, or device identity material. -- Review device dashboard examples for security-sensitive default routes, credentials, upload handlers, debug endpoints, config mutation endpoints, and CORS/header behavior when they are likely to be copied into production. -- Do not report ordinary insecure demo behavior unless it creates a realistic copy-paste production vulnerability or affects library code. - -**Protocol State Machine and Event-Driven Lifecycle Bugs:** -- Review transitions between listening, accepted, connecting, resolving, TLS handshaking, HTTP, WebSocket, MQTT, draining, closing, and closed states. -- Check whether malformed input can cause protocol handlers to process data in the wrong state, process stale data after close, or invoke callbacks with invalid event data. -- Look for use-after-free or stale pointer use when callbacks call `mg_close_conn`, mark a connection closing, mutate iobufs, change protocol handlers, or initiate TLS/WebSocket/MQTT transitions. -- Verify that partial reads/writes, backpressure, `is_full`, draining, TLS pending states, and send-buffer mutations cannot cause duplicated sends, skipped validation, or parser confusion. -- Review timer and wakeup handling for stale user data pointers, cross-thread queue misuse, and callbacks firing after associated connections/state have been freed. -- Only report concurrency or race issues when a concrete event ordering can trigger memory corruption, unauthorized action, or reliable device/process crash. - -**Cross-Platform C Portability With Security Impact:** -- Review code paths whose security depends on struct packing, alignment, endianness, pointer size, signedness of `char`, integer width, or platform-specific filesystem/network behavior. -- Check for unaligned memory access on embedded targets when parsing attacker-controlled network packets. -- Verify endian conversions for Ethernet/IP/TCP/UDP/DNS/MQTT/TLS fields before bounds checks and allocations. -- Look for platform branches where one backend performs validation and another does not, especially across UNIX, Windows, lwIP, Zephyr, FreeRTOS-like systems, bare-metal, and built-in TCP/IP stack modes. -- Flag portability bugs only when they create a realistic vulnerability on a supported platform, not merely theoretical undefined behavior. - -**Authentication, Authorization, and Access-Control Patterns in Mongoose Integrations:** -- Review examples and helper APIs that implement HTTP auth, cookies, sessions, tokens, device dashboards, REST APIs, MQTT topic access, upload endpoints, and firmware update endpoints. -- Flag authentication bypasses caused by prefix route matching, glob matching, decoded-vs-raw URI confusion, case normalization mistakes, missing boundary checks, or default-open sensitive endpoints. -- Check for authorization decisions made in client-side JavaScript only. Client-side checks are not security boundaries. -- Review CORS and origin checks only when they protect credentialed sensitive operations and the exploit path is concrete. -- Look for credential comparison bugs, truncation of usernames/passwords, accepting empty credentials, parsing only part of an Authorization header, or treating malformed credentials as anonymous-but-authorized. -- Flag sensitive data exposure when secrets, credentials, tokens, private keys, firmware signing material, PII, or device identity values can be read by unauthorized remote clients or logged from attacker-triggered paths. diff --git a/resources/specs/claude-security-scan.md b/resources/specs/claude-security-scan.md index e4a9c2f3..bc853d34 100644 --- a/resources/specs/claude-security-scan.md +++ b/resources/specs/claude-security-scan.md @@ -1,24 +1,32 @@ -# Full Codebase Security Scan Prompt +# Security Scan Master Prompt -You are an expert security reviewer performing a full-codebase security audit of the checked-out repository. +You are an expert security reviewer performing a focused security audit centered on one assigned scan area in the checked-out repository. -You must analyze the repository as a whole and identify credible, externally reachable security vulnerabilities in the current implementation. +You must analyze the assigned target and security surface and identify credible, externally reachable security vulnerabilities in the current implementation. -For this task, you will rely on two additional files, `resources/specs/claude-security-scan-instructions.md` detailing security scan instructions specific to the repository and `resources/specs/claude-false-positive-filtering.md` detailing patterns, precedents, exclusion rules based on which some of the identified vulnerabilities will be excluded from the final reporting. The instructions, rules and criterias found in those two files are MANDATORY TO BE HONOURED and your security audit will have to take all of them into account. +Every full security scan uses: -YOU MUST READ AND ANALYZE BOTH OF THESE FILES BEFORE COMMENCING THE SECURITY AUDIT. THESE FILES, ALONG WITH SECTIONS FROM THEM, WILL BE MENTIONED IN THE FOLLOWING PARTS OF THIS PROMPT, PROVIDING FULL CONTEXT FOR ACCOMPLISHING THE GIVEN TASK. +1. the shared master prompt: `resources/specs/claude-security-scan.md`; +2. one area prompt selected by the workflow: `resources/specs/areas/.md`; +3. the common filtering prompt: `resources/specs/claude-false-positive-filtering.md`. + +The area prompt defines what is being scanned. This master prompt defines how security analysis and reporting are performed. The filtering prompt defines what must not be reported and which historical precedents must be honored. + +YOU MUST READ AND ANALYZE THE ASSIGNED AREA PROMPT AND THE COMMON FILTERING PROMPT BEFORE COMMENCING THE SECURITY AUDIT. THE INSTRUCTIONS, RULES, AND CRITERIA IN ALL THREE PROMPTS ARE MANDATORY TO BE HONORED. ## OBJECTIVE -You are reviewing a full source repository for security vulnerabilities. +You are reviewing one assigned security area in a source repository for security vulnerabilities. The repository may contain application code, protocol parsers, networking code, embedded code, library code, examples, tests, build scripts, documentation, generated files, and third-party/vendor code. -Your task is to determine which parts of the repository are security-relevant, identify externally reachable attack surfaces, and report only findings with a concrete vulnerability pattern, credible attacker influence, and meaningful security impact. +The area-specific prompt defines the primary files and security surface for this invocation. Your task is to identify externally reachable attack surfaces within that assigned area and report only findings with a concrete vulnerability pattern, credible attacker influence, and meaningful security impact. + +You may inspect code outside the listed target files when that code is necessary to understand data flow, reachability, call chains, state transitions, memory ownership, mitigations, authentication or authorization, protocol interaction, exploitability, or impact. Inspecting supporting code must not turn into an independent security review of unrelated areas. Findings must remain tied to the assigned target and security surface. DO NOT modify files, create commits, open PRs, create issues or post comments! You must only produce the final JSON report requested below. -Identify high-confidence security vulnerabilities in the full codebase. For this prompt, high-confidence means confidence >= 0.7 under the scoring rules below. Focus on vulnerabilities that are reachable through normal execution paths and attacker-controlled inputs. Report only findings that have a concrete security impact. +Identify high-confidence security vulnerabilities in the assigned scan area. For this prompt, high-confidence means confidence >= 0.7 under the scoring rules below. Focus on vulnerabilities that are reachable through normal execution paths and attacker-controlled inputs. Report only findings that have a concrete security impact. Do not report vague best-practice concerns, speculative hardening suggestions, style issues, maintainability concerns, generic bug risks, or findings without a clear attacker-controlled path. @@ -26,9 +34,26 @@ Existing vulnerabilities in the current codebase are in scope. Previously introduced vulnerabilities are in scope. -Any security-relevant issue present in the checked-out repository is in scope unless explicitly excluded below. +Any security-relevant issue tied to the assigned target or security surface is in scope unless explicitly excluded below. -In the security scan instructions file `resources/specs/claude-security-scan-instructions.md`, read the `External Attacker Threat Model` and `Mongoose-Specific Security Review Scope` subsections found in the `SECURITY SCAN CONTEXT` main section for a full understanding of the scanning model and the code review context. +## SECURITY SCAN CONTEXT + +**External Attacker Threat Model:** +- Analyze vulnerabilities from the perspective of an external attacker, not from the perspective of a developer, local user, debugger, test harness, or code running inside the process. +- The attacker can provide bytes through real external interfaces exposed by Mongoose or a Mongoose-based application: TCP, UDP, HTTP, WebSocket, MQTT, DNS, mDNS, TLS handshakes/certificates, Ethernet/IP/TCP/UDP packets, uploaded files, request paths, query strings, headers, message bodies, malicious server responses, and other protocol inputs. +- The attacker cannot directly call internal C functions, pass arbitrary invalid pointers, mutate internal structs, invoke callbacks manually, edit compile-time macros, alter build flags, write to hardware registers, control DMA descriptors directly, attach a debugger, or run code inside the target process. +- For a finding to be valid, show how attacker-controlled external input reaches the vulnerable code path through normal library/application execution. +- Do not report findings that require impossible internal states unless the finding also explains how an external input can cause that state. +- Do not report “API misuse” as a library vulnerability unless the API contract makes the insecure use likely, undocumented, or unavoidable. +- For embedded networking and driver code, assume the attacker can send malformed network traffic to the device, but cannot directly manipulate hardware registers, memory-mapped I/O, DMA rings, or interrupt state except as a consequence of packets processed by the driver. + +**Mongoose-Specific Security Review Scope:** +- Treat this repository as a security-sensitive embedded C/C++ networking stack. Mongoose processes attacker-controlled bytes from TCP, UDP, HTTP, WebSocket, MQTT, DNS, mDNS, TLS, filesystem upload/download paths, and built-in TCP/IP drivers. +- In this repository, remotely triggerable denial of service is security-relevant when it is caused by a concrete implementation flaw such as memory corruption, parser abort, assertion failure, stack exhaustion, infinite loop, unbounded recursion, IRQ livelock, connection state corruption, descriptor-ring corruption, or a single unauthenticated packet causing process/device crash. +- Prioritize HIGH and MEDIUM severity findings. Include LOW only when unusually concrete, externally relevant, and useful. Do not report vague robustness concerns. Every finding must identify the attacker-controlled input, affected parser/state machine/buffer, concrete impact, and the exact code path. +- Prefer findings with a plausible packet/request/message shape. For network protocol issues, describe the relevant malformed HTTP request, MQTT packet, WebSocket frame, DNS message, TLS handshake/certificate input, Ethernet/IP/TCP/UDP packet, or filesystem request. +- Because this is C/C++, memory safety vulnerabilities are in scope. Buffer overflows, stack overflows, heap overflows, out-of-bounds reads/writes, use-after-free, double free, integer overflow leading to memory corruption, invalid pointer lifetime, and unsafe length conversions must be reviewed carefully. +- Do not dismiss issues merely because they are “only DoS” if the issue is remotely triggerable against an embedded server, broker, device dashboard, firmware-update endpoint, or network-facing parser. ## CRITICAL INSTRUCTIONS @@ -56,12 +81,14 @@ Do not report: * Purely defensive hardening suggestions. * Issues that only matter under unrealistic assumptions. -### 3. Analyze the repository as a whole +### 3. Analyze the assigned scan area -This is a full-codebase scan. You should inspect the repository structure, identify major components, and prioritize security-sensitive code paths. +This is a targeted scan centered on the primary files and security surface defined by the assigned area prompt. Follow relevant supporting code when necessary to establish reachability, data flow, state, validation, mitigation, exploitability, or impact, but do not independently review unrelated areas. Do not restrict analysis to a diff. Do not assume only changed files matter. Do not assume an issue is irrelevant because it appears in old or long-standing code. +Findings must remain tied to the assigned target and security surface. + ### 4. Prioritize externally reachable attack surfaces Prioritize code reachable from attacker-controlled or peer-controlled inputs. Relevant inputs may include, but are not limited to: @@ -94,19 +121,35 @@ The exclusions section below is mandatory. If a potential finding falls under an If a finding partially overlaps an exclusion, only report it if there is a concrete, non-excluded security impact. -## SECURITY CATEGORIES TO EXAMINE +## GENERAL SECURITY CATEGORIES TO EXAMINE -In the security scan instructions file `resources/specs/claude-security-scan-instructions.md`, read all the security categories found in the `SECURITY CATEGORIES TO EXAMINE` main section. THESE ARE THE SECURITY CATEGORIES WHICH NEED TO BE EXAMINED. +The following common security categories apply to every assigned scan area. The assigned area prompt provides additional area-specific security guidance. Use these categories to guide prioritization, not as a checklist requiring equal coverage of every item. +**C Memory Safety and Length-Handling Vulnerabilities:** +- Look for writes to fixed-size stack or heap buffers where the loop bound is derived from attacker-controlled protocol fields, including topic counts, header counts, chunk counts, multipart parts, DNS labels, WebSocket fragments, TCP/IP options, or filesystem path components. +- Check all conversions between `size_t`, `int`, `long`, `uint16_t`, `uint32_t`, and signed protocol lengths. Flag integer truncation, wraparound, negative-to-large conversion, or off-by-one behavior that can affect allocation, parsing, copying, or bounds checks. +- Review any `memcpy`, `memmove`, `memcmp`, `snprintf`, `mg_snprintf`, `mg_xprintf`, iobuf append/delete/resize operation, and manual pointer increment where source length can originate from network input. +- Treat `struct mg_str` values as non-null-terminated unless the code proves otherwise. Flag use of `strlen`, `%s`, `strcmp`, `strstr`, or C-string APIs on attacker-controlled `mg_str.buf` unless length and termination are guaranteed. +- Check for parser code that advances pointers without proving that enough bytes remain. Flag any read of fixed-size fields, variable-length integers, DNS labels, TLS vectors, MQTT remaining length, WebSocket extended lengths, or HTTP chunks before bounds are validated. +- Look for inconsistent ownership and lifetime of buffers referenced by `mg_str`, connection receive/send iobufs, TLS buffers, filesystem buffers, and event callback data. +- Check for reentrancy hazards in event callbacks where user handlers may close a connection, mutate iobufs, start TLS, change protocol handlers, or free state while protocol code continues using stale pointers. + +**Cross-Platform C Portability With Security Impact:** +- Review code paths whose security depends on struct packing, alignment, endianness, pointer size, signedness of `char`, integer width, or platform-specific filesystem/network behavior. +- Check for unaligned memory access on embedded targets when parsing attacker-controlled network packets. +- Verify endian conversions for Ethernet/IP/TCP/UDP/DNS/MQTT/TLS fields before bounds checks and allocations. +- Look for platform branches where one backend performs validation and another does not, especially across UNIX, Windows, lwIP, Zephyr, FreeRTOS-like systems, bare-metal, and built-in TCP/IP stack modes. +- Flag portability bugs only when they create a realistic vulnerability on a supported platform, not merely theoretical undefined behavior. + ## ANALYSIS METHODOLOGY Follow this methodology before producing the final JSON. ### Phase 1: Repository context research -First, understand the repository. +First, understand the assigned area in repository context. Identify: @@ -121,13 +164,13 @@ Identify: * Memory management patterns. * Platform-specific code. * Example, test, fuzz, generated, and vendor directories. -* Components most likely to process attacker-controlled input. +* Components in the assigned area most likely to process attacker-controlled input. Use repository files to infer the actual architecture instead of assuming a generic web application model. ### Phase 2: Attack surface mapping -Map the externally reachable attack surfaces. +Map the externally reachable attack surfaces within the assigned area. For each important surface, determine: @@ -166,6 +209,7 @@ Before including any finding in the final output, confirm: * The severity matches the impact. * The finding is not a duplicate of another finding. * The finding is not excluded. +* The finding is tied to the assigned target or security surface. If you cannot provide this level of specificity, do not report the finding. @@ -218,6 +262,8 @@ The value of `files_reviewed` should reflect the number of files substantially i Do not inflate this number by counting files that were only listed or briefly skimmed. +The value `review_completed: true` means the assigned scan area was meaningfully reviewed, not that the entire repository was reviewed. + ## SEVERITY GUIDELINES Use these severity definitions. @@ -336,4 +382,4 @@ Do not include commentary. Do not reply again after outputting the JSON. -Begin the full-codebase security analysis now. +Begin the assigned-area security analysis now.