1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package x509
22
23 import (
24 "bytes"
25 "crypto"
26 "crypto/ecdh"
27 "crypto/ecdsa"
28 "crypto/ed25519"
29 "crypto/elliptic"
30 "crypto/fips140"
31 "crypto/mldsa"
32 "crypto/rsa"
33 "crypto/sha1"
34 "crypto/sha256"
35 "crypto/x509/pkix"
36 "encoding/asn1"
37 "encoding/pem"
38 "errors"
39 "fmt"
40 "internal/godebug"
41 "io"
42 "math/big"
43 "net"
44 "net/url"
45 "strconv"
46 "time"
47 "unicode"
48
49
50
51 _ "crypto/sha1"
52 _ "crypto/sha256"
53 _ "crypto/sha512"
54
55 "golang.org/x/crypto/cryptobyte"
56 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
57 )
58
59
60
61 type pkixPublicKey struct {
62 Algo pkix.AlgorithmIdentifier
63 BitString asn1.BitString
64 }
65
66
67
68
69
70
71
72
73
74 func ParsePKIXPublicKey(derBytes []byte) (pub any, err error) {
75 var pki publicKeyInfo
76 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
77 if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
78 return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
79 }
80 return nil, err
81 } else if len(rest) != 0 {
82 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
83 }
84 return parsePublicKey(&pki)
85 }
86
87 func marshalPublicKey(pub any) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
88 switch pub := pub.(type) {
89 case *rsa.PublicKey:
90 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
91 N: pub.N,
92 E: pub.E,
93 })
94 if err != nil {
95 return nil, pkix.AlgorithmIdentifier{}, err
96 }
97 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
98
99
100 publicKeyAlgorithm.Parameters = asn1.NullRawValue
101 case *ecdsa.PublicKey:
102 oid, ok := oidFromNamedCurve(pub.Curve)
103 if !ok {
104 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
105 }
106 publicKeyBytes, err = pub.Bytes()
107 if err != nil {
108 return nil, pkix.AlgorithmIdentifier{}, err
109 }
110 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
111 var paramBytes []byte
112 paramBytes, err = asn1.Marshal(oid)
113 if err != nil {
114 return
115 }
116 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
117 case ed25519.PublicKey:
118 publicKeyBytes = pub
119 publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
120 case *mldsa.PublicKey:
121 oid, ok := oidFromMLDSAParameters(pub.Parameters())
122 if !ok {
123 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported ML-DSA parameters")
124 }
125 publicKeyBytes = pub.Bytes()
126 publicKeyAlgorithm.Algorithm = oid
127 case *ecdh.PublicKey:
128 publicKeyBytes = pub.Bytes()
129 if pub.Curve() == ecdh.X25519() {
130 publicKeyAlgorithm.Algorithm = oidPublicKeyX25519
131 } else {
132 oid, ok := oidFromECDHCurve(pub.Curve())
133 if !ok {
134 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
135 }
136 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
137 var paramBytes []byte
138 paramBytes, err = asn1.Marshal(oid)
139 if err != nil {
140 return
141 }
142 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
143 }
144 default:
145 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
146 }
147
148 return publicKeyBytes, publicKeyAlgorithm, nil
149 }
150
151
152
153
154
155
156
157
158
159
160 func MarshalPKIXPublicKey(pub any) ([]byte, error) {
161 var publicKeyBytes []byte
162 var publicKeyAlgorithm pkix.AlgorithmIdentifier
163 var err error
164
165 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
166 return nil, err
167 }
168
169 pkix := pkixPublicKey{
170 Algo: publicKeyAlgorithm,
171 BitString: asn1.BitString{
172 Bytes: publicKeyBytes,
173 BitLength: 8 * len(publicKeyBytes),
174 },
175 }
176
177 ret, _ := asn1.Marshal(pkix)
178 return ret, nil
179 }
180
181
182
183 type certificate struct {
184 TBSCertificate tbsCertificate
185 SignatureAlgorithm pkix.AlgorithmIdentifier
186 SignatureValue asn1.BitString
187 }
188
189 type tbsCertificate struct {
190 Raw asn1.RawContent
191 Version int `asn1:"optional,explicit,default:0,tag:0"`
192 SerialNumber *big.Int
193 SignatureAlgorithm pkix.AlgorithmIdentifier
194 Issuer asn1.RawValue
195 Validity validity
196 Subject asn1.RawValue
197 PublicKey publicKeyInfo
198 UniqueId asn1.BitString `asn1:"optional,tag:1"`
199 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
200 Extensions []pkix.Extension `asn1:"omitempty,optional,explicit,tag:3"`
201 }
202
203 type dsaAlgorithmParameters struct {
204 P, Q, G *big.Int
205 }
206
207 type validity struct {
208 NotBefore, NotAfter time.Time
209 }
210
211 type publicKeyInfo struct {
212 Raw asn1.RawContent
213 Algorithm pkix.AlgorithmIdentifier
214 PublicKey asn1.BitString
215 }
216
217
218 type authKeyId struct {
219 Id []byte `asn1:"optional,tag:0"`
220 }
221
222 type SignatureAlgorithm int
223
224 const (
225 UnknownSignatureAlgorithm SignatureAlgorithm = iota
226
227 MD2WithRSA
228 MD5WithRSA
229 SHA1WithRSA
230 SHA256WithRSA
231 SHA384WithRSA
232 SHA512WithRSA
233 DSAWithSHA1
234 DSAWithSHA256
235 ECDSAWithSHA1
236 ECDSAWithSHA256
237 ECDSAWithSHA384
238 ECDSAWithSHA512
239 SHA256WithRSAPSS
240 SHA384WithRSAPSS
241 SHA512WithRSAPSS
242 PureEd25519
243 MLDSA44
244 MLDSA65
245 MLDSA87
246 )
247
248 func (algo SignatureAlgorithm) isRSAPSS() bool {
249 for _, details := range signatureAlgorithmDetails {
250 if details.algo == algo {
251 return details.isRSAPSS
252 }
253 }
254 return false
255 }
256
257 func (algo SignatureAlgorithm) hashFunc() crypto.Hash {
258 for _, details := range signatureAlgorithmDetails {
259 if details.algo == algo {
260 return details.hash
261 }
262 }
263 return crypto.Hash(0)
264 }
265
266 func (algo SignatureAlgorithm) String() string {
267 for _, details := range signatureAlgorithmDetails {
268 if details.algo == algo {
269 return details.name
270 }
271 }
272 return strconv.Itoa(int(algo))
273 }
274
275 type PublicKeyAlgorithm int
276
277 const (
278 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
279 RSA
280 DSA
281 ECDSA
282 Ed25519
283 MLDSA
284 )
285
286 var publicKeyAlgoName = [...]string{
287 RSA: "RSA",
288 DSA: "DSA",
289 ECDSA: "ECDSA",
290 Ed25519: "Ed25519",
291 MLDSA: "ML-DSA",
292 }
293
294 func (algo PublicKeyAlgorithm) String() string {
295 if 0 < algo && int(algo) < len(publicKeyAlgoName) {
296 return publicKeyAlgoName[algo]
297 }
298 return strconv.Itoa(int(algo))
299 }
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349 var (
350 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
351 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
352 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
353 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
354 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
355 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
356 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
357 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
358 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
359 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
360 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
361 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
362 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
363
364 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
365 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
366 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
367
368 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
369
370
371
372
373 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
374 )
375
376 var signatureAlgorithmDetails = []struct {
377 algo SignatureAlgorithm
378 name string
379 oid asn1.ObjectIdentifier
380 params asn1.RawValue
381 pubKeyAlgo PublicKeyAlgorithm
382 hash crypto.Hash
383 isRSAPSS bool
384 }{
385 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, asn1.NullRawValue, RSA, crypto.MD5, false},
386 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, asn1.NullRawValue, RSA, crypto.SHA1, false},
387 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, asn1.NullRawValue, RSA, crypto.SHA1, false},
388 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, asn1.NullRawValue, RSA, crypto.SHA256, false},
389 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, asn1.NullRawValue, RSA, crypto.SHA384, false},
390 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, asn1.NullRawValue, RSA, crypto.SHA512, false},
391 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, pssParametersSHA256, RSA, crypto.SHA256, true},
392 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, pssParametersSHA384, RSA, crypto.SHA384, true},
393 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, pssParametersSHA512, RSA, crypto.SHA512, true},
394 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, emptyRawValue, DSA, crypto.SHA1, false},
395 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, emptyRawValue, DSA, crypto.SHA256, false},
396 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, emptyRawValue, ECDSA, crypto.SHA1, false},
397 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, emptyRawValue, ECDSA, crypto.SHA256, false},
398 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, emptyRawValue, ECDSA, crypto.SHA384, false},
399 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, emptyRawValue, ECDSA, crypto.SHA512, false},
400 {PureEd25519, "Ed25519", oidSignatureEd25519, emptyRawValue, Ed25519, crypto.Hash(0) , false},
401 {MLDSA44, "ML-DSA-44", oidPublicKeyMLDSA44, emptyRawValue, MLDSA, crypto.Hash(0) , false},
402 {MLDSA65, "ML-DSA-65", oidPublicKeyMLDSA65, emptyRawValue, MLDSA, crypto.Hash(0) , false},
403 {MLDSA87, "ML-DSA-87", oidPublicKeyMLDSA87, emptyRawValue, MLDSA, crypto.Hash(0) , false},
404 }
405
406 var emptyRawValue = asn1.RawValue{}
407
408
409
410
411
412
413
414
415 var (
416 pssParametersSHA256 = asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 162, 3, 2, 1, 32}}
417 pssParametersSHA384 = asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 162, 3, 2, 1, 48}}
418 pssParametersSHA512 = asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 162, 3, 2, 1, 64}}
419 )
420
421
422
423 type pssParameters struct {
424
425
426
427 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
428 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
429 SaltLength int `asn1:"explicit,tag:2"`
430 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
431 }
432
433 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
434 if ai.Algorithm.Equal(oidSignatureEd25519) ||
435 ai.Algorithm.Equal(oidPublicKeyMLDSA44) ||
436 ai.Algorithm.Equal(oidPublicKeyMLDSA65) ||
437 ai.Algorithm.Equal(oidPublicKeyMLDSA87) {
438
439
440
441
442 if len(ai.Parameters.FullBytes) != 0 {
443 return UnknownSignatureAlgorithm
444 }
445 }
446
447 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
448 for _, details := range signatureAlgorithmDetails {
449 if ai.Algorithm.Equal(details.oid) {
450 return details.algo
451 }
452 }
453 return UnknownSignatureAlgorithm
454 }
455
456
457
458
459 var params pssParameters
460 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {
461 return UnknownSignatureAlgorithm
462 }
463
464 var mgf1HashFunc pkix.AlgorithmIdentifier
465 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
466 return UnknownSignatureAlgorithm
467 }
468
469
470
471
472
473
474 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
475 !params.MGF.Algorithm.Equal(oidMGF1) ||
476 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
477 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
478 params.TrailerField != 1 {
479 return UnknownSignatureAlgorithm
480 }
481
482 switch {
483 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
484 return SHA256WithRSAPSS
485 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
486 return SHA384WithRSAPSS
487 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
488 return SHA512WithRSAPSS
489 }
490
491 return UnknownSignatureAlgorithm
492 }
493
494 var (
495
496
497
498
499
500
501
502
503
504 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
505 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
506
507
508
509
510 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
511
512
513
514
515 oidPublicKeyX25519 = asn1.ObjectIdentifier{1, 3, 101, 110}
516 oidPublicKeyEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
517
518
519
520
521
522
523
524
525
526
527
528
529
530 oidPublicKeyMLDSA44 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 17}
531 oidPublicKeyMLDSA65 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 18}
532 oidPublicKeyMLDSA87 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 19}
533 )
534
535
536
537
538 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
539 switch {
540 case oid.Equal(oidPublicKeyRSA):
541 return RSA
542 case oid.Equal(oidPublicKeyDSA):
543 return DSA
544 case oid.Equal(oidPublicKeyECDSA):
545 return ECDSA
546 case oid.Equal(oidPublicKeyEd25519):
547 return Ed25519
548 case oid.Equal(oidPublicKeyMLDSA44),
549 oid.Equal(oidPublicKeyMLDSA65),
550 oid.Equal(oidPublicKeyMLDSA87):
551
552 if fips140.Version() == "v1.0.0" {
553 return UnknownPublicKeyAlgorithm
554 }
555 return MLDSA
556 }
557 return UnknownPublicKeyAlgorithm
558 }
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576 var (
577 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
578 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
579 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
580 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
581 )
582
583 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
584 switch {
585 case oid.Equal(oidNamedCurveP224):
586 return elliptic.P224()
587 case oid.Equal(oidNamedCurveP256):
588 return elliptic.P256()
589 case oid.Equal(oidNamedCurveP384):
590 return elliptic.P384()
591 case oid.Equal(oidNamedCurveP521):
592 return elliptic.P521()
593 }
594 return nil
595 }
596
597 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
598 switch curve {
599 case elliptic.P224():
600 return oidNamedCurveP224, true
601 case elliptic.P256():
602 return oidNamedCurveP256, true
603 case elliptic.P384():
604 return oidNamedCurveP384, true
605 case elliptic.P521():
606 return oidNamedCurveP521, true
607 }
608
609 return nil, false
610 }
611
612 func oidFromECDHCurve(curve ecdh.Curve) (asn1.ObjectIdentifier, bool) {
613 switch curve {
614 case ecdh.X25519():
615 return oidPublicKeyX25519, true
616 case ecdh.P256():
617 return oidNamedCurveP256, true
618 case ecdh.P384():
619 return oidNamedCurveP384, true
620 case ecdh.P521():
621 return oidNamedCurveP521, true
622 }
623
624 return nil, false
625 }
626
627 func mldsaParametersFromOID(oid asn1.ObjectIdentifier) (mldsa.Parameters, bool) {
628 switch {
629 case oid.Equal(oidPublicKeyMLDSA44):
630 return mldsa.MLDSA44(), true
631 case oid.Equal(oidPublicKeyMLDSA65):
632 return mldsa.MLDSA65(), true
633 case oid.Equal(oidPublicKeyMLDSA87):
634 return mldsa.MLDSA87(), true
635 }
636 return mldsa.Parameters{}, false
637 }
638
639 func oidFromMLDSAParameters(params mldsa.Parameters) (asn1.ObjectIdentifier, bool) {
640 switch {
641 case params == mldsa.MLDSA44():
642 return oidPublicKeyMLDSA44, true
643 case params == mldsa.MLDSA65():
644 return oidPublicKeyMLDSA65, true
645 case params == mldsa.MLDSA87():
646 return oidPublicKeyMLDSA87, true
647 }
648 return nil, false
649 }
650
651
652
653 type KeyUsage int
654
655
656
657 const (
658 KeyUsageDigitalSignature KeyUsage = 1 << iota
659 KeyUsageContentCommitment
660 KeyUsageKeyEncipherment
661 KeyUsageDataEncipherment
662 KeyUsageKeyAgreement
663 KeyUsageCertSign
664 KeyUsageCRLSign
665 KeyUsageEncipherOnly
666 KeyUsageDecipherOnly
667 )
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683 var (
684 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
685 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
686 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
687 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
688 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
689 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
690 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
691 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
692 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
693 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
694 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
695 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
696 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
697 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
698 )
699
700
701
702 type ExtKeyUsage int
703
704 const (
705 ExtKeyUsageAny ExtKeyUsage = iota
706 ExtKeyUsageServerAuth
707 ExtKeyUsageClientAuth
708 ExtKeyUsageCodeSigning
709 ExtKeyUsageEmailProtection
710 ExtKeyUsageIPSECEndSystem
711 ExtKeyUsageIPSECTunnel
712 ExtKeyUsageIPSECUser
713 ExtKeyUsageTimeStamping
714 ExtKeyUsageOCSPSigning
715 ExtKeyUsageMicrosoftServerGatedCrypto
716 ExtKeyUsageNetscapeServerGatedCrypto
717 ExtKeyUsageMicrosoftCommercialCodeSigning
718 ExtKeyUsageMicrosoftKernelCodeSigning
719 )
720
721
722 var extKeyUsageOIDs = []struct {
723 extKeyUsage ExtKeyUsage
724 oid asn1.ObjectIdentifier
725 }{
726 {ExtKeyUsageAny, oidExtKeyUsageAny},
727 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
728 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
729 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
730 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
731 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
732 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
733 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
734 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
735 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
736 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
737 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
738 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
739 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
740 }
741
742 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
743 for _, pair := range extKeyUsageOIDs {
744 if oid.Equal(pair.oid) {
745 return pair.extKeyUsage, true
746 }
747 }
748 return
749 }
750
751 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
752 for _, pair := range extKeyUsageOIDs {
753 if eku == pair.extKeyUsage {
754 return pair.oid, true
755 }
756 }
757 return
758 }
759
760
761 func (eku ExtKeyUsage) OID() OID {
762 asn1OID, ok := oidFromExtKeyUsage(eku)
763 if !ok {
764 panic("x509: internal error: known ExtKeyUsage has no OID")
765 }
766 oid, err := OIDFromASN1OID(asn1OID)
767 if err != nil {
768 panic("x509: internal error: known ExtKeyUsage has invalid OID")
769 }
770 return oid
771 }
772
773
774 type Certificate struct {
775 Raw []byte
776 RawTBSCertificate []byte
777 RawSubjectPublicKeyInfo []byte
778 RawSubject []byte
779 RawIssuer []byte
780 RawSignatureAlgorithm []byte
781
782 Signature []byte
783 SignatureAlgorithm SignatureAlgorithm
784
785 PublicKeyAlgorithm PublicKeyAlgorithm
786 PublicKey any
787
788 Version int
789 SerialNumber *big.Int
790 Issuer pkix.Name
791 Subject pkix.Name
792 NotBefore, NotAfter time.Time
793 KeyUsage KeyUsage
794
795
796
797
798
799 Extensions []pkix.Extension
800
801
802
803
804
805 ExtraExtensions []pkix.Extension
806
807
808
809
810
811
812
813
814
815 UnhandledCriticalExtensions []asn1.ObjectIdentifier
816
817 ExtKeyUsage []ExtKeyUsage
818 UnknownExtKeyUsage []asn1.ObjectIdentifier
819
820
821
822 BasicConstraintsValid bool
823 IsCA bool
824
825
826
827
828
829
830
831
832
833
834
835
836
837 MaxPathLen int
838
839
840
841
842 MaxPathLenZero bool
843
844 SubjectKeyId []byte
845 AuthorityKeyId []byte
846
847
848 OCSPServer []string
849 IssuingCertificateURL []string
850
851
852
853
854 DNSNames []string
855 EmailAddresses []string
856 IPAddresses []net.IP
857 URIs []*url.URL
858
859
860 PermittedDNSDomainsCritical bool
861 PermittedDNSDomains []string
862 ExcludedDNSDomains []string
863 PermittedIPRanges []*net.IPNet
864 ExcludedIPRanges []*net.IPNet
865 PermittedEmailAddresses []string
866 ExcludedEmailAddresses []string
867 PermittedURIDomains []string
868 ExcludedURIDomains []string
869
870
871 CRLDistributionPoints []string
872
873
874
875
876
877
878
879
880 PolicyIdentifiers []asn1.ObjectIdentifier
881
882
883
884
885
886 Policies []OID
887
888
889
890
891
892
893
894
895
896
897
898
899
900 InhibitAnyPolicy int
901
902
903
904 InhibitAnyPolicyZero bool
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920 InhibitPolicyMapping int
921
922
923
924 InhibitPolicyMappingZero bool
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943 RequireExplicitPolicy int
944
945
946
947 RequireExplicitPolicyZero bool
948
949
950 PolicyMappings []PolicyMapping
951 }
952
953
954 type PolicyMapping struct {
955
956
957 IssuerDomainPolicy OID
958
959
960 SubjectDomainPolicy OID
961 }
962
963
964
965 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
966
967
968
969 type InsecureAlgorithmError SignatureAlgorithm
970
971 func (e InsecureAlgorithmError) Error() string {
972 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
973 }
974
975
976
977
978 type ConstraintViolationError struct{}
979
980 func (ConstraintViolationError) Error() string {
981 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
982 }
983
984 func (c *Certificate) Equal(other *Certificate) bool {
985 if c == nil || other == nil {
986 return c == other
987 }
988 return bytes.Equal(c.Raw, other.Raw)
989 }
990
991 func (c *Certificate) hasSANExtension() bool {
992 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
993 }
994
995
996
997
998
999 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
1000
1001
1002
1003
1004
1005 if parent.Version == 3 && !parent.BasicConstraintsValid ||
1006 parent.BasicConstraintsValid && !parent.IsCA {
1007 return ConstraintViolationError{}
1008 }
1009
1010 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
1011 return ConstraintViolationError{}
1012 }
1013
1014 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
1015 return ErrUnsupportedAlgorithm
1016 }
1017
1018 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature, parent.PublicKey, false)
1019 }
1020
1021
1022
1023
1024
1025
1026
1027
1028 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
1029 return checkSignature(algo, signed, signature, c.PublicKey, true)
1030 }
1031
1032 func (c *Certificate) hasNameConstraints() bool {
1033 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
1034 }
1035
1036 func (c *Certificate) getSANExtension() []byte {
1037 for _, e := range c.Extensions {
1038 if e.Id.Equal(oidExtensionSubjectAltName) {
1039 return e.Value
1040 }
1041 }
1042 return nil
1043 }
1044
1045 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey any) error {
1046 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
1047 }
1048
1049 func signatureMLDSAParametersMismatchError(expectedSigAlgo SignatureAlgorithm, pubKey *mldsa.PublicKey) error {
1050 return fmt.Errorf("x509: signature algorithm specifies an ML-DSA public key with %s parameters, but have a public key with %s parameters", expectedSigAlgo, pubKey.Parameters())
1051 }
1052
1053
1054
1055 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey, allowSHA1 bool) (err error) {
1056 var hashType crypto.Hash
1057 var pubKeyAlgo PublicKeyAlgorithm
1058
1059 for _, details := range signatureAlgorithmDetails {
1060 if details.algo == algo {
1061 hashType = details.hash
1062 pubKeyAlgo = details.pubKeyAlgo
1063 break
1064 }
1065 }
1066
1067 switch hashType {
1068 case crypto.Hash(0):
1069 if pubKeyAlgo != Ed25519 && pubKeyAlgo != MLDSA {
1070 return ErrUnsupportedAlgorithm
1071 }
1072 case crypto.MD5:
1073 return InsecureAlgorithmError(algo)
1074 case crypto.SHA1:
1075
1076 if !allowSHA1 {
1077 return InsecureAlgorithmError(algo)
1078 }
1079 fallthrough
1080 default:
1081 if !hashType.Available() {
1082 return ErrUnsupportedAlgorithm
1083 }
1084 h := hashType.New()
1085 h.Write(signed)
1086 signed = h.Sum(nil)
1087 }
1088
1089 switch pub := publicKey.(type) {
1090 case *rsa.PublicKey:
1091 if pubKeyAlgo != RSA {
1092 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1093 }
1094 if algo.isRSAPSS() {
1095 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
1096 } else {
1097 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
1098 }
1099 case *ecdsa.PublicKey:
1100 if pubKeyAlgo != ECDSA {
1101 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1102 }
1103 if !ecdsa.VerifyASN1(pub, signed, signature) {
1104 return errors.New("x509: ECDSA verification failure")
1105 }
1106 return
1107 case ed25519.PublicKey:
1108 if pubKeyAlgo != Ed25519 {
1109 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1110 }
1111 if !ed25519.Verify(pub, signed, signature) {
1112 return errors.New("x509: Ed25519 verification failure")
1113 }
1114 return
1115 case *mldsa.PublicKey:
1116 if pubKeyAlgo != MLDSA {
1117 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1118 }
1119 switch pub.Parameters() {
1120 case mldsa.MLDSA44():
1121 if algo != MLDSA44 {
1122 return signatureMLDSAParametersMismatchError(algo, pub)
1123 }
1124 case mldsa.MLDSA65():
1125 if algo != MLDSA65 {
1126 return signatureMLDSAParametersMismatchError(algo, pub)
1127 }
1128 case mldsa.MLDSA87():
1129 if algo != MLDSA87 {
1130 return signatureMLDSAParametersMismatchError(algo, pub)
1131 }
1132 default:
1133 return fmt.Errorf("x509: unknown ML-DSA parameters: %s", pub.Parameters())
1134 }
1135 if err := mldsa.Verify(pub, signed, signature, nil); err != nil {
1136 return fmt.Errorf("x509: ML-DSA verification failure: %w", err)
1137 }
1138 return
1139 }
1140 return ErrUnsupportedAlgorithm
1141 }
1142
1143
1144
1145
1146 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
1147 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
1148 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
1149 }
1150
1151 type UnhandledCriticalExtension struct{}
1152
1153 func (h UnhandledCriticalExtension) Error() string {
1154 return "x509: unhandled critical extension"
1155 }
1156
1157 type basicConstraints struct {
1158 IsCA bool `asn1:"optional"`
1159 MaxPathLen int `asn1:"optional,default:-1"`
1160 }
1161
1162
1163 type policyInformation struct {
1164 Policy asn1.ObjectIdentifier
1165
1166 }
1167
1168 const (
1169 nameTypeEmail = 1
1170 nameTypeDNS = 2
1171 nameTypeURI = 6
1172 nameTypeIP = 7
1173 )
1174
1175
1176 type authorityInfoAccess struct {
1177 Method asn1.ObjectIdentifier
1178 Location asn1.RawValue
1179 }
1180
1181
1182 type distributionPoint struct {
1183 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
1184 Reason asn1.BitString `asn1:"optional,tag:1"`
1185 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
1186 }
1187
1188 type distributionPointName struct {
1189 FullName []asn1.RawValue `asn1:"optional,tag:0"`
1190 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
1191 }
1192
1193 func reverseBitsInAByte(in byte) byte {
1194 b1 := in>>4 | in<<4
1195 b2 := b1>>2&0x33 | b1<<2&0xcc
1196 b3 := b2>>1&0x55 | b2<<1&0xaa
1197 return b3
1198 }
1199
1200
1201
1202
1203 func asn1BitLength(bitString []byte) int {
1204 bitLen := len(bitString) * 8
1205
1206 for i := range bitString {
1207 b := bitString[len(bitString)-i-1]
1208
1209 for bit := uint(0); bit < 8; bit++ {
1210 if (b>>bit)&1 == 1 {
1211 return bitLen
1212 }
1213 bitLen--
1214 }
1215 }
1216
1217 return 0
1218 }
1219
1220 var (
1221 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
1222 oidExtensionKeyUsage = []int{2, 5, 29, 15}
1223 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
1224 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
1225 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
1226 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
1227 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
1228 oidExtensionNameConstraints = []int{2, 5, 29, 30}
1229 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1230 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1231 oidExtensionCRLNumber = []int{2, 5, 29, 20}
1232 oidExtensionReasonCode = []int{2, 5, 29, 21}
1233 )
1234
1235 var (
1236 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1237 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1238 )
1239
1240
1241
1242 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1243 for _, e := range extensions {
1244 if e.Id.Equal(oid) {
1245 return true
1246 }
1247 }
1248 return false
1249 }
1250
1251
1252
1253 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
1254 var rawValues []asn1.RawValue
1255 for _, name := range dnsNames {
1256 if err := isIA5String(name); err != nil {
1257 return nil, err
1258 }
1259 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
1260 }
1261 for _, email := range emailAddresses {
1262 if err := isIA5String(email); err != nil {
1263 return nil, err
1264 }
1265 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1266 }
1267 for _, rawIP := range ipAddresses {
1268
1269 ip := rawIP.To4()
1270 if ip == nil {
1271 ip = rawIP
1272 }
1273 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1274 }
1275 for _, uri := range uris {
1276 uriStr := uri.String()
1277 if err := isIA5String(uriStr); err != nil {
1278 return nil, err
1279 }
1280 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})
1281 }
1282 return asn1.Marshal(rawValues)
1283 }
1284
1285 func isIA5String(s string) error {
1286 for _, r := range s {
1287
1288 if r > unicode.MaxASCII {
1289 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1290 }
1291 }
1292
1293 return nil
1294 }
1295
1296 var x509usepolicies = godebug.New("x509usepolicies")
1297
1298 func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
1299 ret = make([]pkix.Extension, 10 )
1300 n := 0
1301
1302 if template.KeyUsage != 0 &&
1303 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1304 ret[n], err = marshalKeyUsage(template.KeyUsage)
1305 if err != nil {
1306 return nil, err
1307 }
1308 n++
1309 }
1310
1311 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1312 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1313 ret[n], err = marshalExtKeyUsage(template.ExtKeyUsage, template.UnknownExtKeyUsage)
1314 if err != nil {
1315 return nil, err
1316 }
1317 n++
1318 }
1319
1320 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1321 ret[n], err = marshalBasicConstraints(template.IsCA, template.MaxPathLen, template.MaxPathLenZero)
1322 if err != nil {
1323 return nil, err
1324 }
1325 n++
1326 }
1327
1328 if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1329 ret[n].Id = oidExtensionSubjectKeyId
1330 ret[n].Value, err = asn1.Marshal(subjectKeyId)
1331 if err != nil {
1332 return
1333 }
1334 n++
1335 }
1336
1337 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1338 ret[n].Id = oidExtensionAuthorityKeyId
1339 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1340 if err != nil {
1341 return
1342 }
1343 n++
1344 }
1345
1346 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1347 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1348 ret[n].Id = oidExtensionAuthorityInfoAccess
1349 var aiaValues []authorityInfoAccess
1350 for _, name := range template.OCSPServer {
1351 aiaValues = append(aiaValues, authorityInfoAccess{
1352 Method: oidAuthorityInfoAccessOcsp,
1353 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1354 })
1355 }
1356 for _, name := range template.IssuingCertificateURL {
1357 aiaValues = append(aiaValues, authorityInfoAccess{
1358 Method: oidAuthorityInfoAccessIssuers,
1359 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1360 })
1361 }
1362 ret[n].Value, err = asn1.Marshal(aiaValues)
1363 if err != nil {
1364 return
1365 }
1366 n++
1367 }
1368
1369 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1370 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1371 ret[n].Id = oidExtensionSubjectAltName
1372
1373
1374
1375 ret[n].Critical = subjectIsEmpty
1376 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1377 if err != nil {
1378 return
1379 }
1380 n++
1381 }
1382
1383 usePolicies := x509usepolicies.Value() != "0"
1384 if ((!usePolicies && len(template.PolicyIdentifiers) > 0) || (usePolicies && len(template.Policies) > 0)) &&
1385 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1386 ret[n], err = marshalCertificatePolicies(template.Policies, template.PolicyIdentifiers)
1387 if err != nil {
1388 return nil, err
1389 }
1390 n++
1391 }
1392
1393 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1394 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1395 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1396 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1397 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1398 ret[n].Id = oidExtensionNameConstraints
1399 ret[n].Critical = template.PermittedDNSDomainsCritical
1400
1401 ipAndMask := func(ipNet *net.IPNet) ([]byte, error) {
1402 maskedIP := ipNet.IP.Mask(ipNet.Mask)
1403
1404
1405 if len(maskedIP) == net.IPv6len && maskedIP.To4() != nil {
1406 return nil, errors.New("x509: IP constraint contained IPv4-mapped IPv6 address with a IPv6 mask")
1407 }
1408 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1409 ipAndMask = append(ipAndMask, maskedIP...)
1410 ipAndMask = append(ipAndMask, ipNet.Mask...)
1411 return ipAndMask, nil
1412 }
1413
1414 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1415 var b cryptobyte.Builder
1416
1417 for _, name := range dns {
1418 if err = isIA5String(name); err != nil {
1419 return nil, err
1420 }
1421
1422 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1423 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1424 b.AddBytes([]byte(name))
1425 })
1426 })
1427 }
1428
1429 for _, ipNet := range ips {
1430 encodedIPNet, err := ipAndMask(ipNet)
1431 if err != nil {
1432 return nil, err
1433 }
1434 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1435 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1436 b.AddBytes(encodedIPNet)
1437 })
1438 })
1439 }
1440
1441 for _, email := range emails {
1442 if err = isIA5String(email); err != nil {
1443 return nil, err
1444 }
1445
1446 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1447 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1448 b.AddBytes([]byte(email))
1449 })
1450 })
1451 }
1452
1453 for _, uriDomain := range uriDomains {
1454 if err = isIA5String(uriDomain); err != nil {
1455 return nil, err
1456 }
1457
1458 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1459 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1460 b.AddBytes([]byte(uriDomain))
1461 })
1462 })
1463 }
1464
1465 return b.Bytes()
1466 }
1467
1468 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1469 if err != nil {
1470 return nil, err
1471 }
1472
1473 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1474 if err != nil {
1475 return nil, err
1476 }
1477
1478 var b cryptobyte.Builder
1479 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1480 if len(permitted) > 0 {
1481 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1482 b.AddBytes(permitted)
1483 })
1484 }
1485
1486 if len(excluded) > 0 {
1487 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1488 b.AddBytes(excluded)
1489 })
1490 }
1491 })
1492
1493 ret[n].Value, err = b.Bytes()
1494 if err != nil {
1495 return nil, err
1496 }
1497 n++
1498 }
1499
1500 if len(template.CRLDistributionPoints) > 0 &&
1501 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1502 ret[n].Id = oidExtensionCRLDistributionPoints
1503
1504 var crlDp []distributionPoint
1505 for _, name := range template.CRLDistributionPoints {
1506 dp := distributionPoint{
1507 DistributionPoint: distributionPointName{
1508 FullName: []asn1.RawValue{
1509 {Tag: 6, Class: 2, Bytes: []byte(name)},
1510 },
1511 },
1512 }
1513 crlDp = append(crlDp, dp)
1514 }
1515
1516 ret[n].Value, err = asn1.Marshal(crlDp)
1517 if err != nil {
1518 return
1519 }
1520 n++
1521 }
1522
1523
1524
1525
1526
1527 return append(ret[:n], template.ExtraExtensions...), nil
1528 }
1529
1530 func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error) {
1531 ext := pkix.Extension{Id: oidExtensionKeyUsage, Critical: true}
1532
1533 var a [2]byte
1534 a[0] = reverseBitsInAByte(byte(ku))
1535 a[1] = reverseBitsInAByte(byte(ku >> 8))
1536
1537 l := 1
1538 if a[1] != 0 {
1539 l = 2
1540 }
1541
1542 bitString := a[:l]
1543 var err error
1544 ext.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1545 return ext, err
1546 }
1547
1548 func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error) {
1549 ext := pkix.Extension{Id: oidExtensionExtendedKeyUsage}
1550
1551 oids := make([]asn1.ObjectIdentifier, len(extUsages)+len(unknownUsages))
1552 for i, u := range extUsages {
1553 if oid, ok := oidFromExtKeyUsage(u); ok {
1554 oids[i] = oid
1555 } else {
1556 return ext, errors.New("x509: unknown extended key usage")
1557 }
1558 }
1559
1560 copy(oids[len(extUsages):], unknownUsages)
1561
1562 var err error
1563 ext.Value, err = asn1.Marshal(oids)
1564 return ext, err
1565 }
1566
1567 func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error) {
1568 ext := pkix.Extension{Id: oidExtensionBasicConstraints, Critical: true}
1569
1570
1571
1572 if maxPathLen == 0 && !maxPathLenZero {
1573 maxPathLen = -1
1574 }
1575 var err error
1576 ext.Value, err = asn1.Marshal(basicConstraints{isCA, maxPathLen})
1577 return ext, err
1578 }
1579
1580 func marshalCertificatePolicies(policies []OID, policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error) {
1581 ext := pkix.Extension{Id: oidExtensionCertificatePolicies}
1582
1583 b := cryptobyte.NewBuilder(make([]byte, 0, 128))
1584 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1585 if x509usepolicies.Value() != "0" {
1586 x509usepolicies.IncNonDefault()
1587 for _, v := range policies {
1588 child.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1589 child.AddASN1(cryptobyte_asn1.OBJECT_IDENTIFIER, func(child *cryptobyte.Builder) {
1590 if len(v.der) == 0 {
1591 child.SetError(errors.New("invalid policy object identifier"))
1592 return
1593 }
1594 child.AddBytes(v.der)
1595 })
1596 })
1597 }
1598 } else {
1599 for _, v := range policyIdentifiers {
1600 child.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1601 child.AddASN1ObjectIdentifier(v)
1602 })
1603 }
1604 }
1605 })
1606
1607 var err error
1608 ext.Value, err = b.Bytes()
1609 return ext, err
1610 }
1611
1612 func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error) {
1613 var ret []pkix.Extension
1614
1615 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1616 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1617 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1618 if err != nil {
1619 return nil, err
1620 }
1621
1622 ret = append(ret, pkix.Extension{
1623 Id: oidExtensionSubjectAltName,
1624 Value: sanBytes,
1625 })
1626 }
1627
1628 return append(ret, template.ExtraExtensions...), nil
1629 }
1630
1631 func subjectBytes(cert *Certificate) ([]byte, error) {
1632 if len(cert.RawSubject) > 0 {
1633 return cert.RawSubject, nil
1634 }
1635
1636 return asn1.Marshal(cert.Subject.ToRDNSequence())
1637 }
1638
1639
1640
1641
1642 func signingParamsForKey(key crypto.Signer, sigAlgo SignatureAlgorithm) (SignatureAlgorithm, pkix.AlgorithmIdentifier, error) {
1643 var ai pkix.AlgorithmIdentifier
1644 var pubType PublicKeyAlgorithm
1645 var defaultAlgo SignatureAlgorithm
1646
1647 switch pub := key.Public().(type) {
1648 case *rsa.PublicKey:
1649 pubType = RSA
1650 defaultAlgo = SHA256WithRSA
1651
1652 case *ecdsa.PublicKey:
1653 pubType = ECDSA
1654 switch pub.Curve {
1655 case elliptic.P224(), elliptic.P256():
1656 defaultAlgo = ECDSAWithSHA256
1657 case elliptic.P384():
1658 defaultAlgo = ECDSAWithSHA384
1659 case elliptic.P521():
1660 defaultAlgo = ECDSAWithSHA512
1661 default:
1662 return 0, ai, errors.New("x509: unsupported elliptic curve")
1663 }
1664
1665 case ed25519.PublicKey:
1666 pubType = Ed25519
1667 defaultAlgo = PureEd25519
1668
1669 case *mldsa.PublicKey:
1670 pubType = MLDSA
1671 switch pub.Parameters() {
1672 case mldsa.MLDSA44():
1673 defaultAlgo = MLDSA44
1674 case mldsa.MLDSA65():
1675 defaultAlgo = MLDSA65
1676 case mldsa.MLDSA87():
1677 defaultAlgo = MLDSA87
1678 default:
1679 return 0, ai, fmt.Errorf("x509: unsupported ML-DSA parameters: %s", pub.Parameters())
1680 }
1681
1682 default:
1683 return 0, ai, errors.New("x509: only RSA, ECDSA, ML-DSA and Ed25519 keys supported")
1684 }
1685
1686 if sigAlgo == 0 {
1687 sigAlgo = defaultAlgo
1688 }
1689
1690 for _, details := range signatureAlgorithmDetails {
1691 if details.algo == sigAlgo {
1692 if details.pubKeyAlgo != pubType {
1693 return 0, ai, errors.New("x509: requested SignatureAlgorithm does not match private key type")
1694 }
1695 if pubType == MLDSA && sigAlgo != defaultAlgo {
1696 return 0, ai, errors.New("x509: requested SignatureAlgorithm does not match ML-DSA parameters")
1697 }
1698 if details.hash == crypto.MD5 {
1699 return 0, ai, errors.New("x509: signing with MD5 is not supported")
1700 }
1701
1702 return sigAlgo, pkix.AlgorithmIdentifier{
1703 Algorithm: details.oid,
1704 Parameters: details.params,
1705 }, nil
1706 }
1707 }
1708
1709 return 0, ai, errors.New("x509: unknown SignatureAlgorithm")
1710 }
1711
1712 func signTBS(tbs []byte, key crypto.Signer, sigAlg SignatureAlgorithm, rand io.Reader) ([]byte, error) {
1713 hashFunc := sigAlg.hashFunc()
1714
1715 var signerOpts crypto.SignerOpts = hashFunc
1716 if sigAlg.isRSAPSS() {
1717 signerOpts = &rsa.PSSOptions{
1718 SaltLength: rsa.PSSSaltLengthEqualsHash,
1719 Hash: hashFunc,
1720 }
1721 }
1722
1723 signature, err := crypto.SignMessage(key, rand, tbs, signerOpts)
1724 if err != nil {
1725 return nil, err
1726 }
1727
1728
1729 if err := checkSignature(sigAlg, tbs, signature, key.Public(), true); err != nil {
1730 return nil, fmt.Errorf("x509: signature returned by signer is invalid: %w", err)
1731 }
1732
1733 return signature, nil
1734 }
1735
1736
1737
1738 var emptyASN1Subject = []byte{0x30, 0}
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error) {
1808 key, ok := priv.(crypto.Signer)
1809 if !ok {
1810 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1811 }
1812
1813 serialNumber := template.SerialNumber
1814 if serialNumber == nil {
1815
1816
1817
1818 serialBytes := make([]byte, 20)
1819 if _, err := io.ReadFull(rand, serialBytes); err != nil {
1820 return nil, err
1821 }
1822
1823
1824
1825
1826 serialBytes[0] &= 0b0111_1111
1827 serialNumber = new(big.Int).SetBytes(serialBytes)
1828 }
1829
1830
1831
1832
1833
1834
1835 if serialNumber.Sign() == -1 {
1836 return nil, errors.New("x509: serial number must be positive")
1837 }
1838
1839 if template.BasicConstraintsValid && template.MaxPathLen < -1 {
1840 return nil, errors.New("x509: invalid MaxPathLen, must be greater or equal to -1")
1841 }
1842
1843 if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
1844 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
1845 }
1846
1847 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, template.SignatureAlgorithm)
1848 if err != nil {
1849 return nil, err
1850 }
1851
1852 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
1853 if err != nil {
1854 return nil, err
1855 }
1856 if getPublicKeyAlgorithmFromOID(publicKeyAlgorithm.Algorithm) == UnknownPublicKeyAlgorithm {
1857 return nil, fmt.Errorf("x509: unsupported public key type: %T", pub)
1858 }
1859
1860 asn1Issuer, err := subjectBytes(parent)
1861 if err != nil {
1862 return nil, err
1863 }
1864
1865 asn1Subject, err := subjectBytes(template)
1866 if err != nil {
1867 return nil, err
1868 }
1869
1870 authorityKeyId := template.AuthorityKeyId
1871 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
1872 authorityKeyId = parent.SubjectKeyId
1873 }
1874
1875 subjectKeyId := template.SubjectKeyId
1876 if len(subjectKeyId) == 0 && template.IsCA {
1877 if x509sha256skid.Value() == "0" {
1878 x509sha256skid.IncNonDefault()
1879
1880
1881
1882
1883 h := sha1.Sum(publicKeyBytes)
1884 subjectKeyId = h[:]
1885 } else {
1886
1887
1888
1889
1890 h := sha256.Sum256(publicKeyBytes)
1891 subjectKeyId = h[:20]
1892 }
1893 }
1894
1895
1896 type privateKey interface {
1897 Equal(crypto.PublicKey) bool
1898 }
1899 if privPub, ok := key.Public().(privateKey); !ok {
1900 return nil, errors.New("x509: internal error: supported public key does not implement Equal")
1901 } else if parent.PublicKey != nil && !privPub.Equal(parent.PublicKey) {
1902 return nil, errors.New("x509: provided PrivateKey doesn't match parent's PublicKey")
1903 }
1904
1905 extensions, err := buildCertExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
1906 if err != nil {
1907 return nil, err
1908 }
1909
1910 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
1911 c := tbsCertificate{
1912 Version: 2,
1913 SerialNumber: serialNumber,
1914 SignatureAlgorithm: algorithmIdentifier,
1915 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
1916 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
1917 Subject: asn1.RawValue{FullBytes: asn1Subject},
1918 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
1919 Extensions: extensions,
1920 }
1921
1922 tbsCertContents, err := asn1.Marshal(c)
1923 if err != nil {
1924 return nil, err
1925 }
1926 c.Raw = tbsCertContents
1927
1928 signature, err := signTBS(tbsCertContents, key, signatureAlgorithm, rand)
1929 if err != nil {
1930 return nil, err
1931 }
1932
1933 return asn1.Marshal(certificate{
1934 TBSCertificate: c,
1935 SignatureAlgorithm: algorithmIdentifier,
1936 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1937 })
1938 }
1939
1940 var x509sha256skid = godebug.New("x509sha256skid")
1941
1942
1943
1944 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1945
1946
1947 var pemType = "X509 CRL"
1948
1949
1950
1951
1952
1953
1954
1955 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
1956 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1957 block, _ := pem.Decode(crlBytes)
1958 if block != nil && block.Type == pemType {
1959 crlBytes = block.Bytes
1960 }
1961 }
1962 return ParseDERCRL(crlBytes)
1963 }
1964
1965
1966
1967
1968 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
1969 certList := new(pkix.CertificateList)
1970 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
1971 return nil, err
1972 } else if len(rest) != 0 {
1973 return nil, errors.New("x509: trailing data after CRL")
1974 }
1975 return certList, nil
1976 }
1977
1978
1979
1980
1981
1982
1983 func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
1984 key, ok := priv.(crypto.Signer)
1985 if !ok {
1986 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1987 }
1988
1989 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, 0)
1990 if err != nil {
1991 return nil, err
1992 }
1993
1994
1995 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
1996 for i, rc := range revokedCerts {
1997 rc.RevocationTime = rc.RevocationTime.UTC()
1998 revokedCertsUTC[i] = rc
1999 }
2000
2001 tbsCertList := pkix.TBSCertificateList{
2002 Version: 1,
2003 Signature: algorithmIdentifier,
2004 Issuer: c.Subject.ToRDNSequence(),
2005 ThisUpdate: now.UTC(),
2006 NextUpdate: expiry.UTC(),
2007 RevokedCertificates: revokedCertsUTC,
2008 }
2009
2010
2011 if len(c.SubjectKeyId) > 0 {
2012 var aki pkix.Extension
2013 aki.Id = oidExtensionAuthorityKeyId
2014 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
2015 if err != nil {
2016 return nil, err
2017 }
2018 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
2019 }
2020
2021 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2022 if err != nil {
2023 return nil, err
2024 }
2025 tbsCertList.Raw = tbsCertListContents
2026
2027 signature, err := signTBS(tbsCertListContents, key, signatureAlgorithm, rand)
2028 if err != nil {
2029 return nil, err
2030 }
2031
2032 return asn1.Marshal(pkix.CertificateList{
2033 TBSCertList: tbsCertList,
2034 SignatureAlgorithm: algorithmIdentifier,
2035 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2036 })
2037 }
2038
2039
2040 type CertificateRequest struct {
2041 Raw []byte
2042 RawTBSCertificateRequest []byte
2043 RawSubjectPublicKeyInfo []byte
2044 RawSubject []byte
2045 RawSignatureAlgorithm []byte
2046
2047 Version int
2048 Signature []byte
2049 SignatureAlgorithm SignatureAlgorithm
2050
2051 PublicKeyAlgorithm PublicKeyAlgorithm
2052 PublicKey any
2053
2054 Subject pkix.Name
2055
2056
2057
2058
2059
2060
2061 Attributes []pkix.AttributeTypeAndValueSET
2062
2063
2064
2065
2066 Extensions []pkix.Extension
2067
2068
2069
2070
2071
2072
2073
2074
2075 ExtraExtensions []pkix.Extension
2076
2077
2078 DNSNames []string
2079 EmailAddresses []string
2080 IPAddresses []net.IP
2081 URIs []*url.URL
2082 }
2083
2084
2085
2086
2087 type tbsCertificateRequest struct {
2088 Raw asn1.RawContent
2089 Version int
2090 Subject asn1.RawValue
2091 PublicKey publicKeyInfo
2092 RawAttributes []asn1.RawValue `asn1:"tag:0"`
2093 }
2094
2095 type certificateRequest struct {
2096 Raw asn1.RawContent
2097 TBSCSR tbsCertificateRequest
2098 SignatureAlgorithm struct {
2099 Raw asn1.RawContent
2100 Algorithm asn1.ObjectIdentifier
2101 Parameters asn1.RawValue `asn1:"optional"`
2102 }
2103 SignatureValue asn1.BitString
2104 }
2105
2106
2107
2108 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
2109
2110
2111
2112 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
2113 var rawAttributes []asn1.RawValue
2114 b, err := asn1.Marshal(attributes)
2115 if err != nil {
2116 return nil, err
2117 }
2118 rest, err := asn1.Unmarshal(b, &rawAttributes)
2119 if err != nil {
2120 return nil, err
2121 }
2122 if len(rest) != 0 {
2123 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
2124 }
2125 return rawAttributes, nil
2126 }
2127
2128
2129 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
2130 var attributes []pkix.AttributeTypeAndValueSET
2131 for _, rawAttr := range rawAttributes {
2132 var attr pkix.AttributeTypeAndValueSET
2133 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
2134
2135
2136 if err == nil && len(rest) == 0 {
2137 attributes = append(attributes, attr)
2138 }
2139 }
2140 return attributes
2141 }
2142
2143
2144
2145 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
2146
2147 type pkcs10Attribute struct {
2148 Id asn1.ObjectIdentifier
2149 Values []asn1.RawValue `asn1:"set"`
2150 }
2151
2152 var ret []pkix.Extension
2153 requestedExts := make(map[string]bool)
2154 for _, rawAttr := range rawAttributes {
2155 var attr pkcs10Attribute
2156 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
2157
2158 continue
2159 }
2160
2161 if !attr.Id.Equal(oidExtensionRequest) {
2162 continue
2163 }
2164
2165 var extensions []pkix.Extension
2166 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
2167 return nil, err
2168 }
2169 for _, ext := range extensions {
2170 oidStr := ext.Id.String()
2171 if requestedExts[oidStr] {
2172 return nil, errors.New("x509: certificate request contains duplicate requested extensions")
2173 }
2174 requestedExts[oidStr] = true
2175 }
2176 ret = append(ret, extensions...)
2177 }
2178
2179 return ret, nil
2180 }
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error) {
2203 key, ok := priv.(crypto.Signer)
2204 if !ok {
2205 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2206 }
2207
2208 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, template.SignatureAlgorithm)
2209 if err != nil {
2210 return nil, err
2211 }
2212
2213 var publicKeyBytes []byte
2214 var publicKeyAlgorithm pkix.AlgorithmIdentifier
2215 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
2216 if err != nil {
2217 return nil, err
2218 }
2219
2220 extensions, err := buildCSRExtensions(template)
2221 if err != nil {
2222 return nil, err
2223 }
2224
2225
2226 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
2227 for _, attr := range template.Attributes {
2228 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
2229 copy(values, attr.Value)
2230 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
2231 Type: attr.Type,
2232 Value: values,
2233 })
2234 }
2235
2236 extensionsAppended := false
2237 if len(extensions) > 0 {
2238
2239 for _, atvSet := range attributes {
2240 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
2241 continue
2242 }
2243
2244
2245
2246 specifiedExtensions := make(map[string]bool)
2247
2248 for _, atvs := range atvSet.Value {
2249 for _, atv := range atvs {
2250 specifiedExtensions[atv.Type.String()] = true
2251 }
2252 }
2253
2254 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
2255 newValue = append(newValue, atvSet.Value[0]...)
2256
2257 for _, e := range extensions {
2258 if specifiedExtensions[e.Id.String()] {
2259
2260
2261 continue
2262 }
2263
2264 newValue = append(newValue, pkix.AttributeTypeAndValue{
2265
2266
2267 Type: e.Id,
2268 Value: e.Value,
2269 })
2270 }
2271
2272 atvSet.Value[0] = newValue
2273 extensionsAppended = true
2274 break
2275 }
2276 }
2277
2278 rawAttributes, err := newRawAttributes(attributes)
2279 if err != nil {
2280 return nil, err
2281 }
2282
2283
2284
2285 if len(extensions) > 0 && !extensionsAppended {
2286 attr := struct {
2287 Type asn1.ObjectIdentifier
2288 Value [][]pkix.Extension `asn1:"set"`
2289 }{
2290 Type: oidExtensionRequest,
2291 Value: [][]pkix.Extension{extensions},
2292 }
2293
2294 b, err := asn1.Marshal(attr)
2295 if err != nil {
2296 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
2297 }
2298
2299 var rawValue asn1.RawValue
2300 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
2301 return nil, err
2302 }
2303
2304 rawAttributes = append(rawAttributes, rawValue)
2305 }
2306
2307 asn1Subject := template.RawSubject
2308 if len(asn1Subject) == 0 {
2309 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2310 if err != nil {
2311 return nil, err
2312 }
2313 }
2314
2315 tbsCSR := tbsCertificateRequest{
2316 Version: 0,
2317 Subject: asn1.RawValue{FullBytes: asn1Subject},
2318 PublicKey: publicKeyInfo{
2319 Algorithm: publicKeyAlgorithm,
2320 PublicKey: asn1.BitString{
2321 Bytes: publicKeyBytes,
2322 BitLength: len(publicKeyBytes) * 8,
2323 },
2324 },
2325 RawAttributes: rawAttributes,
2326 }
2327
2328 tbsCSRContents, err := asn1.Marshal(tbsCSR)
2329 if err != nil {
2330 return nil, err
2331 }
2332 tbsCSR.Raw = tbsCSRContents
2333
2334 signature, err := signTBS(tbsCSRContents, key, signatureAlgorithm, rand)
2335 if err != nil {
2336 return nil, err
2337 }
2338
2339 cr := certificateRequest{}
2340 cr.TBSCSR = tbsCSR
2341 cr.SignatureAlgorithm.Algorithm = algorithmIdentifier.Algorithm
2342 cr.SignatureAlgorithm.Parameters = algorithmIdentifier.Parameters
2343 cr.SignatureValue = asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}
2344 return asn1.Marshal(cr)
2345 }
2346
2347
2348
2349 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2350 var csr certificateRequest
2351
2352 rest, err := asn1.Unmarshal(asn1Data, &csr)
2353 if err != nil {
2354 return nil, err
2355 } else if len(rest) != 0 {
2356 return nil, asn1.SyntaxError{Msg: "trailing data"}
2357 }
2358
2359 return parseCertificateRequest(&csr)
2360 }
2361
2362 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2363 out := &CertificateRequest{
2364 Raw: in.Raw,
2365 RawTBSCertificateRequest: in.TBSCSR.Raw,
2366 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2367 RawSubject: in.TBSCSR.Subject.FullBytes,
2368 RawSignatureAlgorithm: in.SignatureAlgorithm.Raw,
2369
2370 Signature: in.SignatureValue.RightAlign(),
2371 SignatureAlgorithm: getSignatureAlgorithmFromAI(pkix.AlgorithmIdentifier{
2372 Algorithm: in.SignatureAlgorithm.Algorithm,
2373 Parameters: in.SignatureAlgorithm.Parameters,
2374 }),
2375
2376 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2377
2378 Version: in.TBSCSR.Version,
2379 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2380 }
2381
2382 var err error
2383 if out.PublicKeyAlgorithm != UnknownPublicKeyAlgorithm {
2384 out.PublicKey, err = parsePublicKey(&in.TBSCSR.PublicKey)
2385 if err != nil {
2386 return nil, err
2387 }
2388 }
2389
2390 subject, err := parseName(in.TBSCSR.Subject.FullBytes)
2391 if err != nil {
2392 return nil, err
2393 }
2394 out.Subject.FillFromRDNSequence(subject)
2395
2396 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2397 return nil, err
2398 }
2399
2400 for _, extension := range out.Extensions {
2401 switch {
2402 case extension.Id.Equal(oidExtensionSubjectAltName):
2403 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2404 if err != nil {
2405 return nil, err
2406 }
2407 }
2408 }
2409
2410 return out, nil
2411 }
2412
2413
2414 func (c *CertificateRequest) CheckSignature() error {
2415 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey, true)
2416 }
2417
2418
2419
2420 type RevocationListEntry struct {
2421
2422
2423 Raw []byte
2424
2425
2426
2427
2428 SerialNumber *big.Int
2429
2430
2431
2432 RevocationTime time.Time
2433
2434
2435
2436
2437
2438
2439
2440
2441 ReasonCode int
2442
2443
2444
2445
2446
2447 Extensions []pkix.Extension
2448
2449
2450
2451
2452 ExtraExtensions []pkix.Extension
2453 }
2454
2455
2456
2457 type RevocationList struct {
2458
2459
2460 Raw []byte
2461
2462
2463 RawTBSRevocationList []byte
2464
2465 RawIssuer []byte
2466
2467
2468 RawSignatureAlgorithm []byte
2469
2470
2471 Issuer pkix.Name
2472
2473
2474
2475
2476 AuthorityKeyId []byte
2477
2478 Signature []byte
2479
2480
2481
2482 SignatureAlgorithm SignatureAlgorithm
2483
2484
2485
2486
2487
2488 RevokedCertificateEntries []RevocationListEntry
2489
2490
2491
2492
2493
2494
2495 RevokedCertificates []pkix.RevokedCertificate
2496
2497
2498
2499
2500
2501 Number *big.Int
2502
2503
2504
2505 ThisUpdate time.Time
2506
2507
2508
2509 NextUpdate time.Time
2510
2511
2512
2513 Extensions []pkix.Extension
2514
2515
2516
2517 ExtraExtensions []pkix.Extension
2518 }
2519
2520
2521
2522
2523
2524
2525
2526 type certificateList struct {
2527 TBSCertList tbsCertificateList
2528 SignatureAlgorithm pkix.AlgorithmIdentifier
2529 SignatureValue asn1.BitString
2530 }
2531
2532 type tbsCertificateList struct {
2533 Raw asn1.RawContent
2534 Version int `asn1:"optional,default:0"`
2535 Signature pkix.AlgorithmIdentifier
2536 Issuer asn1.RawValue
2537 ThisUpdate time.Time
2538 NextUpdate time.Time `asn1:"optional"`
2539 RevokedCertificates []pkix.RevokedCertificate `asn1:"optional"`
2540 Extensions []pkix.Extension `asn1:"tag:0,optional,explicit"`
2541 }
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2557 if template == nil {
2558 return nil, errors.New("x509: template can not be nil")
2559 }
2560 if issuer == nil {
2561 return nil, errors.New("x509: issuer can not be nil")
2562 }
2563 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2564 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2565 }
2566 if len(issuer.SubjectKeyId) == 0 {
2567 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2568 }
2569 if template.NextUpdate.Before(template.ThisUpdate) {
2570 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2571 }
2572 if template.Number == nil {
2573 return nil, errors.New("x509: template contains nil Number field")
2574 }
2575
2576 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(priv, template.SignatureAlgorithm)
2577 if err != nil {
2578 return nil, err
2579 }
2580
2581 var revokedCerts []pkix.RevokedCertificate
2582
2583
2584 if len(template.RevokedCertificates) > 0 && len(template.RevokedCertificateEntries) == 0 {
2585
2586 revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2587 for i, rc := range template.RevokedCertificates {
2588 rc.RevocationTime = rc.RevocationTime.UTC()
2589 revokedCerts[i] = rc
2590 }
2591 } else {
2592
2593
2594 revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificateEntries))
2595 for i, rce := range template.RevokedCertificateEntries {
2596 if rce.SerialNumber == nil {
2597 return nil, errors.New("x509: template contains entry with nil SerialNumber field")
2598 }
2599 if rce.RevocationTime.IsZero() {
2600 return nil, errors.New("x509: template contains entry with zero RevocationTime field")
2601 }
2602
2603 rc := pkix.RevokedCertificate{
2604 SerialNumber: rce.SerialNumber,
2605 RevocationTime: rce.RevocationTime.UTC(),
2606 }
2607
2608
2609
2610 exts := make([]pkix.Extension, 0, len(rce.ExtraExtensions))
2611 for _, ext := range rce.ExtraExtensions {
2612 if ext.Id.Equal(oidExtensionReasonCode) {
2613 return nil, errors.New("x509: template contains entry with ReasonCode ExtraExtension; use ReasonCode field instead")
2614 }
2615 exts = append(exts, ext)
2616 }
2617
2618
2619
2620 if rce.ReasonCode != 0 {
2621 reasonBytes, err := asn1.Marshal(asn1.Enumerated(rce.ReasonCode))
2622 if err != nil {
2623 return nil, err
2624 }
2625
2626 exts = append(exts, pkix.Extension{
2627 Id: oidExtensionReasonCode,
2628 Value: reasonBytes,
2629 })
2630 }
2631
2632 if len(exts) > 0 {
2633 rc.Extensions = exts
2634 }
2635 revokedCerts[i] = rc
2636 }
2637 }
2638
2639 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2640 if err != nil {
2641 return nil, err
2642 }
2643
2644 if numBytes := template.Number.Bytes(); len(numBytes) > 20 || (len(numBytes) == 20 && numBytes[0]&0x80 != 0) {
2645 return nil, errors.New("x509: CRL number exceeds 20 octets")
2646 }
2647 crlNum, err := asn1.Marshal(template.Number)
2648 if err != nil {
2649 return nil, err
2650 }
2651
2652
2653 issuerSubject, err := subjectBytes(issuer)
2654 if err != nil {
2655 return nil, err
2656 }
2657
2658 tbsCertList := tbsCertificateList{
2659 Version: 1,
2660 Signature: algorithmIdentifier,
2661 Issuer: asn1.RawValue{FullBytes: issuerSubject},
2662 ThisUpdate: template.ThisUpdate.UTC(),
2663 NextUpdate: template.NextUpdate.UTC(),
2664 Extensions: []pkix.Extension{
2665 {
2666 Id: oidExtensionAuthorityKeyId,
2667 Value: aki,
2668 },
2669 {
2670 Id: oidExtensionCRLNumber,
2671 Value: crlNum,
2672 },
2673 },
2674 }
2675 if len(revokedCerts) > 0 {
2676 tbsCertList.RevokedCertificates = revokedCerts
2677 }
2678
2679 if len(template.ExtraExtensions) > 0 {
2680 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2681 }
2682
2683 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2684 if err != nil {
2685 return nil, err
2686 }
2687
2688
2689
2690 tbsCertList.Raw = tbsCertListContents
2691
2692 signature, err := signTBS(tbsCertListContents, priv, signatureAlgorithm, rand)
2693 if err != nil {
2694 return nil, err
2695 }
2696
2697 return asn1.Marshal(certificateList{
2698 TBSCertList: tbsCertList,
2699 SignatureAlgorithm: algorithmIdentifier,
2700 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2701 })
2702 }
2703
2704
2705
2706 func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error {
2707 if parent.Version == 3 && !parent.BasicConstraintsValid ||
2708 parent.BasicConstraintsValid && !parent.IsCA {
2709 return ConstraintViolationError{}
2710 }
2711
2712 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCRLSign == 0 {
2713 return ConstraintViolationError{}
2714 }
2715
2716 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
2717 return ErrUnsupportedAlgorithm
2718 }
2719
2720 return parent.CheckSignature(rl.SignatureAlgorithm, rl.RawTBSRevocationList, rl.Signature)
2721 }
2722
View as plain text