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