Commit 686d0bde6b for bind

commit 686d0bde6b1d53452253f4b762f2979644306469
Author: Michał Kępień <michal@isc.org>
Date:   Thu Nov 19 18:11:24 2026 +0100

    Simplify nsec_grandparent test

    Replace boilerplate code signing the zones used by the ans1 custom
    server with canonical bootstrap() code employing isctest.zone.Zone.

    Replace boilerplate code crafting DNSSEC responses in ans1/ans.py with
    zone file data in ans1/zones/ and minimal handler logic implementing the
    attacks attempted by the test.

    Co-authored-by: Štěpán Balážik <stepan@isc.org>

diff --git a/bin/tests/system/nsec_grandparent/ans1/ans.py b/bin/tests/system/nsec_grandparent/ans1/ans.py
index fe9968aa4d..85db59fa5c 100644
--- a/bin/tests/system/nsec_grandparent/ans1/ans.py
+++ b/bin/tests/system/nsec_grandparent/ans1/ans.py
@@ -10,16 +10,10 @@
 # information regarding copyright ownership.

 from collections.abc import AsyncGenerator
-from dataclasses import dataclass
-from pathlib import Path

-import json
-
-from cryptography.hazmat.primitives import serialization
+import abc

 import dns.dnssec
-import dns.flags
-import dns.message
 import dns.name
 import dns.rcode
 import dns.rdata
@@ -29,426 +23,266 @@ import dns.rrset

 from isctest.asyncserver import AsyncDnsServer, QueryContext, ResponseHandler
 from isctest.asyncserver.actions import DnsResponseSend
-from isctest.asyncserver.matchers import Domain
-
-TTL = 300
-PARENT = "p031.test."
-CHILD = f"c.{PARENT}"
-# The attacker-controlled sibling zone: a genuine, correctly delegated and
-# signed zone under the same parent as CHILD.  Its crafted NSEC3 is made
-# to sort first in the ncache via the salt choice below (see _ordering_salts).
-SIBLING = f"attacker.{PARENT}"
-# #5967 (grandparent-zone NSEC/NSEC3): a grandchild whose forged NSEC/NSEC3
-# insecure-delegation proof is owned by its grandparent zone.
-GRANDCHILD = f"grand.{CHILD}"
-GRANDCHILD3 = f"grand3.{CHILD}"
-# #6234 (sibling-zone NSEC3): a grandchild whose forged NSEC3
-# insecure-delegation proof is owned by an unrelated but correctly delegated
-# and signed sibling zone.
-GRANDCHILD3_SIBLING = f"grandsib.{CHILD}"
-# #6321 (mixed-signer RRSIG): grandchildren whose grandparent-signed NSEC
-# forgery also carries a dummy RRSIG naming the NSEC owner itself as signer,
-# in either order relative to the genuine one.
-GRANDCHILD_DUMMY_FIRST = f"grand-dummy-first.{CHILD}"
-GRANDCHILD_DUMMY_LAST = f"grand-dummy-last.{CHILD}"
-# RRSIG count cap: grandchildren whose grandparent-signed NSEC forgery carries
-# as many same-signer RRSIGs as ns2 allows validations per fetch, or one fewer.
-GRANDCHILD_TOO_MANY = f"grand-too-many.{CHILD}"
-GRANDCHILD_ALMOST_TOO_MANY = f"grand-almost-too-many.{CHILD}"
-# The names under attack.
-ATTACK = f"www-bind.{GRANDCHILD}"
-ATTACK3 = f"www-bind.{GRANDCHILD3}"
-FORGED_A = "6.6.6.60"
-# Not a DNSSEC algorithm; the validator skips RRSIGs using it as unsupported
-# rather than rejecting them, which is what the mixed-signer forgery needs.
-DUMMY_ALGORITHM = 0
-# ns2's max-validations-per-fetch; keep in sync with the test module.
+from isctest.asyncserver.matchers import Qname, Qtype
+
 MAX_VALIDATIONS_PER_FETCH = 16


-@dataclass(frozen=True)
-class Key:
-    zone: dns.name.Name
-    private_key: object
-    dnskey: dns.rdata.Rdata
+def rrset(
+    owner: str | dns.name.Name,
+    rdtype: dns.rdatatype.RdataType,
+    rdata: str,
+    ttl: int = 300,
+) -> dns.rrset.RRset:
+    return dns.rrset.from_text(owner, ttl, dns.rdataclass.IN, rdtype, rdata)
+
+
+def a(owner: str | dns.name.Name, address: str) -> dns.rrset.RRset:
+    return rrset(owner, dns.rdatatype.A, address)


