Debian Codegraph @

cert/cert_v2.go

raw
1 package cert
2
3 import (
4 "bytes"
5 "crypto/ecdh"
6 "crypto/ecdsa"
7 "crypto/ed25519"
8 "crypto/elliptic"
9 "crypto/sha256"
10 "encoding/hex"
11 "encoding/json"
12 "encoding/pem"
13 "fmt"
14 "net/netip"
15 "slices"
16 "time"
17
18 "golang.org/x/crypto/cryptobyte"
19 "golang.org/x/crypto/cryptobyte/asn1"
20 "golang.org/x/crypto/curve25519"
21 )
22
23 const (
24 classConstructed = 0x20
25 classContextSpecific = 0x80
26
27 TagCertDetails = 0 | classConstructed | classContextSpecific
28 TagCertCurve = 1 | classContextSpecific
29 TagCertPublicKey = 2 | classContextSpecific
30 TagCertSignature = 3 | classContextSpecific
31
32 TagDetailsName = 0 | classContextSpecific
33 TagDetailsNetworks = 1 | classConstructed | classContextSpecific
34 TagDetailsUnsafeNetworks = 2 | classConstructed | classContextSpecific
35 TagDetailsGroups = 3 | classConstructed | classContextSpecific
36 TagDetailsIsCA = 4 | classContextSpecific
37 TagDetailsNotBefore = 5 | classContextSpecific
38 TagDetailsNotAfter = 6 | classContextSpecific
39 TagDetailsIssuer = 7 | classContextSpecific
40 )
41
42 const (
43 // MaxCertificateSize is the maximum length a valid certificate can be
44 MaxCertificateSize = 65536
45
46 // MaxNameLength is limited to a maximum realistic DNS domain name to help facilitate DNS systems
47 MaxNameLength = 253
48
49 // MaxNetworkLength is the maximum length a network value can be.
50 // 16 bytes for an ipv6 address + 1 byte for the prefix length
51 MaxNetworkLength = 17
52 )
53
54 type certificateV2 struct {
55 details detailsV2
56
57 // RawDetails contains the entire asn.1 DER encoded Details struct
58 // This is to benefit forwards compatibility in signature checking.
59 // signature(RawDetails + Curve + PublicKey) == Signature
60 rawDetails []byte
61 curve Curve
62 publicKey []byte
63 signature []byte
64 }
65
66 type detailsV2 struct {
67 name string
68 networks []netip.Prefix // MUST BE SORTED
69 unsafeNetworks []netip.Prefix // MUST BE SORTED
70 groups []string
71 isCA bool
72 notBefore time.Time
73 notAfter time.Time
74 issuer string
75 }
76
77 func (c *certificateV2) Version() Version {
78 return Version2
79 }
80
81 func (c *certificateV2) Curve() Curve {
82 return c.curve
83 }
84
85 func (c *certificateV2) Groups() []string {
86 return c.details.groups
87 }
88
89 func (c *certificateV2) IsCA() bool {
90 return c.details.isCA
91 }
92
93 func (c *certificateV2) Issuer() string {
94 return c.details.issuer
95 }
96
97 func (c *certificateV2) Name() string {
98 return c.details.name
99 }
100
101 func (c *certificateV2) Networks() []netip.Prefix {
102 return c.details.networks
103 }
104
105 func (c *certificateV2) NotAfter() time.Time {
106 return c.details.notAfter
107 }
108
109 func (c *certificateV2) NotBefore() time.Time {
110 return c.details.notBefore
111 }
112
113 func (c *certificateV2) PublicKey() []byte {
114 return c.publicKey
115 }
116
117 func (c *certificateV2) MarshalPublicKeyPEM() []byte {
118 return marshalCertPublicKeyToPEM(c)
119 }
120
121 func (c *certificateV2) Signature() []byte {
122 return c.signature
123 }
124
125 func (c *certificateV2) UnsafeNetworks() []netip.Prefix {
126 return c.details.unsafeNetworks
127 }
128
129 func (c *certificateV2) Fingerprint() (string, error) {
130 if len(c.rawDetails) == 0 {
131 return "", ErrMissingDetails
132 }
133
134 b := make([]byte, len(c.rawDetails)+1+len(c.publicKey)+len(c.signature))
135 copy(b, c.rawDetails)
136 b[len(c.rawDetails)] = byte(c.curve)
137 copy(b[len(c.rawDetails)+1:], c.publicKey)
138 copy(b[len(c.rawDetails)+1+len(c.publicKey):], c.signature)
139 sum := sha256.Sum256(b)
140 return hex.EncodeToString(sum[:]), nil
141 }
142
143 func (c *certificateV2) CheckSignature(key []byte) bool {
144 if len(c.rawDetails) == 0 {
145 return false
146 }
147 b := make([]byte, len(c.rawDetails)+1+len(c.publicKey))
148 copy(b, c.rawDetails)
149 b[len(c.rawDetails)] = byte(c.curve)
150 copy(b[len(c.rawDetails)+1:], c.publicKey)
151
152 switch c.curve {
153 case Curve_CURVE25519:
154 if len(key) != ed25519.PublicKeySize {
155 return false //avoids a panic internal to ed25519
156 }
157 return ed25519.Verify(key, b, c.signature)
158 case Curve_P256:
159 pubKey, err := ecdsa.ParseUncompressedPublicKey(elliptic.P256(), key)
160 if err != nil {
161 return false
162 }
163 hashed := sha256.Sum256(b)
164 return ecdsa.VerifyASN1(pubKey, hashed[:], c.signature)
165 default:
166 return false
167 }
168 }
169
170 func (c *certificateV2) Expired(t time.Time) bool {
171 return c.details.notBefore.After(t) || c.details.notAfter.Before(t)
172 }
173
174 func (c *certificateV2) VerifyPrivateKey(curve Curve, key []byte) error {
175 if curve != c.curve {
176 return ErrPublicPrivateCurveMismatch
177 }
178 if c.details.isCA {
179 switch curve {
180 case Curve_CURVE25519:
181 // the call to PublicKey below will panic slice bounds out of range otherwise
182 if len(key) != ed25519.PrivateKeySize {
183 return ErrInvalidPrivateKey
184 }
185
186 if !ed25519.PublicKey(c.publicKey).Equal(ed25519.PrivateKey(key).Public()) {
187 return ErrPublicPrivateKeyMismatch
188 }
189 case Curve_P256:
190 privkey, err := ecdh.P256().NewPrivateKey(key)
191 if err != nil {
192 return ErrInvalidPrivateKey
193 }
194 pub := privkey.PublicKey().Bytes()
195 if !bytes.Equal(pub, c.publicKey) {
196 return ErrPublicPrivateKeyMismatch
197 }
198 default:
199 return fmt.Errorf("invalid curve: %s", curve)
200 }
201 return nil
202 }
203
204 var pub []byte
205 switch curve {
206 case Curve_CURVE25519:
207 var err error
208 pub, err = curve25519.X25519(key, curve25519.Basepoint)
209 if err != nil {
210 return ErrInvalidPrivateKey
211 }
212 case Curve_P256:
213 privkey, err := ecdh.P256().NewPrivateKey(key)
214 if err != nil {
215 return ErrInvalidPrivateKey
216 }
217 pub = privkey.PublicKey().Bytes()
218 default:
219 return fmt.Errorf("invalid curve: %s", curve)
220 }
221 if !bytes.Equal(pub, c.publicKey) {
222 return ErrPublicPrivateKeyMismatch
223 }
224
225 return nil
226 }
227
228 func (c *certificateV2) String() string {
229 mb, err := c.marshalJSON()
230 if err != nil {
231 return fmt.Sprintf("<error marshalling certificate: %v>", err)
232 }
233
234 b, err := json.MarshalIndent(mb, "", "\t")
235 if err != nil {
236 return fmt.Sprintf("<error marshalling certificate: %v>", err)
237 }
238 return string(b)
239 }
240
241 func (c *certificateV2) MarshalForHandshakes() ([]byte, error) {
242 if c.rawDetails == nil {
243 return nil, ErrEmptyRawDetails
244 }
245 var b cryptobyte.Builder
246 // Outermost certificate
247 b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
248
249 // Add the cert details which is already marshalled
250 b.AddBytes(c.rawDetails)
251
252 // Skipping the curve and public key since those come across in a different part of the handshake
253
254 // Add the signature
255 b.AddASN1(TagCertSignature, func(b *cryptobyte.Builder) {
256 b.AddBytes(c.signature)
257 })
258 })
259
260 return b.Bytes()
261 }
262
263 func (c *certificateV2) Marshal() ([]byte, error) {
264 if c.rawDetails == nil {
265 return nil, ErrEmptyRawDetails
266 }
267 var b cryptobyte.Builder
268 // Outermost certificate
269 b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
270
271 // Add the cert details which is already marshalled
272 b.AddBytes(c.rawDetails)
273
274 // Add the curve only if its not the default value
275 if c.curve != Curve_CURVE25519 {
276 b.AddASN1(TagCertCurve, func(b *cryptobyte.Builder) {
277 b.AddBytes([]byte{byte(c.curve)})
278 })
279 }
280
281 // Add the public key if it is not empty
282 if c.publicKey != nil {
283 b.AddASN1(TagCertPublicKey, func(b *cryptobyte.Builder) {
284 b.AddBytes(c.publicKey)
285 })
286 }
287
288 // Add the signature
289 b.AddASN1(TagCertSignature, func(b *cryptobyte.Builder) {
290 b.AddBytes(c.signature)
291 })
292 })
293
294 return b.Bytes()
295 }
296
297 func (c *certificateV2) MarshalPEM() ([]byte, error) {
298 b, err := c.Marshal()
299 if err != nil {
300 return nil, err
301 }
302 return pem.EncodeToMemory(&pem.Block{Type: CertificateV2Banner, Bytes: b}), nil
303 }
304
305 func (c *certificateV2) MarshalJSON() ([]byte, error) {
306 b, err := c.marshalJSON()
307 if err != nil {
308 return nil, err
309 }
310 return json.Marshal(b)
311 }
312
313 func (c *certificateV2) marshalJSON() (m, error) {
314 fp, err := c.Fingerprint()
315 if err != nil {
316 return nil, err
317 }
318
319 return m{
320 "details": m{
321 "name": c.details.name,
322 "networks": c.details.networks,
323 "unsafeNetworks": c.details.unsafeNetworks,
324 "groups": c.details.groups,
325 "notBefore": c.details.notBefore,
326 "notAfter": c.details.notAfter,
327 "isCa": c.details.isCA,
328 "issuer": c.details.issuer,
329 },
330 "version": Version2,
331 "publicKey": fmt.Sprintf("%x", c.publicKey),
332 "curve": c.curve.String(),
333 "fingerprint": fp,
334 "signature": fmt.Sprintf("%x", c.Signature()),
335 }, nil
336 }
337
338 func (c *certificateV2) Copy() Certificate {
339 nc := &certificateV2{
340 details: detailsV2{
341 name: c.details.name,
342 notBefore: c.details.notBefore,
343 notAfter: c.details.notAfter,
344 isCA: c.details.isCA,
345 issuer: c.details.issuer,
346 },
347 curve: c.curve,
348 publicKey: make([]byte, len(c.publicKey)),
349 signature: make([]byte, len(c.signature)),
350 rawDetails: make([]byte, len(c.rawDetails)),
351 }
352
353 if c.details.groups != nil {
354 nc.details.groups = make([]string, len(c.details.groups))
355 copy(nc.details.groups, c.details.groups)
356 }
357
358 if c.details.networks != nil {
359 nc.details.networks = make([]netip.Prefix, len(c.details.networks))
360 copy(nc.details.networks, c.details.networks)
361 }
362
363 if c.details.unsafeNetworks != nil {
364 nc.details.unsafeNetworks = make([]netip.Prefix, len(c.details.unsafeNetworks))
365 copy(nc.details.unsafeNetworks, c.details.unsafeNetworks)
366 }
367
368 copy(nc.rawDetails, c.rawDetails)
369 copy(nc.signature, c.signature)
370 copy(nc.publicKey, c.publicKey)
371
372 return nc
373 }
374
375 func (c *certificateV2) fromTBSCertificate(t *TBSCertificate) error {
376 c.details = detailsV2{
377 name: t.Name,
378 networks: t.Networks,
379 unsafeNetworks: t.UnsafeNetworks,
380 groups: t.Groups,
381 isCA: t.IsCA,
382 notBefore: t.NotBefore,
383 notAfter: t.NotAfter,
384 issuer: t.issuer,
385 }
386 c.curve = t.Curve
387 c.publicKey = t.PublicKey
388 return c.validate()
389 }
390
391 func (c *certificateV2) validate() error {
392 // Empty names are allowed
393
394 if len(c.publicKey) == 0 {
395 return ErrInvalidPublicKey
396 }
397
398 if !c.details.isCA && len(c.details.networks) == 0 {
399 return NewErrInvalidCertificateProperties("non-CA certificate must contain at least 1 network")
400 }
401
402 hasV4Networks := false
403 hasV6Networks := false
404 for _, network := range c.details.networks {
405 if !network.IsValid() || !network.Addr().IsValid() {
406 return NewErrInvalidCertificateProperties("invalid network: %s", network)
407 }
408
409 if network.Addr().IsUnspecified() {
410 return NewErrInvalidCertificateProperties("non-CA certificates must not use the zero address as a network: %s", network)
411 }
412
413 if network.Addr().Zone() != "" {
414 return NewErrInvalidCertificateProperties("networks may not contain zones: %s", network)
415 }
416
417 if network.Addr().Is4In6() {
418 return NewErrInvalidCertificateProperties("4in6 networks are not allowed: %s", network)
419 }
420
421 hasV4Networks = hasV4Networks || network.Addr().Is4()
422 hasV6Networks = hasV6Networks || network.Addr().Is6()
423 }
424
425 slices.SortFunc(c.details.networks, comparePrefix)
426 err := findDuplicatePrefix(c.details.networks)
427 if err != nil {
428 return err
429 }
430
431 for _, network := range c.details.unsafeNetworks {
432 if !network.IsValid() || !network.Addr().IsValid() {
433 return NewErrInvalidCertificateProperties("invalid unsafe network: %s", network)
434 }
435
436 if network.Addr().Zone() != "" {
437 return NewErrInvalidCertificateProperties("unsafe networks may not contain zones: %s", network)
438 }
439
440 if !c.details.isCA {
441 if network.Addr().Is6() {
442 if !hasV6Networks {
443 return NewErrInvalidCertificateProperties("IPv6 unsafe networks require an IPv6 address assignment: %s", network)
444 }
445 } else if network.Addr().Is4() {
446 if !hasV4Networks {
447 return NewErrInvalidCertificateProperties("IPv4 unsafe networks require an IPv4 address assignment: %s", network)
448 }
449 }
450 }
451 }
452
453 slices.SortFunc(c.details.unsafeNetworks, comparePrefix)
454 err = findDuplicatePrefix(c.details.unsafeNetworks)
455 if err != nil {
456 return err
457 }
458
459 return nil
460 }
461
462 func (c *certificateV2) marshalForSigning() ([]byte, error) {
463 d, err := c.details.Marshal()
464 if err != nil {
465 return nil, fmt.Errorf("marshalling certificate details failed: %w", err)
466 }
467 c.rawDetails = d
468
469 b := make([]byte, len(c.rawDetails)+1+len(c.publicKey))
470 copy(b, c.rawDetails)
471 b[len(c.rawDetails)] = byte(c.curve)
472 copy(b[len(c.rawDetails)+1:], c.publicKey)
473 return b, nil
474 }
475
476 func (c *certificateV2) setSignature(b []byte) error {
477 if len(b) == 0 {
478 return ErrEmptySignature
479 }
480 c.signature = b
481 return nil
482 }
483
484 func (d *detailsV2) Marshal() ([]byte, error) {
485 var b cryptobyte.Builder
486 var err error
487
488 // Details are a structure
489 b.AddASN1(TagCertDetails, func(b *cryptobyte.Builder) {
490
491 // Add the name
492 b.AddASN1(TagDetailsName, func(b *cryptobyte.Builder) {
493 b.AddBytes([]byte(d.name))
494 })
495
496 // Add the networks if any exist
497 if len(d.networks) > 0 {
498 b.AddASN1(TagDetailsNetworks, func(b *cryptobyte.Builder) {
499 for _, n := range d.networks {
500 sb, innerErr := n.MarshalBinary()
501 if innerErr != nil {
502 // MarshalBinary never returns an error
503 err = fmt.Errorf("unable to marshal network: %w", innerErr)
504 return
505 }
506 b.AddASN1OctetString(sb)
507 }
508 })
509 }
510
511 // Add the unsafe networks if any exist
512 if len(d.unsafeNetworks) > 0 {
513 b.AddASN1(TagDetailsUnsafeNetworks, func(b *cryptobyte.Builder) {
514 for _, n := range d.unsafeNetworks {
515 sb, innerErr := n.MarshalBinary()
516 if innerErr != nil {
517 // MarshalBinary never returns an error
518 err = fmt.Errorf("unable to marshal unsafe network: %w", innerErr)
519 return
520 }
521 b.AddASN1OctetString(sb)
522 }
523 })
524 }
525
526 // Add groups if any exist
527 if len(d.groups) > 0 {
528 b.AddASN1(TagDetailsGroups, func(b *cryptobyte.Builder) {
529 for _, group := range d.groups {
530 b.AddASN1(asn1.UTF8String, func(b *cryptobyte.Builder) {
531 b.AddBytes([]byte(group))
532 })
533 }
534 })
535 }
536
537 // Add IsCA only if true
538 if d.isCA {
539 b.AddASN1(TagDetailsIsCA, func(b *cryptobyte.Builder) {
540 b.AddUint8(0xff)
541 })
542 }
543
544 // Add not before
545 b.AddASN1Int64WithTag(d.notBefore.Unix(), TagDetailsNotBefore)
546
547 // Add not after
548 b.AddASN1Int64WithTag(d.notAfter.Unix(), TagDetailsNotAfter)
549
550 // Add the issuer if present
551 if d.issuer != "" {
552 issuerBytes, innerErr := hex.DecodeString(d.issuer)
553 if innerErr != nil {
554 err = fmt.Errorf("failed to decode issuer: %w", innerErr)
555 return
556 }
557 b.AddASN1(TagDetailsIssuer, func(b *cryptobyte.Builder) {
558 b.AddBytes(issuerBytes)
559 })
560 }
561 })
562
563 if err != nil {
564 return nil, err
565 }
566
567 return b.Bytes()
568 }
569
570 func unmarshalCertificateV2(b []byte, publicKey []byte, curve Curve) (*certificateV2, error) {
571 l := len(b)
572 if l == 0 || l > MaxCertificateSize {
573 return nil, ErrBadFormat
574 }
575
576 input := cryptobyte.String(b)
577 // Open the envelope
578 if !input.ReadASN1(&input, asn1.SEQUENCE) || input.Empty() {
579 return nil, ErrBadFormat
580 }
581
582 // Grab the cert details, we need to preserve the tag and length
583 var rawDetails cryptobyte.String
584 if !input.ReadASN1Element(&rawDetails, TagCertDetails) || rawDetails.Empty() {
585 return nil, ErrBadFormat
586 }
587
588 //Maybe grab the curve
589 var rawCurve byte
590 if !readOptionalASN1Byte(&input, &rawCurve, TagCertCurve, byte(curve)) {
591 return nil, ErrBadFormat
592 }
593 curve = Curve(rawCurve)
594
595 // Maybe grab the public key
596 var rawPublicKey cryptobyte.String
597 if len(publicKey) > 0 {
598 // If a public key is passed in, then the handshake certificate must
599 // not have a public key present
600 if input.PeekASN1Tag(TagCertPublicKey) {
601 return nil, ErrCertPubkeyPresent
602 }
603 rawPublicKey = make(cryptobyte.String, len(publicKey))
604 copy(rawPublicKey, publicKey)
605 } else if !input.ReadOptionalASN1(&rawPublicKey, nil, TagCertPublicKey) {
606 return nil, ErrBadFormat
607 }
608
609 if len(rawPublicKey) == 0 {
610 return nil, ErrBadFormat
611 }
612
613 // Grab the signature
614 var rawSignature cryptobyte.String
615 if !input.ReadASN1(&rawSignature, TagCertSignature) || rawSignature.Empty() {
616 return nil, ErrBadFormat
617 }
618
619 // Finally unmarshal the details
620 details, err := unmarshalDetails(rawDetails)
621 if err != nil {
622 return nil, err
623 }
624
625 c := &certificateV2{
626 details: details,
627 rawDetails: rawDetails,
628 curve: curve,
629 publicKey: rawPublicKey,
630 signature: rawSignature,
631 }
632
633 err = c.validate()
634 if err != nil {
635 return nil, err
636 }
637
638 return c, nil
639 }
640
641 func unmarshalDetails(b cryptobyte.String) (detailsV2, error) {
642 // Open the envelope
643 if !b.ReadASN1(&b, TagCertDetails) || b.Empty() {
644 return detailsV2{}, ErrBadFormat
645 }
646
647 // Read the name
648 var name cryptobyte.String
649 if !b.ReadASN1(&name, TagDetailsName) || name.Empty() || len(name) > MaxNameLength {
650 return detailsV2{}, ErrBadFormat
651 }
652
653 // Read the network addresses
654 var subString cryptobyte.String
655 var found bool
656
657 if !b.ReadOptionalASN1(&subString, &found, TagDetailsNetworks) {
658 return detailsV2{}, ErrBadFormat
659 }
660
661 var networks []netip.Prefix
662 var val cryptobyte.String
663 if found {
664 for !subString.Empty() {
665 if !subString.ReadASN1(&val, asn1.OCTET_STRING) || val.Empty() || len(val) > MaxNetworkLength {
666 return detailsV2{}, ErrBadFormat
667 }
668
669 var n netip.Prefix
670 if err := n.UnmarshalBinary(val); err != nil {
671 return detailsV2{}, ErrBadFormat
672 }
673 networks = append(networks, n)
674 }
675 }
676
677 // Read out any unsafe networks
678 if !b.ReadOptionalASN1(&subString, &found, TagDetailsUnsafeNetworks) {
679 return detailsV2{}, ErrBadFormat
680 }
681
682 var unsafeNetworks []netip.Prefix
683 if found {
684 for !subString.Empty() {
685 if !subString.ReadASN1(&val, asn1.OCTET_STRING) || val.Empty() || len(val) > MaxNetworkLength {
686 return detailsV2{}, ErrBadFormat
687 }
688
689 var n netip.Prefix
690 if err := n.UnmarshalBinary(val); err != nil {
691 return detailsV2{}, ErrBadFormat
692 }
693 unsafeNetworks = append(unsafeNetworks, n)
694 }
695 }
696
697 // Read out any groups
698 if !b.ReadOptionalASN1(&subString, &found, TagDetailsGroups) {
699 return detailsV2{}, ErrBadFormat
700 }
701
702 var groups []string
703 if found {
704 for !subString.Empty() {
705 if !subString.ReadASN1(&val, asn1.UTF8String) || val.Empty() {
706 return detailsV2{}, ErrBadFormat
707 }
708 groups = append(groups, string(val))
709 }
710 }
711
712 // Read out IsCA
713 var isCa bool
714 if !readOptionalASN1Boolean(&b, &isCa, TagDetailsIsCA, false) {
715 return detailsV2{}, ErrBadFormat
716 }
717
718 // Read not before and not after
719 var notBefore int64
720 if !b.ReadASN1Int64WithTag(&notBefore, TagDetailsNotBefore) {
721 return detailsV2{}, ErrBadFormat
722 }
723
724 var notAfter int64
725 if !b.ReadASN1Int64WithTag(&notAfter, TagDetailsNotAfter) {
726 return detailsV2{}, ErrBadFormat
727 }
728
729 // Read issuer
730 var issuer cryptobyte.String
731 if !b.ReadOptionalASN1(&issuer, nil, TagDetailsIssuer) {
732 return detailsV2{}, ErrBadFormat
733 }
734
735 return detailsV2{
736 name: string(name),
737 networks: networks,
738 unsafeNetworks: unsafeNetworks,
739 groups: groups,
740 isCA: isCa,
741 notBefore: time.Unix(notBefore, 0),
742 notAfter: time.Unix(notAfter, 0),
743 issuer: hex.EncodeToString(issuer),
744 }, nil
745 }