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