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