1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48 package x509
49
50 import (
51 "bytes"
52 "crypto"
53 "crypto/dsa"
54 "crypto/ecdsa"
55 "crypto/elliptic"
56 "crypto/rsa"
57 _ "crypto/sha1"
58 _ "crypto/sha256"
59 _ "crypto/sha512"
60 "encoding/pem"
61 "errors"
62 "fmt"
63 "io"
64 "math/big"
65 "net"
66 "net/url"
67 "strconv"
68 "strings"
69 "time"
70 "unicode/utf8"
71
72 "golang.org/x/crypto/cryptobyte"
73 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
74 "golang.org/x/crypto/ed25519"
75
76 "github.com/google/certificate-transparency-go/asn1"
77 "github.com/google/certificate-transparency-go/tls"
78 "github.com/google/certificate-transparency-go/x509/pkix"
79 )
80
81
82
83 type pkixPublicKey struct {
84 Algo pkix.AlgorithmIdentifier
85 BitString asn1.BitString
86 }
87
88
89
90
91
92
93
94 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
95 var pki publicKeyInfo
96 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
97 return nil, err
98 } else if len(rest) != 0 {
99 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
100 }
101 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
102 if algo == UnknownPublicKeyAlgorithm {
103 return nil, errors.New("x509: unknown public key algorithm")
104 }
105 var nfe NonFatalErrors
106 pub, err = parsePublicKey(algo, &pki, &nfe)
107 if err != nil {
108 return pub, err
109 }
110
111 if len(nfe.Errors) > 0 {
112 return nil, nfe.Errors[0]
113 }
114 return pub, nil
115 }
116
117 func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
118 switch pub := pub.(type) {
119 case *rsa.PublicKey:
120 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
121 N: pub.N,
122 E: pub.E,
123 })
124 if err != nil {
125 return nil, pkix.AlgorithmIdentifier{}, err
126 }
127 publicKeyAlgorithm.Algorithm = OIDPublicKeyRSA
128
129
130 publicKeyAlgorithm.Parameters = asn1.NullRawValue
131 case *ecdsa.PublicKey:
132 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
133 oid, ok := OIDFromNamedCurve(pub.Curve)
134 if !ok {
135 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
136 }
137 publicKeyAlgorithm.Algorithm = OIDPublicKeyECDSA
138 var paramBytes []byte
139 paramBytes, err = asn1.Marshal(oid)
140 if err != nil {
141 return
142 }
143 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
144 case ed25519.PublicKey:
145 publicKeyBytes = pub
146 publicKeyAlgorithm.Algorithm = OIDPublicKeyEd25519
147 default:
148 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
149 }
150
151 return publicKeyBytes, publicKeyAlgorithm, nil
152 }
153
154
155
156
157
158
159
160 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
161 var publicKeyBytes []byte
162 var publicKeyAlgorithm pkix.AlgorithmIdentifier
163 var err error
164
165 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
166 return nil, err
167 }
168
169 pkix := pkixPublicKey{
170 Algo: publicKeyAlgorithm,
171 BitString: asn1.BitString{
172 Bytes: publicKeyBytes,
173 BitLength: 8 * len(publicKeyBytes),
174 },
175 }
176
177 ret, _ := asn1.Marshal(pkix)
178 return ret, nil
179 }
180
181
182
183 type certificate struct {
184 Raw asn1.RawContent
185 TBSCertificate tbsCertificate
186 SignatureAlgorithm pkix.AlgorithmIdentifier
187 SignatureValue asn1.BitString
188 }
189
190 type tbsCertificate struct {
191 Raw asn1.RawContent
192 Version int `asn1:"optional,explicit,default:0,tag:0"`
193 SerialNumber *big.Int
194 SignatureAlgorithm pkix.AlgorithmIdentifier
195 Issuer asn1.RawValue
196 Validity validity
197 Subject asn1.RawValue
198 PublicKey publicKeyInfo
199 UniqueId asn1.BitString `asn1:"optional,tag:1"`
200 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
201 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
202 }
203
204
205
206
207 type rsaesoaepAlgorithmParameters struct {
208 HashFunc pkix.AlgorithmIdentifier `asn1:"optional,explicit,tag:0,default:sha1Identifier"`
209 MaskgenFunc pkix.AlgorithmIdentifier `asn1:"optional,explicit,tag:1,default:mgf1SHA1Identifier"`
210 PSourceFunc pkix.AlgorithmIdentifier `asn1:"optional,explicit,tag:2,default:pSpecifiedEmptyIdentifier"`
211 }
212
213 type dsaAlgorithmParameters struct {
214 P, Q, G *big.Int
215 }
216
217 type dsaSignature struct {
218 R, S *big.Int
219 }
220
221 type ecdsaSignature dsaSignature
222
223 type validity struct {
224 NotBefore, NotAfter time.Time
225 }
226
227 type publicKeyInfo struct {
228 Raw asn1.RawContent
229 Algorithm pkix.AlgorithmIdentifier
230 PublicKey asn1.BitString
231 }
232
233
234 type authKeyId struct {
235 Id []byte `asn1:"optional,tag:0"`
236 }
237
238
239 type SignatureAlgorithm int
240
241
242 const (
243 UnknownSignatureAlgorithm SignatureAlgorithm = iota
244 MD2WithRSA
245 MD5WithRSA
246 SHA1WithRSA
247 SHA256WithRSA
248 SHA384WithRSA
249 SHA512WithRSA
250 DSAWithSHA1
251 DSAWithSHA256
252 ECDSAWithSHA1
253 ECDSAWithSHA256
254 ECDSAWithSHA384
255 ECDSAWithSHA512
256 SHA256WithRSAPSS
257 SHA384WithRSAPSS
258 SHA512WithRSAPSS
259 PureEd25519
260 )
261
262
263 var oidpSpecified = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 9}
264
265
266
267
268 var (
269 sha1Identifier = pkix.AlgorithmIdentifier{
270 Algorithm: oidSHA1,
271 Parameters: asn1.NullRawValue,
272 }
273 mgf1SHA1Identifier = pkix.AlgorithmIdentifier{
274 Algorithm: oidMGF1,
275
276 Parameters: asn1.RawValue{
277 Class: asn1.ClassUniversal,
278 Tag: asn1.TagSequence,
279 IsCompound: false,
280 Bytes: []byte{6, 5, 43, 14, 3, 2, 26, 5, 0},
281 FullBytes: []byte{16, 9, 6, 5, 43, 14, 3, 2, 26, 5, 0}},
282 }
283 pSpecifiedEmptyIdentifier = pkix.AlgorithmIdentifier{
284 Algorithm: oidpSpecified,
285
286 Parameters: asn1.RawValue{
287 Class: asn1.ClassUniversal,
288 Tag: asn1.TagOctetString,
289 IsCompound: false,
290 Bytes: []byte{},
291 FullBytes: []byte{4, 0}},
292 }
293 )
294
295 func (algo SignatureAlgorithm) isRSAPSS() bool {
296 switch algo {
297 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
298 return true
299 default:
300 return false
301 }
302 }
303
304 func (algo SignatureAlgorithm) String() string {
305 for _, details := range signatureAlgorithmDetails {
306 if details.algo == algo {
307 return details.name
308 }
309 }
310 return strconv.Itoa(int(algo))
311 }
312
313
314 type PublicKeyAlgorithm int
315
316
317 const (
318 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
319 RSA
320 DSA
321 ECDSA
322 Ed25519
323 RSAESOAEP
324 )
325
326 var publicKeyAlgoName = [...]string{
327 RSA: "RSA",
328 DSA: "DSA",
329 ECDSA: "ECDSA",
330 Ed25519: "Ed25519",
331 RSAESOAEP: "RSAESOAEP",
332 }
333
334 func (algo PublicKeyAlgorithm) String() string {
335 if 0 < algo && int(algo) < len(publicKeyAlgoName) {
336 return publicKeyAlgoName[algo]
337 }
338 return strconv.Itoa(int(algo))
339 }
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396 var (
397 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
398 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
399 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
400 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
401 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
402 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
403 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
404 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
405 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
406 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
407 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
408 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
409 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
410 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
411
412 oidSHA1 = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 26}
413 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
414 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
415 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
416
417 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
418
419
420
421
422 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
423 )
424
425 var signatureAlgorithmDetails = []struct {
426 algo SignatureAlgorithm
427 name string
428 oid asn1.ObjectIdentifier
429 pubKeyAlgo PublicKeyAlgorithm
430 hash crypto.Hash
431 }{
432 {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) },
433 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
434 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
435 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
436 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
437 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
438 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
439 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
440 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
441 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
442 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
443 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
444 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
445 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
446 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
447 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
448 {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) },
449 }
450
451
452
453 type pssParameters struct {
454
455
456
457 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
458 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
459 SaltLength int `asn1:"explicit,tag:2"`
460 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
461 }
462
463
464
465 func rsaPSSParameters(hashFunc crypto.Hash) asn1.RawValue {
466 var hashOID asn1.ObjectIdentifier
467
468 switch hashFunc {
469 case crypto.SHA256:
470 hashOID = oidSHA256
471 case crypto.SHA384:
472 hashOID = oidSHA384
473 case crypto.SHA512:
474 hashOID = oidSHA512
475 }
476
477 params := pssParameters{
478 Hash: pkix.AlgorithmIdentifier{
479 Algorithm: hashOID,
480 Parameters: asn1.NullRawValue,
481 },
482 MGF: pkix.AlgorithmIdentifier{
483 Algorithm: oidMGF1,
484 },
485 SaltLength: hashFunc.Size(),
486 TrailerField: 1,
487 }
488
489 mgf1Params := pkix.AlgorithmIdentifier{
490 Algorithm: hashOID,
491 Parameters: asn1.NullRawValue,
492 }
493
494 var err error
495 params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
496 if err != nil {
497 panic(err)
498 }
499
500 serialized, err := asn1.Marshal(params)
501 if err != nil {
502 panic(err)
503 }
504
505 return asn1.RawValue{FullBytes: serialized}
506 }
507
508
509
510 func SignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
511 if ai.Algorithm.Equal(oidSignatureEd25519) {
512
513
514 if len(ai.Parameters.FullBytes) != 0 {
515 return UnknownSignatureAlgorithm
516 }
517 }
518
519 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
520 for _, details := range signatureAlgorithmDetails {
521 if ai.Algorithm.Equal(details.oid) {
522 return details.algo
523 }
524 }
525 return UnknownSignatureAlgorithm
526 }
527
528
529
530
531 var params pssParameters
532 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {
533 return UnknownSignatureAlgorithm
534 }
535
536 var mgf1HashFunc pkix.AlgorithmIdentifier
537 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
538 return UnknownSignatureAlgorithm
539 }
540
541
542
543
544
545
546 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
547 !params.MGF.Algorithm.Equal(oidMGF1) ||
548 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
549 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
550 params.TrailerField != 1 {
551 return UnknownSignatureAlgorithm
552 }
553
554 switch {
555 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
556 return SHA256WithRSAPSS
557 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
558 return SHA384WithRSAPSS
559 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
560 return SHA512WithRSAPSS
561 }
562
563 return UnknownSignatureAlgorithm
564 }
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582 var (
583 OIDPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
584 OIDPublicKeyRSAESOAEP = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 7}
585 OIDPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
586 OIDPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
587 OIDPublicKeyRSAObsolete = asn1.ObjectIdentifier{2, 5, 8, 1, 1}
588 OIDPublicKeyEd25519 = oidSignatureEd25519
589 )
590
591 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
592 switch {
593 case oid.Equal(OIDPublicKeyRSA):
594 return RSA
595 case oid.Equal(OIDPublicKeyDSA):
596 return DSA
597 case oid.Equal(OIDPublicKeyECDSA):
598 return ECDSA
599 case oid.Equal(OIDPublicKeyRSAESOAEP):
600 return RSAESOAEP
601 case oid.Equal(OIDPublicKeyEd25519):
602 return Ed25519
603 }
604 return UnknownPublicKeyAlgorithm
605 }
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628 var (
629 OIDNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
630 OIDNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
631 OIDNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
632 OIDNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
633 OIDNamedCurveP192 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 1}
634 )
635
636 func namedCurveFromOID(oid asn1.ObjectIdentifier, nfe *NonFatalErrors) elliptic.Curve {
637 switch {
638 case oid.Equal(OIDNamedCurveP224):
639 return elliptic.P224()
640 case oid.Equal(OIDNamedCurveP256):
641 return elliptic.P256()
642 case oid.Equal(OIDNamedCurveP384):
643 return elliptic.P384()
644 case oid.Equal(OIDNamedCurveP521):
645 return elliptic.P521()
646 case oid.Equal(OIDNamedCurveP192):
647 nfe.AddError(errors.New("insecure curve (secp192r1) specified"))
648 return secp192r1()
649 }
650 return nil
651 }
652
653
654
655 func OIDFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
656 switch curve {
657 case elliptic.P224():
658 return OIDNamedCurveP224, true
659 case elliptic.P256():
660 return OIDNamedCurveP256, true
661 case elliptic.P384():
662 return OIDNamedCurveP384, true
663 case elliptic.P521():
664 return OIDNamedCurveP521, true
665 case secp192r1():
666 return OIDNamedCurveP192, true
667 }
668
669 return nil, false
670 }
671
672
673
674 type KeyUsage int
675
676
677 const (
678 KeyUsageDigitalSignature KeyUsage = 1 << iota
679 KeyUsageContentCommitment
680 KeyUsageKeyEncipherment
681 KeyUsageDataEncipherment
682 KeyUsageKeyAgreement
683 KeyUsageCertSign
684 KeyUsageCRLSign
685 KeyUsageEncipherOnly
686 KeyUsageDecipherOnly
687 )
688
689
690
691
692
693
694
695
696
697
698
699
700
701 var (
702 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
703 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
704 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
705 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
706 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
707 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
708 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
709 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
710 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
711 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
712 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
713 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
714 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
715 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
716
717 oidExtKeyUsageCertificateTransparency = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 4}
718 )
719
720
721
722 type ExtKeyUsage int
723
724
725 const (
726 ExtKeyUsageAny ExtKeyUsage = iota
727 ExtKeyUsageServerAuth
728 ExtKeyUsageClientAuth
729 ExtKeyUsageCodeSigning
730 ExtKeyUsageEmailProtection
731 ExtKeyUsageIPSECEndSystem
732 ExtKeyUsageIPSECTunnel
733 ExtKeyUsageIPSECUser
734 ExtKeyUsageTimeStamping
735 ExtKeyUsageOCSPSigning
736 ExtKeyUsageMicrosoftServerGatedCrypto
737 ExtKeyUsageNetscapeServerGatedCrypto
738 ExtKeyUsageMicrosoftCommercialCodeSigning
739 ExtKeyUsageMicrosoftKernelCodeSigning
740 ExtKeyUsageCertificateTransparency
741 )
742
743
744 var extKeyUsageOIDs = []struct {
745 extKeyUsage ExtKeyUsage
746 oid asn1.ObjectIdentifier
747 }{
748 {ExtKeyUsageAny, oidExtKeyUsageAny},
749 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
750 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
751 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
752 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
753 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
754 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
755 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
756 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
757 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
758 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
759 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
760 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
761 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
762 {ExtKeyUsageCertificateTransparency, oidExtKeyUsageCertificateTransparency},
763 }
764
765 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
766 for _, pair := range extKeyUsageOIDs {
767 if oid.Equal(pair.oid) {
768 return pair.extKeyUsage, true
769 }
770 }
771 return
772 }
773
774 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
775 for _, pair := range extKeyUsageOIDs {
776 if eku == pair.extKeyUsage {
777 return pair.oid, true
778 }
779 }
780 return
781 }
782
783
784 type SerializedSCT struct {
785 Val []byte `tls:"minlen:1,maxlen:65535"`
786 }
787
788
789 type SignedCertificateTimestampList struct {
790 SCTList []SerializedSCT `tls:"minlen:1,maxlen:65335"`
791 }
792
793
794 type Certificate struct {
795 Raw []byte
796 RawTBSCertificate []byte
797 RawSubjectPublicKeyInfo []byte
798 RawSubject []byte
799 RawIssuer []byte
800
801 Signature []byte
802 SignatureAlgorithm SignatureAlgorithm
803
804 PublicKeyAlgorithm PublicKeyAlgorithm
805 PublicKey interface{}
806
807 Version int
808 SerialNumber *big.Int
809 Issuer pkix.Name
810 Subject pkix.Name
811 NotBefore, NotAfter time.Time
812 KeyUsage KeyUsage
813
814
815
816
817
818 Extensions []pkix.Extension
819
820
821
822
823
824 ExtraExtensions []pkix.Extension
825
826
827
828
829
830
831
832
833
834 UnhandledCriticalExtensions []asn1.ObjectIdentifier
835
836 ExtKeyUsage []ExtKeyUsage
837 UnknownExtKeyUsage []asn1.ObjectIdentifier
838
839
840
841 BasicConstraintsValid bool
842 IsCA bool
843
844
845
846
847
848
849
850
851
852
853
854
855
856 MaxPathLen int
857
858
859
860
861 MaxPathLenZero bool
862
863 SubjectKeyId []byte
864 AuthorityKeyId []byte
865
866
867 OCSPServer []string
868 IssuingCertificateURL []string
869
870
871 SubjectTimestamps []string
872 SubjectCARepositories []string
873
874
875
876
877 DNSNames []string
878 EmailAddresses []string
879 IPAddresses []net.IP
880 URIs []*url.URL
881
882
883 PermittedDNSDomainsCritical bool
884 PermittedDNSDomains []string
885 ExcludedDNSDomains []string
886 PermittedIPRanges []*net.IPNet
887 ExcludedIPRanges []*net.IPNet
888 PermittedEmailAddresses []string
889 ExcludedEmailAddresses []string
890 PermittedURIDomains []string
891 ExcludedURIDomains []string
892
893
894 CRLDistributionPoints []string
895
896 PolicyIdentifiers []asn1.ObjectIdentifier
897
898 RPKIAddressRanges []*IPAddressFamilyBlocks
899 RPKIASNumbers, RPKIRoutingDomainIDs *ASIdentifiers
900
901
902
903 RawSCT []byte
904 SCTList SignedCertificateTimestampList
905 }
906
907
908
909 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
910
911
912
913 type InsecureAlgorithmError SignatureAlgorithm
914
915 func (e InsecureAlgorithmError) Error() string {
916 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
917 }
918
919
920
921
922 type ConstraintViolationError struct{}
923
924 func (ConstraintViolationError) Error() string {
925 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
926 }
927
928
929
930 func (c *Certificate) Equal(other *Certificate) bool {
931 if c == nil || other == nil {
932 return c == other
933 }
934 return bytes.Equal(c.Raw, other.Raw)
935 }
936
937
938
939 func (c *Certificate) IsPrecertificate() bool {
940 if c == nil {
941 return false
942 }
943 for _, ext := range c.Extensions {
944 if ext.Id.Equal(OIDExtensionCTPoison) {
945 return true
946 }
947 }
948 return false
949 }
950
951 func (c *Certificate) hasSANExtension() bool {
952 return oidInExtensions(OIDExtensionSubjectAltName, c.Extensions)
953 }
954
955
956
957
958
959
960
961
962
963
964 var entrustBrokenSPKI = []byte{
965 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
966 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
967 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
968 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
969 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
970 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
971 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
972 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
973 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
974 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
975 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
976 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
977 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
978 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
979 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
980 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
981 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
982 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
983 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
984 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
985 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
986 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
987 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
988 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
989 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
990 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
991 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
992 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
993 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
994 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
995 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
996 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
997 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
998 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
999 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
1000 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
1001 0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
1002 }
1003
1004
1005
1006 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
1007
1008
1009
1010
1011
1012
1013 if (parent.Version == 3 && !parent.BasicConstraintsValid ||
1014 parent.BasicConstraintsValid && !parent.IsCA) &&
1015 !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
1016 return ConstraintViolationError{}
1017 }
1018
1019 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
1020 return ConstraintViolationError{}
1021 }
1022
1023 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
1024 return ErrUnsupportedAlgorithm
1025 }
1026
1027
1028
1029 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
1030 }
1031
1032
1033
1034 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
1035 return checkSignature(algo, signed, signature, c.PublicKey)
1036 }
1037
1038 func (c *Certificate) hasNameConstraints() bool {
1039 return oidInExtensions(OIDExtensionNameConstraints, c.Extensions)
1040 }
1041
1042 func (c *Certificate) getSANExtension() []byte {
1043 for _, e := range c.Extensions {
1044 if e.Id.Equal(OIDExtensionSubjectAltName) {
1045 return e.Value
1046 }
1047 }
1048
1049 return nil
1050 }
1051
1052 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error {
1053 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
1054 }
1055
1056
1057
1058 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
1059 var hashType crypto.Hash
1060 var pubKeyAlgo PublicKeyAlgorithm
1061
1062 for _, details := range signatureAlgorithmDetails {
1063 if details.algo == algo {
1064 hashType = details.hash
1065 pubKeyAlgo = details.pubKeyAlgo
1066 }
1067 }
1068
1069 switch hashType {
1070 case crypto.Hash(0):
1071 if pubKeyAlgo != Ed25519 {
1072 return ErrUnsupportedAlgorithm
1073 }
1074 case crypto.MD5:
1075 return InsecureAlgorithmError(algo)
1076 default:
1077 if !hashType.Available() {
1078 return ErrUnsupportedAlgorithm
1079 }
1080 h := hashType.New()
1081 h.Write(signed)
1082 signed = h.Sum(nil)
1083 }
1084
1085 switch pub := publicKey.(type) {
1086 case *rsa.PublicKey:
1087 if pubKeyAlgo != RSA {
1088 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1089 }
1090 if algo.isRSAPSS() {
1091 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
1092 } else {
1093 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
1094 }
1095 case *dsa.PublicKey:
1096 if pubKeyAlgo != DSA {
1097 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1098 }
1099 dsaSig := new(dsaSignature)
1100 if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil {
1101 return err
1102 } else if len(rest) != 0 {
1103 return errors.New("x509: trailing data after DSA signature")
1104 }
1105 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
1106 return errors.New("x509: DSA signature contained zero or negative values")
1107 }
1108
1109
1110 if maxHashLen := pub.Q.BitLen() / 8; maxHashLen < len(signed) {
1111 signed = signed[:maxHashLen]
1112 }
1113 if !dsa.Verify(pub, signed, dsaSig.R, dsaSig.S) {
1114 return errors.New("x509: DSA verification failure")
1115 }
1116 return
1117 case *ecdsa.PublicKey:
1118 if pubKeyAlgo != ECDSA {
1119 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1120 }
1121 ecdsaSig := new(ecdsaSignature)
1122 if rest, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
1123 return err
1124 } else if len(rest) != 0 {
1125 return errors.New("x509: trailing data after ECDSA signature")
1126 }
1127 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
1128 return errors.New("x509: ECDSA signature contained zero or negative values")
1129 }
1130 if !ecdsa.Verify(pub, signed, ecdsaSig.R, ecdsaSig.S) {
1131 return errors.New("x509: ECDSA verification failure")
1132 }
1133 return
1134 case ed25519.PublicKey:
1135 if pubKeyAlgo != Ed25519 {
1136 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1137 }
1138 if !ed25519.Verify(pub, signed, signature) {
1139 return errors.New("x509: Ed25519 verification failure")
1140 }
1141 return
1142 }
1143 return ErrUnsupportedAlgorithm
1144 }
1145
1146
1147 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
1148 algo := SignatureAlgorithmFromAI(crl.SignatureAlgorithm)
1149 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
1150 }
1151
1152
1153
1154 type UnhandledCriticalExtension struct {
1155 ID asn1.ObjectIdentifier
1156 }
1157
1158 func (h UnhandledCriticalExtension) Error() string {
1159 return fmt.Sprintf("x509: unhandled critical extension (%v)", h.ID)
1160 }
1161
1162
1163
1164
1165
1166 func removeExtension(tbsData []byte, oid asn1.ObjectIdentifier) ([]byte, error) {
1167 var tbs tbsCertificate
1168 rest, err := asn1.Unmarshal(tbsData, &tbs)
1169 if err != nil {
1170 return nil, fmt.Errorf("failed to parse TBSCertificate: %v", err)
1171 } else if rLen := len(rest); rLen > 0 {
1172 return nil, fmt.Errorf("trailing data (%d bytes) after TBSCertificate", rLen)
1173 }
1174 extAt := -1
1175 for i, ext := range tbs.Extensions {
1176 if ext.Id.Equal(oid) {
1177 if extAt != -1 {
1178 return nil, errors.New("multiple extensions of specified type present")
1179 }
1180 extAt = i
1181 }
1182 }
1183 if extAt == -1 {
1184 return nil, errors.New("no extension of specified type present")
1185 }
1186 tbs.Extensions = append(tbs.Extensions[:extAt], tbs.Extensions[extAt+1:]...)
1187
1188
1189 tbs.Raw = nil
1190
1191 data, err := asn1.Marshal(tbs)
1192 if err != nil {
1193 return nil, fmt.Errorf("failed to re-marshal TBSCertificate: %v", err)
1194 }
1195 return data, nil
1196 }
1197
1198
1199
1200
1201
1202 func RemoveSCTList(tbsData []byte) ([]byte, error) {
1203 return removeExtension(tbsData, OIDExtensionCTSCT)
1204 }
1205
1206
1207
1208
1209
1210 func RemoveCTPoison(tbsData []byte) ([]byte, error) {
1211 return BuildPrecertTBS(tbsData, nil)
1212 }
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229 func BuildPrecertTBS(tbsData []byte, preIssuer *Certificate) ([]byte, error) {
1230 data, err := removeExtension(tbsData, OIDExtensionCTPoison)
1231 if err != nil {
1232 return nil, err
1233 }
1234
1235 var tbs tbsCertificate
1236 rest, err := asn1.Unmarshal(data, &tbs)
1237 if err != nil {
1238 return nil, fmt.Errorf("failed to parse TBSCertificate: %v", err)
1239 } else if rLen := len(rest); rLen > 0 {
1240 return nil, fmt.Errorf("trailing data (%d bytes) after TBSCertificate", rLen)
1241 }
1242
1243 if preIssuer != nil {
1244
1245
1246
1247 tbs.Issuer.FullBytes = preIssuer.RawIssuer
1248
1249
1250
1251 var issuerKeyID []byte
1252 for _, ext := range preIssuer.Extensions {
1253 if ext.Id.Equal(OIDExtensionAuthorityKeyId) {
1254 issuerKeyID = ext.Value
1255 break
1256 }
1257 }
1258
1259
1260 seenCTEKU := false
1261 for _, eku := range preIssuer.ExtKeyUsage {
1262 if eku == ExtKeyUsageCertificateTransparency {
1263 seenCTEKU = true
1264 break
1265 }
1266 }
1267 if !seenCTEKU {
1268 return nil, fmt.Errorf("issuer does not have CertificateTransparency extended key usage")
1269 }
1270
1271 keyAt := -1
1272 for i, ext := range tbs.Extensions {
1273 if ext.Id.Equal(OIDExtensionAuthorityKeyId) {
1274 keyAt = i
1275 break
1276 }
1277 }
1278 if keyAt >= 0 {
1279
1280 if issuerKeyID != nil {
1281 tbs.Extensions[keyAt].Value = issuerKeyID
1282 } else {
1283 tbs.Extensions = append(tbs.Extensions[:keyAt], tbs.Extensions[keyAt+1:]...)
1284 }
1285 } else if issuerKeyID != nil {
1286
1287 authKeyIDExt := pkix.Extension{
1288 Id: OIDExtensionAuthorityKeyId,
1289 Critical: false,
1290 Value: issuerKeyID,
1291 }
1292 tbs.Extensions = append(tbs.Extensions, authKeyIDExt)
1293 }
1294
1295
1296
1297 tbs.Raw = nil
1298 }
1299
1300 data, err = asn1.Marshal(tbs)
1301 if err != nil {
1302 return nil, fmt.Errorf("failed to re-marshal TBSCertificate: %v", err)
1303 }
1304 return data, nil
1305 }
1306
1307 type basicConstraints struct {
1308 IsCA bool `asn1:"optional"`
1309 MaxPathLen int `asn1:"optional,default:-1"`
1310 }
1311
1312
1313 type policyInformation struct {
1314 Policy asn1.ObjectIdentifier
1315
1316 }
1317
1318 const (
1319 nameTypeEmail = 1
1320 nameTypeDNS = 2
1321 nameTypeURI = 6
1322 nameTypeIP = 7
1323 )
1324
1325
1326 type accessDescription struct {
1327 Method asn1.ObjectIdentifier
1328 Location asn1.RawValue
1329 }
1330
1331
1332 type distributionPoint struct {
1333 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
1334 Reason asn1.BitString `asn1:"optional,tag:1"`
1335 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
1336 }
1337
1338 type distributionPointName struct {
1339 FullName []asn1.RawValue `asn1:"optional,tag:0"`
1340 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
1341 }
1342
1343 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo, nfe *NonFatalErrors) (interface{}, error) {
1344 asn1Data := keyData.PublicKey.RightAlign()
1345 switch algo {
1346 case RSA, RSAESOAEP:
1347
1348
1349 if algo == RSA && !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1.NullBytes) {
1350 nfe.AddError(errors.New("x509: RSA key missing NULL parameters"))
1351 }
1352 if algo == RSAESOAEP {
1353
1354 paramsData := keyData.Algorithm.Parameters.FullBytes
1355 params := new(rsaesoaepAlgorithmParameters)
1356 params.HashFunc = sha1Identifier
1357 params.MaskgenFunc = mgf1SHA1Identifier
1358 params.PSourceFunc = pSpecifiedEmptyIdentifier
1359 rest, err := asn1.Unmarshal(paramsData, params)
1360 if err != nil {
1361 return nil, err
1362 }
1363 if len(rest) != 0 {
1364 return nil, errors.New("x509: trailing data after RSAES-OAEP parameters")
1365 }
1366 }
1367
1368 p := new(pkcs1PublicKey)
1369 rest, err := asn1.Unmarshal(asn1Data, p)
1370 if err != nil {
1371 var laxErr error
1372 rest, laxErr = asn1.UnmarshalWithParams(asn1Data, p, "lax")
1373 if laxErr != nil {
1374 return nil, laxErr
1375 }
1376 nfe.AddError(err)
1377 }
1378 if len(rest) != 0 {
1379 return nil, errors.New("x509: trailing data after RSA public key")
1380 }
1381
1382 if p.N.Sign() <= 0 {
1383 nfe.AddError(errors.New("x509: RSA modulus is not a positive number"))
1384 }
1385 if p.E <= 0 {
1386 return nil, errors.New("x509: RSA public exponent is not a positive number")
1387 }
1388
1389
1390 pub := &rsa.PublicKey{
1391 E: p.E,
1392 N: p.N,
1393 }
1394 return pub, nil
1395 case DSA:
1396 var p *big.Int
1397 rest, err := asn1.Unmarshal(asn1Data, &p)
1398 if err != nil {
1399 var laxErr error
1400 rest, laxErr = asn1.UnmarshalWithParams(asn1Data, &p, "lax")
1401 if laxErr != nil {
1402 return nil, laxErr
1403 }
1404 nfe.AddError(err)
1405 }
1406 if len(rest) != 0 {
1407 return nil, errors.New("x509: trailing data after DSA public key")
1408 }
1409 paramsData := keyData.Algorithm.Parameters.FullBytes
1410 params := new(dsaAlgorithmParameters)
1411 rest, err = asn1.Unmarshal(paramsData, params)
1412 if err != nil {
1413 return nil, err
1414 }
1415 if len(rest) != 0 {
1416 return nil, errors.New("x509: trailing data after DSA parameters")
1417 }
1418 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
1419 return nil, errors.New("x509: zero or negative DSA parameter")
1420 }
1421 pub := &dsa.PublicKey{
1422 Parameters: dsa.Parameters{
1423 P: params.P,
1424 Q: params.Q,
1425 G: params.G,
1426 },
1427 Y: p,
1428 }
1429 return pub, nil
1430 case ECDSA:
1431 paramsData := keyData.Algorithm.Parameters.FullBytes
1432 namedCurveOID := new(asn1.ObjectIdentifier)
1433 rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
1434 if err != nil {
1435 return nil, errors.New("x509: failed to parse ECDSA parameters as named curve")
1436 }
1437 if len(rest) != 0 {
1438 return nil, errors.New("x509: trailing data after ECDSA parameters")
1439 }
1440 namedCurve := namedCurveFromOID(*namedCurveOID, nfe)
1441 if namedCurve == nil {
1442 return nil, fmt.Errorf("x509: unsupported elliptic curve %v", namedCurveOID)
1443 }
1444 x, y := elliptic.Unmarshal(namedCurve, asn1Data)
1445 if x == nil {
1446 return nil, errors.New("x509: failed to unmarshal elliptic curve point")
1447 }
1448 pub := &ecdsa.PublicKey{
1449 Curve: namedCurve,
1450 X: x,
1451 Y: y,
1452 }
1453 return pub, nil
1454 case Ed25519:
1455 return ed25519.PublicKey(asn1Data), nil
1456 default:
1457 return nil, nil
1458 }
1459 }
1460
1461
1462
1463
1464
1465 type NonFatalErrors struct {
1466 Errors []error
1467 }
1468
1469
1470 func (e *NonFatalErrors) AddError(err error) {
1471 e.Errors = append(e.Errors, err)
1472 }
1473
1474
1475
1476 func (e NonFatalErrors) Error() string {
1477 r := "NonFatalErrors: "
1478 for _, err := range e.Errors {
1479 r += err.Error() + "; "
1480 }
1481 return r
1482 }
1483
1484
1485 func (e *NonFatalErrors) HasError() bool {
1486 if e == nil {
1487 return false
1488 }
1489 return len(e.Errors) > 0
1490 }
1491
1492
1493 func (e *NonFatalErrors) Append(more *NonFatalErrors) *NonFatalErrors {
1494 if e == nil {
1495 return more
1496 }
1497 if more == nil {
1498 return e
1499 }
1500 combined := NonFatalErrors{Errors: make([]error, 0, len(e.Errors)+len(more.Errors))}
1501 combined.Errors = append(combined.Errors, e.Errors...)
1502 combined.Errors = append(combined.Errors, more.Errors...)
1503 return &combined
1504 }
1505
1506
1507 func IsFatal(err error) bool {
1508 if err == nil {
1509 return false
1510 }
1511 if _, ok := err.(NonFatalErrors); ok {
1512 return false
1513 }
1514 if errs, ok := err.(*Errors); ok {
1515 return errs.Fatal()
1516 }
1517 return true
1518 }
1519
1520 func parseDistributionPoints(data []byte, crldp *[]string) error {
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532 var cdp []distributionPoint
1533 if rest, err := asn1.Unmarshal(data, &cdp); err != nil {
1534 return err
1535 } else if len(rest) != 0 {
1536 return errors.New("x509: trailing data after X.509 CRL distribution point")
1537 }
1538
1539 for _, dp := range cdp {
1540
1541 if len(dp.DistributionPoint.FullName) == 0 {
1542 continue
1543 }
1544
1545 for _, fullName := range dp.DistributionPoint.FullName {
1546 if fullName.Tag == 6 {
1547 *crldp = append(*crldp, string(fullName.Bytes))
1548 }
1549 }
1550 }
1551 return nil
1552 }
1553
1554 func forEachSAN(extension []byte, callback func(tag int, data []byte) error) error {
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571 var seq asn1.RawValue
1572 rest, err := asn1.Unmarshal(extension, &seq)
1573 if err != nil {
1574 return err
1575 } else if len(rest) != 0 {
1576 return errors.New("x509: trailing data after X.509 extension")
1577 }
1578 if !seq.IsCompound || seq.Tag != asn1.TagSequence || seq.Class != asn1.ClassUniversal {
1579 return asn1.StructuralError{Msg: "bad SAN sequence"}
1580 }
1581
1582 rest = seq.Bytes
1583 for len(rest) > 0 {
1584 var v asn1.RawValue
1585 rest, err = asn1.Unmarshal(rest, &v)
1586 if err != nil {
1587 return err
1588 }
1589
1590 if err := callback(v.Tag, v.Bytes); err != nil {
1591 return err
1592 }
1593 }
1594
1595 return nil
1596 }
1597
1598 func parseSANExtension(value []byte, nfe *NonFatalErrors) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error) {
1599 err = forEachSAN(value, func(tag int, data []byte) error {
1600 switch tag {
1601 case nameTypeEmail:
1602 emailAddresses = append(emailAddresses, string(data))
1603 case nameTypeDNS:
1604 dnsNames = append(dnsNames, string(data))
1605 case nameTypeURI:
1606 uri, err := url.Parse(string(data))
1607 if err != nil {
1608 return fmt.Errorf("x509: cannot parse URI %q: %s", string(data), err)
1609 }
1610 if len(uri.Host) > 0 {
1611 if _, ok := domainToReverseLabels(uri.Host); !ok {
1612 return fmt.Errorf("x509: cannot parse URI %q: invalid domain", string(data))
1613 }
1614 }
1615 uris = append(uris, uri)
1616 case nameTypeIP:
1617 switch len(data) {
1618 case net.IPv4len, net.IPv6len:
1619 ipAddresses = append(ipAddresses, data)
1620 default:
1621 nfe.AddError(errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data))))
1622 }
1623 }
1624
1625 return nil
1626 })
1627
1628 return
1629 }
1630
1631
1632 func isValidIPMask(mask []byte) bool {
1633 seenZero := false
1634
1635 for _, b := range mask {
1636 if seenZero {
1637 if b != 0 {
1638 return false
1639 }
1640
1641 continue
1642 }
1643
1644 switch b {
1645 case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe:
1646 seenZero = true
1647 case 0xff:
1648 default:
1649 return false
1650 }
1651 }
1652
1653 return true
1654 }
1655
1656 func parseNameConstraintsExtension(out *Certificate, e pkix.Extension, nfe *NonFatalErrors) (unhandled bool, err error) {
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672 outer := cryptobyte.String(e.Value)
1673 var toplevel, permitted, excluded cryptobyte.String
1674 var havePermitted, haveExcluded bool
1675 if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) ||
1676 !outer.Empty() ||
1677 !toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) ||
1678 !toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) ||
1679 !toplevel.Empty() {
1680 return false, errors.New("x509: invalid NameConstraints extension")
1681 }
1682
1683 if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 {
1684
1685
1686
1687
1688 return false, errors.New("x509: empty name constraints extension")
1689 }
1690
1691 getValues := func(subtrees cryptobyte.String) (dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) {
1692 for !subtrees.Empty() {
1693 var seq, value cryptobyte.String
1694 var tag cryptobyte_asn1.Tag
1695 if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) ||
1696 !seq.ReadAnyASN1(&value, &tag) {
1697 return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension")
1698 }
1699
1700 var (
1701 dnsTag = cryptobyte_asn1.Tag(2).ContextSpecific()
1702 emailTag = cryptobyte_asn1.Tag(1).ContextSpecific()
1703 ipTag = cryptobyte_asn1.Tag(7).ContextSpecific()
1704 uriTag = cryptobyte_asn1.Tag(6).ContextSpecific()
1705 )
1706
1707 switch tag {
1708 case dnsTag:
1709 domain := string(value)
1710 if err := isIA5String(domain); err != nil {
1711 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1712 }
1713
1714 trimmedDomain := domain
1715 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1716
1717
1718
1719
1720 trimmedDomain = trimmedDomain[1:]
1721 }
1722 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1723 nfe.AddError(fmt.Errorf("x509: failed to parse dnsName constraint %q", domain))
1724 }
1725 dnsNames = append(dnsNames, domain)
1726
1727 case ipTag:
1728 l := len(value)
1729 var ip, mask []byte
1730
1731 switch l {
1732 case 8:
1733 ip = value[:4]
1734 mask = value[4:]
1735
1736 case 32:
1737 ip = value[:16]
1738 mask = value[16:]
1739
1740 default:
1741 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l)
1742 }
1743
1744 if !isValidIPMask(mask) {
1745 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask)
1746 }
1747
1748 ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)})
1749
1750 case emailTag:
1751 constraint := string(value)
1752 if err := isIA5String(constraint); err != nil {
1753 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1754 }
1755
1756
1757
1758 if strings.Contains(constraint, "@") {
1759 if _, ok := parseRFC2821Mailbox(constraint); !ok {
1760 nfe.AddError(fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint))
1761 }
1762 } else {
1763
1764 domain := constraint
1765 if len(domain) > 0 && domain[0] == '.' {
1766 domain = domain[1:]
1767 }
1768 if _, ok := domainToReverseLabels(domain); !ok {
1769 nfe.AddError(fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint))
1770 }
1771 }
1772 emails = append(emails, constraint)
1773
1774 case uriTag:
1775 domain := string(value)
1776 if err := isIA5String(domain); err != nil {
1777 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1778 }
1779
1780 if net.ParseIP(domain) != nil {
1781 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain)
1782 }
1783
1784 trimmedDomain := domain
1785 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1786
1787
1788
1789
1790 trimmedDomain = trimmedDomain[1:]
1791 }
1792 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1793 nfe.AddError(fmt.Errorf("x509: failed to parse URI constraint %q", domain))
1794 }
1795 uriDomains = append(uriDomains, domain)
1796
1797 default:
1798 unhandled = true
1799 }
1800 }
1801
1802 return dnsNames, ips, emails, uriDomains, nil
1803 }
1804
1805 if out.PermittedDNSDomains, out.PermittedIPRanges, out.PermittedEmailAddresses, out.PermittedURIDomains, err = getValues(permitted); err != nil {
1806 return false, err
1807 }
1808 if out.ExcludedDNSDomains, out.ExcludedIPRanges, out.ExcludedEmailAddresses, out.ExcludedURIDomains, err = getValues(excluded); err != nil {
1809 return false, err
1810 }
1811 out.PermittedDNSDomainsCritical = e.Critical
1812
1813 return unhandled, nil
1814 }
1815
1816 func parseCertificate(in *certificate) (*Certificate, error) {
1817 var nfe NonFatalErrors
1818
1819 out := new(Certificate)
1820 out.Raw = in.Raw
1821 out.RawTBSCertificate = in.TBSCertificate.Raw
1822 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
1823 out.RawSubject = in.TBSCertificate.Subject.FullBytes
1824 out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
1825
1826 out.Signature = in.SignatureValue.RightAlign()
1827 out.SignatureAlgorithm = SignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm)
1828
1829 out.PublicKeyAlgorithm =
1830 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
1831 var err error
1832 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey, &nfe)
1833 if err != nil {
1834 return nil, err
1835 }
1836
1837 out.Version = in.TBSCertificate.Version + 1
1838 out.SerialNumber = in.TBSCertificate.SerialNumber
1839
1840 var issuer, subject pkix.RDNSequence
1841 if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
1842 var laxErr error
1843 rest, laxErr = asn1.UnmarshalWithParams(in.TBSCertificate.Subject.FullBytes, &subject, "lax")
1844 if laxErr != nil {
1845 return nil, laxErr
1846 }
1847 nfe.AddError(err)
1848 } else if len(rest) != 0 {
1849 return nil, errors.New("x509: trailing data after X.509 subject")
1850 }
1851 if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
1852 var laxErr error
1853 rest, laxErr = asn1.UnmarshalWithParams(in.TBSCertificate.Issuer.FullBytes, &issuer, "lax")
1854 if laxErr != nil {
1855 return nil, laxErr
1856 }
1857 nfe.AddError(err)
1858 } else if len(rest) != 0 {
1859 return nil, errors.New("x509: trailing data after X.509 subject")
1860 }
1861
1862 out.Issuer.FillFromRDNSequence(&issuer)
1863 out.Subject.FillFromRDNSequence(&subject)
1864
1865 out.NotBefore = in.TBSCertificate.Validity.NotBefore
1866 out.NotAfter = in.TBSCertificate.Validity.NotAfter
1867
1868 for _, e := range in.TBSCertificate.Extensions {
1869 out.Extensions = append(out.Extensions, e)
1870 unhandled := false
1871
1872 if len(e.Id) == 4 && e.Id[0] == OIDExtensionArc[0] && e.Id[1] == OIDExtensionArc[1] && e.Id[2] == OIDExtensionArc[2] {
1873 switch e.Id[3] {
1874 case OIDExtensionKeyUsage[3]:
1875
1876 var usageBits asn1.BitString
1877 if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil {
1878 return nil, err
1879 } else if len(rest) != 0 {
1880 return nil, errors.New("x509: trailing data after X.509 KeyUsage")
1881 }
1882
1883 var usage int
1884 for i := 0; i < 9; i++ {
1885 if usageBits.At(i) != 0 {
1886 usage |= 1 << uint(i)
1887 }
1888 }
1889 out.KeyUsage = KeyUsage(usage)
1890
1891 case OIDExtensionBasicConstraints[3]:
1892
1893 var constraints basicConstraints
1894 if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
1895 return nil, err
1896 } else if len(rest) != 0 {
1897 return nil, errors.New("x509: trailing data after X.509 BasicConstraints")
1898 }
1899
1900 out.BasicConstraintsValid = true
1901 out.IsCA = constraints.IsCA
1902 out.MaxPathLen = constraints.MaxPathLen
1903 out.MaxPathLenZero = out.MaxPathLen == 0
1904
1905
1906 case OIDExtensionSubjectAltName[3]:
1907 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(e.Value, &nfe)
1908 if err != nil {
1909 return nil, err
1910 }
1911
1912 if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 && len(out.URIs) == 0 {
1913
1914 unhandled = true
1915 }
1916
1917 case OIDExtensionNameConstraints[3]:
1918 unhandled, err = parseNameConstraintsExtension(out, e, &nfe)
1919 if err != nil {
1920 return nil, err
1921 }
1922
1923 case OIDExtensionCRLDistributionPoints[3]:
1924
1925 if err := parseDistributionPoints(e.Value, &out.CRLDistributionPoints); err != nil {
1926 return nil, err
1927 }
1928
1929 case OIDExtensionAuthorityKeyId[3]:
1930
1931 var a authKeyId
1932 if rest, err := asn1.Unmarshal(e.Value, &a); err != nil {
1933 return nil, err
1934 } else if len(rest) != 0 {
1935 return nil, errors.New("x509: trailing data after X.509 authority key-id")
1936 }
1937 out.AuthorityKeyId = a.Id
1938
1939 case OIDExtensionExtendedKeyUsage[3]:
1940
1941
1942
1943
1944
1945
1946
1947
1948 var keyUsage []asn1.ObjectIdentifier
1949 if len(e.Value) == 0 {
1950 nfe.AddError(errors.New("x509: empty ExtendedKeyUsage"))
1951 } else {
1952 rest, err := asn1.Unmarshal(e.Value, &keyUsage)
1953 if err != nil {
1954 var laxErr error
1955 rest, laxErr = asn1.UnmarshalWithParams(e.Value, &keyUsage, "lax")
1956 if laxErr != nil {
1957 return nil, laxErr
1958 }
1959 nfe.AddError(err)
1960 }
1961 if len(rest) != 0 {
1962 return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage")
1963 }
1964 }
1965
1966 for _, u := range keyUsage {
1967 if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
1968 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
1969 } else {
1970 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
1971 }
1972 }
1973
1974 case OIDExtensionSubjectKeyId[3]:
1975
1976 var keyid []byte
1977 if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil {
1978 return nil, err
1979 } else if len(rest) != 0 {
1980 return nil, errors.New("x509: trailing data after X.509 key-id")
1981 }
1982 out.SubjectKeyId = keyid
1983
1984 case OIDExtensionCertificatePolicies[3]:
1985
1986 var policies []policyInformation
1987 if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil {
1988 return nil, err
1989 } else if len(rest) != 0 {
1990 return nil, errors.New("x509: trailing data after X.509 certificate policies")
1991 }
1992 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
1993 for i, policy := range policies {
1994 out.PolicyIdentifiers[i] = policy.Policy
1995 }
1996
1997 default:
1998
1999 unhandled = true
2000 }
2001 } else if e.Id.Equal(OIDExtensionAuthorityInfoAccess) {
2002
2003 var aia []accessDescription
2004 if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil {
2005 return nil, err
2006 } else if len(rest) != 0 {
2007 return nil, errors.New("x509: trailing data after X.509 authority information")
2008 }
2009 if len(aia) == 0 {
2010 nfe.AddError(errors.New("x509: empty AuthorityInfoAccess extension"))
2011 }
2012
2013 for _, v := range aia {
2014
2015 if v.Location.Tag != 6 {
2016 continue
2017 }
2018 if v.Method.Equal(OIDAuthorityInfoAccessOCSP) {
2019 out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
2020 } else if v.Method.Equal(OIDAuthorityInfoAccessIssuers) {
2021 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
2022 }
2023 }
2024 } else if e.Id.Equal(OIDExtensionSubjectInfoAccess) {
2025
2026 var sia []accessDescription
2027 if rest, err := asn1.Unmarshal(e.Value, &sia); err != nil {
2028 return nil, err
2029 } else if len(rest) != 0 {
2030 return nil, errors.New("x509: trailing data after X.509 subject information")
2031 }
2032 if len(sia) == 0 {
2033 nfe.AddError(errors.New("x509: empty SubjectInfoAccess extension"))
2034 }
2035
2036 for _, v := range sia {
2037
2038
2039 if v.Location.Tag != 6 {
2040 continue
2041 }
2042 if v.Method.Equal(OIDSubjectInfoAccessTimestamp) {
2043 out.SubjectTimestamps = append(out.SubjectTimestamps, string(v.Location.Bytes))
2044 } else if v.Method.Equal(OIDSubjectInfoAccessCARepo) {
2045 out.SubjectCARepositories = append(out.SubjectCARepositories, string(v.Location.Bytes))
2046 }
2047 }
2048 } else if e.Id.Equal(OIDExtensionIPPrefixList) {
2049 out.RPKIAddressRanges = parseRPKIAddrBlocks(e.Value, &nfe)
2050 } else if e.Id.Equal(OIDExtensionASList) {
2051 out.RPKIASNumbers, out.RPKIRoutingDomainIDs = parseRPKIASIdentifiers(e.Value, &nfe)
2052 } else if e.Id.Equal(OIDExtensionCTSCT) {
2053 if rest, err := asn1.Unmarshal(e.Value, &out.RawSCT); err != nil {
2054 nfe.AddError(fmt.Errorf("failed to asn1.Unmarshal SCT list extension: %v", err))
2055 } else if len(rest) != 0 {
2056 nfe.AddError(errors.New("trailing data after ASN1-encoded SCT list"))
2057 } else {
2058 if rest, err := tls.Unmarshal(out.RawSCT, &out.SCTList); err != nil {
2059 nfe.AddError(fmt.Errorf("failed to tls.Unmarshal SCT list: %v", err))
2060 } else if len(rest) != 0 {
2061 nfe.AddError(errors.New("trailing data after TLS-encoded SCT list"))
2062 }
2063 }
2064 } else {
2065
2066 unhandled = true
2067 }
2068
2069 if e.Critical && unhandled {
2070 out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
2071 }
2072 }
2073 if nfe.HasError() {
2074 return out, nfe
2075 }
2076 return out, nil
2077 }
2078
2079
2080
2081 func ParseTBSCertificate(asn1Data []byte) (*Certificate, error) {
2082 var tbsCert tbsCertificate
2083 var nfe NonFatalErrors
2084 rest, err := asn1.Unmarshal(asn1Data, &tbsCert)
2085 if err != nil {
2086 var laxErr error
2087 rest, laxErr = asn1.UnmarshalWithParams(asn1Data, &tbsCert, "lax")
2088 if laxErr != nil {
2089 return nil, laxErr
2090 }
2091 nfe.AddError(err)
2092 }
2093 if len(rest) > 0 {
2094 return nil, asn1.SyntaxError{Msg: "trailing data"}
2095 }
2096 ret, err := parseCertificate(&certificate{
2097 Raw: tbsCert.Raw,
2098 TBSCertificate: tbsCert})
2099 if err != nil {
2100 errs, ok := err.(NonFatalErrors)
2101 if !ok {
2102 return nil, err
2103 }
2104 nfe.Errors = append(nfe.Errors, errs.Errors...)
2105 }
2106 if nfe.HasError() {
2107 return ret, nfe
2108 }
2109 return ret, nil
2110 }
2111
2112
2113
2114
2115 func ParseCertificate(asn1Data []byte) (*Certificate, error) {
2116 var cert certificate
2117 var nfe NonFatalErrors
2118 rest, err := asn1.Unmarshal(asn1Data, &cert)
2119 if err != nil {
2120 var laxErr error
2121 rest, laxErr = asn1.UnmarshalWithParams(asn1Data, &cert, "lax")
2122 if laxErr != nil {
2123 return nil, laxErr
2124 }
2125 nfe.AddError(err)
2126 }
2127 if len(rest) > 0 {
2128 return nil, asn1.SyntaxError{Msg: "trailing data"}
2129 }
2130 ret, err := parseCertificate(&cert)
2131 if err != nil {
2132 errs, ok := err.(NonFatalErrors)
2133 if !ok {
2134 return nil, err
2135 }
2136 nfe.Errors = append(nfe.Errors, errs.Errors...)
2137 }
2138 if nfe.HasError() {
2139 return ret, nfe
2140 }
2141 return ret, nil
2142 }
2143
2144
2145
2146
2147
2148 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
2149 var v []*certificate
2150 var nfe NonFatalErrors
2151
2152 for len(asn1Data) > 0 {
2153 cert := new(certificate)
2154 var err error
2155 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
2156 if err != nil {
2157 var laxErr error
2158 asn1Data, laxErr = asn1.UnmarshalWithParams(asn1Data, &cert, "lax")
2159 if laxErr != nil {
2160 return nil, laxErr
2161 }
2162 nfe.AddError(err)
2163 }
2164 v = append(v, cert)
2165 }
2166
2167 ret := make([]*Certificate, len(v))
2168 for i, ci := range v {
2169 cert, err := parseCertificate(ci)
2170 if err != nil {
2171 errs, ok := err.(NonFatalErrors)
2172 if !ok {
2173 return nil, err
2174 }
2175 nfe.Errors = append(nfe.Errors, errs.Errors...)
2176 }
2177 ret[i] = cert
2178 }
2179
2180 if nfe.HasError() {
2181 return ret, nfe
2182 }
2183 return ret, nil
2184 }
2185
2186 func reverseBitsInAByte(in byte) byte {
2187 b1 := in>>4 | in<<4
2188 b2 := b1>>2&0x33 | b1<<2&0xcc
2189 b3 := b2>>1&0x55 | b2<<1&0xaa
2190 return b3
2191 }
2192
2193
2194
2195
2196 func asn1BitLength(bitString []byte) int {
2197 bitLen := len(bitString) * 8
2198
2199 for i := range bitString {
2200 b := bitString[len(bitString)-i-1]
2201
2202 for bit := uint(0); bit < 8; bit++ {
2203 if (b>>bit)&1 == 1 {
2204 return bitLen
2205 }
2206 bitLen--
2207 }
2208 }
2209
2210 return 0
2211 }
2212
2213
2214 var (
2215 OIDExtensionArc = asn1.ObjectIdentifier{2, 5, 29}
2216 OIDExtensionSubjectKeyId = asn1.ObjectIdentifier{2, 5, 29, 14}
2217 OIDExtensionKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 15}
2218 OIDExtensionExtendedKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 37}
2219 OIDExtensionAuthorityKeyId = asn1.ObjectIdentifier{2, 5, 29, 35}
2220 OIDExtensionBasicConstraints = asn1.ObjectIdentifier{2, 5, 29, 19}
2221 OIDExtensionSubjectAltName = asn1.ObjectIdentifier{2, 5, 29, 17}
2222 OIDExtensionCertificatePolicies = asn1.ObjectIdentifier{2, 5, 29, 32}
2223 OIDExtensionNameConstraints = asn1.ObjectIdentifier{2, 5, 29, 30}
2224 OIDExtensionCRLDistributionPoints = asn1.ObjectIdentifier{2, 5, 29, 31}
2225 OIDExtensionIssuerAltName = asn1.ObjectIdentifier{2, 5, 29, 18}
2226 OIDExtensionSubjectDirectoryAttributes = asn1.ObjectIdentifier{2, 5, 29, 9}
2227 OIDExtensionInhibitAnyPolicy = asn1.ObjectIdentifier{2, 5, 29, 54}
2228 OIDExtensionPolicyConstraints = asn1.ObjectIdentifier{2, 5, 29, 36}
2229 OIDExtensionPolicyMappings = asn1.ObjectIdentifier{2, 5, 29, 33}
2230 OIDExtensionFreshestCRL = asn1.ObjectIdentifier{2, 5, 29, 46}
2231
2232 OIDExtensionAuthorityInfoAccess = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 1}
2233 OIDExtensionSubjectInfoAccess = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 11}
2234
2235
2236 OIDExtensionCTPoison = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 3}
2237
2238 OIDExtensionCTSCT = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 2}
2239
2240 OIDExtensionIPPrefixList = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 7}
2241
2242 OIDExtensionASList = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 8}
2243 )
2244
2245 var (
2246 OIDAuthorityInfoAccessOCSP = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
2247 OIDAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
2248 OIDSubjectInfoAccessTimestamp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 3}
2249 OIDSubjectInfoAccessCARepo = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 5}
2250 OIDAnyPolicy = asn1.ObjectIdentifier{2, 5, 29, 32, 0}
2251 )
2252
2253
2254
2255 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
2256 for _, e := range extensions {
2257 if e.Id.Equal(oid) {
2258 return true
2259 }
2260 }
2261 return false
2262 }
2263
2264
2265
2266 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
2267 var rawValues []asn1.RawValue
2268 for _, name := range dnsNames {
2269 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: asn1.ClassContextSpecific, Bytes: []byte(name)})
2270 }
2271 for _, email := range emailAddresses {
2272 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: asn1.ClassContextSpecific, Bytes: []byte(email)})
2273 }
2274 for _, rawIP := range ipAddresses {
2275
2276 ip := rawIP.To4()
2277 if ip == nil {
2278 ip = rawIP
2279 }
2280 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: asn1.ClassContextSpecific, Bytes: ip})
2281 }
2282 for _, uri := range uris {
2283 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: asn1.ClassContextSpecific, Bytes: []byte(uri.String())})
2284 }
2285 return asn1.Marshal(rawValues)
2286 }
2287
2288 func isIA5String(s string) error {
2289 for _, r := range s {
2290 if r >= utf8.RuneSelf {
2291 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
2292 }
2293 }
2294
2295 return nil
2296 }
2297
2298 func buildExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte) (ret []pkix.Extension, err error) {
2299 ret = make([]pkix.Extension, 12 )
2300 n := 0
2301
2302 if template.KeyUsage != 0 &&
2303 !oidInExtensions(OIDExtensionKeyUsage, template.ExtraExtensions) {
2304 ret[n].Id = OIDExtensionKeyUsage
2305 ret[n].Critical = true
2306
2307 var a [2]byte
2308 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
2309 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
2310
2311 l := 1
2312 if a[1] != 0 {
2313 l = 2
2314 }
2315
2316 bitString := a[:l]
2317 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
2318 if err != nil {
2319 return
2320 }
2321 n++
2322 }
2323
2324 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
2325 !oidInExtensions(OIDExtensionExtendedKeyUsage, template.ExtraExtensions) {
2326 ret[n].Id = OIDExtensionExtendedKeyUsage
2327
2328 var oids []asn1.ObjectIdentifier
2329 for _, u := range template.ExtKeyUsage {
2330 if oid, ok := oidFromExtKeyUsage(u); ok {
2331 oids = append(oids, oid)
2332 } else {
2333 panic("internal error")
2334 }
2335 }
2336
2337 oids = append(oids, template.UnknownExtKeyUsage...)
2338
2339 ret[n].Value, err = asn1.Marshal(oids)
2340 if err != nil {
2341 return
2342 }
2343 n++
2344 }
2345
2346 if template.BasicConstraintsValid && !oidInExtensions(OIDExtensionBasicConstraints, template.ExtraExtensions) {
2347
2348
2349
2350 maxPathLen := template.MaxPathLen
2351 if maxPathLen == 0 && !template.MaxPathLenZero {
2352 maxPathLen = -1
2353 }
2354 ret[n].Id = OIDExtensionBasicConstraints
2355 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen})
2356 ret[n].Critical = true
2357 if err != nil {
2358 return
2359 }
2360 n++
2361 }
2362
2363 if len(template.SubjectKeyId) > 0 && !oidInExtensions(OIDExtensionSubjectKeyId, template.ExtraExtensions) {
2364 ret[n].Id = OIDExtensionSubjectKeyId
2365 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
2366 if err != nil {
2367 return
2368 }
2369 n++
2370 }
2371
2372 if len(authorityKeyId) > 0 && !oidInExtensions(OIDExtensionAuthorityKeyId, template.ExtraExtensions) {
2373 ret[n].Id = OIDExtensionAuthorityKeyId
2374 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
2375 if err != nil {
2376 return
2377 }
2378 n++
2379 }
2380
2381 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
2382 !oidInExtensions(OIDExtensionAuthorityInfoAccess, template.ExtraExtensions) {
2383 ret[n].Id = OIDExtensionAuthorityInfoAccess
2384 var aiaValues []accessDescription
2385 for _, name := range template.OCSPServer {
2386 aiaValues = append(aiaValues, accessDescription{
2387 Method: OIDAuthorityInfoAccessOCSP,
2388 Location: asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(name)},
2389 })
2390 }
2391 for _, name := range template.IssuingCertificateURL {
2392 aiaValues = append(aiaValues, accessDescription{
2393 Method: OIDAuthorityInfoAccessIssuers,
2394 Location: asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(name)},
2395 })
2396 }
2397 ret[n].Value, err = asn1.Marshal(aiaValues)
2398 if err != nil {
2399 return
2400 }
2401 n++
2402 }
2403
2404 if len(template.SubjectTimestamps) > 0 || len(template.SubjectCARepositories) > 0 &&
2405 !oidInExtensions(OIDExtensionSubjectInfoAccess, template.ExtraExtensions) {
2406 ret[n].Id = OIDExtensionSubjectInfoAccess
2407 var siaValues []accessDescription
2408 for _, ts := range template.SubjectTimestamps {
2409 siaValues = append(siaValues, accessDescription{
2410 Method: OIDSubjectInfoAccessTimestamp,
2411 Location: asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(ts)},
2412 })
2413 }
2414 for _, repo := range template.SubjectCARepositories {
2415 siaValues = append(siaValues, accessDescription{
2416 Method: OIDSubjectInfoAccessCARepo,
2417 Location: asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(repo)},
2418 })
2419 }
2420 ret[n].Value, err = asn1.Marshal(siaValues)
2421 if err != nil {
2422 return
2423 }
2424 n++
2425 }
2426
2427 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
2428 !oidInExtensions(OIDExtensionSubjectAltName, template.ExtraExtensions) {
2429 ret[n].Id = OIDExtensionSubjectAltName
2430
2431
2432
2433 ret[n].Critical = subjectIsEmpty
2434 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
2435 if err != nil {
2436 return
2437 }
2438 n++
2439 }
2440
2441 if len(template.PolicyIdentifiers) > 0 &&
2442 !oidInExtensions(OIDExtensionCertificatePolicies, template.ExtraExtensions) {
2443 ret[n].Id = OIDExtensionCertificatePolicies
2444 policies := make([]policyInformation, len(template.PolicyIdentifiers))
2445 for i, policy := range template.PolicyIdentifiers {
2446 policies[i].Policy = policy
2447 }
2448 ret[n].Value, err = asn1.Marshal(policies)
2449 if err != nil {
2450 return
2451 }
2452 n++
2453 }
2454
2455 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
2456 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
2457 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
2458 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
2459 !oidInExtensions(OIDExtensionNameConstraints, template.ExtraExtensions) {
2460 ret[n].Id = OIDExtensionNameConstraints
2461 ret[n].Critical = template.PermittedDNSDomainsCritical
2462
2463 ipAndMask := func(ipNet *net.IPNet) []byte {
2464 maskedIP := ipNet.IP.Mask(ipNet.Mask)
2465 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
2466 ipAndMask = append(ipAndMask, maskedIP...)
2467 ipAndMask = append(ipAndMask, ipNet.Mask...)
2468 return ipAndMask
2469 }
2470
2471 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
2472 var b cryptobyte.Builder
2473
2474 for _, name := range dns {
2475 if err = isIA5String(name); err != nil {
2476 return nil, err
2477 }
2478
2479 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
2480 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
2481 b.AddBytes([]byte(name))
2482 })
2483 })
2484 }
2485
2486 for _, ipNet := range ips {
2487 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
2488 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
2489 b.AddBytes(ipAndMask(ipNet))
2490 })
2491 })
2492 }
2493
2494 for _, email := range emails {
2495 if err = isIA5String(email); err != nil {
2496 return nil, err
2497 }
2498
2499 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
2500 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
2501 b.AddBytes([]byte(email))
2502 })
2503 })
2504 }
2505
2506 for _, uriDomain := range uriDomains {
2507 if err = isIA5String(uriDomain); err != nil {
2508 return nil, err
2509 }
2510
2511 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
2512 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
2513 b.AddBytes([]byte(uriDomain))
2514 })
2515 })
2516 }
2517
2518 return b.Bytes()
2519 }
2520
2521 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
2522 if err != nil {
2523 return nil, err
2524 }
2525
2526 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
2527 if err != nil {
2528 return nil, err
2529 }
2530
2531 var b cryptobyte.Builder
2532 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
2533 if len(permitted) > 0 {
2534 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
2535 b.AddBytes(permitted)
2536 })
2537 }
2538
2539 if len(excluded) > 0 {
2540 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
2541 b.AddBytes(excluded)
2542 })
2543 }
2544 })
2545
2546 ret[n].Value, err = b.Bytes()
2547 if err != nil {
2548 return nil, err
2549 }
2550 n++
2551 }
2552
2553 if len(template.CRLDistributionPoints) > 0 &&
2554 !oidInExtensions(OIDExtensionCRLDistributionPoints, template.ExtraExtensions) {
2555 ret[n].Id = OIDExtensionCRLDistributionPoints
2556
2557 var crlDp []distributionPoint
2558 for _, name := range template.CRLDistributionPoints {
2559 dp := distributionPoint{
2560 DistributionPoint: distributionPointName{
2561 FullName: []asn1.RawValue{
2562 {Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(name)},
2563 },
2564 },
2565 }
2566 crlDp = append(crlDp, dp)
2567 }
2568
2569 ret[n].Value, err = asn1.Marshal(crlDp)
2570 if err != nil {
2571 return
2572 }
2573 n++
2574 }
2575
2576 if (len(template.RawSCT) > 0 || len(template.SCTList.SCTList) > 0) && !oidInExtensions(OIDExtensionCTSCT, template.ExtraExtensions) {
2577 rawSCT := template.RawSCT
2578 if len(template.SCTList.SCTList) > 0 {
2579 rawSCT, err = tls.Marshal(template.SCTList)
2580 if err != nil {
2581 return
2582 }
2583 }
2584 ret[n].Id = OIDExtensionCTSCT
2585 ret[n].Value, err = asn1.Marshal(rawSCT)
2586 if err != nil {
2587 return
2588 }
2589 n++
2590 }
2591
2592
2593
2594
2595
2596 return append(ret[:n], template.ExtraExtensions...), nil
2597 }
2598
2599 func subjectBytes(cert *Certificate) ([]byte, error) {
2600 if len(cert.RawSubject) > 0 {
2601 return cert.RawSubject, nil
2602 }
2603
2604 return asn1.Marshal(cert.Subject.ToRDNSequence())
2605 }
2606
2607
2608
2609
2610 func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
2611 var pubType PublicKeyAlgorithm
2612
2613 switch pub := pub.(type) {
2614 case *rsa.PublicKey:
2615 pubType = RSA
2616 hashFunc = crypto.SHA256
2617 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
2618 sigAlgo.Parameters = asn1.NullRawValue
2619
2620 case *ecdsa.PublicKey:
2621 pubType = ECDSA
2622
2623 switch pub.Curve {
2624 case elliptic.P224(), elliptic.P256():
2625 hashFunc = crypto.SHA256
2626 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
2627 case elliptic.P384():
2628 hashFunc = crypto.SHA384
2629 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
2630 case elliptic.P521():
2631 hashFunc = crypto.SHA512
2632 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
2633 default:
2634 err = errors.New("x509: unknown elliptic curve")
2635 }
2636
2637 case ed25519.PublicKey:
2638 pubType = Ed25519
2639 sigAlgo.Algorithm = oidSignatureEd25519
2640
2641 default:
2642 err = errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
2643 }
2644
2645 if err != nil {
2646 return
2647 }
2648
2649 if requestedSigAlgo == 0 {
2650 return
2651 }
2652
2653 found := false
2654 for _, details := range signatureAlgorithmDetails {
2655 if details.algo == requestedSigAlgo {
2656 if details.pubKeyAlgo != pubType {
2657 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
2658 return
2659 }
2660 sigAlgo.Algorithm, hashFunc = details.oid, details.hash
2661 if hashFunc == 0 && pubType != Ed25519 {
2662 err = errors.New("x509: cannot sign with hash function requested")
2663 return
2664 }
2665 if requestedSigAlgo.isRSAPSS() {
2666 sigAlgo.Parameters = rsaPSSParameters(hashFunc)
2667 }
2668 found = true
2669 break
2670 }
2671 }
2672
2673 if !found {
2674 err = errors.New("x509: unknown SignatureAlgorithm")
2675 }
2676
2677 return
2678 }
2679
2680
2681
2682 var emptyASN1Subject = []byte{0x30, 0}
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) {
2720 key, ok := priv.(crypto.Signer)
2721 if !ok {
2722 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2723 }
2724
2725 if template.SerialNumber == nil {
2726 return nil, errors.New("x509: no SerialNumber given")
2727 }
2728
2729 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2730 if err != nil {
2731 return nil, err
2732 }
2733
2734 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
2735 if err != nil {
2736 return nil, err
2737 }
2738
2739 asn1Issuer, err := subjectBytes(parent)
2740 if err != nil {
2741 return
2742 }
2743
2744 asn1Subject, err := subjectBytes(template)
2745 if err != nil {
2746 return
2747 }
2748
2749 authorityKeyId := template.AuthorityKeyId
2750 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
2751 authorityKeyId = parent.SubjectKeyId
2752 }
2753
2754 extensions, err := buildExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId)
2755 if err != nil {
2756 return
2757 }
2758
2759 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
2760 c := tbsCertificate{
2761 Version: 2,
2762 SerialNumber: template.SerialNumber,
2763 SignatureAlgorithm: signatureAlgorithm,
2764 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
2765 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
2766 Subject: asn1.RawValue{FullBytes: asn1Subject},
2767 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
2768 Extensions: extensions,
2769 }
2770
2771 tbsCertContents, err := asn1.Marshal(c)
2772 if err != nil {
2773 return
2774 }
2775 c.Raw = tbsCertContents
2776
2777 signed := tbsCertContents
2778 if hashFunc != 0 {
2779 h := hashFunc.New()
2780 h.Write(signed)
2781 signed = h.Sum(nil)
2782 }
2783
2784 var signerOpts crypto.SignerOpts = hashFunc
2785 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
2786 signerOpts = &rsa.PSSOptions{
2787 SaltLength: rsa.PSSSaltLengthEqualsHash,
2788 Hash: hashFunc,
2789 }
2790 }
2791
2792 var signature []byte
2793 signature, err = key.Sign(rand, signed, signerOpts)
2794 if err != nil {
2795 return
2796 }
2797
2798 return asn1.Marshal(certificate{
2799 nil,
2800 c,
2801 signatureAlgorithm,
2802 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2803 })
2804 }
2805
2806
2807
2808 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
2809
2810
2811 var pemType = "X509 CRL"
2812
2813
2814
2815
2816
2817 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
2818 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
2819 block, _ := pem.Decode(crlBytes)
2820 if block != nil && block.Type == pemType {
2821 crlBytes = block.Bytes
2822 }
2823 }
2824 return ParseDERCRL(crlBytes)
2825 }
2826
2827
2828 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
2829 certList := new(pkix.CertificateList)
2830 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
2831 return nil, err
2832 } else if len(rest) != 0 {
2833 return nil, errors.New("x509: trailing data after CRL")
2834 }
2835 return certList, nil
2836 }
2837
2838
2839
2840 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
2841 key, ok := priv.(crypto.Signer)
2842 if !ok {
2843 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2844 }
2845
2846 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
2847 if err != nil {
2848 return nil, err
2849 }
2850
2851
2852 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
2853 for i, rc := range revokedCerts {
2854 rc.RevocationTime = rc.RevocationTime.UTC()
2855 revokedCertsUTC[i] = rc
2856 }
2857
2858 tbsCertList := pkix.TBSCertificateList{
2859 Version: 1,
2860 Signature: signatureAlgorithm,
2861 Issuer: c.Subject.ToRDNSequence(),
2862 ThisUpdate: now.UTC(),
2863 NextUpdate: expiry.UTC(),
2864 RevokedCertificates: revokedCertsUTC,
2865 }
2866
2867
2868 if len(c.SubjectKeyId) > 0 {
2869 var aki pkix.Extension
2870 aki.Id = OIDExtensionAuthorityKeyId
2871 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
2872 if err != nil {
2873 return
2874 }
2875 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
2876 }
2877
2878 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2879 if err != nil {
2880 return
2881 }
2882
2883 signed := tbsCertListContents
2884 if hashFunc != 0 {
2885 h := hashFunc.New()
2886 h.Write(signed)
2887 signed = h.Sum(nil)
2888 }
2889
2890 var signature []byte
2891 signature, err = key.Sign(rand, signed, hashFunc)
2892 if err != nil {
2893 return
2894 }
2895
2896 return asn1.Marshal(pkix.CertificateList{
2897 TBSCertList: tbsCertList,
2898 SignatureAlgorithm: signatureAlgorithm,
2899 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2900 })
2901 }
2902
2903
2904 type CertificateRequest struct {
2905 Raw []byte
2906 RawTBSCertificateRequest []byte
2907 RawSubjectPublicKeyInfo []byte
2908 RawSubject []byte
2909
2910 Version int
2911 Signature []byte
2912 SignatureAlgorithm SignatureAlgorithm
2913
2914 PublicKeyAlgorithm PublicKeyAlgorithm
2915 PublicKey interface{}
2916
2917 Subject pkix.Name
2918
2919
2920
2921
2922
2923
2924 Attributes []pkix.AttributeTypeAndValueSET
2925
2926
2927
2928
2929 Extensions []pkix.Extension
2930
2931
2932
2933
2934
2935
2936
2937
2938 ExtraExtensions []pkix.Extension
2939
2940
2941 DNSNames []string
2942 EmailAddresses []string
2943 IPAddresses []net.IP
2944 URIs []*url.URL
2945 }
2946
2947
2948
2949
2950 type tbsCertificateRequest struct {
2951 Raw asn1.RawContent
2952 Version int
2953 Subject asn1.RawValue
2954 PublicKey publicKeyInfo
2955 RawAttributes []asn1.RawValue `asn1:"tag:0"`
2956 }
2957
2958 type certificateRequest struct {
2959 Raw asn1.RawContent
2960 TBSCSR tbsCertificateRequest
2961 SignatureAlgorithm pkix.AlgorithmIdentifier
2962 SignatureValue asn1.BitString
2963 }
2964
2965
2966
2967 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
2968
2969
2970
2971 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
2972 var rawAttributes []asn1.RawValue
2973 b, err := asn1.Marshal(attributes)
2974 if err != nil {
2975 return nil, err
2976 }
2977 rest, err := asn1.Unmarshal(b, &rawAttributes)
2978 if err != nil {
2979 return nil, err
2980 }
2981 if len(rest) != 0 {
2982 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
2983 }
2984 return rawAttributes, nil
2985 }
2986
2987
2988 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
2989 var attributes []pkix.AttributeTypeAndValueSET
2990 for _, rawAttr := range rawAttributes {
2991 var attr pkix.AttributeTypeAndValueSET
2992 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
2993
2994
2995 if err == nil && len(rest) == 0 {
2996 attributes = append(attributes, attr)
2997 }
2998 }
2999 return attributes
3000 }
3001
3002
3003
3004 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
3005
3006 type pkcs10Attribute struct {
3007 Id asn1.ObjectIdentifier
3008 Values []asn1.RawValue `asn1:"set"`
3009 }
3010
3011 var ret []pkix.Extension
3012 for _, rawAttr := range rawAttributes {
3013 var attr pkcs10Attribute
3014 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
3015
3016 continue
3017 }
3018
3019 if !attr.Id.Equal(oidExtensionRequest) {
3020 continue
3021 }
3022
3023 var extensions []pkix.Extension
3024 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
3025 return nil, err
3026 }
3027 ret = append(ret, extensions...)
3028 }
3029
3030 return ret, nil
3031 }
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
3053 key, ok := priv.(crypto.Signer)
3054 if !ok {
3055 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
3056 }
3057
3058 var hashFunc crypto.Hash
3059 var sigAlgo pkix.AlgorithmIdentifier
3060 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
3061 if err != nil {
3062 return nil, err
3063 }
3064
3065 var publicKeyBytes []byte
3066 var publicKeyAlgorithm pkix.AlgorithmIdentifier
3067 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
3068 if err != nil {
3069 return nil, err
3070 }
3071
3072 var extensions []pkix.Extension
3073
3074 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
3075 !oidInExtensions(OIDExtensionSubjectAltName, template.ExtraExtensions) {
3076 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
3077 if err != nil {
3078 return nil, err
3079 }
3080
3081 extensions = append(extensions, pkix.Extension{
3082 Id: OIDExtensionSubjectAltName,
3083 Value: sanBytes,
3084 })
3085 }
3086
3087 extensions = append(extensions, template.ExtraExtensions...)
3088
3089
3090 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
3091 for _, attr := range template.Attributes {
3092 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
3093 copy(values, attr.Value)
3094 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
3095 Type: attr.Type,
3096 Value: values,
3097 })
3098 }
3099
3100 extensionsAppended := false
3101 if len(extensions) > 0 {
3102
3103 for _, atvSet := range attributes {
3104 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
3105 continue
3106 }
3107
3108
3109
3110 specifiedExtensions := make(map[string]bool)
3111
3112 for _, atvs := range atvSet.Value {
3113 for _, atv := range atvs {
3114 specifiedExtensions[atv.Type.String()] = true
3115 }
3116 }
3117
3118 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
3119 newValue = append(newValue, atvSet.Value[0]...)
3120
3121 for _, e := range extensions {
3122 if specifiedExtensions[e.Id.String()] {
3123
3124
3125 continue
3126 }
3127
3128 newValue = append(newValue, pkix.AttributeTypeAndValue{
3129
3130
3131 Type: e.Id,
3132 Value: e.Value,
3133 })
3134 }
3135
3136 atvSet.Value[0] = newValue
3137 extensionsAppended = true
3138 break
3139 }
3140 }
3141
3142 rawAttributes, err := newRawAttributes(attributes)
3143 if err != nil {
3144 return
3145 }
3146
3147
3148
3149 if len(extensions) > 0 && !extensionsAppended {
3150 attr := struct {
3151 Type asn1.ObjectIdentifier
3152 Value [][]pkix.Extension `asn1:"set"`
3153 }{
3154 Type: oidExtensionRequest,
3155 Value: [][]pkix.Extension{extensions},
3156 }
3157
3158 b, err := asn1.Marshal(attr)
3159 if err != nil {
3160 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
3161 }
3162
3163 var rawValue asn1.RawValue
3164 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
3165 return nil, err
3166 }
3167
3168 rawAttributes = append(rawAttributes, rawValue)
3169 }
3170
3171 asn1Subject := template.RawSubject
3172 if len(asn1Subject) == 0 {
3173 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
3174 if err != nil {
3175 return nil, err
3176 }
3177 }
3178
3179 tbsCSR := tbsCertificateRequest{
3180 Version: 0,
3181 Subject: asn1.RawValue{FullBytes: asn1Subject},
3182 PublicKey: publicKeyInfo{
3183 Algorithm: publicKeyAlgorithm,
3184 PublicKey: asn1.BitString{
3185 Bytes: publicKeyBytes,
3186 BitLength: len(publicKeyBytes) * 8,
3187 },
3188 },
3189 RawAttributes: rawAttributes,
3190 }
3191
3192 tbsCSRContents, err := asn1.Marshal(tbsCSR)
3193 if err != nil {
3194 return
3195 }
3196 tbsCSR.Raw = tbsCSRContents
3197
3198 signed := tbsCSRContents
3199 if hashFunc != 0 {
3200 h := hashFunc.New()
3201 h.Write(signed)
3202 signed = h.Sum(nil)
3203 }
3204
3205 var signature []byte
3206 signature, err = key.Sign(rand, signed, hashFunc)
3207 if err != nil {
3208 return
3209 }
3210
3211 return asn1.Marshal(certificateRequest{
3212 TBSCSR: tbsCSR,
3213 SignatureAlgorithm: sigAlgo,
3214 SignatureValue: asn1.BitString{
3215 Bytes: signature,
3216 BitLength: len(signature) * 8,
3217 },
3218 })
3219 }
3220
3221
3222
3223 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
3224 var csr certificateRequest
3225
3226 rest, err := asn1.Unmarshal(asn1Data, &csr)
3227 if err != nil {
3228 return nil, err
3229 } else if len(rest) != 0 {
3230 return nil, asn1.SyntaxError{Msg: "trailing data"}
3231 }
3232
3233 return parseCertificateRequest(&csr)
3234 }
3235
3236 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
3237 out := &CertificateRequest{
3238 Raw: in.Raw,
3239 RawTBSCertificateRequest: in.TBSCSR.Raw,
3240 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
3241 RawSubject: in.TBSCSR.Subject.FullBytes,
3242
3243 Signature: in.SignatureValue.RightAlign(),
3244 SignatureAlgorithm: SignatureAlgorithmFromAI(in.SignatureAlgorithm),
3245
3246 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
3247
3248 Version: in.TBSCSR.Version,
3249 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
3250 }
3251
3252 var err error
3253 var nfe NonFatalErrors
3254 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey, &nfe)
3255 if err != nil {
3256 return nil, err
3257 }
3258
3259 if len(nfe.Errors) > 0 {
3260 return nil, nfe.Errors[0]
3261 }
3262
3263 var subject pkix.RDNSequence
3264 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
3265 return nil, err
3266 } else if len(rest) != 0 {
3267 return nil, errors.New("x509: trailing data after X.509 Subject")
3268 }
3269
3270 out.Subject.FillFromRDNSequence(&subject)
3271
3272 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
3273 return nil, err
3274 }
3275
3276 for _, extension := range out.Extensions {
3277 if extension.Id.Equal(OIDExtensionSubjectAltName) {
3278 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value, &nfe)
3279 if err != nil {
3280 return nil, err
3281 }
3282 }
3283 }
3284
3285 return out, nil
3286 }
3287
3288
3289 func (c *CertificateRequest) CheckSignature() error {
3290 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
3291 }
3292
View as plain text