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(defaultBufSize)
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 orig := rr.Header().Name
54 canonicalize(zone[i])
55 _, off, err := packRR(zone[i], rrdata, 0, nil)
56 if err != nil {
57 return err
58 }
59 s.Write(rrdata[:off])
60 rr.Header().Name = orig
61 }
62 rr.Digest = hex.EncodeToString(s.Sum(nil))
63 return nil
64 }
65
66 // Verify verifies the digest in rr with the one derived from zone. This simply calls [ZONEMD.Sign] and
67 // compares the digests, on succes nil is returned.
68 func (rr *ZONEMD) Verify(zone []RR, options *ZONEMDOption) error {
69 rr1 := NewZONEMD(rr.Header().Name, rr.Scheme, rr.Hash)
70 if err := rr1.Sign(zone, options); err != nil {
71 return err
72 }
73 digest1, err := hex.DecodeString(rr1.Digest)
74 if err != nil {
75 return err
76 }
77 digest, err := hex.DecodeString(rr.Digest)
78 if err != nil {
79 return err
80 }
81 if bytes.Equal(digest1, digest) {
82 return nil
83 }
84 return fmt.Errorf("bad ZONEMD Digest")
85 }
86
87 // NewZONEMD returns a ZONEMD record that can be used as a placeholder in a zone.
88 func NewZONEMD(origin string, scheme, hash uint8) *ZONEMD {
89 return &ZONEMD{Header{Name: origin, Class: ClassINET}, rdata.ZONEMD{Scheme: scheme, Hash: hash}}
90 }