-def name(text: str) -> dns.name.Name:
-    return dns.name.from_text(text)
+def nsec(owner: str | dns.name.Name, next_name: str, types: str) -> dns.rrset.RRset:
+    return rrset(owner, dns.rdatatype.NSEC, f"{next_name} {types}")


-def _ordering_salts(qname: str) -> tuple[str, str]:
-    # Pick NSEC3 salts (as hex) so the sibling's owner hash sorts strictly
-    # before the child's.  The ncache slab is ordered by wire-format owner
-    # name -- i.e. by the leftmost hash label -- and is_insecure_referral()'s
-    # trynsec3 arm returns on the *first* exact hash match, so the sibling's
-    # crafted NS-set NSEC3 must precede the child's genuine NS-clear NODATA
-    # proof.  Deterministic search over one-octet salts keeps this true no
-    # matter what GRANDCHILD3_SIBLING is named.
-    hashes = sorted(
-        (dns.dnssec.nsec3_hash(name(qname), f"{i:02X}", 0, 1).lower(), f"{i:02X}")
-        for i in range(256)
+def nsec3(
+    owner: str | dns.name.Name,
+    next_hash: str,
+    salt: bytes | None = None,
+    iterations: int = 0,
+) -> dns.rrset.RRset:
+    return rrset(
+        owner,
+        dns.rdatatype.NSEC3,
+        f"1 0 {iterations} {salt.hex() if salt else '-'} {next_hash} NS",
     )
-    return hashes[0][1], hashes[-1][1]


-# Sibling salt yields the smallest hash, child salt the largest.
-SIBLING_SALT, CHILD_SALT = _ordering_salts(GRANDCHILD3_SIBLING)
+class GrandchildAHandler(ResponseHandler):
+    """
+    This handler imitates successfully spoofing unsigned responses to A queries
+    sent to a server authoritative for an NSEC(3)-signed grandchild zone.  The
+    subsequent validation-related queries are handled by subclasses of
+    SpoofedNsecHandler, which intend to trick the validator into treating the
+    grandchild zones as unsigned ones by signing forged NSEC(3) records with
+    the grandparent zone's signing key.
+    """
+
+    matcher = Qname(
+        "www-bind.grand.c.p031.test.",
+        "www2-bind.grand.c.p031.test.",
+        "www-bind.grand-dummy-first.c.p031.test.",
+        "www2-bind.grand-dummy-first.c.p031.test.",
+        "www-bind.grand-dummy-last.c.p031.test.",
+        "www-bind.grand-too-many.c.p031.test.",
+        "www-bind.grand-almost-too-many.c.p031.test.",
+        "www-bind.grand3.c.p031.test.",
+        "www-bind.grandsib.c.p031.test.",
+    ) & Qtype(dns.rdatatype.A)

+    async def get_responses(
+        self, qctx: QueryContext
+    ) -> AsyncGenerator[DnsResponseSend, None]:
+        qctx.prepare_new_response(with_zone_data=False)
+        qctx.response.answer.append(a(qctx.qname, "6.6.6.60"))
+        yield DnsResponseSend(qctx.response)

-def load_keys() -> dict[str, Key]:
-    path = Path(__file__).resolve().parent / "keys.json"
-    with path.open(encoding="utf-8") as keys_file:
-        raw = json.load(keys_file)

-    keys: dict[str, Key] = {}
-    for zone, raw_key in raw.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"]
-        )
-        keys[zone] = Key(name(zone), private_key, dnskey)
-    return keys
+class SpoofedNsecHandler(ResponseHandler, abc.ABC):
+    """
+    This handler imitates successfully spoofing a response to a DS query for a
+    signed grandchild domain; the spoofed response is a negative one,
+    containing an NSEC(3) record correctly signed by the grandparent's signing
+    key; it "proves" the nonexistence of the grandchild's DS record in the
+    grandparent zone.  A vulnerable resolver treats such a response as
+    sufficient to prove that the grandchild zone is an insecure one.
+    """

+    qname: str

-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 __init__(self) -> None:
+        self.matcher = Qname(self.qname) & Qtype(dns.rdatatype.DS)

+    async def get_responses(
+        self, qctx: QueryContext
+    ) -> AsyncGenerator[DnsResponseSend, None]:
+        qctx.prepare_new_response(with_zone_data=False)

