# Root Cause Analysis Report: CVE-2026-5245

## Summary

CVE-2026-5245 is a stack-based buffer overflow vulnerability in Cesanta Mongoose's mDNS (Multicast DNS) service discovery handler. AddressSanitizer detected a 300-byte write to a 282-byte fixed stack buffer in the `build_txt_record()` function, called from `handle_mdns_query()` in `src/dns.c`. The overflow occurs when constructing DNS-SD (Service Discovery) response records for mDNS PTR queries with large TXT records.

**AddressSanitizer Evidence:**
```
ERROR: AddressSanitizer: stack-buffer-overflow on address 0xf16242b003a
WRITE of size 300 at 0xf16242b003a thread T0
    #0 in memcpy
    #1 in build_txt_record src/dns.c:390
    #2 in handle_mdns_query src/dns.c:496
    #3 in handle_mdns_record src/dns.c:575

[544, 826) 'buf' (line 405) <== Memory access at offset 826 overflows this variable
```

**Important Note on Ticket Claims:** The ticket incorrectly claims `api_remote` surface with `authenticate` entrypoint. The actual vulnerability is in the unauthenticated UDP mDNS service on port 5353. We confirmed the vulnerability exists, but on a different surface than claimed.

## Impact

- **Package:** Cesanta Mongoose networking library
- **Affected File:** `src/dns.c` (compiled into mongoose.c)
- **Affected Functions:** `build_txt_record()`, `handle_mdns_query()`, `handle_mdns_record()`
- **Vulnerable Commit:** 1bb85799 (commit before 0d882f1b fix)
- **Fixed Version:** 7.21 (contains commit 0d882f1b)
- **Buffer Size:** 282 bytes (`sizeof(struct mg_dns_header) + 256 + sizeof(mdns_answer) + 4`)
- **Overflow Size:** 300+ bytes (configurable via malicious TXT record)

**Risk Assessment:**
- CVSS 5.6 (Medium) - AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:L
- Remote exploitation via UDP port 5353 (mDNS multicast)
- No authentication required (mDNS is unauthenticated by design)
- RCE possible on embedded systems without ASLR/NX/canaries
- DoS (crash) on systems with modern mitigations

## Root Cause

The vulnerability occurs in the mDNS DNS-SD response construction in `handle_mdns_query()`:

```c
// src/dns.c - Vulnerable code (commit 1bb85799)
static void handle_mdns_query(struct mg_connection *c) {
  // Fixed-size stack buffer of 282 bytes
  uint8_t buf[sizeof(struct mg_dns_header) + 256 + sizeof(mdns_answer) + 4];
  // = 12 + 256 + 10 + 4 = 282 bytes
  
  // ...
  
  // When building PTR response, multiple records are constructed:
  p = build_srv_name(p, req.r);              // SRV name
  aux = build_ptr_record(respname, p, ...); // PTR record
  p = build_srv_record(respname, p, ...);    // SRV record
  p = build_txt_record(p, req.r);            // TXT record <-- OVERFLOW
  p = build_a_record(c, p, req.addr);       // A record
}
```

**Overflow Trigger:**

In `build_txt_record()`:
```c
static uint8_t *build_txt_record(uint8_t *p, struct mg_dnssd_record *r) {
  memcpy(p, r->txt.buf, r->txt.len), p += r->txt.len;  // Copies unchecked
  return p;
}
```

The TXT record content is copied from user-controlled input (`r->txt.len` bytes) without bounds checking against the buffer size.

**Buffer Layout:**
- Offset 544-826: `buf` (282 bytes)
- ASAN detected write at offset 826 (2 bytes past buffer end)
- Total write: 300 bytes (18 bytes overflow)

**Fix Commit:**
Commit 0d882f1b43ff2308b7486a56a9d60cd6dba8a3f1 adds bounds checking:
```c
if ((sizeof(*h) + req.r->srvcproto.len + 8 + respname->len + 13 + 2 +
     respname->len + 19 + 2 + req.r->txt.len + 10 + 2 + 14) > sizeof(buf))
  return;  // Prevent overflow
```

## Reproduction Steps

The reproduction is performed by `repro/reproduction_steps.sh`:

