Bläddra i källkod

v0.3.2: close third-audit findings (negative-test proof, probe exit codes, GPG --status-fd, cosign digest)

Closes the findings of the third audit of v0.3.1 (678fdbf):

[P2] DNSSEC negative test now proves SIGNATURE REJECTION, not just a
     SERVFAIL. The old static responder served one packet for every query
     (only the tid was patched), so a SERVFAIL could come from a failed DNSKEY
     fetch; and a zone with no parent DS is not per se a validation failure
     (RFC 4035 5.2). Now: a controlled zone broken.example with an EXPLICIT
     trust anchor (the zone DNSKEY) and three assertions:
       - valid zone            -> NOERROR + AD
       - broken zone (A data modified, same RRSIG) -> SERVFAIL
       - broken zone, validator off (module-config: iterator) -> NOERROR
     The counter-test (validator off) separates signature rejection from a
     generic resolution failure. The responder now serves the zone DNSKEY (with
     its RRSIG) so unbound can prime the trust anchor, and selects A vs DNSKEY
     by query name.

[P3] Probe exit codes distinguish timeouts from execution errors. Only exit
     code 2 is a timeout (NOT VERIFIED); any other unexpected code (e.g. a
     Docker start error, exit 125) is an execution error and fails the run.

Changed:
- GPG signer binding uses machine-readable --status-fd output
  ([GNUPG:] VALIDSIG <fpr>) instead of parsing the human-readable line.
- cosign digest taken from the docker push output (digest: sha256:...) rather
  than .RepoDigests[0].

Test suite: 40 passed, 0 failed, 3 not verified (all three are external UDP
probes flaky on WSL; the deterministic loopback checks and config assertions
pass).
ric 1 månad sedan
förälder
incheckning
e4dfe4a68a
8 ändrade filer med 393 tillägg och 129 borttagningar
  1. 46 0
      CHANGELOG.md
  2. 6 8
      Dockerfile
  3. 13 6
      README.md
  4. 11 4
      build.sh
  5. 46 8
      test/broken-zone-responder.py
  6. 39 0
      test/cd-check.py
  7. 96 30
      test/make-broken-zone.py
  8. 136 73
      test/run-tests.sh

+ 46 - 0
CHANGELOG.md

@@ -2,6 +2,52 @@
 
 All notable changes to this project are documented here.
 
+## [0.3.2] - 2026-10-23
+
+Closes the findings of the third audit of v0.3.1 (commit `678fdbf`): the
+DNSSEC negative test now proves signature rejection (not just a SERVFAIL),
+probe exit codes distinguish timeouts from execution errors, the GPG signer
+check uses machine-readable `--status-fd` output, and the cosign digest comes
+from the push result.
+
+### Fixed (P2)
+- **The DNSSEC negative test did not reliably prove rejection of invalid
+  signatures.** The old static responder served one packet for every query
+  (only the transaction ID was patched), so a SERVFAIL could come from a failed
+  DNSKEY fetch rather than a signature rejection; and a zone with no parent DS
+  is not *per se* a validation failure (RFC 4035 5.2 — a proven unsigned
+  delegation is *insecure*). Now the test uses a controlled zone `broken.example`
+  with an **explicit trust anchor** (the zone DNSKEY), so validation is
+  well-defined. It asserts three things:
+  1. **valid** zone → `NOERROR` + `AD` (the signature validates);
+  2. **broken** zone (A data modified, same RRSIG) → `SERVFAIL` (the signature
+     is rejected);
+  3. **broken** zone with **validation off** (`module-config: iterator`) →
+     `NOERROR` — the counter-test that separates signature rejection from a
+     generic resolution failure: the broken answer resolves fine, yet its
+     signature is rejected.
+  The responder now serves the zone DNSKEY (with its RRSIG) so unbound can prime
+  the trust anchor, and selects the A vs. DNSKEY packet by query name. New file:
+  `test/cd-check.py`.
+
+### Fixed (P3)
+- **Arbitrary execution errors were classified as "timeout".** The probe
+  evaluation treated every non-zero/non-one exit code (e.g. a Docker start
+  error, exit 125) as `NOT VERIFIED`. Now **only exit code 2** is a timeout
+  (`NOT VERIFIED`); any other unexpected code is reported as an **execution
+  error** and fails the run, so a broken probe can no longer masquerade as a
+  network hiccup.
+
+### Changed
+- **GPG signer binding uses `--status-fd`.** The build now extracts the signer
+  fingerprint from GnuPG's machine-readable status output
+  (`[GNUPG:] VALIDSIG <fpr> …`) instead of parsing the human-readable
+  `using … key <fpr>` line — more robust against GnuPG locale/version changes.
+- **Cosign digest from the push result.** `build.sh` now takes the digest from
+  the `docker push` output (`digest: sha256:…`) rather than
+  `.RepoDigests[0]`, which with multiple entries need not be the reference just
+  published. The signature is bound to the exact pushed digest.
+
 ## [0.3.1] - 2026-10-23
 
 Closes the remaining findings of the post-audit acceptance review of v0.3.0

+ 6 - 8
Dockerfile

@@ -73,11 +73,10 @@ RUN set -eux \
  && gpg --no-tty --list-keys --with-colons \
     | awk -F: '/^fpr:/{print $10}' \
     | grep -qx "$GNUPG_FINGERPRINT" \
- && out="$(gpg --batch --verify unbound.tar.gz.asc unbound.tar.gz 2>&1)" \
- && printf '%s\n' "$out" | grep -q "Good signature" \
- && printf '%s\n' "$out" | grep -oE 'key [0-9A-F]{40}' \
-    | grep -oE '[0-9A-F]{40}' | head -n1 \
+ && gpg --batch --verify --status-fd 1 unbound.tar.gz.asc unbound.tar.gz 2>/dev/null \
+    | grep '^\[GNUPG:\] VALIDSIG' | awk '{print $3}' \
     | grep -qx "$GNUPG_FINGERPRINT" \
