Debian Codegraph @

cmd/atomdns/handlers/sign/dnssec.go

raw
1 package sign
2
3 import (
4 "errors"
5 "fmt"
6 "io"
7 "log/slog"
8 "os"
9 "path/filepath"
10 "slices"
11 "sort"
12 "time"
13
14 "codeberg.org/miekg/dns"
15 "codeberg.org/miekg/dns/cmd/atomdns/handlers/dbfile/zone"
16 "codeberg.org/miekg/dns/cmd/atomdns/internal/dnszone"
17 "codeberg.org/miekg/dns/dnsutil"
18 )
19
20 // Sign signs the zone with origin from s. It returns the signed zone.
21 func (s *Sign) Sign(origin string) (*zone.Zone, error) {
22 z := zone.New(origin, s.Path)
23 err := z.Load()
24 if err != nil {
25 return z, err
26 }
27 alog := log().With(slog.String("zone", origin))
28 now := time.Now()
29
30 n := &dnszone.Node{Name: origin}
31 for _, pair := range s.KeyPairs {
32 n.RRs = append(n.RRs, pair.DNSKEY)
33 n.RRs = append(n.RRs, pair.ToDS(dns.SHA1).ToCDS())
34 n.RRs = append(n.RRs, pair.ToDS(dns.SHA256).ToCDS())
35 n.RRs = append(n.RRs, pair.ToCDNSKEY())
36 }
37 z.Set(n)
38
39 // Add nsecs + rrsig in the first pass.
40 nf := &nsecfn{keypairs: s.KeyPairs, ttl: s.ttl, origin: origin, zonemd: s.Zonemd}
41 z.AuthoritativeWalk(nf.Walk)
42 for i := range nf.nsecs {
43 z.Set(nf.nsecs[i])
44 }
45 z.Set(nf.Last(z.Origin()))
46
47 // Now walk again to sign the rest.
48 rrset := []dns.RR{}
49 incep, expir := lifetime(time.Now().UTC())
50
51 options := &dns.SignOption{Pooler: s.pool}
52 z.AuthoritativeWalk(func(n *dnszone.Node, auth bool) bool {
53 if len(n.RRs) == 0 || !auth {
54 return true
55 }
56 types := types(n, s.ttl)
57 for _, t := range types {
58 if t == dns.TypeRRSIG {
59 continue
60 }
61 if t == dns.TypeNS && len(n.Name) > len(z.Origin()) { // delegation NS
62 continue
63 }
64
65 rrset = rrset[:0]
66 for _, rr := range n.RRs {
67 if dns.RRToType(rr) == t {
68 if t == dns.TypeSOA {
69 rr.(*dns.SOA).Serial = uint32(time.Now().Unix())
70 }
71 rrset = append(rrset, rr)
72 }
73 }
74
75 for _, pair := range s.KeyPairs {
76 rrsig := dns.NewRRSIG(origin, pair.Algorithm, pair.Tag, incep, expir)
77 if err := rrsig.Sign(pair.Signer, rrset, options); err != nil {
78 alog.Error("Failed to sign", Err(err))
79 return false
80 }
81 n.RRs = append(n.RRs, rrsig)
82 }
83 }
84 return true
85 })
86 if !s.Zonemd {
87 Duration.WithLabelValues(z.Origin()).Set(float64(time.Since(now)))
88 return z, nil
89 }
90
91 zonemd := &dns.ZONEMD{Hdr: dns.Header{Name: origin, Class: dns.ClassINET, TTL: s.ttl}, Scheme: dns.ZONEMDSchemeSimple, Hash: dns.ZONEMDHashSHA384}
92 zone := []dns.RR{}
93 z.Walk(func(n *dnszone.Node) bool {
94 zone = append(zone, n.RRs...)
95 return true
96 })
97
98 sort.Sort(dns.RRset(zone))
99 zonemd.Sign(zone, &dns.ZONEMDOption{})
100
101 apex := z.Apex()
102 apex.RRs = append(apex.RRs, zonemd)
103
104 for _, pair := range s.KeyPairs {
105 rrsig := dns.NewRRSIG(origin, pair.Algorithm, pair.Tag, incep, expir)
106 rrsig.Sign(pair.Signer, []dns.RR{zonemd}, options)
107 apex.RRs = append(apex.RRs, rrsig)
108 }
109
110 Duration.WithLabelValues(z.Origin()).Set(float64(time.Since(now)))
111 return z, nil
112 }
113
114 type nsecfn struct {
115 keypairs []KeyPair
116 bitmap []uint16
117 nsecs []*dnszone.Node
118 origin string
119
120 last string
121 ttl uint32
122
123 zonemd bool
124 }
125
126 func types(n *dnszone.Node, ttl uint32) []uint16 {
127 // while looking at them anyway we set the ttl.
128 types := []uint16{}
129 for j := range n.RRs {
130 types = append(types, dns.RRToType(n.RRs[j]))
131 n.RRs[j].Header().TTL = ttl
132 }
133 types = append(types, []uint16{dns.TypeRRSIG, dns.TypeNSEC}...)
134
135 slices.Sort(types)
136 return slices.Compact(types)
137 }
138
139 // Walk is used when signing a zone. It generates all the NSECs that a zone needs.
140 // We can't insert while walking, so we need save the nsec+rssig and insert them post walk.
141 func (nf *nsecfn) Walk(n *dnszone.Node, auth bool) bool {
142 if len(n.RRs) == 0 || !auth { // empty non-terminal
143 return true
144 }
145
146 if nf.last != "" {
147 nsecnode := nf.nsec(n.Name)
148 nf.nsecs = append(nf.nsecs, nsecnode)
149 }
150 nf.last = n.Name
151 nf.bitmap = types(n, nf.ttl)
152 if nf.zonemd && dns.EqualName(nf.origin, n.Name) {
153 nf.bitmap = append(nf.bitmap, dns.TypeZONEMD)
154 slices.Sort(nf.bitmap)
155 }
156 return true
157 }
158
159 // Last creates the last NSEC, that loops back to the origin. Walk misses this.
160 func (nf *nsecfn) Last(origin string) *dnszone.Node { return nf.nsec(origin) }
161
162 // nsec creates an NSEC node from nf.
163 func (nf *nsecfn) nsec(name string) *dnszone.Node {
164 nsec := &dns.NSEC{Hdr: dns.Header{Name: nf.last, TTL: nf.ttl, Class: dns.ClassINET},
165 NextDomain: name, TypeBitMap: nf.bitmap,
166 }
167 nsecnode := &dnszone.Node{Name: nf.last}
168 nsecnode.RRs = append(nsecnode.RRs, nsec)
169 return nsecnode
170 }
171
172 // lifetime returns signature incep, expire timestamp used in the signature creation.
173 func lifetime(now time.Time) (uint32, uint32) {
174 incep := uint32(now.Add(signatureInception).Add(inceptionJitter).Unix())
175 expir := uint32(now.Add(signatureExpire).Add(expirationJitter).Unix())
176 return incep, expir
177 }
178
179 // Expired returns true when 'a' signature on the SOA record has only 9 days left.
180 func (s *Sign) Expired(origin string) (bool, error) {
181 f, err := os.Open(s.Zones[origin].Path + Signed)
182 if err != nil {
183 if errors.Is(err, os.ErrNotExist) {
184 return true, nil
185 }
186 return false, err
187 }
188 now := time.Now().UTC()
189 zp := dns.NewZoneParser(f, origin, f.Name())
190 i := 0
191 for rr, ok := zp.Next(); ok; rr, ok = zp.Next() {
192 if s, ok := rr.(*dns.RRSIG); ok && s.TypeCovered == dns.TypeSOA {
193 alog := log().With(slog.String("zone", origin), slog.String("path", filepath.Base(f.Name())))
194 if !s.ValidPeriod(now) {
195 alog.Warn("Validity period has passed")
196 return true, nil
197 }
198 expire, _ := time.Parse("20060102150405", dnsutil.TimeToString(s.Expiration))
199 Expire.WithLabelValues(origin).Set(float64(expire.Unix()))
200 days := Expired(now, expire)
201 if days < 15 {
202 alog.Warn("Left before expiration", slog.Int("days", days))
203 } else {
204 alog.Info("Left before expiration", slog.Int("days", days))
205 }
206 return days < expireDays, nil
207 }
208
209 i++
210 if i > 50 {
211 break
212 }
213 }
214 if zp.Err() != nil {
215 return false, fmt.Errorf("failed to parse zone %s with origin %s: %w ", s.Zones[origin].Path, origin, zp.Err())
216 }
217 return true, fmt.Errorf("no SOA signature found in first 50 records")
218 }
219
220 // Expired returns an integer saying how many days expire is still valid taking now as a starting point.
221 func Expired(now, expire time.Time) int {
222 left := expire.Sub(now)
223 return int(left / Day)
224 }
225
226 func (s Sign) Write(z *zone.Zone) error {
227 f, err := os.CreateTemp(s.Directory, "atomdns")
228 if err != nil {
229 return err
230 }
231 defer os.Remove(f.Name())
232
233 z.Walk(func(n *dnszone.Node) bool {
234 if len(n.RRs) == 0 { // skip empty non-terminals
235 return true
236 }
237 io.WriteString(f, n.String())
238 return true
239 })
240 f.Close()
241 target := filepath.Join(s.Directory, filepath.Base(z.Path)+Signed)
242 return os.Rename(f.Name(), target)
243 }