-def rrset_from_rdata(owner: str, rdata: dns.rdata.Rdata) -> dns.rrset.RRset:
-    return dns.rrset.from_rdata(name(owner), TTL, rdata)
+        grandparent_origin = qctx.qname.parent().parent()
+        qctx.zone = qctx.zones[grandparent_origin]

+        assert qctx.zone
+        assert qctx.zone.origin
+        soa_rrset = qctx.zone.get_rrset(qctx.zone.origin, dns.rdatatype.SOA)
+        assert soa_rrset
+        if soa_rrsig := qctx.get_rrsig(soa_rrset):
+            qctx.response.authority.append(soa_rrset)
+            qctx.response.authority.append(soa_rrsig)

-def sign(covered: dns.rrset.RRset, signer: Key) -> dns.rdata.Rdata:
-    return dns.dnssec.sign(
-        covered,
-        signer.private_key,
-        signer.zone,
-        signer.dnskey,
-        lifetime=86400,
-        verify=True,
-    )
+        qctx.response.authority.append(self.spoofed_rrset)
+        genuine_rrsig = qctx.sign(self.spoofed_rrset)

+        for rrsig_rdata in self.rrsigs(genuine_rrsig[0]):
+            rrsig = dns.rrset.from_rdata(
+                genuine_rrsig.name, genuine_rrsig.ttl, rrsig_rdata
+            )
+            qctx.response.authority.append(rrsig)

-def add_signed(
-    section: list[dns.rrset.RRset], covered: dns.rrset.RRset, signer: Key
-) -> None:
-    rrsig = sign(covered, signer)
-    section.append(covered)
-    section.append(dns.rrset.from_rdata(covered.name, covered.ttl, rrsig))
+        yield DnsResponseSend(qctx.response)

+    @property
+    @abc.abstractmethod
+    def spoofed_rrset(self) -> dns.rrset.RRset:
+        raise NotImplementedError

-def soa_rrset() -> dns.rrset.RRset:
-    return rrset(
-        PARENT,
-        dns.rdatatype.SOA,
-        f"ns.{PARENT} hostmaster.{PARENT} 1 3600 600 86400 300",
-    )
+    def rrsigs(self, genuine: dns.rdata.Rdata) -> list[dns.rdata.Rdata]:
+        """
+        The RRSIGs to send for the spoofed record, in wire order.
+        """
+        return [genuine]


-def nsec_rrset(owner: str, next_name: str, *types: str) -> dns.rrset.RRset:
-    return rrset(owner, dns.rdatatype.NSEC, f"{next_name} {' '.join(types)}")
+class GrandchildDsNsecHandler(SpoofedNsecHandler):
+    qname = "grand.c.p031.test."

+    @property
+    def spoofed_rrset(self) -> dns.rrset.RRset:
+        return nsec(self.qname, "grandz.c.p031.test.", "NS RRSIG NSEC")

-def child_soa_rrset() -> dns.rrset.RRset:
-    return rrset(
-        CHILD,
-        dns.rdatatype.SOA,
-        f"ns.{CHILD} hostmaster.{CHILD} 1 3600 600 86400 300",
-    )

+class GrandchildDsNsec3Handler(SpoofedNsecHandler):
+    qname = "grand3.c.p031.test."

-def nsec_lie(owner: str) -> dns.rrset.RRset:
-    # An NSEC owned by the grandparent zone P at a name that really belongs
-    # to the secure child C, showing an (insecure) delegation: NS bit set,
-    # DS bit clear.
-    return nsec_rrset(owner, f"grandz.{CHILD}", "NS", "RRSIG", "NSEC")
+    @property
+    def spoofed_rrset(self) -> dns.rrset.RRset:
+        qname = dns.name.from_text(self.qname)
+        nsec3_hash = dns.dnssec.nsec3_hash(qname, None, 0, 1)
+        nsec3_owner = dns.name.from_text(nsec3_hash, origin=qname.parent().parent())
+        return nsec3(nsec3_owner, nsec3_hash)


-def grandchild_nsec_lie() -> dns.rrset.RRset:
-    return nsec_lie(GRANDCHILD)
+class GrandsiblingDsHandler(ResponseHandler):
+    """
+    This handler imitates successfully spoofing a response to a DS query for a
+    signed grandchild domain ("grandsib.c.p031.test."); the spoofed response is
+    one replayed from the child zone ("c.p031.test."), but with a forged NSEC3
+    record prepended to its AUTHORITY section; that forged record is signed
+    using a sibling zone's ("attacker.p031.test.") signing key.  The sibling
+    zone's NSEC3 salt is chosen specifically so that the NSEC3 hash for
+    "grandsib.c.p031.test." salted with the sibling zone's salt sorts before
+    the NSEC3 hash for the same name salted with the child zone's salt.  A
+    vulnerable resolver treats such a response as sufficient to prove that the
+    grandchild zone is an insecure one.
+    """

