Commit 1d516f3951 for bind

commit 1d516f3951a5f4ae08d9a77f718c430600d4b758
Author: Štěpán Balážik <stepan@isc.org>
Date:   Mon Oct 19 18:09:18 2026 +0200

    Sign the f004 zone with isctest.zone

    ans1 loaded a key from keys.json, signed every answer by hand and
    picked its answer with one if-else over the query.  The fixture now
    signs f004.test, the server answers from the zone, and the forged NSECs
    for CD=1 queries are subclasses of the shared forging handler; their
    RRSIGs keep the key tag no key of the zone has, so the resolver caches
    them at pending trust instead of failing them.  The two f004 modules
    set the zone up the same way, so f004_bootstrap() and the zone's names
    live in common.py.

    Assisted-by: Claude:claude-fable-5-1

diff --git a/bin/tests/system/nsec_synthesis/ans1/ans.py b/bin/tests/system/nsec_synthesis/ans1/ans.py
index 0528197e4d..8a93bc33bc 100644
--- a/bin/tests/system/nsec_synthesis/ans1/ans.py
+++ b/bin/tests/system/nsec_synthesis/ans1/ans.py
@@ -9,14 +9,59 @@
 # See the COPYRIGHT file distributed with this work for additional
 # information regarding copyright ownership.

+
+import dns.flags
+import dns.rcode
+import dns.rdatatype
+
 from isctest.asyncserver import AsyncDnsServer
-from nsec_synthesis.ans1 import common, f004
+from isctest.asyncserver.handlers import StaticResponseHandler
+from isctest.asyncserver.matchers import Flags, Qname, Qtype
+
+from ..nsec_synthesis_ans import AttackNsecHandler
+
+
+class AttackCoveringNsecHandler(AttackNsecHandler):
+    """
+    An NSEC whose next name reaches past victim.f004.test, covering it.
+    """
+
+    matcher = (
+        Qname("attacker.f004.test.") & Qtype(dns.rdatatype.NSEC) & Flags(dns.flags.CD)
+    )
+    nsec = "b.victim.f004.test. NS SOA RRSIG NSEC DNSKEY"
+    key_tag = 9999
+
+
+class AttackNodataNsecHandler(AttackNsecHandler):
+    """
+    An NSEC owned by victim.f004.test itself, whose type bitmap omits A but
+    includes the NSEC and RRSIG types query_coveringnsec() requires; if
+    trusted, it would prove a NODATA for victim/A and hide the real A record.
+    """
+
+    matcher = (
+        Qname("victim.f004.test.") & Qtype(dns.rdatatype.NSEC) & Flags(dns.flags.CD)
+    )
+    nsec = "z.f004.test. TXT RRSIG NSEC"
+    key_tag = 9999
+
+
+class RefusedNsecHandler(StaticResponseHandler):
+    matcher = Qname("attacker.f004.test.", "victim.f004.test.") & Qtype(
+        dns.rdatatype.NSEC
+    )
+    rcode = dns.rcode.REFUSED
+    authoritative = True


 def main() -> None:
-    keys = common.load_keys()
-    server = AsyncDnsServer(default_aa=True)
-    server.install_response_handler(f004.F004Handler(keys))
+    server = AsyncDnsServer(default_rcode=dns.rcode.NOERROR)
+    server.install_response_handlers(
+        AttackCoveringNsecHandler(),
+        AttackNodataNsecHandler(),
+    )
+    server.install_response_handlers(RefusedNsecHandler())
     server.run()