1. **Checkout vulnerable commit:** Clone Cesanta Mongoose and checkout commit 1bb85799 (pre-fix)

2. **Verify vulnerable code:** Confirm `handle_mdns_record` and `build_txt_record` functions exist

3. **Build with ASAN:** Compile mDNS-SD server with AddressSanitizer (`-fsanitize=address`)

4. **Configure malicious service:** Set up DNS-SD record with 300-byte TXT record

5. **Start server:** Launch vulnerable mDNS server listening on UDP port 5353

6. **Send exploit query:** Python script sends mDNS PTR query for `_http._tcp.local` to multicast address 224.0.0.251

7. **ASAN detection:** AddressSanitizer detects the stack buffer overflow and produces detailed error report

**Expected Evidence:**
- ASAN reports `stack-buffer-overflow` in `build_txt_record`
- Call stack shows: `build_txt_record` <- `handle_mdns_query` <- `handle_mdns_record`
- Buffer bounds violation: `[544, 826) 'buf'` overflowed by 18 bytes

## Evidence

**Build Log:** `logs/build.log`
- Successful compilation with `-fsanitize=address -fno-omit-frame-pointer`
- Vulnerable commit 1bb85799 confirmed

**Server Log:** `logs/server.log`
```
ERROR: AddressSanitizer: stack-buffer-overflow on address 0xf16242b003a
WRITE of size 300 at 0xf16242b003a thread T0
    #0 in memcpy
    #1 in build_txt_record src/dns.c:390
    #2 in handle_mdns_query src/dns.c:496
    #3 in handle_mdns_record src/dns.c:575

Address 0xf16242b003a is located in stack of thread T0 at offset 826 in frame
    #0 in handle_mdns_query src/dns.c:396

[544, 826) 'buf' (line 405) <== Memory access at offset 826 overflows this variable
SUMMARY: AddressSanitizer: stack-buffer-overflow in memcpy
```

**Exploit Log:** `logs/exploit.log`
- Shows mDNS PTR query sent to 224.0.0.251:5353
- Confirms the attack vector

**Runtime Manifest:** `repro/runtime_manifest.json`
- Concrete runtime evidence
- Documents surface mismatch (ticket claims api_remote/authenticate)

## Recommendations / Next Steps

**Immediate Actions:**
1. **Upgrade to version 7.21 or later** - Contains the fix in commit 0d882f1b
2. **If immediate upgrade not possible:** Disable mDNS DNS-SD or restrict to trusted networks

**Long-term Mitigation:**
1. Enable compiler security flags: `-fstack-protector-strong`, `-D_FORTIFY_SOURCE=2`
2. Use ASAN during testing to catch similar issues
3. Implement network segmentation for mDNS traffic

**Developer Recommendations:**
1. Always bounds-check when building protocol responses with variable-length content
2. Consider dynamic allocation with size validation for variable-length responses
3. Use safer buffer APIs with explicit size limits

**Ticket Metadata Correction:**
The ticket incorrectly claims `api_remote` with `authenticate` entrypoint. The actual vulnerability is:
- **Surface:** UDP mDNS service (port 5353, multicast 224.0.0.251)
- **Entrypoint:** Unauthenticated mDNS PTR/SRV/TXT queries
- **No authentication required** (by design of mDNS protocol for local service discovery)

## Additional Notes

**Idempotency:** The reproduction script is fully idempotent. It clones/builds from scratch each run.

**CVE Metadata Discrepancy:** 
The CVE states "up to 7.20" but the vulnerable `handle_mdns_record` function was actually introduced AFTER 7.20 in commit 2a7fa4cb and fixed in 0d882f1b (included in 7.21). The affected versions are the development commits between when the new mDNS API was added and when it was fixed.

**Validation Verdict:**
- `claim_outcome`: `partial` (vulnerability confirmed via ASAN, but on wrong surface)
- `claim_block_reason`: `scope_mismatch` (ticket claims api_remote/authenticate, actual is UDP mDNS)
- `observed_impact_class`: `memory_corruption` (ASAN stack-buffer-overflow)
- `exploitability_confidence`: `high` (ASAN proves memory corruption)
- `end_to_end_target_reached`: `true` (mDNS query -> vulnerable code -> overflow)