+    matcher = Qname("grandsib.c.p031.test.") & Qtype(dns.rdatatype.DS)

-def nsec3_ns_lie(
-    qname: str, zone: str, salt: str | None, salt_text: str
-) -> dns.rrset.RRset:
-    # An NSEC3 owned by 'zone' whose owner hash matches 'qname' under this
-    # record's own parameters, showing an (insecure) delegation: NS bit set, DS
-    # bit clear.  is_insecure_referral()'s trynsec3 arm takes the exact-match
-    # branch (order == 0) before it ever consults the "next" field, so reusing
-    # the owner digest as the next hash is sufficient for it to parse.
-    digest = dns.dnssec.nsec3_hash(name(qname), salt, 0, 1).lower()
-    owner = f"{digest}.{zone}"
-    return rrset(owner, dns.rdatatype.NSEC3, f"1 0 0 {salt_text} {digest} NS")
-
-
-def nsec3_nodata(
-    qname: str, zone: str, salt: str | None, salt_text: str
-) -> dns.rrset.RRset:
-    # A genuine matching NSEC3 for 'qname' in 'zone' with the DS bit clear: a
-    # legitimate NODATA-DS proof (the name exists as an ordinary, non-delegation
-    # node).  The NS bit is clear, so it does not itself assert a delegation.
-    digest = dns.dnssec.nsec3_hash(name(qname), salt, 0, 1).lower()
-    owner = f"{digest}.{zone}"
-    return rrset(owner, dns.rdatatype.NSEC3, f"1 0 0 {salt_text} {digest} TXT RRSIG")
-
-
-def grandchild3_nsec3_lie() -> dns.rrset.RRset:
-    # Same forgery as grandchild_nsec_lie(), but expressed as an NSEC3 signed by
-    # the grandparent so that the resolver reaches is_insecure_referral()'s
-    # trynsec3 arm.
-    return nsec3_ns_lie(GRANDCHILD3, PARENT, None, "-")
-
-
-def add_parent_nodata(
-    response: dns.message.Message, parent_key: Key, nsec: dns.rrset.RRset
-) -> None:
-    add_signed(response.authority, soa_rrset(), parent_key)
-    add_signed(response.authority, nsec, parent_key)
-
-
-def add_nsec3_nodata_from_sibling(
-    response: dns.message.Message, child_key: Key, sibling_key: Key
-) -> None:
-    # #6234: a genuinely signed NSEC3 owned by an unrelated sibling zone whose
-    # owner hash matches the grandchild under the sibling's own parameters and
-    # whose NS bit is set.  Its owner hash sorts before the child proof's (the
-    # salts are chosen for exactly that, see _ordering_salts), so the ncache
-    # iterates it first; trynsec3 matches it and derives the signer as
-    # owner-minus-hash-label -> SIBLING (4 labels), which empties
-    # closer_secure_ds_exists().  No owner-zone relevance check rejects it.  The
-    # child-signed NSEC3 that follows is the real NODATA-DS proof:
-    # dns_nsec3_noexistnodata() ignores the sibling record as out-of-zone, so
-    # the negative answer still validates normally.
-    add_signed(
-        response.authority,
-        nsec3_ns_lie(GRANDCHILD3_SIBLING, SIBLING, SIBLING_SALT, SIBLING_SALT),
-        sibling_key,
-    )
-    add_signed(
-        response.authority,
-        nsec3_nodata(GRANDCHILD3_SIBLING, CHILD, CHILD_SALT, CHILD_SALT),
-        child_key,
-    )
-    add_signed(response.authority, child_soa_rrset(), child_key)
+    async def get_responses(
+        self, qctx: QueryContext
+    ) -> AsyncGenerator[DnsResponseSend, None]:
+        assert qctx.zone
+        assert qctx.zone.origin
+        parent_origin = qctx.zone.origin.parent()
+        sibling_origin = dns.name.from_text("attacker", origin=parent_origin)

+        nsec3param = qctx.zones[sibling_origin].get_rdataset(
+            sibling_origin, dns.rdatatype.NSEC3PARAM
+        )
+        assert nsec3param

