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