+ && echo "GPG-VALIDSIG unbound.tar.gz signer=$GNUPG_FINGERPRINT" \
  && tar xzf unbound.tar.gz --strip 1
 
 FROM base AS ldns-src
@@ -100,11 +99,10 @@ RUN set -eux \
  && gpg --no-tty --list-keys --with-colons \
     | awk -F: '/^fpr:/{print $10}' \
     | grep -qx "$GNUPG_FINGERPRINT" \
- && out="$(gpg --batch --verify ldns.tar.gz.asc ldns.tar.gz 2>&1)" \
- && printf '%s\n' "$out" | grep -q "Good signature" \
- && printf '%s\n' "$out" | grep -oE 'key [0-9A-F]{40}' \
-    | grep -oE '[0-9A-F]{40}' | head -n1 \
+ && gpg --batch --verify --status-fd 1 ldns.tar.gz.asc ldns.tar.gz 2>/dev/null \
+    | grep '^\[GNUPG:\] VALIDSIG' | awk '{print $3}' \
     | grep -qx "$GNUPG_FINGERPRINT" \
+ && echo "GPG-VALIDSIG ldns.tar.gz signer=$GNUPG_FINGERPRINT" \
  && tar xzf ldns.tar.gz --strip 1
 
 FROM base-build AS unbound-build

+ 13 - 6
README.md

@@ -181,9 +181,13 @@ the socket mounted; all assertions target containers):
 
 Covers: build, healthcheck, version pin, DNS resolution, DNSSEC via correct
 EDNS-DO queries (signed zone -> AD=1, no DO request -> AD=0, repeat),
-**DNSSEC negative test** (a controlled zone `broken.example` with a
-well-formed RRSIG whose DNSKEY cannot be anchored -> **SERVFAIL** without CD,
-catching regressions like `val-permissive-mode: yes`), non-root uid,
+**DNSSEC negative test** (a controlled zone `broken.example` with an
+**explicit trust anchor** and three assertions: a valid zone validates to
+`NOERROR`+`AD`, a zone with a **manipulated signature** is rejected with
+**`SERVFAIL`** (no CD), and the same broken answer resolves to `NOERROR` with
+**validation off** — the counter-test that proves the SERVFAIL is a signature
+rejection, not a generic resolution failure; catches regressions like
+`val-permissive-mode: yes`), non-root uid,
 CapEff=0, no SUID binaries, read-only root fs, no-new-privileges, seccomp,
 hide-identity (with control container proving the identity is revealed when
 the flag is off), drop-in include (accept + reject), attack surface (no curl,
@@ -199,7 +203,9 @@ of the 10/2026 external audit).
 `0`=pass, `1`=content deviation, `2`=timeout. A content deviation (e.g. a
 leaked identity, a missing AD bit) **fails** the run; a network timeout is
 reported as **NOT VERIFIED** in the result line (visible, re-run to clear) so