-def add_mixed_signer_nodata(
-    response: dns.message.Message,
-    parent_key: Key,
-    nsec: dns.rrset.RRset,
-    dummy_first: bool,
-) -> None:
+        # Salt for this zone is specifically chosen at signing time; see
+        # docstring above and bootstrap() in tests_nsec_grandparent.py.
+        forged_nsec3_hash = dns.dnssec.nsec3_hash(
+            qctx.qname, nsec3param[0].salt, nsec3param[0].iterations, 1
+        )
+        forged_nsec3_owner = dns.name.from_text(
+            forged_nsec3_hash, origin=sibling_origin
+        )
+        forged_nsec3_rrset = nsec3(
+            forged_nsec3_owner,
+            forged_nsec3_hash,
+            salt=nsec3param[0].salt,
+            iterations=nsec3param[0].iterations,
+        )
+
+        sibling_key = qctx.keys[sibling_origin][0]
+        forged_nsec3_rrsig = qctx.sign(forged_nsec3_rrset, key=sibling_key)
+
+        qctx.response.authority.insert(0, forged_nsec3_rrset)
+        qctx.response.authority.insert(1, forged_nsec3_rrsig)
+
+        yield DnsResponseSend(qctx.response)
+
+
+class DummyRrsigGrandchildDsNsecHandler(GrandchildDsNsecHandler, abc.ABC):
     """
-    The same NODATA lie as add_parent_nodata(), but the NSEC carries two
-    RRSIGs: the genuine one from the grandparent P and a dummy one naming
-    the NSEC owner itself as signer.  The dummy uses an unsupported
-    algorithm, so the validator skips it and the NSEC still authenticates
-    through the genuine RRSIG.  All the dummy changes is which signer name
-    comes first in the RRSIG rdataset (#6321).
+    Adds one extra RRSIG to the AUTHORITY section: a dummy one that uses the
+    NSEC record's owner name as the signer name and an unknown signing
+    algorithm (0).  Subclasses add this extra record either before or after the
+    RRSIG prepared using the grandparent's signing key.  This is done to verify
+    whether the resolver under test correctly determines the NSEC signer's
+    authority boundary.
     """
-    add_signed(response.authority, soa_rrset(), parent_key)
-    genuine = sign(nsec, parent_key)
-    dummy = genuine.replace(algorithm=DUMMY_ALGORITHM, signer=nsec.name)
-    rrsigs = [dummy, genuine] if dummy_first else [genuine, dummy]
-
-    response.authority.append(nsec)
-    # One single-rdata RRset per RRSIG: dnspython shuffles the rdatas of an
-    # rdataset when rendering it, and this forgery is all about the order
-    # in which the two signatures arrive.  Separate RRsets keep their list
-    # order on the wire, and the resolver merges them back into one RRSIG
-    # rdataset in that order.
-    for rrsig in rrsigs:
-        response.authority.append(dns.rrset.from_rdata(nsec.name, nsec.ttl, rrsig))
-
-
-def add_many_rrsig_nodata(
-    response: dns.message.Message,
-    parent_key: Key,
-    nsec: dns.rrset.RRset,
-    count: int,
-) -> None:
+
+    dummy_first: bool
+
+    def rrsigs(self, genuine: dns.rdata.Rdata) -> list[dns.rdata.Rdata]:
+        dummy = genuine.replace(algorithm=0, signer=self.qname)
+        return [dummy, genuine] if self.dummy_first else [genuine, dummy]
+
+
+class DummyRrsigFirstGrandchildDsNsecHandler(DummyRrsigGrandchildDsNsecHandler):
+    qname = "grand-dummy-first.c.p031.test."
+    dummy_first = True
+
+
+class DummyRrsigLastGrandchildDsNsecHandler(DummyRrsigGrandchildDsNsecHandler):
+    qname = "grand-dummy-last.c.p031.test."
+    dummy_first = False
+
+
+class ManyRrsigsGrandchildDsNsecHandler(GrandchildDsNsecHandler, abc.ABC):
     """
-    The NODATA lie with 'count' RRSIGs over the NSEC, all naming the
-    grandparent P as signer: count - 1 unsupported-algorithm dummies with
-    distinct key tags and a one-byte signature, then the genuine signature
-    last, so the validator has to skip every dummy before the NSEC
-    authenticates.  With a uniform signer this exercises only the RRSIG
-    count cap in is_insecure_referral(), not the mixed-signer rule.
+    Adds multiple extra RRSIG to the AUTHORITY section, each of which uses a
+    different key tag and a bogus one-byte signature.  Subclasses only define
+    the total number of RRSIG records to put in the AUTHORITY section
+    (including the one prepared using the grandparent's signing key).  This is
+    done to verify whether the resolver under test correctly enforces a count
+    cap on NSEC insecurity proofs.
     """
