Debian Codegraph @

dnssec.go

raw
1 package dns
2
3 import (
4 "crypto"
5 "crypto/ecdsa"
6 "crypto/ed25519"
7 "crypto/mldsa"
8 "crypto/rand"
9 "crypto/rsa"
10 _ "crypto/sha1" // need its init function
11 _ "crypto/sha256" // need its init function
12 _ "crypto/sha512" // need its init function
13 "encoding/asn1"
14 "encoding/hex"
15 "hash"
16 "math/big"
17 "strings"
18 "time"
19
20 "codeberg.org/miekg/dns/internal/pack"
21 "codeberg.org/miekg/dns/internal/unpack"
22 "codeberg.org/miekg/dns/pkg/pool"
23 )
24
25 // DNSSEC encryption algorithm codes.
26 const (
27 _ uint8 = iota
28 RSAMD5 // Deprecated.
29 DH
30 DSA
31 _ // Skip 4, RFC 6725, section 2.1
32 RSASHA1
33 DSANSEC3SHA1
34 RSASHA1NSEC3SHA1
35 RSASHA256
36 _ // Skip 9, RFC 6725, section 2.1
37 RSASHA512
38 _ // Skip 11, RFC 6725, section 2.1
39 ECCGOST // Deprecated.
40 ECDSAP256SHA256
41 ECDSAP384SHA384
42 ED25519
43 ED448
44 SM2SM3 // See RFC 9563.
45 MLDSA44 // See draft-westerbaan-dnssec-mldsa.
46 ECCGOST12 uint8 = 23 // See RFC 9558
47 INDIRECT uint8 = 252
48 PRIVATEDNS uint8 = 253 // Private (experimental keys).
49 PRIVATEOID uint8 = 254
50 )
51
52 // AlgorithmToString is a map of algorithm IDs to algorithm names.
53 var AlgorithmToString = map[uint8]string{
54 RSAMD5: "RSAMD5",
55 DH: "DH",
56 DSA: "DSA",
57 RSASHA1: "RSASHA1",
58 DSANSEC3SHA1: "DSA-NSEC3-SHA1",
59 RSASHA1NSEC3SHA1: "RSASHA1-NSEC3-SHA1",
60 RSASHA256: "RSASHA256",
61 RSASHA512: "RSASHA512",
62 ECCGOST: "ECC-GOST",
63 ECDSAP256SHA256: "ECDSAP256SHA256",
64 ECDSAP384SHA384: "ECDSAP384SHA384",
65 ED25519: "ED25519",
66 ED448: "ED448",
67 SM2SM3: "SM2SM3",
68 MLDSA44: "MLDSA44",
69 ECCGOST12: "ECC-GOST12",
70 INDIRECT: "INDIRECT",
71 PRIVATEDNS: "PRIVATEDNS",
72 PRIVATEOID: "PRIVATEOID",
73 }
74
75 // AlgorithmToHash is a map of algorithm crypto hash IDs to crypto.Hash's.
76 // Newer algorithm that do their own hashing (i.e. ED25519 and MLDSA44) are not present here.
77 var AlgorithmToHash = map[uint8]crypto.Hash{
78 RSAMD5: crypto.MD5, // Deprecated in RFC 6725.
79 DSA: crypto.SHA1,
80 RSASHA1: crypto.SHA1,
81 RSASHA1NSEC3SHA1: crypto.SHA1,
82 RSASHA256: crypto.SHA256,
83 ECDSAP256SHA256: crypto.SHA256,
84 ECDSAP384SHA384: crypto.SHA384,
85 RSASHA512: crypto.SHA512,
86 }
87
88 // DNSSEC hashing algorithm codes.
89 const (
90 SHA1 uint8 = 1 // RFC 4034.
91 SHA256 uint8 = 2 // RFC 4509.
92 GOST94 uint8 = 3 // RFC 5933.
93 SHA384 uint8 = 4 // RFC 6605.
94 GOST2012 uint8 = 5 // RFC 9558.
95 SM3 uint8 = 6 // RFC 9563.
96 )
97
98 // HashToString is a map of hash IDs to names.
99 var HashToString = map[uint8]string{
100 SHA1: "SHA1",
101 SHA256: "SHA256",
102 GOST94: "GOST94",
103 SHA384: "SHA384",
104 GOST2012: "GOST2012",
105 SM3: "SM3",
106 }
107
108 // DNSKEY flag values.
109 const (
110 FlagSEP = 1
111 FlagREVOKE = 1 << 7
112 FlagZONE = 1 << 8
113 FlagDELEG = 1 << 14
114 )
115
116 // KeyTag returns the keytag (or key-id) of the DNSKEY. If k.Tag is not zero, that value is returned instead,
117 // otherwise the tag is calculated, set and returned.
118 func (k *DNSKEY) KeyTag() uint16 {
119 if k.Tag > 0 {
120 return k.Tag
121 }
122 keytag := 0
123 wire := make([]byte, defaultBufSize/2)
124 n, err := k.pack(wire, 0, nil)
125 if err != nil {
126 return 0
127 }
128 wire = wire[:n]
129 for i, v := range wire {
130 if i&1 != 0 {
131 keytag += int(v) // must be larger than uint32
132 } else {
133 keytag += int(v) << 8
134 }
135 }
136 keytag += keytag >> 16 & 0xFFFF
137 keytag &= 0xFFFF
138
139 k.Tag = uint16(keytag)
140 return k.Tag
141 }
142
143 // ToDS converts a DNSKEY record to a DS record.
144 func (k *DNSKEY) ToDS(h uint8) *DS {
145 if k == nil {
146 return nil
147 }
148 ds := new(DS)
149 ds.Hdr.Name = k.Hdr.Name
150 ds.Hdr.Class = k.Hdr.Class
151 ds.Hdr.TTL = k.Hdr.TTL
152 ds.Algorithm = k.Algorithm
153 ds.DigestType = h
154 ds.KeyTag = k.KeyTag()
155
156 wire := make([]byte, defaultBufSize/2)
157 n, err := k.pack(wire, 0, nil)
158 if err != nil {
159 return nil
160 }
161 wire = wire[:n]
162
163 owner := make([]byte, len(k.Hdr.Name)+1)
164 off, err1 := pack.Name(dnsutilCanonical(k.Hdr.Name), owner, 0, nil, false)
165 if err1 != nil {
166 return nil
167 }
168 owner = owner[:off]
169 // RFC4034:
170 // digest = digest_algorithm( DNSKEY owner name | DNSKEY RDATA);
171 // "|" denotes concatenation
172 // DNSKEY RDATA = Flags | Protocol | Algorithm | Public Key.
173
174 var hash crypto.Hash
175 switch h {
176 case SHA1:
177 hash = crypto.SHA1
178 case SHA256:
179 hash = crypto.SHA256
180 case SHA384:
181 hash = crypto.SHA384
182 default:
183 return nil
184 }
185
186 s := hash.New()
187 s.Write(owner)
188 s.Write(wire)
189 ds.Digest = hex.EncodeToString(s.Sum(nil))
190 return ds
191 }
192
193 // ToCDNSKEY converts a DNSKEY record to a CDNSKEY record.
194 func (k *DNSKEY) ToCDNSKEY() *CDNSKEY {
195 c := &CDNSKEY{DNSKEY: *k}
196 c.Hdr = k.Hdr
197 return c
198 }
199
200 // ToCDS converts a DS record to a CDS record.
201 func (d *DS) ToCDS() *CDS {
202 c := &CDS{DS: *d}
203 c.Hdr = d.Hdr
204 return c
205 }
206
207 // Sign signs an RRset. The signature needs to be filled in with the values:
208 // Inception, Expiration, KeyTag, SignerName and Algorithm. See [NewRRSIG], the rest is copied
209 // from the RRset. Sign returns a non-nil error when the signing went OK.
210 // There is no check if RRSet is a proper (RFC 2181) RRSet.
211 // Sign expect RRSIG to be initialized with [NewRRSIG]. Sign will skip RRSIG records, and return nil in that case.
212 func (rr *RRSIG) Sign(k crypto.Signer, rrset []RR, options *SignOption) error {
213 // s.Inception and s.Expiration may be 0 (rollover etc.), the rest must be set
214 if rr.KeyTag == 0 || len(rr.SignerName) == 0 || rr.Algorithm == 0 {
215 return ErrKey
216 }
217
218 if rr.Algorithm == RSAMD5 || rr.Algorithm == DSA || rr.Algorithm == DSANSEC3SHA1 {
219 return ErrAlg
220 }
221
222 if options.Pooler == nil {
223 options.Pooler = pool.NewNoop(defaultBufSize)
224 }
225
226 h0 := rrset[0].Header()
227 t0 := RRToType(rrset[0])
228 if t0 == TypeRRSIG {
229 return nil
230 }
231 rr.Hdr.Name = h0.Name
232 rr.Hdr.TTL = h0.TTL
233 rr.Hdr.Class = h0.Class
234 rr.OrigTTL = h0.TTL
235 rr.TypeCovered = t0
236 rr.Labels = uint8(dnsutilLabels(h0.Name))
237 if strings.HasPrefix(h0.Name, "*.") {
238 rr.Labels-- // wildcard, remove from label count
239 }
240 rr.Signature = ""
241
242 // Create the desired binary blob
243 signdata := options.Get()
244 defer options.Put(signdata)
245
246 n, err := rr.pack(signdata, 0, nil)
247 if err != nil {
248 return err
249 }
250 m, err := rawSignatureData(signdata[n:], rrset, rr)
251 if err != nil {
252 return err
253 }
254
255 signdata = signdata[:m+n]
256
257 var h hash.Hash
258 hash, ok := AlgorithmToHash[rr.Algorithm]
259 // Some newer algorithms do their own hashing, i.e. ED25519 (maybe all elliptic curve ones do), so no hash
260 // is OK.
261 if !ok {
262 signature, err := sign(k, signdata, hash, rr.Algorithm)
263 if err != nil {
264 return err
265 }
266
267 rr.Signature = unpack.Base64(signature)
268 return nil
269 }
270
271 // older algorithms with explicit hashing
272 h = hash.New()
273 h.Write(signdata)
274
275 signature, err := sign(k, h.Sum(nil), hash, rr.Algorithm)
276 if err != nil {
277 return err
278 }
279
280 rr.Signature = unpack.Base64(signature)
281 return nil
282 }
283
284 func sign(k crypto.Signer, hashed []byte, hash crypto.Hash, alg uint8) ([]byte, error) {
285 signature, err := k.Sign(rand.Reader, hashed, hash)
286 if err != nil {
287 return nil, err
288 }
289
290 switch alg {
291 case ECDSAP256SHA256, ECDSAP384SHA384:
292 ecdsaSignature := &struct {
293 R, S *big.Int
294 }{}
295 if _, err := asn1.Unmarshal(signature, ecdsaSignature); err != nil {
296 return nil, err
297 }
298
299 var intlen int
300 switch alg {
301 case ECDSAP256SHA256:
302 intlen = 32
303 case ECDSAP384SHA384:
304 intlen = 48
305 }
306
307 signature := intToBytes(ecdsaSignature.R, intlen)
308 signature = append(signature, intToBytes(ecdsaSignature.S, intlen)...)
309 return signature, nil
310
311 default:
312 return signature, nil
313 }
314 }
315
316 // Verify validates an RRSet with the signature and key. This is only the cryptographic test, the signature
317 // validity period must be checked separately. The rrset is not checked for actually being an rrset. See
318 // [codeberg.org/miekg/dns/dnsutil.IsRRset], and neither is checked if the RRSIG's TypeCovered matches the
319 // type in rrset.
320 //
321 // This function overwrites the rdata of some RRs (to lowercase domain names) for the validation to work. If
322 // you need
323 // It also checks that the Zone Key bit (RFC 4034 2.1.1) is set on the DNSKEY
324 // and that the Protocol field is set to 3 (RFC 4034 2.1.2). Options can not be nil.
325 //
326 // See the documentation of the [SignOption]'s VerifyFunc if you want to use a algorithm that is not supported
327 // by this package.
328 func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR, options *SignOption) error {
329 if rr.KeyTag != k.KeyTag() || rr.Hdr.Class != k.Hdr.Class || rr.Algorithm != k.Algorithm {
330 return ErrKey
331 }
332 // RFC 4034 2.1.1 If bit 7 has value 0, then the DNSKEY record holds some
333 // other type of DNS public key and MUST NOT be used to verify RRSIGs that
334 // cover RRsets.
335 if k.Flags&FlagZONE == 0 {
336 return ErrKey
337 }
338
339 if k.Protocol != 3 || !EqualName(rr.SignerName, k.Hdr.Name) {
340 return ErrKey
341 }
342
343 if options.Pooler == nil {
344 options.Pooler = pool.NewNoop(defaultBufSize)
345 }
346
347 rr.Hdr.Name = rrset[0].Header().Name
348
349 signeddata := options.Get()
350 defer options.Put(signeddata)
351
352 // RFC 4035 5.3.2. Reconstructing the Signed Data
353 // Remove signature to get correct wiredata, and then set it again
354 signature := rr.Signature
355 rr.Signature = ""
356 n, err := rr.pack(signeddata, 0, nil)
357 if err != nil {
358 return err
359 }
360
361 rr.Signature = signature
362
363 m, err := rawSignatureData(signeddata[n:], rrset, rr)
364 if err != nil {
365 return err
366 }
367 signeddata = signeddata[:m+n]
368
369 sigbuf, _ := pack.Base64([]byte(rr.Signature))
370
371 var h hash.Hash
372 hash := AlgorithmToHash[rr.Algorithm] // newer alg do their own hashing, ignore...
373
374 switch rr.Algorithm {
375 case RSASHA1, RSASHA1NSEC3SHA1, RSASHA256, RSASHA512:
376 pubkey := k.publicKeyRSA()
377 if pubkey == nil {
378 return ErrKey
379 }
380
381 h = hash.New()
382 h.Write(signeddata)
383 return rsa.VerifyPKCS1v15(pubkey, hash, h.Sum(nil), sigbuf)
384
385 case ECDSAP256SHA256, ECDSAP384SHA384:
386 pubkey := k.publicKeyECDSA()
387 if pubkey == nil {
388 return ErrKey
389 }
390
391 // Split sigbuf into the r and s coordinates
392 r := new(big.Int).SetBytes(sigbuf[:len(sigbuf)/2])
393 s := new(big.Int).SetBytes(sigbuf[len(sigbuf)/2:])
394
395 h = hash.New()
396 h.Write(signeddata)
397 if ecdsa.Verify(pubkey, h.Sum(nil), r, s) {
398 return nil
399 }
400 return ErrSig
401
402 case ED25519:
403 pubkey := k.publicKeyED25519()
404 if pubkey == nil {
405 return ErrKey
406 }
407
408 if ed25519.Verify(pubkey, signeddata, sigbuf) {
409 return nil
410 }
411 return ErrSig
412
413 case MLDSA44:
414 pubkey := k.publicKeyMLDSA44()
415 if pubkey == nil {
416 return ErrKey
417 }
418
419 // Nil options selects pure ML-DSA with an empty context, see draft-westerbaan-dnssec-mldsa.
420 if mldsa.Verify(pubkey, signeddata, sigbuf, nil) == nil {
421 return nil
422 }
423 return ErrSig
424
425 default:
426 if options.VerifyFunc != nil {
427 if options.VerifyFunc(k, signeddata, sigbuf) {
428 return nil
429 }
430 return ErrSig
431 }
432 return ErrAlg
433 }
434 }
435
436 // ValidPeriod uses RFC1982 serial arithmetic to calculate
437 // if a signature period is valid. If t is the zero time, the
438 // current time is taken other t is. Returns true if the signature
439 // is valid at the given time, otherwise returns false.
440 func (rr *RRSIG) ValidPeriod(t time.Time) bool {
441 var utc int64
442 if t.IsZero() {
443 utc = time.Now().UTC().Unix()
444 } else {
445 utc = t.UTC().Unix()
446 }
447 modi := (int64(rr.Inception) - utc) / MaxSerialIncrement
448 mode := (int64(rr.Expiration) - utc) / MaxSerialIncrement
449 ti := int64(rr.Inception) + modi*MaxSerialIncrement
450 te := int64(rr.Expiration) + mode*MaxSerialIncrement
451 return ti <= utc && utc <= te
452 }
453
454 // SignOption are options that are given to the signer and verifier.
455 type SignOption struct {
456 // If Pooler is set it will be used for all memory allocations. If nil the [pool.Noop] pooler will be
457 // used.
458 pool.Pooler
459
460 // If VerifyFunc is non-nil it will be used to verify a signture in [RRSIG.Verify]. This is useful when
461 // you are using a external (to this package) cryptographic algorithm. For this you also need add your
462 // algorithm to [AlgorithmToString]. In the case of ed448 this could like:
463 //
464 // func(k *dns.DNSKEY, message, sig []byte) bool {
465 // pub, _ := base64.StdEncoding.DecodeString(k.PublicKey)
466 // return ed448.Verify(ed448.PublicKey(pub), message, sig, "")
467 // }
468 VerifyFunc func(k *DNSKEY, message, sig []byte) bool
469 }
470
471 const defaultBufSize = 8192