diff --git a/bin/tests/system/nsec_synthesis/ans1/common.py b/bin/tests/system/nsec_synthesis/ans1/common.py
deleted file mode 100644
index da10366591..0000000000
--- a/bin/tests/system/nsec_synthesis/ans1/common.py
+++ /dev/null
@@ -1,105 +0,0 @@
-# Copyright (C) Internet Systems Consortium, Inc. ("ISC")
-#
-# SPDX-License-Identifier: MPL-2.0
-#
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, you can obtain one at https://mozilla.org/MPL/2.0/.
-#
-# See the COPYRIGHT file distributed with this work for additional
-# information regarding copyright ownership.
-
-from dataclasses import dataclass
-from pathlib import Path
-
-import json
-
-from cryptography.hazmat.primitives import serialization
-
-import dns.dnssec
-import dns.flags
-import dns.message
-import dns.name
-import dns.rcode
-import dns.rdata
-import dns.rdataclass
-import dns.rdatatype
-import dns.rrset
-
-from isctest.asyncserver import QueryContext
-
-TTL = 300
-
-
-@dataclass(frozen=True)
-class Key:
-    zone: dns.name.Name
-    private_key: object
-    dnskey: dns.rdata.Rdata
-    ds: dns.rdata.Rdata
-
-
-def name(text: str) -> dns.name.Name:
-    return dns.name.from_text(text)
-
-
-def load_keys() -> dict[str, Key]:
-    keys = {}
-
-    path = Path(".") / "keys.json"
-    if not path.exists():
-        return keys
-
-    with path.open(encoding="utf-8") as keys_file:
-        raw_keys = json.load(keys_file)
-
-    for zone, raw_key in raw_keys.items():
-        private_key = serialization.load_pem_private_key(
-            raw_key["private_pem"].encode("ascii"),
-            password=None,
-        )
-        dnskey = dns.rdata.from_text(
-            dns.rdataclass.IN, dns.rdatatype.DNSKEY, raw_key["dnskey"]
-        )
-        ds = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.DS, raw_key["ds"])
-        keys[zone] = Key(name(zone), private_key, dnskey, ds)
-
-    return keys
-
-
-def rrset(owner: str, rdtype: dns.rdatatype.RdataType, *rdatas: str) -> dns.rrset.RRset:
-    return dns.rrset.from_text(owner, TTL, dns.rdataclass.IN, rdtype, *rdatas)
-
-
-def rrset_from_rdata(owner: str, rdata: dns.rdata.Rdata) -> dns.rrset.RRset:
-    return dns.rrset.from_rdata(owner, TTL, rdata)
-
-
-def add_signed(
-    section: list[dns.rrset.RRset], covered: dns.rrset.RRset, signer: Key
-) -> None:
-    rrsig = dns.dnssec.sign(
-        covered,
-        signer.private_key,
-        signer.zone,
-        signer.dnskey,
-        lifetime=86400,
-        verify=True,
-    )
-    section.append(covered)
-    section.append(dns.rrset.from_rdata(covered.name, covered.ttl, rrsig))
-
-
-def soa_rrset(zone) -> dns.rrset.RRset:
-    return rrset(
-        zone,
-        dns.rdatatype.SOA,
-        f"ns.{zone} hostmaster.{zone} 1 3600 600 86400 300",
-    )
-
-
-def prepare_response(qctx: QueryContext) -> dns.message.Message:
-    qctx.prepare_new_response(with_zone_data=False)
-    qctx.response.flags |= dns.flags.AA
-    qctx.response.set_rcode(dns.rcode.NOERROR)
-    return qctx.response
diff --git a/bin/tests/system/nsec_synthesis/ans1/f004.py b/bin/tests/system/nsec_synthesis/ans1/f004.py
deleted file mode 100644
index 648730d15d..0000000000
--- a/bin/tests/system/nsec_synthesis/ans1/f004.py
+++ /dev/null
@@ -1,132 +0,0 @@
-# Copyright (C) Internet Systems Consortium, Inc. ("ISC")
-#
-# SPDX-License-Identifier: MPL-2.0
-#
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, you can obtain one at https://mozilla.org/MPL/2.0/.
-#
-# See the COPYRIGHT file distributed with this work for additional
-# information regarding copyright ownership.
-
-from collections.abc import AsyncGenerator
-from datetime import datetime, timedelta, timezone
-
-import base64
-
-import dns.flags
-import dns.rcode
-import dns.rdata
-import dns.rdataclass
-import dns.rdatatype
-import dns.rrset
-
-from isctest.asyncserver import QueryContext, ResponseHandler
-from isctest.asyncserver.actions import DnsResponseSend
-from isctest.asyncserver.matchers import Domain
-from nsec_synthesis.ans1.common import (
-    Key,
-    add_signed,
-    name,
-    prepare_response,
-    rrset,
-    rrset_from_rdata,
-    soa_rrset,
-)
-
-TTL = 300
-F004_ZONE = "f004.test."
-ATTACKER = "attacker.f004.test."
-VICTIM = "victim.f004.test."
-VICTIM_A = "203.0.113.1"
-POISON_NEXT = f"b.{VICTIM}"
-VICTIM_NODATA_NEXT = f"z.{F004_ZONE}"
-
-
-def attacker_nsec_rrset() -> dns.rrset.RRset:
-    return rrset(
-        ATTACKER,
-        dns.rdatatype.NSEC,
-        f"{POISON_NEXT} NS SOA RRSIG NSEC DNSKEY",
-    )
-
-
-def victim_nodata_nsec_rrset() -> dns.rrset.RRset:
-    # An NSEC owned by the victim name itself, whose type bitmap omits A but
-    # includes the NSEC and RRSIG types query_coveringnsec requires. If it
-    # were trusted, it would prove a NODATA for victim/A and hide the real
-    # A record below.
-    return rrset(
-        VICTIM,
-        dns.rdatatype.NSEC,
-        f"{VICTIM_NODATA_NEXT} TXT RRSIG NSEC",
-    )
-
-
-def garbage_rrsig(covered: dns.rrset.RRset, signer: Key) -> dns.rrset.RRset:
-    now = datetime.now(timezone.utc)
-    inception = (now - timedelta(hours=1)).strftime("%Y%m%d%H%M%S")
-    expiration = (now + timedelta(days=1)).strftime("%Y%m%d%H%M%S")
-    signature = base64.b64encode(bytes(64)).decode("ascii")
-    text = (
-        f"{dns.rdatatype.to_text(covered.rdtype)} "
-        f"{signer.dnskey.algorithm} 3 {covered.ttl} "
-        f"{expiration} {inception} 9999 {F004_ZONE} {signature}"
-    )
-    rdata = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.RRSIG, text)
-    return dns.rrset.from_rdata(covered.name, covered.ttl, rdata)
-
-
-class F004Handler(ResponseHandler):
-    matcher = Domain(F004_ZONE)
-
-    def __init__(self, keys: dict[str, Key]) -> None:
-        super().__init__()
-        self.keys = keys
-
-        if F004_ZONE not in keys:
-            return
-
-        self.key = keys[F004_ZONE]
-        self.parent = name(F004_ZONE)
-        self.attacker = name(ATTACKER)
-        self.victim = name(VICTIM)
-
-    async def get_responses(
-        self, qctx: QueryContext
-    ) -> AsyncGenerator[DnsResponseSend, None]:
-        response = prepare_response(qctx)
-
-        if qctx.qname == self.parent and qctx.qtype == dns.rdatatype.DNSKEY:
-            add_signed(
-                response.answer,
-                rrset_from_rdata(F004_ZONE, self.key.dnskey),
-                self.key,
-            )
-        elif qctx.qname == self.parent and qctx.qtype == dns.rdatatype.SOA:
-            add_signed(response.answer, soa_rrset(F004_ZONE), self.key)
-        elif qctx.qname == self.attacker and qctx.qtype == dns.rdatatype.NSEC:
-            if qctx.query.flags & dns.flags.CD:
-                nsec = attacker_nsec_rrset()
-                response.answer.append(nsec)
-                response.answer.append(garbage_rrsig(nsec, self.key))
-            else:
-                response.set_rcode(dns.rcode.REFUSED)
-        elif qctx.qname == self.victim and qctx.qtype == dns.rdatatype.NSEC:
-            if qctx.query.flags & dns.flags.CD:
-                nsec = victim_nodata_nsec_rrset()
-                response.answer.append(nsec)
-                response.answer.append(garbage_rrsig(nsec, self.key))
-            else:
-                response.set_rcode(dns.rcode.REFUSED)
-        elif qctx.qname == self.victim and qctx.qtype == dns.rdatatype.A:
-            add_signed(
-                response.answer,
-                rrset(VICTIM, dns.rdatatype.A, VICTIM_A),
-                self.key,
-            )
-        else:
-            response.set_rcode(dns.rcode.NXDOMAIN)
-            add_signed(response.authority, soa_rrset(F004_ZONE), self.key)
-
-        yield DnsResponseSend(response, authoritative=True)
diff --git a/bin/tests/system/nsec_synthesis/ans1/zones/f004.test.db.j2.manual b/bin/tests/system/nsec_synthesis/ans1/zones/f004.test.db.j2.manual
new file mode 100644
index 0000000000..fb6ce61025
--- /dev/null
+++ b/bin/tests/system/nsec_synthesis/ans1/zones/f004.test.db.j2.manual
@@ -0,0 +1,4 @@
+{% include "_common/zones/soa.partial.db.j2" %}
+{% include "_common/zones/ns.partial.db.j2" %}
+
+victim	A	203.0.113.1
diff --git a/bin/tests/system/nsec_synthesis/common.py b/bin/tests/system/nsec_synthesis/common.py
index a24ad70c06..a44ce149e4 100644
--- a/bin/tests/system/nsec_synthesis/common.py
+++ b/bin/tests/system/nsec_synthesis/common.py
@@ -9,10 +9,6 @@
 # See the COPYRIGHT file distributed with this work for additional
 # information regarding copyright ownership.