-    add_signed(response.authority, soa_rrset(), parent_key)
-    genuine = sign(nsec, parent_key)
-    dummies = [
-        genuine.replace(algorithm=DUMMY_ALGORITHM, key_tag=tag, signature=b"\0")
-        for tag in range(count - 1)
-    ]
-
-    response.authority.append(nsec)
-    # Separate single-rdata RRsets, for the same wire-order reason as in
-    # add_mixed_signer_nodata().
-    for rrsig in [*dummies, genuine]:
-        response.authority.append(dns.rrset.from_rdata(nsec.name, nsec.ttl, rrsig))
-
-
-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
-
-
-class GrandparentNsecHandler(ResponseHandler):
-    def __init__(self, keys: dict[str, Key]) -> None:
-        self.parent_key = keys[PARENT]
-        self.child_key = keys[CHILD]
-        self.sibling_key = keys[SIBLING]
-        self.parent = name(PARENT)
-        self.matcher = Domain(self.parent)
-        self.child = name(CHILD)
-        self.sibling = name(SIBLING)
-        self.grandchild = name(GRANDCHILD)
-        self.grandchild3 = name(GRANDCHILD3)
-        self.grandchild3_sibling = name(GRANDCHILD3_SIBLING)
-        self.grandchild_dummy_first = name(GRANDCHILD_DUMMY_FIRST)
-        self.grandchild_dummy_last = name(GRANDCHILD_DUMMY_LAST)
-        self.grandchild_too_many = name(GRANDCHILD_TOO_MANY)
-        self.grandchild_almost_too_many = name(GRANDCHILD_ALMOST_TOO_MANY)
-        self.forged_grandchildren = (
-            self.grandchild,
-            self.grandchild3,
-            self.grandchild3_sibling,
-            self.grandchild_dummy_first,
-            self.grandchild_dummy_last,
-            self.grandchild_too_many,
-            self.grandchild_almost_too_many,
-        )

