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