-from cryptography.hazmat.primitives import serialization
-from cryptography.hazmat.primitives.asymmetric import ec
-
-import dns.dnssec
 import dns.name
 import dns.rdataclass
 import dns.rdatatype
@@ -20,13 +16,14 @@ import pytest

 import isctest
 import isctest.mark
+import isctest.template
+import isctest.zone

 SIGNED_ZONE_MARKS = [
     isctest.mark.with_ecdsa_deterministic,
     pytest.mark.extra_artifacts(
         [
             "ans*/dsset-*",
-            "ans*/keys.json",
             "ans*/zones/*.db",
             "ans*/zones/*.db.signed",
         ]
@@ -34,24 +31,15 @@ SIGNED_ZONE_MARKS = [
 ]


-def make_key(zone: str):
-    private_key = ec.generate_private_key(ec.SECP256R1())
-    dnskey = dns.dnssec.make_dnskey(
-        private_key.public_key(),
-        algorithm="ECDSAP256SHA256",
-        flags=257,
-    )
-    ds = dns.dnssec.make_ds(dns.name.from_text(zone), dnskey, "SHA256")
-    private_pem = private_key.private_bytes(
-        encoding=serialization.Encoding.PEM,
-        format=serialization.PrivateFormat.PKCS8,
-        encryption_algorithm=serialization.NoEncryption(),
-    ).decode("ascii")
-    return {
-        "private_pem": private_pem,
-        "dnskey": dnskey.to_text(),
-        "ds": ds.to_text(),
-    }
+F004_ZONE = "f004.test."
+F004_VICTIM = f"victim.{F004_ZONE}"
+F004_VICTIM_A = "203.0.113.1"
+
+
+def f004_bootstrap():
+    zone = isctest.zone.Zone(F004_ZONE, isctest.template.ANS1, signed=True)
+    zone.configure(csk=True)
+    return {"trust_anchors": zone.trust_anchors()}


 def has_a(response, owner, address):
diff --git a/bin/tests/system/nsec_synthesis/tests_nsec_exact_nodata.py b/bin/tests/system/nsec_synthesis/tests_nsec_exact_nodata.py
index a89aba2cfd..c8d743cbde 100644
--- a/bin/tests/system/nsec_synthesis/tests_nsec_exact_nodata.py
+++ b/bin/tests/system/nsec_synthesis/tests_nsec_exact_nodata.py
@@ -9,37 +9,28 @@
 # See the COPYRIGHT file distributed with this work for additional
 # information regarding copyright ownership.

-from pathlib import Path
-
-import json
-
-from isctest.template import TrustAnchor
 from nsec_synthesis.common import (
+    F004_VICTIM,
+    F004_VICTIM_A,
+    F004_ZONE,
     SIGNED_ZONE_MARKS,
     check_forged_nsec,
+    f004_bootstrap,
     get_nsec,
     has_a,
-    make_key,
 )

 import isctest
+import isctest.template

-F004_ZONE = "f004.test."
-VICTIM = f"victim.{F004_ZONE}"
 POISON_NEXT = f"z.{F004_ZONE}"
-VICTIM_A = "203.0.113.1"
-AUTH = "10.53.0.1"
-RESOLVER = "10.53.0.2"
+RESOLVER = isctest.template.NS2.ip

 pytestmark = SIGNED_ZONE_MARKS


 def bootstrap():
-    keys = {F004_ZONE: make_key(F004_ZONE)}
-    Path("ans1/keys.json").write_text(json.dumps(keys, indent=2), encoding="ascii")
-    dnskey = keys[F004_ZONE]["dnskey"].split()
-    contents = f'{" ".join(dnskey[:3])} "{"".join(dnskey[3:])}"'
-    return {"trust_anchors": [TrustAnchor(F004_ZONE, "static-key", contents)]}
+    return f004_bootstrap()


 def test_pending_exact_nodata_nsec_cache_poisoning():
@@ -60,16 +51,18 @@ def test_pending_exact_nodata_nsec_cache_poisoning():

     # Inject a forged NSEC owned by the victim name via a CD=1 query; it is
     # cached at pending trust on the victim node.
-    poison = isctest.query.tcp(isctest.query.create(VICTIM, "NSEC", cd=True), RESOLVER)
+    poison = isctest.query.tcp(
+        isctest.query.create(F004_VICTIM, "NSEC", cd=True), RESOLVER
+    )
     isctest.check.noerror(poison)
     isctest.check.noadflag(poison)
-    check_forged_nsec(poison, poison.answer, VICTIM, POISON_NEXT, F004_ZONE, 9999)
+    check_forged_nsec(poison, poison.answer, F004_VICTIM, POISON_NEXT, F004_ZONE, 9999)

     # Query the victim's A record. The pending NSEC must not be used to
     # synthesize a NODATA; the resolver fetches and validates the real A.
-    response = isctest.query.tcp(isctest.query.create(VICTIM, "A"), RESOLVER)
+    response = isctest.query.tcp(isctest.query.create(F004_VICTIM, "A"), RESOLVER)
     isctest.check.noerror(response)
-    assert has_a(response, VICTIM, VICTIM_A), response.to_text()
+    assert has_a(response, F004_VICTIM, F004_VICTIM_A), response.to_text()
     isctest.check.adflag(response)
-    assert not get_nsec(response, response.answer, VICTIM)
-    assert not get_nsec(response, response.authority, VICTIM)
+    assert not get_nsec(response, response.answer, F004_VICTIM)
+    assert not get_nsec(response, response.authority, F004_VICTIM)
diff --git a/bin/tests/system/nsec_synthesis/tests_nsec_pending_cd.py b/bin/tests/system/nsec_synthesis/tests_nsec_pending_cd.py
index a2f4ac37ad..aadb0853e7 100644
--- a/bin/tests/system/nsec_synthesis/tests_nsec_pending_cd.py
+++ b/bin/tests/system/nsec_synthesis/tests_nsec_pending_cd.py
@@ -9,38 +9,29 @@
 # See the COPYRIGHT file distributed with this work for additional
 # information regarding copyright ownership.

-from pathlib import Path
-
-import json
-
-from isctest.template import TrustAnchor
 from nsec_synthesis.common import (
+    F004_VICTIM,
+    F004_VICTIM_A,
+    F004_ZONE,
     SIGNED_ZONE_MARKS,
     check_forged_nsec,
+    f004_bootstrap,
     get_nsec,
     has_a,
-    make_key,
 )

 import isctest
+import isctest.template

-F004_ZONE = "f004.test."
 ATTACKER = f"attacker.{F004_ZONE}"
-VICTIM = f"victim.{F004_ZONE}"
-POISON_NEXT = f"b.{VICTIM}"
-VICTIM_A = "203.0.113.1"
-AUTH = "10.53.0.1"
-RESOLVER = "10.53.0.2"
+POISON_NEXT = f"b.{F004_VICTIM}"
+RESOLVER = isctest.template.NS2.ip

 pytestmark = SIGNED_ZONE_MARKS


 def bootstrap():
-    keys = {F004_ZONE: make_key(F004_ZONE)}
-    Path("ans1/keys.json").write_text(json.dumps(keys, indent=2), encoding="ascii")
-    dnskey = keys[F004_ZONE]["dnskey"].split()
-    contents = f'{" ".join(dnskey[:3])} "{"".join(dnskey[3:])}"'
-    return {"trust_anchors": [TrustAnchor(F004_ZONE, "static-key", contents)]}
+    return f004_bootstrap()


 def test_pending_trust_nsec_cd_cache_poisoning():
@@ -62,21 +53,21 @@ def test_pending_trust_nsec_cd_cache_poisoning():
     check_forged_nsec(poison, poison.answer, ATTACKER, POISON_NEXT, F004_ZONE, 9999)

     # Step 3: Exploit Against Victim Domain
-    response = isctest.query.tcp(isctest.query.create(VICTIM, "A"), RESOLVER)
+    response = isctest.query.tcp(isctest.query.create(F004_VICTIM, "A"), RESOLVER)
     isctest.check.noerror(response)
-    assert has_a(response, VICTIM, VICTIM_A), response.to_text()
+    assert has_a(response, F004_VICTIM, F004_VICTIM_A), response.to_text()
     isctest.check.adflag(response)
     assert not get_nsec(response, response.authority, ATTACKER)

     # Step 4: Exploit Against Stub Client
     response = isctest.query.tcp(
-        isctest.query.create(VICTIM, "A", dnssec=False), RESOLVER
+        isctest.query.create(F004_VICTIM, "A", dnssec=False), RESOLVER
     )
     isctest.check.noerror(response)
-    assert has_a(response, VICTIM, VICTIM_A), response.to_text()
+    assert has_a(response, F004_VICTIM, F004_VICTIM_A), response.to_text()
     isctest.check.adflag(response)
     assert not get_nsec(response, response.authority, ATTACKER)

     # Step 5: Verify Upstream Queries
     with open("ans1/ans.run", "r", encoding="utf-8") as file:
-        assert f"Received {VICTIM.rstrip('.')}/IN/A" in file.read()
+        assert f"Received {F004_VICTIM.rstrip('.')}/IN/A" in file.read()