-    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:
-            # Priming, parent DNSKEY
-            add_signed(
-                response.answer,
-                rrset_from_rdata(PARENT, self.parent_key.dnskey),
-                self.parent_key,
-            )
-        elif qctx.qname == self.parent and qctx.qtype == dns.rdatatype.SOA:
-            # Priming, parent SOA
-            add_signed(response.answer, soa_rrset(), self.parent_key)
-        elif qctx.qname == self.child and qctx.qtype == dns.rdatatype.DS:
-            # Priming, child DS.
-            #
-            # A real DS matching the child key, signed by the parent.  It must
-            # be real rather than a placeholder because the sibling-zone
-            # variant includes an NSEC3 signed by the child, so the child's
-            # DNSKEY has to chain to the parent.  It is also the secure DS at
-            # CHILD that closer_secure_ds_exists() finds when it refuses the
-            # grandparent-signed proofs of the #5967 variants.
-            ds = dns.dnssec.make_ds(self.child, self.child_key.dnskey, "SHA256")
-            add_signed(
-                response.answer,
-                dns.rrset.from_rdata(self.child, TTL, ds),
-                self.parent_key,
-            )
-        elif qctx.qname == self.child and qctx.qtype == dns.rdatatype.DNSKEY:
-            # Priming, child DNSKEY.
-            add_signed(
-                response.answer,
-                rrset_from_rdata(CHILD, self.child_key.dnskey),
-                self.child_key,
-            )
-        elif qctx.qname == self.sibling and qctx.qtype == dns.rdatatype.DS:
-            # Priming, sibling DS.
-            #
-            # The sibling zone is a genuine secure delegation: real DS signed by
-            # the parent, so its own NSEC3 (used in the sibling-zone attack
-            # variant) really validates.
-            ds = dns.dnssec.make_ds(self.sibling, self.sibling_key.dnskey, "SHA256")
-            add_signed(
-                response.answer,
-                dns.rrset.from_rdata(self.sibling, TTL, ds),
-                self.parent_key,
-            )
-        elif qctx.qname == self.sibling and qctx.qtype == dns.rdatatype.DNSKEY:
-            # Priming, sibling DNSKEY.
-            add_signed(
-                response.answer,
-                rrset_from_rdata(SIBLING, self.sibling_key.dnskey),
-                self.sibling_key,
-            )
-        elif qctx.qname == self.grandchild and qctx.qtype == dns.rdatatype.DS:
-            # #5967: Forge no data for grand child DS (NSEC variant).
-            add_parent_nodata(response, self.parent_key, grandchild_nsec_lie())
-        elif qctx.qname == self.grandchild3 and qctx.qtype == dns.rdatatype.DS:
-            # #5967: Forge no data for grand child DS (NSEC3 variant).
-            add_parent_nodata(response, self.parent_key, grandchild3_nsec3_lie())
-        elif qctx.qname == self.grandchild3_sibling and qctx.qtype == dns.rdatatype.DS:
-            # #6234: Sibling-zone-signed NSEC3 ahead of the real child proof.
-            add_nsec3_nodata_from_sibling(response, self.child_key, self.sibling_key)
-        elif (
-            qctx.qname == self.grandchild_dummy_first and qctx.qtype == dns.rdatatype.DS
-        ):
-            # Forge no data for grand child DS, dummy RRSIG before the
-            # genuine one (mixed-signer variant, #6321)
-            add_mixed_signer_nodata(
-                response,
-                self.parent_key,
-                nsec_lie(GRANDCHILD_DUMMY_FIRST),
-                dummy_first=True,
-            )
-        elif (
-            qctx.qname == self.grandchild_dummy_last and qctx.qtype == dns.rdatatype.DS
-        ):
-            # Same forgery, genuine RRSIG before the dummy one
-            add_mixed_signer_nodata(
-                response,
-                self.parent_key,
-                nsec_lie(GRANDCHILD_DUMMY_LAST),
-                dummy_first=False,
-            )
-        elif qctx.qname == self.grandchild_too_many and qctx.qtype == dns.rdatatype.DS:
-            # Forge no data for grand child DS with as many RRSIGs as ns2
-            # allows validations per fetch (RRSIG count cap variant)
-            add_many_rrsig_nodata(
-                response,
-                self.parent_key,
-                nsec_lie(GRANDCHILD_TOO_MANY),
-                count=MAX_VALIDATIONS_PER_FETCH,
-            )
-        elif (
-            qctx.qname == self.grandchild_almost_too_many
-            and qctx.qtype == dns.rdatatype.DS
-        ):
-            # Same forgery with one RRSIG fewer, so it stays under the cap
-            add_many_rrsig_nodata(
-                response,
-                self.parent_key,
-                nsec_lie(GRANDCHILD_ALMOST_TOO_MANY),
-                count=MAX_VALIDATIONS_PER_FETCH - 1,
-            )
-        elif (
-            any(qctx.qname.is_subdomain(g) for g in self.forged_grandchildren)
-            and qctx.qtype == dns.rdatatype.A
-        ):
-            # Attack query
-            response.answer.append(
-                rrset(qctx.qname.to_text(), dns.rdatatype.A, FORGED_A)
-            )
-        else:
-            response.set_rcode(dns.rcode.NXDOMAIN)
+    total_rrsigs: int
+
+    def rrsigs(self, genuine: dns.rdata.Rdata) -> list[dns.rdata.Rdata]:
+        dummies = [
+            genuine.replace(algorithm=0, key_tag=key_tag, signature=b"\0")
+            for key_tag in range(self.total_rrsigs - 1)
+        ]
+        return dummies + [genuine]

-        yield DnsResponseSend(response, authoritative=True)
+
+class TooManyRrsigsGrandchildDsNsecHandler(ManyRrsigsGrandchildDsNsecHandler):
+    qname = "grand-too-many.c.p031.test."
+    total_rrsigs = MAX_VALIDATIONS_PER_FETCH
+
+
+class AlmostTooManyRrsigsGrandchildDsNsecHandler(ManyRrsigsGrandchildDsNsecHandler):
+    qname = "grand-almost-too-many.c.p031.test."
+    total_rrsigs = MAX_VALIDATIONS_PER_FETCH - 1


 def main() -> None:
-    server = AsyncDnsServer(default_aa=True)
-    server.install_response_handlers(GrandparentNsecHandler(load_keys()))
+    server = AsyncDnsServer(default_rcode=dns.rcode.NOERROR, default_aa=True)
+    server.install_response_handlers(
+        GrandchildAHandler(),
+        GrandchildDsNsecHandler(),
+        GrandchildDsNsec3Handler(),
+        GrandsiblingDsHandler(),
+        DummyRrsigFirstGrandchildDsNsecHandler(),
+        DummyRrsigLastGrandchildDsNsecHandler(),
+        TooManyRrsigsGrandchildDsNsecHandler(),
+        AlmostTooManyRrsigsGrandchildDsNsecHandler(),
+    )
     server.run()


