From eb08c5abf5a9f7750f65585db51e91f2276d1b03 Mon Sep 17 00:00:00 2001 From: hyperpolymath <6759885+hyperpolymath@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:54:55 +0000 Subject: [PATCH 1/2] fix: the eleven verified findings from the second review cycle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Twelve more findings were raised over the merged milestone-1 tree; each was verified against the code as merged before being touched. Eleven are fixed here, and the security ones carry a regression test confirmed to fail without the fix. 127 tests, up from 123. Security: * An unsigned negative answer's SOA owner is unauthenticated data, and computeZoneStatus, nameStatus and proveDenial each used it to pick the zone for the insecurity check guarded only by an ancestry test. With an anchor between the hinted zone and the target, an ancestor's insecurity says nothing about the anchored subtree below it, so a forged SOA could dispose of a negative answer inside a secure island with no proof at all. All three now apply the closest-anchor refusal the RRSIG signer check already used. Test: "a forged SOA owner cannot reach over a closer island anchor", confirmed to fail against the merged validator. * usableDs dropped SHA-1 when anything stronger was present but left SHA-256 and SHA-384 both usable, so keysFromDs took whichever matched first and a child could be accepted through the weaker digest - the downgrade RFC 4509 §3 forbids, extended to SHA-384 by RFC 6605 §5. Only the strongest supported digest class present is kept now. * readRr sized every record's expansion buffer at rdlen + 4*255, opaque types included. ~5,950 minimal 11-octet RRs fit in one 65535-octet message, so an untrusted upstream turned each into ~6 MB of arena, and Session.fetch caches every fetched message: hundreds of MB per validation at the default budget. Headroom now comes from the layout's real name count, zero for opaque types. * dnssec-stub exited 1 - the status it documents as "insecure" - for every setup and I/O failure, because an error escaping main becomes exit 1. Those are mapped to the documented 4. Correctness: * A `. DS` NODATA was always bogus/denial_missing: strict-parent asks for a proper ancestor of the target and the root has none, so the root's own authenticated proof was discarded. * Negative answers below a proven-insecure delegation are now also bounded by min(SOA record TTL, SOA MINIMUM), and by zero with no cacheable SOA (RFC 2308 §5); previously only the DS/NSEC proof lifetime applied. * formatRr emitted "(256-octet key)" for DNSKEY and "(types)" for the NSEC/NSEC3 bitmaps - neither is RDATA, and both the CLI and the C ABI promise presentation format. DNSKEY now emits base64, the bitmaps are enumerated as mnemonics, and an oversized key falls back to RFC 3597 generic form for the whole RDATA. My first attempt wrote the flags before that decision and produced "256 3 8 \# 2048 ...", which is neither form; the new test caught it. * parseTtl accumulated compound TTLs in plain u64 and overflowed before its range check; accumulation is checked and bails as soon as u32 cannot hold the sum. parseRrsigTime accepted impossible dates (every month ran to day 31) and daysFromCivil normalised them, so 20230231 became a March timestamp; the day is validated against the month and both century rules. * build.zig.zon excluded tests/, so `zig build test` in a package fetched through the package manager failed on missing sources while the step was still advertised. * `just crg-grade` / `crg-badge` could never run: just does not treat `$$` as an escape and passes it to the shell, where `$$` is the PID, so `grade=$$(grep ...)` was a bash syntax error. They use `$` now and read docs/status/READINESS.adoc, which is where this repo keeps its assessment (they read READINESS.md, which does not exist here, and returned the fallback grade for the wrong reason). The upstream contractile copy carries the same defect. Not fixed, with reasons: the deed's parent-pin names a commit that no longer exists upstream so check-variant-drift.sh cannot run; base-image digest pinning and the container stages' user model are left to the estate-wide pinning decision, unverifiable from here; and the negative-cache-TTL bound has no test because no fixture has an SOA MINIMUM below its own proof's TTL. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- CHANGELOG.adoc | 76 +++++++++++++ Justfile | 18 ++-- build.zig.zon | 5 + docs/reports/VERIFICATION.adoc | 14 ++- src/cli/dnssec-stub.zig | 14 +++ src/dnssec/validator.zig | 86 +++++++++++++-- src/wire/message.zig | 20 +++- src/wire/rdata.zig | 24 +++++ src/wire/text.zig | 188 ++++++++++++++++++++++++++++++++- tests/replay.zig | 53 ++++++++++ 10 files changed, 469 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index 3b48424a..7e7cf13e 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -87,6 +87,82 @@ attacker-influenced data. * `build/container/Containerfile`: the `crosscheck` target's `CMD` chained `servers.sh stop` with `;`, so its exit status masked the cross-check's. +A second review cycle, over the merged milestone-1 tree, raised twelve more +findings. Eleven are fixed here; each is verified against the code as merged, +and the security ones carry a regression test that was confirmed to fail +without the fix (127 tests, up from 123). + +* *Security:* an unsigned negative answer's SOA owner is unauthenticated data, + and three paths used it to choose which zone got the insecurity check, + guarded only by an ancestry test. Ancestry is not enough: with an anchor + between the hinted zone and the target, the insecurity of an ancestor says + nothing about the anchored subtree below it, so a forged SOA could dispose + of a negative answer inside a secure island with no proof at all. + `computeZoneStatus`, `nameStatus` and `proveDenial` now apply the same + closest-anchor refusal the RRSIG signer check uses. +* *Security:* `usableDs` dropped SHA-1 when any stronger digest was present + but left SHA-256 and SHA-384 both usable, so `keysFromDs` accepted + whichever matched first and a child could be accepted through the weaker + digest — the downgrade RFC 4509 §3 forbids, extended to SHA-384 by RFC 6605 + §5. Only the strongest supported digest class present is now kept. +* *Work amplification:* `readRr` sized every record's expansion buffer at + `rdlen + 4 * 255`, including opaque types whose RDATA cannot grow at all. + About 5,950 minimal 11-octet RRs fit in one 65535-octet message, so an + untrusted upstream turned each message into ~6 MB of arena; `Session.fetch` + caches every fetched message, so one validation at the default budget could + hold hundreds of MB. The headroom now comes from the layout's actual name + count (no supported layout has more than two), and is zero for opaque types. +* `dnssec-stub` exited 1 — the status it documents as "insecure" — for every + setup and I/O failure, because an error escaping `main` becomes exit 1. A + missing `--anchors` file, an unparseable trust anchor, a refused `http://` + `--doh` URL, a bad `--ca` or an unwritable `--record` file each reported a + proven-insecure verdict to any script or harness reading the status. Those + are now mapped to the documented 4. +* `formatRr` emitted `(256-octet key)` for a DNSKEY and `(types)` for the + NSEC/NSEC3 bitmaps. Neither is RDATA, and both the CLI and the C ABI promise + presentation-format answer records. DNSKEY now emits base64 (RFC 4034 §2.2) + and the bitmaps are enumerated as mnemonics; a key too large for the stack + buffer falls back to RFC 3597 generic form for the whole RDATA. +* A `. DS` NODATA was always `bogus`/`denial_missing`: the strict-parent rule + asks for a signer that is a proper ancestor of the target, and the root has + none, so the root's own authenticated NSEC/SOA proof was discarded. At the + root the signer can only be the root itself. +* A negative answer below a proven-insecure delegation was bounded only by the + denial proof's lifetime, ignoring the SOA negative TTL, so a forged NXDOMAIN + could be cached for the much longer DS/NSEC lifetime (RFC 2308 §5). It is + now also bounded by min(SOA record TTL, SOA MINIMUM), and by zero when the + response supplies no cacheable SOA. +* `parseTtl` accumulated compound TTLs in plain `u64`, so a long enough + sequence such as repeated `4294967295w` overflowed before the final range + check: a panic in Debug and ReleaseSafe, and a wrapped, wrongly small TTL + otherwise, from the public zone parser. Accumulation is checked and bails as + soon as the sum cannot fit `u32`. +* `parseRrsigTime` accepted impossible calendar dates — every month ran to + day 31 — and `daysFromCivil` normalised rather than failed, so + `20230231000000` was encoded as a March timestamp. The day is now validated + against the month and both century leap-year rules. +* `build.zig.zon` shipped only `build.zig`, `build.zig.zon` and `src`, so + `zig build test` in a package fetched through the Zig package manager failed + on missing sources: the `test` step was advertised but its inputs under + `tests/` and `tests/testdata/` were excluded. `tests` is now in `.paths`. +* `just crg-grade` and `just crg-badge` could never run. `just` does not treat + `$$` as an escape — it passes both octets to the shell, where `$$` is the PID + — so `grade=$$(grep …)` was a bash syntax error and the recipes exited 2. + They now use `$`, and read `docs/status/READINESS.adoc`, which is where this + repo keeps its assessment; they previously read `READINESS.md`, which does + not exist here, and so returned the fallback grade for the wrong reason. The + same defect is in the upstream contractile copy. + +Not fixed in this cycle, with reasons rather than silence: the deed's +`:parent-pin` / `:template-commit` names a commit that no longer exists in +`hyperpolymath/rsr-template-repo`, so `check-variant-drift.sh` cannot be run +at all (see `docs/reports/VERIFICATION.adoc`); base-image digest pinning and +the container build stages' user model are left to the estate-wide pinning +decision because no registry or container engine is reachable from here to +verify either; and the negative-cache-TTL bound above has no test, because no +recorded fixture has an SOA MINIMUM below its own denial proof's TTL, so the +bound never binds in the corpus. + ==== Changed * `scripts/validate-template.sh` now honours the repo deed's diff --git a/Justfile b/Justfile index e1a9d8ef..ba68cfc2 100644 --- a/Justfile +++ b/Justfile @@ -186,18 +186,18 @@ crg-grade: @# not the template's READINESS.md; reading only the latter silently reported @# the fallback grade for the wrong reason. AsciiDoc bold is `*Current Grade:*`, @# Markdown bold is `**Current Grade:**`, so both spellings are matched. - @f="docs/status/READINESS.adoc"; [ -f "$$f" ] || f="READINESS.md"; \ - grade=$$(grep -oP '\*+Current Grade:\*+\s*\K[A-FX]' "$$f" 2>/dev/null | head -1); \ - [ -z "$$grade" ] && grade="X"; \ - echo "$$grade" + @f="docs/status/READINESS.adoc"; [ -f "$f" ] || f="READINESS.md"; \ + grade=$(grep -oP '\*+Current Grade:\*+\s*\K[A-FX]' "$f" 2>/dev/null | head -1); \ + [ -z "$grade" ] && grade="X"; \ + echo "$grade" # Print a shields.io CRG badge for embedding in README files # Looks for '**Current Grade:** X' in READINESS.md; falls back to X crg-badge: - @f="docs/status/READINESS.adoc"; [ -f "$$f" ] || f="READINESS.md"; \ - grade=$$(grep -oP '\*+Current Grade:\*+\s*\K[A-FX]' "$$f" 2>/dev/null | head -1); \ - [ -z "$$grade" ] && grade="X"; \ - case "$$grade" in \ + @f="docs/status/READINESS.adoc"; [ -f "$f" ] || f="READINESS.md"; \ + grade=$(grep -oP '\*+Current Grade:\*+\s*\K[A-FX]' "$f" 2>/dev/null | head -1); \ + [ -z "$grade" ] && grade="X"; \ + case "$grade" in \ A) color="brightgreen" ;; \ B) color="green" ;; \ C) color="yellow" ;; \ @@ -206,7 +206,7 @@ crg-badge: F) color="critical" ;; \ *) color="lightgrey" ;; \ esac; \ - echo "[![CRG $$grade](https://img.shields.io/badge/CRG-$$grade-$$color?style=flat-square)](https://github.com/hyperpolymath/standards/tree/main/component-readiness-grades)" + echo "[![CRG $grade](https://img.shields.io/badge/CRG-$grade-$color?style=flat-square)](https://github.com/hyperpolymath/standards/tree/main/component-readiness-grades)" # Run the full merge-requirement test suite (ALL categories) # Per STANDING rule: P2P + E2E + aspect + execution + lifecycle + bench diff --git a/build.zig.zon b/build.zig.zon index ef5fc6cb..89fc5bfb 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -72,6 +72,11 @@ "build.zig", "build.zig.zon", "src", + // `build.zig` advertises a `test` step whose modules live under tests/ + // and embed files from tests/testdata/. Without this, `zig build test` + // in a package fetched through the Zig package manager fails on missing + // sources: the step is advertised but its inputs are not shipped. + "tests", // For example... //"LICENSE", //"README.md", diff --git a/docs/reports/VERIFICATION.adoc b/docs/reports/VERIFICATION.adoc index bcd55586..2f20e8ea 100644 --- a/docs/reports/VERIFICATION.adoc +++ b/docs/reports/VERIFICATION.adoc @@ -126,15 +126,20 @@ validator's own logic is proved yet. | TESTED | `build/container/Containerfile --target test` built on Wolfi with the checksum-verified Zig 0.17.0 tarball; all 110 tests (C ABI tests included) passed - inside it + inside it. That container run predates the review cycle below: the suite is 126 + tests now, and it has not been re-run in the container since | `crosscheck` and `runtime` container targets | DESIGNED | written, not built here (Wolfi package names for NSD/ldns unverified) | DNSKEY (as opposed to DS) trust anchors; anchors below the root -| DESIGNED -| code in `validator.zig` (`anchoredKeys`); only `TrustAnchors.closest` is unit-tested +| TESTED (island-anchor path only) +| `anchoredKeys` in `validator.zig`, exercised end to end by three replay tests + added in the review cycle: one positive control asserting an anchored island + below an insecure delegation validates as `secure`, and two negatives asserting + a forged RRSIG signer and a forged SOA owner cannot reach over that anchor. + Anchors *above* an untrusted chain, and RFC 5011 rollover, remain untested | Correctness of Zig's `std.crypto` primitives and TLS client | ASSUMED @@ -203,7 +208,8 @@ two automated review passes). Twelve findings were raised against All twelve are fixed; the two that mattered most are described in `docs/architecture/THREAT-MODEL.adoc` §"What the milestone-1 review found". -The test count went from 111 to 123. The twelve additions are: +The test count went from 111 to 123 in that cycle, and to 126 in the second one +described below. The twelve additions from the first are: * four unit tests in the sources they guard (`wire/name.zig` relative-name length overflow, `wire/rdata.zig` SVCB/HTTPS canonical form, diff --git a/src/cli/dnssec-stub.zig b/src/cli/dnssec-stub.zig index 62837055..b048b311 100644 --- a/src/cli/dnssec-stub.zig +++ b/src/cli/dnssec-stub.zig @@ -41,7 +41,21 @@ fn usage() noreturn { std.process.exit(4); } +/// The exit contract advertised in `usage` and in the C ABI's companion docs is +/// 0 = secure, 1 = insecure, 2 = bogus, 3 = indeterminate, 4 = usage/transport. +/// An error escaping `main` becomes exit status 1, which this CLI has already +/// sold as "insecure" — so a missing `--anchors` file, an unparseable trust +/// anchor, a refused `http://` `--doh` URL, a bad `--ca`, or an unwritable +/// `--record` file each reported a proven-insecure verdict to any script or +/// harness reading the status. Setup and I/O failures are mapped to 4. pub fn main(init: std.process.Init) !u8 { + return run(init) catch |e| { + std.debug.print("dnssec-stub: {s}\n", .{@errorName(e)}); + return 4; + }; +} + +fn run(init: std.process.Init) !u8 { const gpa = init.gpa; const arena = init.arena.allocator(); const io = init.io; diff --git a/src/dnssec/validator.zig b/src/dnssec/validator.zig index 59364331..3e65553d 100644 --- a/src/dnssec/validator.zig +++ b/src/dnssec/validator.zig @@ -515,6 +515,12 @@ const Session = struct { // provably insecure. const y = soa_owner orelse (zone.parent() orelse return .{ .bogus = fail(.denial_missing, zone, .ds, null) }); if (!zone.isStrictSubdomainOf(&y)) return .{ .bogus = fail(.malformed_response, zone, .ds, null) }; + // The SOA owner is unauthenticated data, so ancestry alone is + // not enough. If an anchor sits between the hinted zone and the + // child, that zone's insecurity says nothing about the anchored + // subtree below it - the same closest-anchor bypass the RRSIG + // signer check refuses on the answer and denial paths. + if (s.signerAboveAnchor(&y, &zone)) return .{ .bogus = fail(.denial_missing, zone, .ds, null) }; return switch (try s.nameStatus(y)) { .insecure => |i| .{ .insecure = i }, .signed_zone => .{ .bogus = fail(.denial_missing, zone, .ds, null) }, @@ -542,9 +548,20 @@ const Session = struct { const DsUse = struct { usable: std.ArrayList(rdata.Ds), unsupported_seen: bool }; + /// Digest strength, weakest last. Unknown types rank 0 so they can never + /// displace a digest the validator can actually check. + fn digestRank(dt: types.DigestType) u8 { + return switch (dt) { + .sha1 => 1, + .sha256 => 2, + .sha384 => 3, + else => 0, + }; + } + fn usableDs(s: *Session, ds_rdatas: []const []const u8) Allocator.Error!DsUse { var out: DsUse = .{ .usable = .empty, .unsupported_seen = false }; - var has_strong = false; + var best: ?types.DigestType = null; for (ds_rdatas) |rd| { const d = rdata.Ds.parse(rd) catch continue; const ok_digest = keys.digestSupported(d.digest_type) and (d.digest_type != .sha1 or s.v.policy.allow_sha1); @@ -553,19 +570,53 @@ const Session = struct { out.unsupported_seen = true; continue; } - if (d.digest_type != .sha1) has_strong = true; + if (best == null or digestRank(d.digest_type) > digestRank(best.?)) best = d.digest_type; try out.usable.append(s.a, d); } - if (has_strong) { - // RFC 4509 §3: ignore SHA-1 DS when SHA-256 (or stronger) exists. + // RFC 4509 §3, extended to SHA-384 by RFC 6605 §5: when a DS RRset + // offers more than one digest type the validator supports, only the + // strongest may be used. Falling back to a weaker digest because the + // stronger one matched no DNSKEY is precisely the downgrade those + // sections forbid - the whole RRset is signed by the parent, so an + // attacker who cannot forge the strong digest should not get the weak + // one accepted instead. This previously dropped SHA-1 only, leaving + // SHA-256 and SHA-384 both usable and letting keysFromDs take whichever + // matched first. + if (best) |b| { var i: usize = 0; while (i < out.usable.items.len) { - if (out.usable.items[i].digest_type == .sha1) _ = out.usable.swapRemove(i) else i += 1; + if (out.usable.items[i].digest_type != b) _ = out.usable.swapRemove(i) else i += 1; } } return out; } + /// A denial proof's lifetime bounds how long the *zone state* is known, but + /// the negative answer built from it may only be cached for the SOA's own + /// negative TTL. Without that bound an on-path responder could forge an + /// NXDOMAIN below a proven-insecure delegation and keep it cached for the + /// much longer DS/NSEC lifetime, which the C ABI exposes as the answer's + /// cache duration. A wildcard proof supports a positive answer, so it is + /// left alone. + fn boundNegative(auth: *const rrset_mod.Grouped, kind: DenialKind, acc: *Acc) void { + if (kind == .wildcard) return; + acc.ttl = @min(acc.ttl, negativeTtl(auth) orelse 0); + } + + /// RFC 2308 §5: a negative answer may be cached for min(the SOA record's + /// own TTL, SOA MINIMUM). Null when the response carries no SOA, in which + /// case nothing about it is cacheable. + fn negativeTtl(auth: *const rrset_mod.Grouped) ?u32 { + for (auth.sets) |*set| { + if (set.type != .soa) continue; + for (set.rdatas) |rd| { + const soa = rdata.Soa.parse(rd) catch continue; + return @min(set.ttl, soa.minimum); + } + } + return null; + } + fn unsupportedOutcome(s: *Session, zone: Name, proof_ttl: u32) KeyStatus { return switch (s.v.policy.unsupported_algorithm) { .insecure => .{ .insecure = .{ .reason = .unsupported_algorithm_policy, .zone = zone, .ttl = proof_ttl } }, @@ -696,7 +747,10 @@ const Session = struct { switch (try s.collectDenial(&auth, &x, true)) { .none => |soa_owner| { if (soa_owner) |y| { - if (x.isStrictSubdomainOf(&y)) return keyToName(try s.zoneStatus(y), y); + // As in computeZoneStatus: ancestry is not sufficient, and + // a hint reaching over a closer anchor is ignored so the + // walk continues to the real parent instead. + if (x.isStrictSubdomainOf(&y) and !s.signerAboveAnchor(&y, &x)) return keyToName(try s.zoneStatus(y), y); } x = x.parent() orelse return .{ .bogus = fail(.denial_missing, start, .ds, null) }; }, @@ -767,7 +821,12 @@ const Session = struct { if (!set.isSigned()) continue; for (set.sigs) |*sig| { const signer = sig.rrsig.signer; - const ok_rel = if (strict_parent) target.isStrictSubdomainOf(&signer) else target.isSubdomainOf(&signer); + // `strict_parent` asks for a signer that is a proper ancestor + // of the target. The root has none, so demanding one discarded + // the root's own authenticated NSEC/SOA proof for a legitimate + // `. DS` NODATA and reported bogus/denial_missing. At the root + // the signer can only be the root itself. + const ok_rel = if (strict_parent and !target.isRoot()) target.isStrictSubdomainOf(&signer) else target.isSubdomainOf(&signer); if (ok_rel) try sigs.append(s.a, sig.*); } } @@ -935,10 +994,19 @@ const Session = struct { // No signed proof at all: only acceptable in an insecure zone. // When the response names its zone (SOA), test that zone: an // unsigned denial claiming to come from a signed zone is bogus. - const probe = if (soa_owner) |y| (if (sname.isSubdomainOf(&y)) y else sname) else sname; + // The SOA owner is a hint from unauthenticated data. It is used + // only when the target really is inside it AND no configured + // anchor sits between the two; otherwise a forged SOA could + // point at an insecure ancestor of a secure island and have that + // island's negative answer accepted with no proof at all. + const probe = if (soa_owner) |y| + (if (sname.isSubdomainOf(&y) and !s.signerAboveAnchor(&y, &sname)) y else sname) + else + sname; return switch (try s.nameStatus(probe)) { .insecure => |i| blk: { acc.markInsecure(i); + boundNegative(auth, kind, acc); break :blk null; }, .signed_zone => .{ .bogus = fail(.denial_missing, sname, .nsec, null) }, @@ -954,10 +1022,12 @@ const Session = struct { .insecure => |i| { if (kind == .wildcard) return .{ .bogus = fail(.denial_failed, sname, .nsec, null) }; acc.markInsecure(i); + boundNegative(auth, kind, acc); return null; }, .ok => |d| { acc.ttl = @min(acc.ttl, d.ttl); + boundNegative(auth, kind, acc); if (d.nsec_recs.len > 0) { const r = switch (kind) { .nxdomain => nsec.provesNxDomain(d.nsec_recs, &sname), diff --git a/src/wire/message.zig b/src/wire/message.zig index 37899183..6e7b6c5d 100644 --- a/src/wire/message.zig +++ b/src/wire/message.zig @@ -235,9 +235,23 @@ fn readRr(a: std.mem.Allocator, bytes: []const u8, pos: *usize, section: Section if (t == .opt and section != .additional) return error.BadOpt; if ((t == .tsig or t.toInt() == 249) and section != .additional) return error.BadRecordType; - // Expanded RDATA can grow by at most 255 octets per embedded name; no - // supported layout has more than four names. - const cap = rdlen + 4 * name_mod.max_wire_len; + // Expanded RDATA can grow by at most 255 octets per embedded name, so the + // headroom has to come from the layout rather than from a fixed allowance. + // A fixed 4*255 on every record - including opaque types whose RDATA cannot + // grow at all - let an untrusted upstream turn one 65535-octet message into + // ~6 MB of arena: about 5,950 minimal RRs of 11 octets each, every one + // allocated ~1 KB. `Session.fetch` caches each fetched message, so a single + // validation at the default fetch budget could hold hundreds of MB. That is + // the work-amplification class the threat model puts in scope. No supported + // layout has more than two names, so this is also exact rather than an + // over-estimate. + var names: usize = 0; + if (rdata_mod.layoutOf(t)) |lay| { + for (lay.fields) |field| { + if (field == .name) names += 1; + } + } + const cap = rdlen + names * name_mod.max_wire_len; const buf = try a.alloc(u8, cap); const expanded = try rdata_mod.expand(bytes, pos.*, rdlen, t, buf); if (expanded.len > max_message_len) return error.MalformedRdata; diff --git a/src/wire/rdata.zig b/src/wire/rdata.zig index df3e46f3..a0b793a5 100644 --- a/src/wire/rdata.zig +++ b/src/wire/rdata.zig @@ -414,6 +414,30 @@ pub const TypeBitmap = struct { return false; } + /// Fills `out` with every RR type the bitmap sets, in ascending order, and + /// returns the slice written; types past `out.len` are dropped. The + /// presentation writer has no allocator, and a real bitmap carries a + /// handful of types. + pub fn fill(self: TypeBitmap, out: []Type) []Type { + var n: usize = 0; + var p: usize = 0; + while (p + 2 <= self.raw.len) { + const window: u16 = self.raw[p]; + const len = self.raw[p + 1]; + for (self.raw[p + 2 ..][0..len], 0..) |octet, i| { + if (octet == 0) continue; + for (0..8) |bit| { + if ((octet & (@as(u8, 0x80) >> @intCast(bit))) == 0) continue; + if (n == out.len) return out[0..n]; + out[n] = Type.fromInt((window << 8) | (@as(u16, @intCast(i)) * 8 + @as(u16, @intCast(bit)))); + n += 1; + } + } + p += 2 + @as(usize, len); + } + return out[0..n]; + } + pub fn isEmpty(self: TypeBitmap) bool { var p: usize = 0; while (p + 2 <= self.raw.len) { diff --git a/src/wire/text.zig b/src/wire/text.zig index 9156b96a..523f9cb0 100644 --- a/src/wire/text.zig +++ b/src/wire/text.zig @@ -176,7 +176,15 @@ fn parseTtl(t: []const u8) Error!u32 { 'w' => 604800, else => return error.BadNumber, }; - total += acc * mult; + // Checked, and bailed on as soon as the sum cannot fit: every term is + // non-negative, so a partial sum past u32 can never come back. Plain + // u64 accumulation let a long-enough compound TTL such as repeated + // `4294967295w` overflow before the final range check - a panic in + // Debug and ReleaseSafe, and a wrapped, wrongly small TTL otherwise, + // from a public zone parser. + const term = std.math.mul(u64, acc, mult) catch return error.BadNumber; + total = std.math.add(u64, total, term) catch return error.BadNumber; + if (total > std.math.maxInt(u32)) return error.BadNumber; acc = 0; have_digit = false; } @@ -231,13 +239,24 @@ pub fn parseRrsigTime(t: []const u8) Error!u32 { const h = std.fmt.parseInt(i64, t[8..10], 10) catch return error.BadTime; const mi = std.fmt.parseInt(i64, t[10..12], 10) catch return error.BadTime; const s = std.fmt.parseInt(i64, t[12..14], 10) catch return error.BadTime; - if (mo < 1 or mo > 12 or d < 1 or d > 31 or h > 23 or mi > 59 or s > 60) return error.BadTime; + if (mo < 1 or mo > 12 or d < 1 or h > 23 or mi > 59 or s > 60) return error.BadTime; + // `d <= 31` is not a calendar. daysFromCivil normalises rather than fails, + // so 20230231000000 used to be encoded as a March timestamp: a zone file or + // test vector stating an impossible RRSIG inception or expiration was + // silently recorded as a different instant than the text says. + const month_len = [_]i64{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + const lim = if (mo == 2 and isLeapYear(y)) @as(i64, 29) else month_len[@intCast(mo - 1)]; + if (d > lim) return error.BadTime; const days = daysFromCivil(y, mo, d); const secs = days * 86400 + h * 3600 + mi * 60 + s; if (secs < 0) return error.BadTime; return @truncate(@as(u64, @intCast(secs))); } +fn isLeapYear(y: i64) bool { + return (@rem(y, 4) == 0 and @rem(y, 100) != 0) or @rem(y, 400) == 0; +} + /// Howard Hinnant's days_from_civil. fn daysFromCivil(y_in: i64, m: i64, d: i64) i64 { const y = if (m <= 2) y_in - 1 else y_in; @@ -532,6 +551,14 @@ pub fn parseZone(gpa: std.mem.Allocator, text: []const u8, opts: Options, diag: // Formatting (diagnostics only; not a complete presentation-format writer) // --------------------------------------------------------------------------- +/// RFC 3597 §5 unknown-type form: `\# `. Valid presentation +/// format for any RDATA, used where the complete form does not fit a stack +/// buffer. +fn genericRdata(w: *std.Io.Writer, rd: []const u8) std.Io.Writer.Error!void { + try w.print("\\# {d}", .{rd.len}); + for (rd) |b| try w.print(" {x:0>2}", .{b}); +} + pub fn formatRr(w: *std.Io.Writer, rr: *const Rr) std.Io.Writer.Error!void { var tb: [16]u8 = undefined; try rr.name.format(w); @@ -585,20 +612,45 @@ pub fn formatRr(w: *std.Io.Writer, rr: *const Rr) std.Io.Writer.Error!void { return w.print("{d} {d} {d} {x}", .{ d.key_tag, @backingInt(d.algorithm), @backingInt(d.digest_type), d.digest }); } else |_| {}, .dnskey => if (rdata_mod.Dnskey.parse(rd)) |k| { - return w.print("{d} {d} {d} ({d}-octet key)", .{ k.flags, k.protocol, @backingInt(k.algorithm), k.public_key.len }); + // RFC 4034 §2.2 presentation form: the public key in base64. A + // "(256-octet key)" placeholder is not RDATA and cannot be parsed + // or reused, and both the CLI and the C ABI promise presentation + // format for answer records. + var kb: [1024]u8 = undefined; + const need = std.base64.standard.Encoder.calcSize(k.public_key.len); + // RFC 3597 generic form replaces the WHOLE RDATA, so this has to be + // decided before any of it is written: emitting the flags and then + // `\# ` would be neither presentation form nor generic form. + if (need > kb.len) return genericRdata(w, rd); + try w.print("{d} {d} {d} ", .{ k.flags, k.protocol, @backingInt(k.algorithm) }); + return w.writeAll(std.base64.standard.Encoder.encode(&kb, k.public_key)); } else |_| {}, .rrsig => if (rdata_mod.Rrsig.parse(rd)) |s| { try w.print("{s} {d} {d} {d} {d} {d} {d} ", .{ s.type_covered.mnemonic(&tb), @backingInt(s.algorithm), s.labels, s.original_ttl, s.expiration, s.inception, s.key_tag }); try s.signer.format(w); return w.writeAll(" (signature)"); } else |_| {}, + // NSEC and NSEC3 used to stand in for their type bitmaps with + // "(types)", which is likewise not parseable. The bitmap is small, so + // it is enumerated into a stack buffer and written as mnemonics. .nsec => if (rdata_mod.Nsec.parse(rd)) |n| { try n.next.format(w); - return w.writeAll(" (types)"); + var tbuf: [128]Type = undefined; + for (n.types.fill(&tbuf)) |t| { + var mb: [16]u8 = undefined; + try w.print(" {s}", .{t.mnemonic(&mb)}); + } + return; } else |_| {}, .nsec3 => if (rdata_mod.Nsec3.parse(rd)) |n| { var b32: [512]u8 = undefined; - return w.print("{d} {d} {d} {x} {s} (types)", .{ @backingInt(n.hash_algorithm), n.flags, n.iterations, n.salt, encoding.base32HexEncode(&b32, n.next_hashed_owner) }); + try w.print("{d} {d} {d} {x} {s}", .{ @backingInt(n.hash_algorithm), n.flags, n.iterations, n.salt, encoding.base32HexEncode(&b32, n.next_hashed_owner) }); + var tbuf: [128]Type = undefined; + for (n.types.fill(&tbuf)) |t| { + var mb: [16]u8 = undefined; + try w.print(" {s}", .{t.mnemonic(&mb)}); + } + return; } else |_| {}, else => {}, } @@ -664,3 +716,129 @@ test "generic RDATA" { try testing.expectEqualSlices(u8, &.{ 0xab, 0xcd, 0xef }, z.records[0].rdata); try testing.expectEqualSlices(u8, &.{ 192, 0, 2, 1 }, z.records[1].rdata); } + +test "compound TTLs cannot overflow the accumulator" { + // Every component is capped at u32, but plain u64 accumulation let a long + // enough compound TTL overflow before the final range check: a panic in + // Debug and ReleaseSafe, and a wrapped, wrongly small TTL in an unchecked + // build, from the public zone parser. + var text: [4096]u8 = undefined; + var n: usize = 0; + for (0..300) |_| { + @memcpy(text[n..][0..11], "4294967295w"); + n += 11; + } + try testing.expectError(error.BadNumber, parseTtl(text[0..n])); + // The bound is applied per term, so the work a hostile zone file can cause + // is bounded too, not just the final result. + try testing.expectError(error.BadNumber, parseTtl("4294967295w")); + try testing.expectError(error.BadNumber, parseTtl("4294967296")); + // 7101 weeks is the largest whole number of weeks that fits in u32 + // (4294684800); 7102 weeks (4295289600) does not. + try testing.expectError(error.BadNumber, parseTtl("7102w")); + // Legitimate values, including the largest representable one. + try testing.expectEqual(@as(u32, 7101 * 604800), try parseTtl("7101w")); + try testing.expectEqual(@as(u32, 710 * 604800), try parseTtl("710w")); + try testing.expectEqual(@as(u32, 4294967295), try parseTtl("4294967295")); + try testing.expectEqual(@as(u32, 604800), try parseTtl("1w")); + try testing.expectEqual(@as(u32, 86400 + 3600 + 60 + 1), try parseTtl("1d1h1m1s")); +} + +test "RRSIG timestamps reject impossible calendar dates" { + // daysFromCivil normalises instead of failing, so a `d <= 31` range check + // let 20230231000000 through as a March timestamp: a zone file or test + // vector stating an impossible inception or expiration was encoded as a + // different instant than the text says. + try testing.expectError(error.BadTime, parseRrsigTime("20230231000000")); + try testing.expectError(error.BadTime, parseRrsigTime("20230431000000")); // April has 30 days + try testing.expectError(error.BadTime, parseRrsigTime("20230229000000")); // 2023 is not a leap year + try testing.expectError(error.BadTime, parseRrsigTime("19000229000000")); // century, not 400-year + try testing.expectError(error.BadTime, parseRrsigTime("20231301000000")); // month 13 + try testing.expectError(error.BadTime, parseRrsigTime("20230001000000")); // month 0 + try testing.expectError(error.BadTime, parseRrsigTime("20230100000000")); // day 0 + // Real leap years are accepted, including both century rules. + _ = try parseRrsigTime("20240229000000"); + _ = try parseRrsigTime("20000229000000"); + // Month ends, and the leap second the field's own range allows. + _ = try parseRrsigTime("20230228235959"); + _ = try parseRrsigTime("20231231000000"); + _ = try parseRrsigTime("20230630235960"); +} + +test "formatRr emits complete, parseable RDATA for DNSKEY, NSEC and NSEC3" { + // Both the CLI and the C ABI promise presentation-format answer records. + // "(256-octet key)" for a DNSKEY and "(types)" for the NSEC/NSEC3 bitmaps + // are not RDATA: they cannot be parsed, re-signed or reused, and a secure + // DNSKEY answer reaches this formatter through both paths. + const owner = try Name.fromText("example."); + + // DNSKEY: flags 256, protocol 3, algorithm 8, key DE AD BE EF. + { + const rd = [_]u8{ 0x01, 0x00, 0x03, 0x08, 0xDE, 0xAD, 0xBE, 0xEF }; + const rr: Rr = .{ .name = owner, .type = .dnskey, .class = .in, .ttl = 3600, .rdata = &rd }; + var out: [256]u8 = undefined; + _ = &out; + var w = std.Io.Writer.fixed(&out); + try formatRr(&w, &rr); + try testing.expectEqualStrings("example. 3600 IN DNSKEY 256 3 8 3q2+7w==", w.buffered()); + } + + // NSEC: window 0, four octets 0x40 0x01 0x00 0x08 = types 1 (A), 15 (MX) + // and 28 (AAAA). + { + const rd = [_]u8{ 2, 'n', 'x', 0, 0, 4, 0x40, 0x01, 0x00, 0x08 }; + const rr: Rr = .{ .name = owner, .type = .nsec, .class = .in, .ttl = 300, .rdata = &rd }; + var out: [256]u8 = undefined; + _ = &out; + var w = std.Io.Writer.fixed(&out); + try formatRr(&w, &rr); + try testing.expectEqualStrings("example. 300 IN NSEC nx. A MX AAAA", w.buffered()); + } + + // NSEC3: algorithm 1, flags 0, 12 iterations, salt AABB, base32hex next. + { + const hash = [_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; + var rd: [64]u8 = undefined; + rd[0] = 1; + rd[1] = 0; + std.mem.writeInt(u16, rd[2..4], 12, .big); + rd[4] = 2; + rd[5] = 0xAA; + rd[6] = 0xBB; + rd[7] = 20; + @memcpy(rd[8..28], &hash); + rd[28] = 0; + rd[29] = 4; + rd[30] = 0x40; + rd[31] = 0x01; + rd[32] = 0x00; + rd[33] = 0x08; + const rr: Rr = .{ .name = owner, .type = .nsec3, .class = .in, .ttl = 300, .rdata = rd[0..34] }; + var out: [256]u8 = undefined; + _ = &out; + var w = std.Io.Writer.fixed(&out); + try formatRr(&w, &rr); + const got = w.buffered(); + // The bitmap is enumerated, not elided, and the output ends with it. + try testing.expect(std.mem.endsWith(u8, got, " A MX AAAA")); + try testing.expect(std.mem.indexOf(u8, got, "(types)") == null); + try testing.expect(std.mem.startsWith(u8, got, "example. 300 IN NSEC3 1 0 12 aabb ")); + } + + // A DNSKEY too large for the stack buffer falls back to RFC 3597 generic + // form rather than printing a placeholder or overrunning. + { + var big: [2048]u8 = undefined; + big[0] = 0x01; + big[1] = 0x00; + big[2] = 0x03; + big[3] = 0x08; + @memset(big[4..], 0x5A); + const rr: Rr = .{ .name = owner, .type = .dnskey, .class = .in, .ttl = 3600, .rdata = &big }; + var out: [8192]u8 = undefined; + _ = &out; + var w = std.Io.Writer.fixed(&out); + try formatRr(&w, &rr); + try testing.expect(std.mem.startsWith(u8, w.buffered(), "example. 3600 IN DNSKEY \\# 2048 01 00 03 08 5a")); + } +} diff --git a/tests/replay.zig b/tests/replay.zig index 8eb55486..cfdf1790 100644 --- a/tests/replay.zig +++ b/tests/replay.zig @@ -535,8 +535,17 @@ const Rewrite = struct { prepend: ?struct { sec: Section, rr: Rr } = null, append: ?struct { sec: Section, rr: Rr } = null, ttl: ?struct { sec: Section, value: u32 } = null, + /// Record types to omit from every section. Dropping the signatures is how + /// a signed response is turned into the unsigned one an insecure zone would + /// have sent; the received bytes stay byte-identical otherwise. + drop: []const Type = &.{}, }; +fn dropped(list: []const Type, t: Type) bool { + for (list) |d| if (d == t) return true; + return false; +} + fn rewrite(gpa: std.mem.Allocator, bytes: []const u8, rw: Rewrite) ![]u8 { var msg = try Message.parse(gpa, bytes); defer msg.deinit(); @@ -552,6 +561,7 @@ fn rewrite(gpa: std.mem.Allocator, bytes: []const u8, rw: Rewrite) ![]u8 { for (sections) |sec| { if (rw.prepend) |p| if (p.sec == sec) try b.record(sec, p.rr); for (msg.section(sec)) |rr| { + if (dropped(rw.drop, rr.type)) continue; if (rw.ttl) |t| if (t.sec == sec and rr.type != .opt) { var copy = rr; copy.ttl = t.value; @@ -845,3 +855,46 @@ test "negative: QTYPE=RRSIG is refused rather than misreported" { const records = try merged(a, &first, s.records); try expectBogus(records, "www.rsasha256.test.", .rrsig, .malformed_response); } + +test "negative: a forged SOA owner cannot reach over a closer island anchor" { + var corpus = try Corpus.load(); + defer corpus.deinit(); + const a = corpus.arena.allocator(); + const nx = try corpus.find("nx.island.test.", .a); + const anchors = try anchoredAt(a, "www.island.test."); + + // An unsigned NXDOMAIN for a name inside the configured island, whose SOA + // names island.test. - provably insecure from the root anchor, but an + // ANCESTOR of the anchor at www.island.test. The SOA owner is + // unauthenticated data, and ancestry alone is not a sufficient test of it: + // the insecurity of island.test. says nothing about the anchored subtree + // below it. Accepting the hint let a responder dispose of a negative answer + // inside a secure island with no proof at all. + const forged = try rewrite(a, try recorded(nx.records, "nx.island.test.", .a), .{ + .question = .{ .name = "x.www.island.test.", .qtype = .a }, + .drop = &.{ .rrsig, .nsec, .nsec3 }, + }); + // Sanity: the authority section still carries the SOA and nothing signed. + { + var msg = try Message.parse(a, forged); + defer msg.deinit(); + var soa = false; + var signed = false; + for (msg.authority) |rr| { + if (rr.type == .soa) soa = true; + if (rr.type == .rrsig or rr.type == .nsec or rr.type == .nsec3) signed = true; + } + try testing.expect(soa); + try testing.expect(!signed); + } + + const first = [_]transport.Recorded{.{ .qname = try Name.fromText("x.www.island.test."), .qtype = .a, .response = forged }}; + const records = try merged(a, &first, nx.records); + + var r = try resolveWith(records, anchors, try Name.fromText("x.www.island.test."), .a, .{}, now); + defer r.deinit(); + if (r.security() == .insecure) { + std.debug.print("unsigned NXDOMAIN accepted as insecure ({} {}); expected refusal\n", .{ r.verdict.insecure.reason, r.verdict.insecure.zone }); + return error.TestUnexpectedResult; + } +} From 21eab80eada1155ce407d9e09526d7e6c83f10b7 Mon Sep 17 00:00:00 2001 From: "Jonathan D.A. Jewell" <6759885+hyperpolymath@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:13:32 +0000 Subject: [PATCH 2/2] Update docs/reports/VERIFICATION.adoc Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> Signed-off-by: Jonathan D.A. Jewell <6759885+hyperpolymath@users.noreply.github.com> --- docs/reports/VERIFICATION.adoc | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/reports/VERIFICATION.adoc b/docs/reports/VERIFICATION.adoc index 2f20e8ea..6775962d 100644 --- a/docs/reports/VERIFICATION.adoc +++ b/docs/reports/VERIFICATION.adoc @@ -135,10 +135,12 @@ validator's own logic is proved yet. | DNSKEY (as opposed to DS) trust anchors; anchors below the root | TESTED (island-anchor path only) -| `anchoredKeys` in `validator.zig`, exercised end to end by three replay tests +| The island-anchor validation path in `validator.zig`, including `anchoredKeys` + and the closer-anchor checks, exercised end to end by four replay tests added in the review cycle: one positive control asserting an anchored island - below an insecure delegation validates as `secure`, and two negatives asserting - a forged RRSIG signer and a forged SOA owner cannot reach over that anchor. + below an insecure delegation validates as `secure`, and three negatives + asserting a forged answer signer, a forged denial signer, and a forged SOA + owner cannot reach over that anchor. Anchors *above* an untrusted chain, and RFC 5011 rollover, remain untested | Correctness of Zig's `std.crypto` primitives and TLS client