Debian Codegraph @

zonemd.go

raw
1 package dns
2
3 import (
4 "bytes"
5 "crypto"
6 "encoding/hex"
7 "fmt"
8
9 "codeberg.org/miekg/dns/pkg/pool"
10 "codeberg.org/miekg/dns/rdata"
11 )
12
13 // ZONEMDption are options that are given to the signer and verifier.
14 type ZONEMDOption struct {
15 pool.Pooler // If Pooler is set is will be used for all memory allocations.
16 }
17
18 // Sign "signs" an zone. When done successfully the rr's digest will be updated. ZONEMD must be a skeleton
19 // (placeholder) [RR], where scheme and hash are filled out. See [NewZONEMD] on how to create such a record.
20 // The zone's [RR]s must be in canonical order, but this isn't enforced by Sign, see [Sort]. As RFC 8976 specifies
21 // that for the simple scheme (the only supported scheme) some records are excluded from the digest calculation.
22 func (rr *ZONEMD) Sign(zone []RR, options *ZONEMDOption) error {
23 if rr.Scheme != ZONEMDSchemeSimple {
24 return fmt.Errorf("bad ZONEMD Scheme")
25 }
26 if options.Pooler == nil {
27 options.Pooler = pool.NewNoop(DefaultMsgSize)
28 }
29
30 var hash crypto.Hash
31 switch rr.Hash {
32 case ZONEMDHashSHA384:
33 hash = crypto.SHA384
34 case ZONEMDHashSHA512:
35 hash = crypto.SHA512
36 default:
37 return fmt.Errorf("bad ZONEMD Hash")
38 }
39
40 rrdata := options.Get()
41 defer options.Put(rrdata)
42 s := hash.New()
43 for i := range zone {
44 if _, ok := zone[i].(*ZONEMD); ok {
45 continue
46 }
47 if s, ok := zone[i].(*RRSIG); ok && s.TypeCovered == TypeZONEMD {
48 continue
49 }
50 if s, ok := zone[i].(*SOA); ok {
51 rr.Serial = s.Serial
52 }
53 canonicalize(zone[i])
54 _, off, err := packRR(zone[i], rrdata, 0, nil)
55 if err != nil {
56 return err
57 }
58 s.Write(rrdata[:off])
59 }
60 rr.Digest = hex.EncodeToString(s.Sum(nil))
61 return nil
62 }
63
64 // Verify verifies the digest in rr with the one derived from zone. This simply calls [ZONEMD.Sign] and
65 // compares the digests, on succes nil is returned.
66 func (rr *ZONEMD) Verify(zone []RR, options *ZONEMDOption) error {
67 rr1 := NewZONEMD(rr.Header().Name, rr.Scheme, rr.Hash)
68 if err := rr1.Sign(zone, options); err != nil {
69 return err
70 }
71 digest1, err := hex.DecodeString(rr1.Digest)
72 if err != nil {
73 return err
74 }
75 digest, err := hex.DecodeString(rr.Digest)
76 if err != nil {
77 return err
78 }
79 if bytes.Equal(digest1, digest) {
80 return nil
81 }
82 return fmt.Errorf("bad ZONEMD Digest")
83 }
84
85 // NewZONEMD returns a ZONEMD record that can be used as a placeholder in a zone.
86 func NewZONEMD(origin string, scheme, hash uint8) *ZONEMD {
87 return &ZONEMD{Header{Name: origin, Class: ClassINET}, rdata.ZONEMD{Scheme: scheme, Hash: hash}}
88 }