-infrastructure flakiness never masks a real finding.
+infrastructure flakiness never masks a real finding. Any **other** exit code
+(e.g. a Docker start error, exit 125) is reported as an **execution error** and
+fails the run — a broken probe can no longer masquerade as a network hiccup.
 
 **Test isolation:** the suite runs the compose template under the dedicated
 project `unbound-sec-test` with a test-image override (`test/compose.test.yml`
@@ -226,8 +232,9 @@ anchor volume for RFC5011 persistence.
 
 `build.sh` signs the image with cosign in keyless mode (GitHub OIDC token).
 With `COSIGN_SIGN=1` it first **pushes** `REGISTRY_IMAGE`, then signs the
-**exact pushed digest** — so the signature is bound to the built image, not to
-a (possibly pre-existing) registry tag:
+**digest reported by the push** (`digest: sha256:…` from the push output) — so
+the signature is bound to the exact registry reference that was just published,
+not to a (possibly pre-existing) registry tag:
 
 ```sh
 REGISTRY_IMAGE=ghcr.io/<owner>/unbound-sec:latest COSIGN_SIGN=1 ./build.sh

+ 11 - 4
build.sh

@@ -37,11 +37,18 @@ if [ "${COSIGN_SIGN:-0}" = "1" ]; then
 
   echo "==> pushing $REG"
   docker tag "$IMAGE" "$REG"
-  docker push "$REG"
+  PUSH_OUT="$(docker push "$REG" 2>&1)"
+  printf '%s\n' "$PUSH_OUT"
 
-  # Sign the exact digest that was just pushed (not a mutable tag).
-  FULL="$(docker inspect --format='{{index .RepoDigests 0}}' "$REG")"
-  DG="${FULL##*@}" # sha256:...
+  # Take the digest from the PUSH result itself ("digest: sha256:..."), so the
+  # signature is bound to the registry reference that was just published. This
+  # is more explicit than .RepoDigests[0], which with multiple entries need not
+  # be the one just pushed.
+  DG="$(printf '%s\n' "$PUSH_OUT" | grep -oE 'digest: sha256:[0-9a-f]+' | head -1 | awk '{print $2}')"
+  if [ -z "$DG" ]; then
+    echo "could not determine pushed digest from push output" >&2
+    exit 1
+  fi
   echo "==> cosign keyless sign $REG@${DG}"
   cosign sign --yes "$REG@${DG}"
   echo "==> done. Verify with:"

+ 46 - 8
test/broken-zone-responder.py

@@ -1,9 +1,39 @@
 #!/usr/bin/env python3
-"""Static DNS responder with per-query logging."""
-import socket, sys, time
+"""Static DNS responder for the controlled broken.example zone.
 
-pkt = open(sys.argv[1], "rb").read()
-port = int(sys.argv[2])
+Serves two pre-built response packets, selected by the query name:
+  - www.broken.example  -> the A-answer packet (valid OR broken, given by argv[1])
+  - broken.example      -> the DNSKEY packet (argv[2]); needed so unbound can
+                           prime the trust anchor (it fetches the zone DNSKEY)
+
+The transaction ID of the served packet is patched to match the query, so the
+responses are matched to the right request.
+
+Usage: python broken-zone-responder.py <a-packet.bin> <dnskey-packet.bin> <port>
+"""
+import socket
+import sys
+import time
+
+
+def parse_qname(data):
+    """Extract the question name from a DNS query (data is the full packet)."""
+    i = 12  # after the 12-byte header
+    labels = []
+    while i < len(data):
+        ln = data[i]
+        if ln == 0:
+            i += 1
+            break
+        i += 1
+        labels.append(data[i:i + ln].decode("ascii", "replace"))
+        i += ln
+    return ".".join(labels) + "."
+
+
+apkt = open(sys.argv[1], "rb").read()
+dnskey_pkt = open(sys.argv[2], "rb").read()
+port = int(sys.argv[3])
 
 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 s.bind(("0.0.0.0", port))
@@ -18,14 +48,22 @@ try:
     probe.close()
 except Exception:
     my_ip = "0.0.0.0"
-print(f"responder ip={my_ip} on :{port}, serving {len(pkt)} bytes", flush=True)
+print(f"responder ip={my_ip} on :{port} "
+      f"(a={len(apkt)}B dnskey={len(dnskey_pkt)}B)", flush=True)
 n = 0
 while True:
     data, addr = s.recvfrom(4096)
     n += 1
-    # decode question name (best-effort) for logging
-    print(f"[{time.time():.0f}] query #{n} from {addr[0]} ({len(data)} bytes)", flush=True)
-    if len(data) < 2:
+    if len(data) < 12:
         continue
+    qname = parse_qname(data)
+    if qname.startswith("www.broken.example"):
+        pkt = apkt
+    elif qname.startswith("broken.example"):
+        pkt = dnskey_pkt
+    else:
+        pkt = apkt
+    print(f"[{time.time():.0f}] query #{n} from {addr[0]} q={qname}", flush=True)
+    # patch the transaction ID to match the query
     resp = data[:2] + pkt[2:]
     s.sendto(resp, addr)

+ 39 - 0
test/cd-check.py

@@ -0,0 +1,39 @@
+#!/usr/bin/env python3
+"""Send a DNS query with the DO and CD bits set; print the rcode.
+Usage: python cd-check.py <ip> <port>
+Exit: 0 if rcode==0 (NOERROR), 1 if rcode==2 (SERVFAIL), 2 otherwise/timeout.
+"""
+import socket
+import struct
+import sys
+
+ip = sys.argv[1]
+port = int(sys.argv[2])
+
+name = b"\x03www\x08broken\x07example\x00"  # www.broken.example
+qtype, qclass = 1, 1
+flags = 0x0110  # RD | CD
+tid = 0x1234
+# OPT record carrying the DO bit: name(root) + type(41) + class(extflags=DO)
+# + ttl(udp-size) + rdlength(0). The 32-bit TTL field must be present.
+opt = b"\x00" + struct.pack(">HHIH", 41, 0x8000, 0, 0)
+hdr = struct.pack(">HHHHHH", tid, flags, 1, 0, 0, 1)
+pkt = hdr + name + struct.pack(">HH", qtype, qclass) + opt
+
+s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+s.settimeout(5)
+try:
+    s.sendto(pkt, (ip, port))
+    data, _ = s.recvfrom(4096)
+    rcode = data[3] & 0x0F
+    print(f"CD+DO query rcode={rcode} (0=NOERROR, 2=SERVFAIL)")
+    if rcode == 0:
+        sys.exit(0)
+    if rcode == 2:
+        sys.exit(1)
+    sys.exit(2)
+except Exception as e:
+    print(f"CD probe error: {e}")
+    sys.exit(2)
+finally:
+    s.close()

+ 96 - 30
test/make-broken-zone.py

@@ -1,17 +1,38 @@
 #!/usr/bin/env python3
-"""Build a controlled DNSSEC zone (broken.example) as a binary DNS response packet.
+"""Build a controlled DNSSEC zone (broken.example) as binary DNS response packets.
 
-The zone presents a well-formed RRSIG (validly signed by its own DNSKEY) plus
-NSEC, but the DNSKEY cannot be anchored in the trust chain (broken.example is not
-delegated/signed by the root, and no parent DS exists). A validating resolver
-therefore MUST reject the data with SERVFAIL (without CD).
+Generates, for the query "www.broken.example A":
+  - VALID:  A + RRSIG (validly signed by the zone DNSKEY) + DNSKEY
+  - BROKEN: A (data modified) + RRSIG (unchanged, now invalid) + DNSKEY
+  - ANCHOR: a trusted-key file containing the zone DNSKEY.
 
-Output: a DNS response packet for "www.broken.example A" suitable for a static
-UDP responder to serve to any query.
+Rationale (RFC 4035 5.2): a zone whose DNSKEY is an explicit trust anchor is
+validated against that anchor — no parent DS is needed. So:
+  - VALID  -> NOERROR + AD  (the signature validates)
+  - BROKEN -> SERVFAIL      (the signature is rejected)
+  - BROKEN + CD -> NOERROR  (the answer is resolvable, just not validated)
+
+The CD counter-test is what separates SIGNATURE REJECTION from a generic
+resolution failure: the broken answer resolves fine (CD) yet its signature is
+rejected (no CD). A static responder that merely fails to serve the DNSKEY
+would not produce this pattern.
+
+Usage: python make-broken-zone.py <outdir>
+Writes: <outdir>/.broken-valid.bin, <outdir>/.broken-broken.bin,
+        <outdir>/.broken-anchor.key
 """
-import struct, sys
+import base64
+import struct
+import sys
+
 from cryptography.hazmat.primitives.asymmetric import rsa
-import dns.dnssec, dns.zone, dns.name, dns.rdataclass, dns.rdatatype
+import dns.dnssec
+import dns.name
+import dns.rdata
+import dns.rdataclass
+import dns.rdatatype
+import dns.rrset
+import dns.zone
 
 ORIGIN = "broken.example."
 z = dns.zone.from_text(
@@ -21,7 +42,8 @@ broken.example.      300 IN NS  ns1.broken.example.
 ns1.broken.example.  300 IN A   192.0.2.53
 www.broken.example.  300 IN A   192.0.2.1
 """,
-    origin=dns.name.from_text(ORIGIN), relativize=False,
+    origin=dns.name.from_text(ORIGIN),
+    relativize=False,
 )
 
 pk = rsa.generate_private_key(public_exponent=65537, key_size=2048)
@@ -30,21 +52,21 @@ dns.dnssec.sign_zone(z, keys=[(pk, dnskey)], add_dnskey=True,
                      deterministic=True, lifetime=3600)
 
 qname = dns.name.from_text("www.broken.example.")
-# Collect rrsets via iteration (find_rrset has a relativize quirk).
-# RRSIGs with different 'covers' are separate rdatasets -> gather all.
 a_rrset = None
 a_rrsig = None
 k_rrset = None
+k_rrsig = None
 for name, rds in z.iterate_rdatasets():
     if name == qname and rds.rdtype == dns.rdatatype.A:
         a_rrset = rds
     if name == qname and rds.rdtype == dns.rdatatype.RRSIG:
-        # pick the RRSIG that covers the A rrset
         if any(r.covers() == dns.rdatatype.A for r in rds):
             a_rrsig = rds
     if name == dns.name.from_text(ORIGIN) and rds.rdtype == dns.rdatatype.DNSKEY:
         k_rrset = rds
-ans = list(a_rrset) + list(a_rrsig)
+    if name == dns.name.from_text(ORIGIN) and rds.rdtype == dns.rdatatype.RRSIG:
+        if any(r.covers() == dns.rdatatype.DNSKEY for r in rds):
+            k_rrsig = rds
 
 
 def enc(n):
@@ -56,19 +78,63 @@ def rd_bytes(rd):
     return struct.pack(">HHIH", rd.rdtype, 1, 300, len(w)) + w
 
 
-tid = 0xabcd
-flags = 0x8500  # QR | AA | RA
-pkt = struct.pack(">HHHHHH", tid, flags, 1, len(ans), 0, len(k_rrset))
-pkt += enc(qname) + struct.pack(">HH", 1, 1)
-for rd in ans:
-    pkt += enc(qname) + rd_bytes(rd)
-for rd in k_rrset:
-    pkt += enc(dns.name.from_text(ORIGIN)) + rd_bytes(rd)
-
-out = sys.argv[1] if len(sys.argv) > 1 else "broken-zone.bin"
-open(out, "wb").write(pkt)
-print(f"wrote {out}: {len(pkt)} bytes "
-      f"({len(a_rrset)} A + {len(a_rrsig)} RRSIG answer, {len(k_rrset)} DNSKEY add'l)")
-print("A     :", a_rrset[0].to_text())
-print("RRSIG :", a_rrsig[0].to_text()[:75], "...")
-print("DNSKEY:", k_rrset[0].to_text()[:55], "...")
+def build_packet(a_rr, a_rrsig, k_rrset):
+    flags = 0x8500  # QR | AA | RA
+    ans = list(a_rr) + list(a_rrsig)
+    pkt = struct.pack(">HHHHHH", 0, flags, 1, len(ans), 0, len(k_rrset))
+    pkt += enc(qname) + struct.pack(">HH", 1, 1)
+    for rd in ans:
+        pkt += enc(qname) + rd_bytes(rd)
+    for rd in k_rrset:
+        pkt += enc(dns.name.from_text(ORIGIN)) + rd_bytes(rd)
+    return pkt
+
+
+def build_dnskey_packet(k_rrset, k_rrsig):
+    """A response to 'broken.example DNSKEY' carrying the DNSKEY rrset PLUS its
+    RRSIG (so the rrset is 'secure' and unbound can prime the trust anchor)."""
+    flags = 0x8500  # QR | AA | RA
+    zonename = dns.name.from_text(ORIGIN)
+    ans = list(k_rrset) + list(k_rrsig)
+    pkt = struct.pack(">HHHHHH", 0, flags, 1, len(ans), 0, 0)
+    pkt += enc(zonename) + struct.pack(">HH", dns.rdatatype.DNSKEY, 1)
+    for rd in ans:
+        pkt += enc(zonename) + rd_bytes(rd)
+    return pkt
+
+
+# VALID: original A + valid RRSIG
+valid_pkt = build_packet(a_rrset, a_rrsig, k_rrset)
+# DNSKEY-only (+ its RRSIG): for trust-anchor priming (broken.example DNSKEY)
+dnskey_pkt = build_dnskey_packet(k_rrset, k_rrsig)
+
+# BROKEN: same RRSIG, but the A record data is changed (192.0.2.1 -> .2),
+# so the RRSIG no longer covers the data -> signature is invalid.
+broken_a_rd = dns.rdata.from_text(
+    dns.rdataclass.IN, dns.rdatatype.A, "192.0.2.2"
+)
+broken_a_rr = dns.rrset.from_rdata(qname, 300, broken_a_rd)
+broken_pkt = build_packet(broken_a_rr, a_rrsig, k_rrset)
+
+# ANCHOR: trusted-key file for the zone DNSKEY. Unbound's trusted-key format
+# (as in /usr/share/dnssec-root/trusted-key.key) is a full DNSKEY RR:
+#   <zone> IN DNSKEY <flags> <protocol> <algorithm> <base64-key>
+dnskey_rd = k_rrset[0]
+key_b64 = base64.b64encode(dnskey_rd.key).decode()
+anchor = (
+    "; Trust anchor for the controlled test zone broken.example\n"
+    f"{ORIGIN} IN DNSKEY {dnskey_rd.flags} {dnskey_rd.protocol} "
+    f"{dnskey_rd.algorithm} {key_b64}\n"
+)
+
+out = sys.argv[1] if len(sys.argv) > 1 else "."
+open(f"{out}/.broken-valid.bin", "wb").write(valid_pkt)
+open(f"{out}/.broken-broken.bin", "wb").write(broken_pkt)
+open(f"{out}/.broken-dnskey.bin", "wb").write(dnskey_pkt)
+open(f"{out}/.broken-anchor.key", "w").write(anchor)
+
+print(f"wrote {out}/.broken-valid.bin   ({len(valid_pkt)} bytes)  A={a_rrset[0].to_text()}")
+print(f"wrote {out}/.broken-broken.bin  ({len(broken_pkt)} bytes)  A={broken_a_rd.to_text()}")
+print(f"wrote {out}/.broken-dnskey.bin  ({len(dnskey_pkt)} bytes)  DNSKEY (for anchor priming)")
+print(f"wrote {out}/.broken-anchor.key  ({len(anchor)} chars)  DNSKEY flags={dnskey_rd.flags}")
+print("RRSIG:", a_rrsig[0].to_text()[:75], "...")

+ 136 - 73
test/run-tests.sh

@@ -17,8 +17,11 @@ C2="ubsec-t2"          # valid drop-in container
 C3="ubsec-t3"          # broken drop-in container
 C4="ubsec-t4"          # identity control container
 C5="ubsec-t5"          # anchor persistence container
-C6="ubsec-t6"          # DNSSEC negative-test unbound (forward-zone)
-RESP="ubsec-t6-resp"   # static DNS responder for the negative test
+C6="ubsec-t6"          # negative-test: valid zone + trust anchor (expect AD)
+C7="ubsec-t7"          # negative-test: broken signature + trust anchor (expect SERVFAIL)
+C8="ubsec-t8"          # negative-test: broken zone, validator off (counter-test, expect NOERROR)
+RESP="ubsec-t6-resp"   # static DNS responder, VALID zone (port 5353)
+RESP_BROKEN="ubsec-t7-resp" # static DNS responder, BROKEN zone (port 5354)
 NET="ubsec-testnet"
 # The compose template is tested under a DEDICATED project name so the test
 # never touches a production deployment of the same template on this daemon
@@ -55,13 +58,18 @@ cleanup() {
   # Remove ONLY resources this test run created. The fixed container name
   # "unbound" is gone from the template, so we no longer rm a name that a
   # production deployment might use.
-  docker rm -f "$C1" "$C2" "$C3" "$C4" "$C5" "$C6" "$RESP" >/dev/null 2>&1
+  docker rm -f "$C1" "$C2" "$C3" "$C4" "$C5" "$C6" "$C7" "$C8" "$RESP" "$RESP_BROKEN" >/dev/null 2>&1
   compose_test down --remove-orphans --volumes >/dev/null 2>&1
   docker network rm "$NET" >/dev/null 2>&1
   docker network rm "ubsec-negnet" >/dev/null 2>&1
   rm -rf "$(pwd)/test/fixture-identity" 2>/dev/null
-  rm -rf "$(pwd)/test/fixture-broken-fwd" 2>/dev/null
-  rm -f "$(pwd)/test/.broken-zone.bin" 2>/dev/null
+  rm -rf "$(pwd)/test/fixture-broken-valid" 2>/dev/null
+  rm -rf "$(pwd)/test/fixture-broken-broken" 2>/dev/null
+  rm -rf "$(pwd)/test/fixture-broken-noval" 2>/dev/null
+  rm -f "$(pwd)/test/.broken-valid.bin" 2>/dev/null
+  rm -f "$(pwd)/test/.broken-broken.bin" 2>/dev/null
+  rm -f "$(pwd)/test/.broken-dnskey.bin" 2>/dev/null
+  rm -f "$(pwd)/test/.broken-anchor.key" 2>/dev/null
   rm -rf "$ANCHOR_DIR" 2>/dev/null
   rm -f "$(pwd)/test/build.log" 2>/dev/null
 }
@@ -157,7 +165,9 @@ case $probe_rc in
   0) ok "external EDNS-DO probe (AD=1 with DO, AD=0 without)";;
   1) bad "external EDNS-DO probe: CONTENT deviation"
      printf '%s\n' "$probe_out" | sed 's/^/      /';;
-  *) nv "external EDNS-DO probe (timeout; loopback check is the proof)"
+  2) nv "external EDNS-DO probe (timeout; loopback check is the proof)"
+     printf '%s\n' "$probe_out" | sed 's/^/      /';;
+  *) bad "external EDNS-DO probe: execution error (exit $probe_rc)"
      printf '%s\n' "$probe_out" | sed 's/^/      /';;
 esac
 
@@ -223,7 +233,9 @@ case $id_rc in
   0) ok "hide-identity: id.server. answer is empty";;
   1) bad "hide-identity: id.server. answer is empty (CONTENT deviation)"
      printf '%s\n' "$id_out" | sed 's/^/      /';;
-  *) nv "hide-identity CHAOS probe (timeout; config asserted below)"
+  2) nv "hide-identity CHAOS probe (timeout; config asserted below)"
+     printf '%s\n' "$id_out" | sed 's/^/      /';;
+  *) bad "hide-identity CHAOS probe: execution error (exit $id_rc)"
      printf '%s\n' "$id_out" | sed 's/^/      /';;
 esac
 # Config-level assertion (deterministic): the base config must set it.
@@ -245,7 +257,9 @@ case $id2_rc in
   0) ok "identity control: hide-identity:no reveals identity";;
   1) bad "identity control: hide-identity:no reveals identity (CONTENT deviation)"
      printf '%s\n' "$id2_out" | sed 's/^/      /';;
-  *) nv "identity-control CHAOS probe (timeout)"
+  2) nv "identity-control CHAOS probe (timeout)"
+     printf '%s\n' "$id2_out" | sed 's/^/      /';;
+  *) bad "identity-control CHAOS probe: execution error (exit $id2_rc)"
      printf '%s\n' "$id2_out" | sed 's/^/      /';;
 esac
 
@@ -286,11 +300,14 @@ else
 fi
 
 say "== 15. supply chain: GPG + SHA256 of source tarballs =="
-sigs="$(grep -c "Good signature" "$BUILDLOG" 2>/dev/null)"
+# The build echoes "GPG-VALIDSIG <tarball> signer=<fpr>" after each successful
+# signature verification (the signer fingerprint is extracted from GnuPG's
+# machine-readable --status-fd output and must equal the pinned fingerprint).
+sigs="$(grep -c "GPG-VALIDSIG" "$BUILDLOG" 2>/dev/null)"
 if [ "$sigs" -ge 2 ]; then
-  ok "GPG: Good signature x$sigs (unbound + ldns tarballs)"
+  ok "GPG: signer bound via VALIDSIG x$sigs (unbound + ldns tarballs)"
 else
-  bad "GPG: Good signature (found: $sigs, need >= 2)"
+  bad "GPG: signer bound via VALIDSIG (found: $sigs, need >= 2)"
 fi
 if grep -E "unbound\.tar\.gz: OK|ldns\.tar\.gz: OK" "$BUILDLOG" >/dev/null 2>&1; then
   ok "SHA256: tarball checksums OK"
@@ -431,78 +448,124 @@ fi
 compose_test down --remove-orphans --volumes >/dev/null 2>&1
 
 say "== 20. DNSSEC negative test: invalid signature -> SERVFAIL =="
-# Controlled zone "broken.example" served by a static responder: a
-# well-formed RRSIG whose DNSKEY cannot be anchored in the trust chain (no
-# parent DS). A validating resolver must reject it with SERVFAIL (without
-# CD). This catches regressions like val-permissive-mode: yes, which would
-# still validate good answers but let broken ones through.
+# Controlled zone "broken.example" with an EXPLICIT trust anchor (the zone
+# DNSKEY), so validation is well-defined (RFC 4035 5.2 — no parent DS needed):
+#   C6 valid  : A + RRSIG (valid)          -> NOERROR + AD
+#   C7 broken : A (data modified) + RRSIG  -> SERVFAIL (signature rejected)
+#   C8 noval  : broken zone, validator off -> NOERROR (resolvable, counter-test)
+# The counter-test (C8) separates SIGNATURE REJECTION from a generic
+# resolution failure: the broken answer resolves fine with validation off,
+# yet its signature is rejected with validation on. A static responder that
+# merely failed to serve the DNSKEY would not produce this pattern.
 #
-# 1) generate the zone packet (fresh RRSIG timestamps) in a python container
-# 2) start a static UDP responder serving it
-# 3) start a test unbound with a forward-zone to the responder
-# 4) query www.broken.example A with DO -> expect SERVFAIL (rcode=2)
-#
-# RESP and C6 get their OWN network (not $NET), so they can't be affected by
-# the other test containers and the test stays deterministic.
+# RESP/RESP_BROKEN and C6/C7/C8 get their OWN network (not $NET), so they
+# can't be affected by the other test containers and the test stays
+# deterministic.
 REPO="${REPO_PATH:-$(pwd)}"
 NEG_NET="ubsec-negnet"
 docker network create "$NEG_NET" >/dev/null 2>&1
-BZBIN="$(pwd)/test/.broken-zone.bin"
-# Remove any stale BZBIN first: if a previous run left a DIRECTORY there (Docker
-# creates a dir when mounting a missing file), the generator would fail with
-# IsADirectoryError.
-rm -rf "$BZBIN"
-docker run --rm -v "$REPO/test/make-broken-zone.py:/m.py:ro" -v "$(pwd)/test:/o" \
-  python:alpine sh -c "pip install -q dnspython cryptography 2>/dev/null; python /m.py /o/.broken-zone.bin" >/dev/null 2>&1
-if [ ! -f "$BZBIN" ]; then
-  bad "generate broken.example zone packet"
+BZDIR="$(pwd)/test"
+# Remove stale zone files first: a DIRECTORY left there by a previous mount of
+# a missing file would make the generator fail with IsADirectoryError.
+rm -f "$BZDIR/.broken-valid.bin" "$BZDIR/.broken-broken.bin" \
+      "$BZDIR/.broken-dnskey.bin" "$BZDIR/.broken-anchor.key"
+docker run --rm -v "$REPO/test/make-broken-zone.py:/m.py:ro" -v "$BZDIR:/o" \
+  python:alpine sh -c "pip install -q dnspython cryptography 2>/dev/null; python /m.py /o" >/dev/null 2>&1
+if [ ! -f "$BZDIR/.broken-valid.bin" ] || [ ! -f "$BZDIR/.broken-broken.bin" ] \
+   || [ ! -f "$BZDIR/.broken-dnskey.bin" ] || [ ! -f "$BZDIR/.broken-anchor.key" ]; then
+  bad "generate broken.example zone packets"
 else
-  ok "generate broken.example zone packet"
+  ok "generate broken.example zone packets (valid + broken + anchor)"
 fi
+# Two static responders: VALID (5353) and BROKEN (5354). Both serve the same
+# DNSKEY packet (for trust-anchor priming); only the A packet differs.
 docker run -d --name "$RESP" --network "$NEG_NET" \
-  -v "$BZBIN:/p.bin:ro" -v "$REPO/test/broken-zone-responder.py:/r.py:ro" \
-  python:alpine python /r.py /p.bin 5353 >/dev/null
-# Get the responder's IP from ITS OWN log (it prints its container IP). This
-# is more reliable than `docker inspect` from the host, which can be empty
-# while the container is starting on a slow WSL daemon.
-RESP_IP=""; i=0
-while [ $i -lt 15 ]; do
-  RESP_IP="$(docker logs "$RESP" 2>&1 | grep -oE 'responder ip=[0-9.]+' | head -1 | cut -d= -f2)"
-  [ -n "$RESP_IP" ] && [ "$RESP_IP" != "0.0.0.0" ] && break
-  sleep 2; i=$((i+1))
-done
-# Fallback to docker inspect if the log didn't yield an IP.
-if [ -z "$RESP_IP" ] || [ "$RESP_IP" = "0.0.0.0" ]; then
-  RESP_IP="$(docker inspect -f '{{(index .NetworkSettings.Networks "'"$NEG_NET"').IPAddress}}' "$RESP" 2>/dev/null)"
-fi
-[ -n "$RESP_IP" ] || { bad "negative-test responder has an IP (got empty)"
-  docker logs "$RESP" 2>&1 | tail -3 | sed 's/^/      /'
-  say "      networks: $(docker inspect -f '{{json .NetworkSettings.Networks}}' "$RESP" 2>/dev/null)"
-  say "      state: $(docker inspect -f '{{.State.Running}} exit={{.State.ExitCode}}' "$RESP" 2>/dev/null)"; }
-FWD_DIR="$(pwd)/test/fixture-broken-fwd"
-rm -rf "$FWD_DIR"; mkdir -p "$FWD_DIR"; chmod 755 "$FWD_DIR"
-printf 'forward-zone:\n    name: "broken.example"\n    forward-addr: %s@5353\n' "$RESP_IP" > "$FWD_DIR/99-broken.conf"
-chmod 644 "$FWD_DIR/99-broken.conf"
-docker run -d --name "$C6" --network "$NEG_NET" -v "$FWD_DIR:/config:ro" "$IMAGE" >/dev/null
-# wait for readiness: unbound is ready when it answers the (broken) query at
-# all — a SERVFAIL is a valid response, so we check for ANY rcode, not a
-# successful (exit 0) drill.
-ready="no"; i=0
-while [ $i -lt 15 ]; do
-  if docker exec "$C6" drill -p 5053 -D www.broken.example A @127.0.0.1 2>/dev/null | grep -q "rcode:"; then
-    ready="yes"; break
+  -v "$BZDIR/.broken-valid.bin:/a.bin:ro" -v "$BZDIR/.broken-dnskey.bin:/k.bin:ro" \
+  -v "$REPO/test/broken-zone-responder.py:/r.py:ro" \
+  python:alpine python /r.py /a.bin /k.bin 5353 >/dev/null
+docker run -d --name "$RESP_BROKEN" --network "$NEG_NET" \
+  -v "$BZDIR/.broken-broken.bin:/a.bin:ro" -v "$BZDIR/.broken-dnskey.bin:/k.bin:ro" \
+  -v "$REPO/test/broken-zone-responder.py:/r.py:ro" \
+  python:alpine python /r.py /a.bin /k.bin 5354 >/dev/null
+# Get a responder's IP from ITS OWN log (it prints its container IP); fall
+# back to docker inspect. This is more reliable than host-side inspect, which
+# can be empty while a container is starting on a slow WSL daemon.
+get_ip() {
+  _c="$1"; _ip=""; _i=0
+  while [ $_i -lt 15 ]; do
+    _ip="$(docker logs "$_c" 2>&1 | grep -oE 'responder ip=[0-9.]+' | head -1 | cut -d= -f2)"
+    [ -n "$_ip" ] && [ "$_ip" != "0.0.0.0" ] && break
+    sleep 2; _i=$((_i+1))
+  done
+  if [ -z "$_ip" ] || [ "$_ip" = "0.0.0.0" ]; then
+    _ip="$(docker inspect -f '{{(index .NetworkSettings.Networks "'"$NEG_NET"').IPAddress}}' "$_c" 2>/dev/null)"
   fi
-  sleep 2; i=$((i+1))
-done
-[ "$ready" = "yes" ] || bad "negative-test resolver ready"
-sf_out="$(docker exec "$C6" drill -p 5053 -D www.broken.example A @127.0.0.1 2>/dev/null)"
-if printf '%s' "$sf_out" | grep -q "rcode: SERVFAIL"; then
-  ok "invalid signature -> SERVFAIL (no CD; validator rejects unanchorable DNSKEY)"
+  printf '%s' "$_ip"
+}
+RVALID="$(get_ip "$RESP")"
+RBROKEN="$(get_ip "$RESP_BROKEN")"
+[ -n "$RVALID" ] && [ -n "$RBROKEN" ] || {
+  bad "negative-test responders have IPs (valid=$RVALID broken=$RBROKEN)"
+  docker logs "$RESP" 2>&1 | tail -2 | sed 's/^/      /'
+  docker logs "$RESP_BROKEN" 2>&1 | tail -2 | sed 's/^/      /'
+}
+# C6: trust anchor + forward to VALID + validator -> expect NOERROR + AD
+FWD_V="$(pwd)/test/fixture-broken-valid"; rm -rf "$FWD_V"; mkdir -p "$FWD_V"; chmod 755 "$FWD_V"
+printf 'trust-anchor-file: "/anchor.key"\nforward-zone:\n    name: "broken.example"\n    forward-addr: %s@5353\n' "$RVALID" > "$FWD_V/99.conf"
+chmod 644 "$FWD_V/99.conf"
+docker run -d --name "$C6" --network "$NEG_NET" -v "$FWD_V:/config:ro" -v "$BZDIR/.broken-anchor.key:/anchor.key:ro" "$IMAGE" >/dev/null
+# C7: trust anchor + forward to BROKEN + validator -> expect SERVFAIL
+FWD_B="$(pwd)/test/fixture-broken-broken"; rm -rf "$FWD_B"; mkdir -p "$FWD_B"; chmod 755 "$FWD_B"
+printf 'trust-anchor-file: "/anchor.key"\nforward-zone:\n    name: "broken.example"\n    forward-addr: %s@5354\n' "$RBROKEN" > "$FWD_B/99.conf"
+chmod 644 "$FWD_B/99.conf"
+docker run -d --name "$C7" --network "$NEG_NET" -v "$FWD_B:/config:ro" -v "$BZDIR/.broken-anchor.key:/anchor.key:ro" "$IMAGE" >/dev/null
+# C8: validator disabled (module-config: iterator) + forward to BROKEN ->
+# expect NOERROR (the broken answer is resolvable, just not validated).
+FWD_N="$(pwd)/test/fixture-broken-noval"; rm -rf "$FWD_N"; mkdir -p "$FWD_N"; chmod 755 "$FWD_N"
+printf 'module-config: iterator\nforward-zone:\n    name: "broken.example"\n    forward-addr: %s@5354\n' "$RBROKEN" > "$FWD_N/99.conf"
+chmod 644 "$FWD_N/99.conf"
+docker run -d --name "$C8" --network "$NEG_NET" -v "$FWD_N:/config:ro" "$IMAGE" >/dev/null
+# Readiness: unbound is ready when it answers the query at all — a SERVFAIL is
+# a valid response, so check for ANY rcode, not a successful (exit 0) drill.
+ready_c() {
+  _c="$1"; _r="no"; _i=0
+  while [ $_i -lt 15 ]; do
+    if docker exec "$_c" drill -p 5053 -D www.broken.example A @127.0.0.1 2>/dev/null | grep -q "rcode:"; then
+      _r="yes"; break
+    fi
+    sleep 2; _i=$((_i+1))
+  done
+  [ "$_r" = "yes" ]
+}
+ready_c "$C6" && ok "negative-test: valid resolver ready" || bad "negative-test: valid resolver ready"
+ready_c "$C7" && ok "negative-test: broken resolver ready" || bad "negative-test: broken resolver ready"
+ready_c "$C8" && ok "negative-test: noval resolver ready" || bad "negative-test: noval resolver ready"
+# 1) VALID zone validates: NOERROR + AD
+v_out="$(docker exec "$C6" drill -p 5053 -D www.broken.example A @127.0.0.1 2>/dev/null)"
+if printf '%s' "$v_out" | grep -q "rcode: NOERROR" && printf '%s' "$v_out" | grep -qE "flags:.*ad"; then
+  ok "valid zone validates (NOERROR + AD with explicit trust anchor)"
+else
+  bad "valid zone validates (got: $(printf '%s' "$v_out" | grep rcode | head -1))"
+  printf '%s\n' "$v_out" | sed 's/^/    /'
+fi
+# 2) BROKEN signature rejected: SERVFAIL (no CD)
+b_out="$(docker exec "$C7" drill -p 5053 -D www.broken.example A @127.0.0.1 2>/dev/null)"
+if printf '%s' "$b_out" | grep -q "rcode: SERVFAIL"; then
+  ok "broken signature -> SERVFAIL (no CD; validator rejects the invalid RRSIG)"
+else
+  bad "broken signature -> SERVFAIL (got: $(printf '%s' "$b_out" | grep rcode | head -1))"
+  printf '%s\n' "$b_out" | sed 's/^/    /'
+fi
+# 3) Counter-test: broken answer is RESOLVABLE with validation off -> NOERROR.
+#    This proves step 2 is a signature rejection, not a resolution failure.
+n_out="$(docker exec "$C8" drill -p 5053 www.broken.example A @127.0.0.1 2>/dev/null)"
+if printf '%s' "$n_out" | grep -q "rcode: NOERROR" && printf '%s' "$n_out" | grep -qE "IN[[:space:]]+A[[:space:]]"; then
+  ok "broken answer resolvable with validation off (counter-test: signature rejection, not resolution failure)"
 else
-  bad "invalid signature -> SERVFAIL (got: $(printf '%s' "$sf_out" | grep rcode | head -1))"
-  printf '%s\n' "$sf_out" | sed 's/^/    /'
+  bad "broken answer resolvable with validation off (got: $(printf '%s' "$n_out" | grep rcode | head -1))"
+  printf '%s\n' "$n_out" | sed 's/^/    /'
 fi
-rm -rf "$FWD_DIR"
+rm -rf "$FWD_V" "$FWD_B" "$FWD_N"
 
 say ""
 say "=================================================="