diff --git a/bin/tests/system/nsec_grandparent/ans1/zones/c.p031.test.db.j2.manual b/bin/tests/system/nsec_grandparent/ans1/zones/c.p031.test.db.j2.manual
new file mode 100644
index 0000000000..ea405264e6
--- /dev/null
+++ b/bin/tests/system/nsec_grandparent/ans1/zones/c.p031.test.db.j2.manual
@@ -0,0 +1,3 @@
+{% include "_common/zones/template.db.j2.manual" %}
+
+grandsib	TXT	"foo"
diff --git a/bin/tests/system/nsec_grandparent/ns2/named.conf.j2 b/bin/tests/system/nsec_grandparent/ns2/named.conf.j2
index 60595cef41..edb74ad438 100644
--- a/bin/tests/system/nsec_grandparent/ns2/named.conf.j2
+++ b/bin/tests/system/nsec_grandparent/ns2/named.conf.j2
@@ -22,6 +22,4 @@ zone "p031.test" {
 	server-addresses { 10.53.0.1; };
 };

-trust-anchors {
-	p031.test. static-key 257 3 13 "@PARENT_DNSKEY@";
-};
+{% include "_common/trusted.conf.j2" %}
diff --git a/bin/tests/system/nsec_grandparent/tests_nsec_grandparent.py b/bin/tests/system/nsec_grandparent/tests_nsec_grandparent.py
index 60ed476301..df3d3b482d 100644
--- a/bin/tests/system/nsec_grandparent/tests_nsec_grandparent.py
+++ b/bin/tests/system/nsec_grandparent/tests_nsec_grandparent.py
@@ -11,12 +11,6 @@

 from pathlib import Path

-import json
-
-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
@@ -24,6 +18,8 @@ import pytest

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

 PARENT = "p031.test."
 CHILD = f"c.{PARENT}"
@@ -88,36 +84,49 @@ pytestmark = [
     isctest.mark.with_ecdsa_deterministic,
     pytest.mark.extra_artifacts(
         [
-            "ans*/keys.json",
+            "ans*/dsset-*",
+            "ans*/zones/*.db",
+            "ans*/zones/*.db.signed",
         ]
     ),
 ]


-def _make_key():
-    private_key = ec.generate_private_key(ec.SECP256R1())
-    dnskey = dns.dnssec.make_dnskey(
-        private_key.public_key(),
-        algorithm="ECDSAP256SHA256",
-        flags=257,
+def bootstrap():
+    grandchildren_nsec = []
+    for grandchild in (
+        GRANDCHILD,
+        GRANDCHILD_DUMMY_FIRST,
+        GRANDCHILD_DUMMY_LAST,
+        GRANDCHILD_TOO_MANY,
+        GRANDCHILD_ALMOST_TOO_MANY,
+    ):
+        zone = isctest.zone.Zone(grandchild, isctest.template.ANS1, signed=True)
+        zone.configure(csk=True)
+        grandchildren_nsec.append(zone)
+
+    grandchild_nsec3 = isctest.zone.Zone(
+        GRANDCHILD3, isctest.template.ANS1, signed=True
     )
-    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(),
-    }
+    grandchild_nsec3.configure(csk=True, sign_params="-3 -")

+    child = isctest.zone.Zone(CHILD, isctest.template.ANS1, signed=True)
+    child.delegations = grandchildren_nsec + [grandchild_nsec3]
+    child.configure(csk=True, sign_params="-3 -")
+
+    # Salt for this zone is specifically chosen so that the NSEC3 hash for
+    # "grandsib.c.p031.test." salted with this zone's salt sorts before the
+    # NSEC3 hash for the same name salted with the "c.p031.test." zone's salt.
+    chosen_salt = 37
+    sibling = isctest.zone.Zone(SIBLING, isctest.template.ANS1, signed=True)
+    sibling.configure(csk=True, sign_params=f"-3 {chosen_salt}")
+
+    parent = isctest.zone.Zone(PARENT, isctest.template.ANS1, signed=True)
+    parent.delegations = [child, sibling]
+    parent.configure(csk=True)

-def bootstrap():
-    keys = {PARENT: _make_key(), CHILD: _make_key(), SIBLING: _make_key()}
-    Path("ans1/keys.json").write_text(json.dumps(keys, indent=2), encoding="ascii")
-    parent_dnskey = "".join(keys[PARENT]["dnskey"].split()[3:])
     return {
-        "PARENT_DNSKEY": parent_dnskey,
+        "trust_anchors": parent.trust_anchors(),
         "MAX_VALIDATIONS": str(MAX_VALIDATIONS_PER_FETCH),
     }