1
2
3
4
5 package x509
6
7 import (
8 "bytes"
9 "crypto/dsa"
10 "crypto/ecdh"
11 "crypto/ecdsa"
12 "crypto/ed25519"
13 "crypto/elliptic"
14 "crypto/rsa"
15 "crypto/x509/pkix"
16 "encoding/asn1"
17 "errors"
18 "fmt"
19 "internal/godebug"
20 "math/big"
21 "net"
22 "net/url"
23 "strconv"
24 "strings"
25 "time"
26 "unicode/utf16"
27 "unicode/utf8"
28
29 "golang.org/x/crypto/cryptobyte"
30 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
31 )
32
33
34
35 func isPrintable(b byte) bool {
36 return 'a' <= b && b <= 'z' ||
37 'A' <= b && b <= 'Z' ||
38 '0' <= b && b <= '9' ||
39 '\'' <= b && b <= ')' ||
40 '+' <= b && b <= '/' ||
41 b == ' ' ||
42 b == ':' ||
43 b == '=' ||
44 b == '?' ||
45
46
47
48 b == '*' ||
49
50
51
52
53 b == '&'
54 }
55
56
57
58
59
60 func parseASN1String(tag cryptobyte_asn1.Tag, value []byte) (string, error) {
61 switch tag {
62 case cryptobyte_asn1.T61String:
63 return string(value), nil
64 case cryptobyte_asn1.PrintableString:
65 for _, b := range value {
66 if !isPrintable(b) {
67 return "", errors.New("invalid PrintableString")
68 }
69 }
70 return string(value), nil
71 case cryptobyte_asn1.UTF8String:
72 if !utf8.Valid(value) {
73 return "", errors.New("invalid UTF-8 string")
74 }
75 return string(value), nil
76 case cryptobyte_asn1.Tag(asn1.TagBMPString):
77 if len(value)%2 != 0 {
78 return "", errors.New("invalid BMPString")
79 }
80
81
82 if l := len(value); l >= 2 && value[l-1] == 0 && value[l-2] == 0 {
83 value = value[:l-2]
84 }
85
86 s := make([]uint16, 0, len(value)/2)
87 for len(value) > 0 {
88 s = append(s, uint16(value[0])<<8+uint16(value[1]))
89 value = value[2:]
90 }
91
92 return string(utf16.Decode(s)), nil
93 case cryptobyte_asn1.IA5String:
94 s := string(value)
95 if isIA5String(s) != nil {
96 return "", errors.New("invalid IA5String")
97 }
98 return s, nil
99 case cryptobyte_asn1.Tag(asn1.TagNumericString):
100 for _, b := range value {
101 if !('0' <= b && b <= '9' || b == ' ') {
102 return "", errors.New("invalid NumericString")
103 }
104 }
105 return string(value), nil
106 }
107 return "", fmt.Errorf("unsupported string type: %v", tag)
108 }
109
110
111
112 func parseName(raw cryptobyte.String) (*pkix.RDNSequence, error) {
113 if !raw.ReadASN1(&raw, cryptobyte_asn1.SEQUENCE) {
114 return nil, errors.New("x509: invalid RDNSequence")
115 }
116
117 var rdnSeq pkix.RDNSequence
118 for !raw.Empty() {
119 var rdnSet pkix.RelativeDistinguishedNameSET
120 var set cryptobyte.String
121 if !raw.ReadASN1(&set, cryptobyte_asn1.SET) {
122 return nil, errors.New("x509: invalid RDNSequence")
123 }
124 for !set.Empty() {
125 var atav cryptobyte.String
126 if !set.ReadASN1(&atav, cryptobyte_asn1.SEQUENCE) {
127 return nil, errors.New("x509: invalid RDNSequence: invalid attribute")
128 }
129 var attr pkix.AttributeTypeAndValue
130 if !atav.ReadASN1ObjectIdentifier(&attr.Type) {
131 return nil, errors.New("x509: invalid RDNSequence: invalid attribute type")
132 }
133 var rawValue cryptobyte.String
134 var valueTag cryptobyte_asn1.Tag
135 if !atav.ReadAnyASN1(&rawValue, &valueTag) {
136 return nil, errors.New("x509: invalid RDNSequence: invalid attribute value")
137 }
138 var err error
139 attr.Value, err = parseASN1String(valueTag, rawValue)
140 if err != nil {
141 return nil, fmt.Errorf("x509: invalid RDNSequence: invalid attribute value: %s", err)
142 }
143 rdnSet = append(rdnSet, attr)
144 }
145
146 rdnSeq = append(rdnSeq, rdnSet)
147 }
148
149 return &rdnSeq, nil
150 }
151
152 func parseAI(der cryptobyte.String) (pkix.AlgorithmIdentifier, error) {
153 ai := pkix.AlgorithmIdentifier{}
154 if !der.ReadASN1ObjectIdentifier(&ai.Algorithm) {
155 return ai, errors.New("x509: malformed OID")
156 }
157 if der.Empty() {
158 return ai, nil
159 }
160 var params cryptobyte.String
161 var tag cryptobyte_asn1.Tag
162 if !der.ReadAnyASN1Element(¶ms, &tag) {
163 return ai, errors.New("x509: malformed parameters")
164 }
165 ai.Parameters.Tag = int(tag)
166 ai.Parameters.FullBytes = params
167 return ai, nil
168 }
169
170 func parseTime(der *cryptobyte.String) (time.Time, error) {
171 var t time.Time
172 switch {
173 case der.PeekASN1Tag(cryptobyte_asn1.UTCTime):
174 if !der.ReadASN1UTCTime(&t) {
175 return t, errors.New("x509: malformed UTCTime")
176 }
177 case der.PeekASN1Tag(cryptobyte_asn1.GeneralizedTime):
178 if !der.ReadASN1GeneralizedTime(&t) {
179 return t, errors.New("x509: malformed GeneralizedTime")
180 }
181 default:
182 return t, errors.New("x509: unsupported time format")
183 }
184 return t, nil
185 }
186
187 func parseValidity(der cryptobyte.String) (time.Time, time.Time, error) {
188 notBefore, err := parseTime(&der)
189 if err != nil {
190 return time.Time{}, time.Time{}, err
191 }
192 notAfter, err := parseTime(&der)
193 if err != nil {
194 return time.Time{}, time.Time{}, err
195 }
196
197 return notBefore, notAfter, nil
198 }
199
200 func parseExtension(der cryptobyte.String) (pkix.Extension, error) {
201 var ext pkix.Extension
202 if !der.ReadASN1ObjectIdentifier(&ext.Id) {
203 return ext, errors.New("x509: malformed extension OID field")
204 }
205 if der.PeekASN1Tag(cryptobyte_asn1.BOOLEAN) {
206 if !der.ReadASN1Boolean(&ext.Critical) {
207 return ext, errors.New("x509: malformed extension critical field")
208 }
209 }
210 var val cryptobyte.String
211 if !der.ReadASN1(&val, cryptobyte_asn1.OCTET_STRING) {
212 return ext, errors.New("x509: malformed extension value field")
213 }
214 ext.Value = val
215 return ext, nil
216 }
217
218 func parsePublicKey(keyData *publicKeyInfo) (any, error) {
219 oid := keyData.Algorithm.Algorithm
220 params := keyData.Algorithm.Parameters
221 der := cryptobyte.String(keyData.PublicKey.RightAlign())
222 switch {
223 case oid.Equal(oidPublicKeyRSA):
224
225
226 if !bytes.Equal(params.FullBytes, asn1.NullBytes) {
227 return nil, errors.New("x509: RSA key missing NULL parameters")
228 }
229
230 p := &pkcs1PublicKey{N: new(big.Int)}
231 if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
232 return nil, errors.New("x509: invalid RSA public key")
233 }
234 if !der.ReadASN1Integer(p.N) {
235 return nil, errors.New("x509: invalid RSA modulus")
236 }
237 if !der.ReadASN1Integer(&p.E) {
238 return nil, errors.New("x509: invalid RSA public exponent")
239 }
240
241 if p.N.Sign() <= 0 {
242 return nil, errors.New("x509: RSA modulus is not a positive number")
243 }
244 if p.E <= 0 {
245 return nil, errors.New("x509: RSA public exponent is not a positive number")
246 }
247
248 pub := &rsa.PublicKey{
249 E: p.E,
250 N: p.N,
251 }
252 return pub, nil
253 case oid.Equal(oidPublicKeyECDSA):
254 paramsDer := cryptobyte.String(params.FullBytes)
255 namedCurveOID := new(asn1.ObjectIdentifier)
256 if !paramsDer.ReadASN1ObjectIdentifier(namedCurveOID) {
257 return nil, errors.New("x509: invalid ECDSA parameters")
258 }
259 namedCurve := namedCurveFromOID(*namedCurveOID)
260 if namedCurve == nil {
261 return nil, errors.New("x509: unsupported elliptic curve")
262 }
263 x, y := elliptic.Unmarshal(namedCurve, der)
264 if x == nil {
265 return nil, errors.New("x509: failed to unmarshal elliptic curve point")
266 }
267 pub := &ecdsa.PublicKey{
268 Curve: namedCurve,
269 X: x,
270 Y: y,
271 }
272 return pub, nil
273 case oid.Equal(oidPublicKeyEd25519):
274
275
276 if len(params.FullBytes) != 0 {
277 return nil, errors.New("x509: Ed25519 key encoded with illegal parameters")
278 }
279 if len(der) != ed25519.PublicKeySize {
280 return nil, errors.New("x509: wrong Ed25519 public key size")
281 }
282 return ed25519.PublicKey(der), nil
283 case oid.Equal(oidPublicKeyX25519):
284
285
286 if len(params.FullBytes) != 0 {
287 return nil, errors.New("x509: X25519 key encoded with illegal parameters")
288 }
289 return ecdh.X25519().NewPublicKey(der)
290 case oid.Equal(oidPublicKeyDSA):
291 y := new(big.Int)
292 if !der.ReadASN1Integer(y) {
293 return nil, errors.New("x509: invalid DSA public key")
294 }
295 pub := &dsa.PublicKey{
296 Y: y,
297 Parameters: dsa.Parameters{
298 P: new(big.Int),
299 Q: new(big.Int),
300 G: new(big.Int),
301 },
302 }
303 paramsDer := cryptobyte.String(params.FullBytes)
304 if !paramsDer.ReadASN1(¶msDer, cryptobyte_asn1.SEQUENCE) ||
305 !paramsDer.ReadASN1Integer(pub.Parameters.P) ||
306 !paramsDer.ReadASN1Integer(pub.Parameters.Q) ||
307 !paramsDer.ReadASN1Integer(pub.Parameters.G) {
308 return nil, errors.New("x509: invalid DSA parameters")
309 }
310 if pub.Y.Sign() <= 0 || pub.Parameters.P.Sign() <= 0 ||
311 pub.Parameters.Q.Sign() <= 0 || pub.Parameters.G.Sign() <= 0 {
312 return nil, errors.New("x509: zero or negative DSA parameter")
313 }
314 return pub, nil
315 default:
316 return nil, errors.New("x509: unknown public key algorithm")
317 }
318 }
319
320 func parseKeyUsageExtension(der cryptobyte.String) (KeyUsage, error) {
321 var usageBits asn1.BitString
322 if !der.ReadASN1BitString(&usageBits) {
323 return 0, errors.New("x509: invalid key usage")
324 }
325
326 var usage int
327 for i := 0; i < 9; i++ {
328 if usageBits.At(i) != 0 {
329 usage |= 1 << uint(i)
330 }
331 }
332 return KeyUsage(usage), nil
333 }
334
335 func parseBasicConstraintsExtension(der cryptobyte.String) (bool, int, error) {
336 var isCA bool
337 if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
338 return false, 0, errors.New("x509: invalid basic constraints")
339 }
340 if der.PeekASN1Tag(cryptobyte_asn1.BOOLEAN) {
341 if !der.ReadASN1Boolean(&isCA) {
342 return false, 0, errors.New("x509: invalid basic constraints")
343 }
344 }
345 maxPathLen := -1
346 if der.PeekASN1Tag(cryptobyte_asn1.INTEGER) {
347 if !der.ReadASN1Integer(&maxPathLen) {
348 return false, 0, errors.New("x509: invalid basic constraints")
349 }
350 }
351
352
353 return isCA, maxPathLen, nil
354 }
355
356 func forEachSAN(der cryptobyte.String, callback func(tag int, data []byte) error) error {
357 if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
358 return errors.New("x509: invalid subject alternative names")
359 }
360 for !der.Empty() {
361 var san cryptobyte.String
362 var tag cryptobyte_asn1.Tag
363 if !der.ReadAnyASN1(&san, &tag) {
364 return errors.New("x509: invalid subject alternative name")
365 }
366 if err := callback(int(tag^0x80), san); err != nil {
367 return err
368 }
369 }
370
371 return nil
372 }
373
374 func parseSANExtension(der cryptobyte.String) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error) {
375 err = forEachSAN(der, func(tag int, data []byte) error {
376 switch tag {
377 case nameTypeEmail:
378 email := string(data)
379 if err := isIA5String(email); err != nil {
380 return errors.New("x509: SAN rfc822Name is malformed")
381 }
382 emailAddresses = append(emailAddresses, email)
383 case nameTypeDNS:
384 name := string(data)
385 if err := isIA5String(name); err != nil {
386 return errors.New("x509: SAN dNSName is malformed")
387 }
388 dnsNames = append(dnsNames, string(name))
389 case nameTypeURI:
390 uriStr := string(data)
391 if err := isIA5String(uriStr); err != nil {
392 return errors.New("x509: SAN uniformResourceIdentifier is malformed")
393 }
394 uri, err := url.Parse(uriStr)
395 if err != nil {
396 return fmt.Errorf("x509: cannot parse URI %q: %s", uriStr, err)
397 }
398 if len(uri.Host) > 0 {
399 if _, ok := domainToReverseLabels(uri.Host); !ok {
400 return fmt.Errorf("x509: cannot parse URI %q: invalid domain", uriStr)
401 }
402 }
403 uris = append(uris, uri)
404 case nameTypeIP:
405 switch len(data) {
406 case net.IPv4len, net.IPv6len:
407 ipAddresses = append(ipAddresses, data)
408 default:
409 return errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data)))
410 }
411 }
412
413 return nil
414 })
415
416 return
417 }
418
419 func parseAuthorityKeyIdentifier(e pkix.Extension) ([]byte, error) {
420
421 if e.Critical {
422
423 return nil, errors.New("x509: authority key identifier incorrectly marked critical")
424 }
425 val := cryptobyte.String(e.Value)
426 var akid cryptobyte.String
427 if !val.ReadASN1(&akid, cryptobyte_asn1.SEQUENCE) {
428 return nil, errors.New("x509: invalid authority key identifier")
429 }
430 if akid.PeekASN1Tag(cryptobyte_asn1.Tag(0).ContextSpecific()) {
431 if !akid.ReadASN1(&akid, cryptobyte_asn1.Tag(0).ContextSpecific()) {
432 return nil, errors.New("x509: invalid authority key identifier")
433 }
434 return akid, nil
435 }
436 return nil, nil
437 }
438
439 func parseExtKeyUsageExtension(der cryptobyte.String) ([]ExtKeyUsage, []asn1.ObjectIdentifier, error) {
440 var extKeyUsages []ExtKeyUsage
441 var unknownUsages []asn1.ObjectIdentifier
442 if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
443 return nil, nil, errors.New("x509: invalid extended key usages")
444 }
445 for !der.Empty() {
446 var eku asn1.ObjectIdentifier
447 if !der.ReadASN1ObjectIdentifier(&eku) {
448 return nil, nil, errors.New("x509: invalid extended key usages")
449 }
450 if extKeyUsage, ok := extKeyUsageFromOID(eku); ok {
451 extKeyUsages = append(extKeyUsages, extKeyUsage)
452 } else {
453 unknownUsages = append(unknownUsages, eku)
454 }
455 }
456 return extKeyUsages, unknownUsages, nil
457 }
458
459 func parseCertificatePoliciesExtension(der cryptobyte.String) ([]OID, error) {
460 var oids []OID
461 seenOIDs := map[string]bool{}
462 if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
463 return nil, errors.New("x509: invalid certificate policies")
464 }
465 for !der.Empty() {
466 var cp cryptobyte.String
467 var OIDBytes cryptobyte.String
468 if !der.ReadASN1(&cp, cryptobyte_asn1.SEQUENCE) || !cp.ReadASN1(&OIDBytes, cryptobyte_asn1.OBJECT_IDENTIFIER) {
469 return nil, errors.New("x509: invalid certificate policies")
470 }
471 if seenOIDs[string(OIDBytes)] {
472 return nil, errors.New("x509: invalid certificate policies")
473 }
474 seenOIDs[string(OIDBytes)] = true
475 oid, ok := newOIDFromDER(OIDBytes)
476 if !ok {
477 return nil, errors.New("x509: invalid certificate policies")
478 }
479 oids = append(oids, oid)
480 }
481 return oids, nil
482 }
483
484
485 func isValidIPMask(mask []byte) bool {
486 seenZero := false
487
488 for _, b := range mask {
489 if seenZero {
490 if b != 0 {
491 return false
492 }
493
494 continue
495 }
496
497 switch b {
498 case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe:
499 seenZero = true
500 case 0xff:
501 default:
502 return false
503 }
504 }
505
506 return true
507 }
508
509 func parseNameConstraintsExtension(out *Certificate, e pkix.Extension) (unhandled bool, err error) {
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525 outer := cryptobyte.String(e.Value)
526 var toplevel, permitted, excluded cryptobyte.String
527 var havePermitted, haveExcluded bool
528 if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) ||
529 !outer.Empty() ||
530 !toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) ||
531 !toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) ||
532 !toplevel.Empty() {
533 return false, errors.New("x509: invalid NameConstraints extension")
534 }
535
536 if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 {
537
538
539
540
541 return false, errors.New("x509: empty name constraints extension")
542 }
543
544 getValues := func(subtrees cryptobyte.String) (dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) {
545 for !subtrees.Empty() {
546 var seq, value cryptobyte.String
547 var tag cryptobyte_asn1.Tag
548 if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) ||
549 !seq.ReadAnyASN1(&value, &tag) {
550 return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension")
551 }
552
553 var (
554 dnsTag = cryptobyte_asn1.Tag(2).ContextSpecific()
555 emailTag = cryptobyte_asn1.Tag(1).ContextSpecific()
556 ipTag = cryptobyte_asn1.Tag(7).ContextSpecific()
557 uriTag = cryptobyte_asn1.Tag(6).ContextSpecific()
558 )
559
560 switch tag {
561 case dnsTag:
562 domain := string(value)
563 if err := isIA5String(domain); err != nil {
564 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
565 }
566
567 trimmedDomain := domain
568 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
569
570
571
572
573 trimmedDomain = trimmedDomain[1:]
574 }
575 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
576 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse dnsName constraint %q", domain)
577 }
578 dnsNames = append(dnsNames, domain)
579
580 case ipTag:
581 l := len(value)
582 var ip, mask []byte
583
584 switch l {
585 case 8:
586 ip = value[:4]
587 mask = value[4:]
588
589 case 32:
590 ip = value[:16]
591 mask = value[16:]
592
593 default:
594 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l)
595 }
596
597 if !isValidIPMask(mask) {
598 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask)
599 }
600
601 ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)})
602
603 case emailTag:
604 constraint := string(value)
605 if err := isIA5String(constraint); err != nil {
606 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
607 }
608
609
610
611 if strings.Contains(constraint, "@") {
612 if _, ok := parseRFC2821Mailbox(constraint); !ok {
613 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
614 }
615 } else {
616
617 domain := constraint
618 if len(domain) > 0 && domain[0] == '.' {
619 domain = domain[1:]
620 }
621 if _, ok := domainToReverseLabels(domain); !ok {
622 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
623 }
624 }
625 emails = append(emails, constraint)
626
627 case uriTag:
628 domain := string(value)
629 if err := isIA5String(domain); err != nil {
630 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
631 }
632
633 if net.ParseIP(domain) != nil {
634 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain)
635 }
636
637 trimmedDomain := domain
638 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
639
640
641
642
643 trimmedDomain = trimmedDomain[1:]
644 }
645 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
646 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q", domain)
647 }
648 uriDomains = append(uriDomains, domain)
649
650 default:
651 unhandled = true
652 }
653 }
654
655 return dnsNames, ips, emails, uriDomains, nil
656 }
657
658 if out.PermittedDNSDomains, out.PermittedIPRanges, out.PermittedEmailAddresses, out.PermittedURIDomains, err = getValues(permitted); err != nil {
659 return false, err
660 }
661 if out.ExcludedDNSDomains, out.ExcludedIPRanges, out.ExcludedEmailAddresses, out.ExcludedURIDomains, err = getValues(excluded); err != nil {
662 return false, err
663 }
664 out.PermittedDNSDomainsCritical = e.Critical
665
666 return unhandled, nil
667 }
668
669 func processExtensions(out *Certificate) error {
670 var err error
671 for _, e := range out.Extensions {
672 unhandled := false
673
674 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
675 switch e.Id[3] {
676 case 15:
677 out.KeyUsage, err = parseKeyUsageExtension(e.Value)
678 if err != nil {
679 return err
680 }
681 case 19:
682 out.IsCA, out.MaxPathLen, err = parseBasicConstraintsExtension(e.Value)
683 if err != nil {
684 return err
685 }
686 out.BasicConstraintsValid = true
687 out.MaxPathLenZero = out.MaxPathLen == 0
688 case 17:
689 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(e.Value)
690 if err != nil {
691 return err
692 }
693
694 if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 && len(out.URIs) == 0 {
695
696 unhandled = true
697 }
698
699 case 30:
700 unhandled, err = parseNameConstraintsExtension(out, e)
701 if err != nil {
702 return err
703 }
704
705 case 31:
706
707
708
709
710
711
712
713
714
715
716
717
718 val := cryptobyte.String(e.Value)
719 if !val.ReadASN1(&val, cryptobyte_asn1.SEQUENCE) {
720 return errors.New("x509: invalid CRL distribution points")
721 }
722 for !val.Empty() {
723 var dpDER cryptobyte.String
724 if !val.ReadASN1(&dpDER, cryptobyte_asn1.SEQUENCE) {
725 return errors.New("x509: invalid CRL distribution point")
726 }
727 var dpNameDER cryptobyte.String
728 var dpNamePresent bool
729 if !dpDER.ReadOptionalASN1(&dpNameDER, &dpNamePresent, cryptobyte_asn1.Tag(0).Constructed().ContextSpecific()) {
730 return errors.New("x509: invalid CRL distribution point")
731 }
732 if !dpNamePresent {
733 continue
734 }
735 if !dpNameDER.ReadASN1(&dpNameDER, cryptobyte_asn1.Tag(0).Constructed().ContextSpecific()) {
736 return errors.New("x509: invalid CRL distribution point")
737 }
738 for !dpNameDER.Empty() {
739 if !dpNameDER.PeekASN1Tag(cryptobyte_asn1.Tag(6).ContextSpecific()) {
740 break
741 }
742 var uri cryptobyte.String
743 if !dpNameDER.ReadASN1(&uri, cryptobyte_asn1.Tag(6).ContextSpecific()) {
744 return errors.New("x509: invalid CRL distribution point")
745 }
746 out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(uri))
747 }
748 }
749
750 case 35:
751 out.AuthorityKeyId, err = parseAuthorityKeyIdentifier(e)
752 if err != nil {
753 return err
754 }
755 case 36:
756 val := cryptobyte.String(e.Value)
757 if !val.ReadASN1(&val, cryptobyte_asn1.SEQUENCE) {
758 return errors.New("x509: invalid policy constraints extension")
759 }
760 if val.PeekASN1Tag(cryptobyte_asn1.Tag(0).ContextSpecific()) {
761 var v int64
762 if !val.ReadASN1Int64WithTag(&v, cryptobyte_asn1.Tag(0).ContextSpecific()) {
763 return errors.New("x509: invalid policy constraints extension")
764 }
765 out.RequireExplicitPolicy = int(v)
766
767 if int64(out.RequireExplicitPolicy) != v {
768 return errors.New("x509: policy constraints requireExplicitPolicy field overflows int")
769 }
770 out.RequireExplicitPolicyZero = out.RequireExplicitPolicy == 0
771 }
772 if val.PeekASN1Tag(cryptobyte_asn1.Tag(1).ContextSpecific()) {
773 var v int64
774 if !val.ReadASN1Int64WithTag(&v, cryptobyte_asn1.Tag(1).ContextSpecific()) {
775 return errors.New("x509: invalid policy constraints extension")
776 }
777 out.InhibitPolicyMapping = int(v)
778
779 if int64(out.InhibitPolicyMapping) != v {
780 return errors.New("x509: policy constraints inhibitPolicyMapping field overflows int")
781 }
782 out.InhibitPolicyMappingZero = out.InhibitPolicyMapping == 0
783 }
784 case 37:
785 out.ExtKeyUsage, out.UnknownExtKeyUsage, err = parseExtKeyUsageExtension(e.Value)
786 if err != nil {
787 return err
788 }
789 case 14:
790 if e.Critical {
791
792 return errors.New("x509: subject key identifier incorrectly marked critical")
793 }
794 val := cryptobyte.String(e.Value)
795 var skid cryptobyte.String
796 if !val.ReadASN1(&skid, cryptobyte_asn1.OCTET_STRING) {
797 return errors.New("x509: invalid subject key identifier")
798 }
799 out.SubjectKeyId = skid
800 case 32:
801 out.Policies, err = parseCertificatePoliciesExtension(e.Value)
802 if err != nil {
803 return err
804 }
805 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, 0, len(out.Policies))
806 for _, oid := range out.Policies {
807 if oid, ok := oid.toASN1OID(); ok {
808 out.PolicyIdentifiers = append(out.PolicyIdentifiers, oid)
809 }
810 }
811 case 33:
812 val := cryptobyte.String(e.Value)
813 if !val.ReadASN1(&val, cryptobyte_asn1.SEQUENCE) {
814 return errors.New("x509: invalid policy mappings extension")
815 }
816 for !val.Empty() {
817 var s cryptobyte.String
818 var issuer, subject cryptobyte.String
819 if !val.ReadASN1(&s, cryptobyte_asn1.SEQUENCE) ||
820 !s.ReadASN1(&issuer, cryptobyte_asn1.OBJECT_IDENTIFIER) ||
821 !s.ReadASN1(&subject, cryptobyte_asn1.OBJECT_IDENTIFIER) {
822 return errors.New("x509: invalid policy mappings extension")
823 }
824 out.PolicyMappings = append(out.PolicyMappings, PolicyMapping{OID{issuer}, OID{subject}})
825 }
826 case 54:
827 val := cryptobyte.String(e.Value)
828 if !val.ReadASN1Integer(&out.InhibitAnyPolicy) {
829 return errors.New("x509: invalid inhibit any policy extension")
830 }
831 out.InhibitAnyPolicyZero = out.InhibitAnyPolicy == 0
832 default:
833
834 unhandled = true
835 }
836 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
837
838 if e.Critical {
839
840 return errors.New("x509: authority info access incorrectly marked critical")
841 }
842 val := cryptobyte.String(e.Value)
843 if !val.ReadASN1(&val, cryptobyte_asn1.SEQUENCE) {
844 return errors.New("x509: invalid authority info access")
845 }
846 for !val.Empty() {
847 var aiaDER cryptobyte.String
848 if !val.ReadASN1(&aiaDER, cryptobyte_asn1.SEQUENCE) {
849 return errors.New("x509: invalid authority info access")
850 }
851 var method asn1.ObjectIdentifier
852 if !aiaDER.ReadASN1ObjectIdentifier(&method) {
853 return errors.New("x509: invalid authority info access")
854 }
855 if !aiaDER.PeekASN1Tag(cryptobyte_asn1.Tag(6).ContextSpecific()) {
856 continue
857 }
858 if !aiaDER.ReadASN1(&aiaDER, cryptobyte_asn1.Tag(6).ContextSpecific()) {
859 return errors.New("x509: invalid authority info access")
860 }
861 switch {
862 case method.Equal(oidAuthorityInfoAccessOcsp):
863 out.OCSPServer = append(out.OCSPServer, string(aiaDER))
864 case method.Equal(oidAuthorityInfoAccessIssuers):
865 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(aiaDER))
866 }
867 }
868 } else {
869
870 unhandled = true
871 }
872
873 if e.Critical && unhandled {
874 out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
875 }
876 }
877
878 return nil
879 }
880
881 var x509negativeserial = godebug.New("x509negativeserial")
882
883 func parseCertificate(der []byte) (*Certificate, error) {
884 cert := &Certificate{}
885
886 input := cryptobyte.String(der)
887
888
889
890 if !input.ReadASN1Element(&input, cryptobyte_asn1.SEQUENCE) {
891 return nil, errors.New("x509: malformed certificate")
892 }
893 cert.Raw = input
894 if !input.ReadASN1(&input, cryptobyte_asn1.SEQUENCE) {
895 return nil, errors.New("x509: malformed certificate")
896 }
897
898 var tbs cryptobyte.String
899
900
901 if !input.ReadASN1Element(&tbs, cryptobyte_asn1.SEQUENCE) {
902 return nil, errors.New("x509: malformed tbs certificate")
903 }
904 cert.RawTBSCertificate = tbs
905 if !tbs.ReadASN1(&tbs, cryptobyte_asn1.SEQUENCE) {
906 return nil, errors.New("x509: malformed tbs certificate")
907 }
908
909 if !tbs.ReadOptionalASN1Integer(&cert.Version, cryptobyte_asn1.Tag(0).Constructed().ContextSpecific(), 0) {
910 return nil, errors.New("x509: malformed version")
911 }
912 if cert.Version < 0 {
913 return nil, errors.New("x509: malformed version")
914 }
915
916
917 cert.Version++
918 if cert.Version > 3 {
919 return nil, errors.New("x509: invalid version")
920 }
921
922 serial := new(big.Int)
923 if !tbs.ReadASN1Integer(serial) {
924 return nil, errors.New("x509: malformed serial number")
925 }
926 if serial.Sign() == -1 {
927 if x509negativeserial.Value() != "1" {
928 return nil, errors.New("x509: negative serial number")
929 } else {
930 x509negativeserial.IncNonDefault()
931 }
932 }
933 cert.SerialNumber = serial
934
935 var sigAISeq cryptobyte.String
936 if !tbs.ReadASN1(&sigAISeq, cryptobyte_asn1.SEQUENCE) {
937 return nil, errors.New("x509: malformed signature algorithm identifier")
938 }
939
940
941
942 var outerSigAISeq cryptobyte.String
943 if !input.ReadASN1(&outerSigAISeq, cryptobyte_asn1.SEQUENCE) {
944 return nil, errors.New("x509: malformed algorithm identifier")
945 }
946 if !bytes.Equal(outerSigAISeq, sigAISeq) {
947 return nil, errors.New("x509: inner and outer signature algorithm identifiers don't match")
948 }
949 sigAI, err := parseAI(sigAISeq)
950 if err != nil {
951 return nil, err
952 }
953 cert.SignatureAlgorithm = getSignatureAlgorithmFromAI(sigAI)
954
955 var issuerSeq cryptobyte.String
956 if !tbs.ReadASN1Element(&issuerSeq, cryptobyte_asn1.SEQUENCE) {
957 return nil, errors.New("x509: malformed issuer")
958 }
959 cert.RawIssuer = issuerSeq
960 issuerRDNs, err := parseName(issuerSeq)
961 if err != nil {
962 return nil, err
963 }
964 cert.Issuer.FillFromRDNSequence(issuerRDNs)
965
966 var validity cryptobyte.String
967 if !tbs.ReadASN1(&validity, cryptobyte_asn1.SEQUENCE) {
968 return nil, errors.New("x509: malformed validity")
969 }
970 cert.NotBefore, cert.NotAfter, err = parseValidity(validity)
971 if err != nil {
972 return nil, err
973 }
974
975 var subjectSeq cryptobyte.String
976 if !tbs.ReadASN1Element(&subjectSeq, cryptobyte_asn1.SEQUENCE) {
977 return nil, errors.New("x509: malformed issuer")
978 }
979 cert.RawSubject = subjectSeq
980 subjectRDNs, err := parseName(subjectSeq)
981 if err != nil {
982 return nil, err
983 }
984 cert.Subject.FillFromRDNSequence(subjectRDNs)
985
986 var spki cryptobyte.String
987 if !tbs.ReadASN1Element(&spki, cryptobyte_asn1.SEQUENCE) {
988 return nil, errors.New("x509: malformed spki")
989 }
990 cert.RawSubjectPublicKeyInfo = spki
991 if !spki.ReadASN1(&spki, cryptobyte_asn1.SEQUENCE) {
992 return nil, errors.New("x509: malformed spki")
993 }
994 var pkAISeq cryptobyte.String
995 if !spki.ReadASN1(&pkAISeq, cryptobyte_asn1.SEQUENCE) {
996 return nil, errors.New("x509: malformed public key algorithm identifier")
997 }
998 pkAI, err := parseAI(pkAISeq)
999 if err != nil {
1000 return nil, err
1001 }
1002 cert.PublicKeyAlgorithm = getPublicKeyAlgorithmFromOID(pkAI.Algorithm)
1003 var spk asn1.BitString
1004 if !spki.ReadASN1BitString(&spk) {
1005 return nil, errors.New("x509: malformed subjectPublicKey")
1006 }
1007 if cert.PublicKeyAlgorithm != UnknownPublicKeyAlgorithm {
1008 cert.PublicKey, err = parsePublicKey(&publicKeyInfo{
1009 Algorithm: pkAI,
1010 PublicKey: spk,
1011 })
1012 if err != nil {
1013 return nil, err
1014 }
1015 }
1016
1017 if cert.Version > 1 {
1018 if !tbs.SkipOptionalASN1(cryptobyte_asn1.Tag(1).ContextSpecific()) {
1019 return nil, errors.New("x509: malformed issuerUniqueID")
1020 }
1021 if !tbs.SkipOptionalASN1(cryptobyte_asn1.Tag(2).ContextSpecific()) {
1022 return nil, errors.New("x509: malformed subjectUniqueID")
1023 }
1024 if cert.Version == 3 {
1025 var extensions cryptobyte.String
1026 var present bool
1027 if !tbs.ReadOptionalASN1(&extensions, &present, cryptobyte_asn1.Tag(3).Constructed().ContextSpecific()) {
1028 return nil, errors.New("x509: malformed extensions")
1029 }
1030 if present {
1031 seenExts := make(map[string]bool)
1032 if !extensions.ReadASN1(&extensions, cryptobyte_asn1.SEQUENCE) {
1033 return nil, errors.New("x509: malformed extensions")
1034 }
1035 for !extensions.Empty() {
1036 var extension cryptobyte.String
1037 if !extensions.ReadASN1(&extension, cryptobyte_asn1.SEQUENCE) {
1038 return nil, errors.New("x509: malformed extension")
1039 }
1040 ext, err := parseExtension(extension)
1041 if err != nil {
1042 return nil, err
1043 }
1044 oidStr := ext.Id.String()
1045 if seenExts[oidStr] {
1046 return nil, fmt.Errorf("x509: certificate contains duplicate extension with OID %q", oidStr)
1047 }
1048 seenExts[oidStr] = true
1049 cert.Extensions = append(cert.Extensions, ext)
1050 }
1051 err = processExtensions(cert)
1052 if err != nil {
1053 return nil, err
1054 }
1055 }
1056 }
1057 }
1058
1059 var signature asn1.BitString
1060 if !input.ReadASN1BitString(&signature) {
1061 return nil, errors.New("x509: malformed signature")
1062 }
1063 cert.Signature = signature.RightAlign()
1064
1065 return cert, nil
1066 }
1067
1068
1069
1070
1071
1072
1073 func ParseCertificate(der []byte) (*Certificate, error) {
1074 cert, err := parseCertificate(der)
1075 if err != nil {
1076 return nil, err
1077 }
1078 if len(der) != len(cert.Raw) {
1079 return nil, errors.New("x509: trailing data")
1080 }
1081 return cert, err
1082 }
1083
1084
1085
1086 func ParseCertificates(der []byte) ([]*Certificate, error) {
1087 var certs []*Certificate
1088 for len(der) > 0 {
1089 cert, err := parseCertificate(der)
1090 if err != nil {
1091 return nil, err
1092 }
1093 certs = append(certs, cert)
1094 der = der[len(cert.Raw):]
1095 }
1096 return certs, nil
1097 }
1098
1099
1100
1101 const x509v2Version = 1
1102
1103
1104
1105 func ParseRevocationList(der []byte) (*RevocationList, error) {
1106 rl := &RevocationList{}
1107
1108 input := cryptobyte.String(der)
1109
1110
1111
1112 if !input.ReadASN1Element(&input, cryptobyte_asn1.SEQUENCE) {
1113 return nil, errors.New("x509: malformed crl")
1114 }
1115 rl.Raw = input
1116 if !input.ReadASN1(&input, cryptobyte_asn1.SEQUENCE) {
1117 return nil, errors.New("x509: malformed crl")
1118 }
1119
1120 var tbs cryptobyte.String
1121
1122
1123 if !input.ReadASN1Element(&tbs, cryptobyte_asn1.SEQUENCE) {
1124 return nil, errors.New("x509: malformed tbs crl")
1125 }
1126 rl.RawTBSRevocationList = tbs
1127 if !tbs.ReadASN1(&tbs, cryptobyte_asn1.SEQUENCE) {
1128 return nil, errors.New("x509: malformed tbs crl")
1129 }
1130
1131 var version int
1132 if !tbs.PeekASN1Tag(cryptobyte_asn1.INTEGER) {
1133 return nil, errors.New("x509: unsupported crl version")
1134 }
1135 if !tbs.ReadASN1Integer(&version) {
1136 return nil, errors.New("x509: malformed crl")
1137 }
1138 if version != x509v2Version {
1139 return nil, fmt.Errorf("x509: unsupported crl version: %d", version)
1140 }
1141
1142 var sigAISeq cryptobyte.String
1143 if !tbs.ReadASN1(&sigAISeq, cryptobyte_asn1.SEQUENCE) {
1144 return nil, errors.New("x509: malformed signature algorithm identifier")
1145 }
1146
1147
1148
1149 var outerSigAISeq cryptobyte.String
1150 if !input.ReadASN1(&outerSigAISeq, cryptobyte_asn1.SEQUENCE) {
1151 return nil, errors.New("x509: malformed algorithm identifier")
1152 }
1153 if !bytes.Equal(outerSigAISeq, sigAISeq) {
1154 return nil, errors.New("x509: inner and outer signature algorithm identifiers don't match")
1155 }
1156 sigAI, err := parseAI(sigAISeq)
1157 if err != nil {
1158 return nil, err
1159 }
1160 rl.SignatureAlgorithm = getSignatureAlgorithmFromAI(sigAI)
1161
1162 var signature asn1.BitString
1163 if !input.ReadASN1BitString(&signature) {
1164 return nil, errors.New("x509: malformed signature")
1165 }
1166 rl.Signature = signature.RightAlign()
1167
1168 var issuerSeq cryptobyte.String
1169 if !tbs.ReadASN1Element(&issuerSeq, cryptobyte_asn1.SEQUENCE) {
1170 return nil, errors.New("x509: malformed issuer")
1171 }
1172 rl.RawIssuer = issuerSeq
1173 issuerRDNs, err := parseName(issuerSeq)
1174 if err != nil {
1175 return nil, err
1176 }
1177 rl.Issuer.FillFromRDNSequence(issuerRDNs)
1178
1179 rl.ThisUpdate, err = parseTime(&tbs)
1180 if err != nil {
1181 return nil, err
1182 }
1183 if tbs.PeekASN1Tag(cryptobyte_asn1.GeneralizedTime) || tbs.PeekASN1Tag(cryptobyte_asn1.UTCTime) {
1184 rl.NextUpdate, err = parseTime(&tbs)
1185 if err != nil {
1186 return nil, err
1187 }
1188 }
1189
1190 if tbs.PeekASN1Tag(cryptobyte_asn1.SEQUENCE) {
1191 var revokedSeq cryptobyte.String
1192 if !tbs.ReadASN1(&revokedSeq, cryptobyte_asn1.SEQUENCE) {
1193 return nil, errors.New("x509: malformed crl")
1194 }
1195 for !revokedSeq.Empty() {
1196 rce := RevocationListEntry{}
1197
1198 var certSeq cryptobyte.String
1199 if !revokedSeq.ReadASN1Element(&certSeq, cryptobyte_asn1.SEQUENCE) {
1200 return nil, errors.New("x509: malformed crl")
1201 }
1202 rce.Raw = certSeq
1203 if !certSeq.ReadASN1(&certSeq, cryptobyte_asn1.SEQUENCE) {
1204 return nil, errors.New("x509: malformed crl")
1205 }
1206
1207 rce.SerialNumber = new(big.Int)
1208 if !certSeq.ReadASN1Integer(rce.SerialNumber) {
1209 return nil, errors.New("x509: malformed serial number")
1210 }
1211 rce.RevocationTime, err = parseTime(&certSeq)
1212 if err != nil {
1213 return nil, err
1214 }
1215 var extensions cryptobyte.String
1216 var present bool
1217 if !certSeq.ReadOptionalASN1(&extensions, &present, cryptobyte_asn1.SEQUENCE) {
1218 return nil, errors.New("x509: malformed extensions")
1219 }
1220 if present {
1221 for !extensions.Empty() {
1222 var extension cryptobyte.String
1223 if !extensions.ReadASN1(&extension, cryptobyte_asn1.SEQUENCE) {
1224 return nil, errors.New("x509: malformed extension")
1225 }
1226 ext, err := parseExtension(extension)
1227 if err != nil {
1228 return nil, err
1229 }
1230 if ext.Id.Equal(oidExtensionReasonCode) {
1231 val := cryptobyte.String(ext.Value)
1232 if !val.ReadASN1Enum(&rce.ReasonCode) {
1233 return nil, fmt.Errorf("x509: malformed reasonCode extension")
1234 }
1235 }
1236 rce.Extensions = append(rce.Extensions, ext)
1237 }
1238 }
1239
1240 rl.RevokedCertificateEntries = append(rl.RevokedCertificateEntries, rce)
1241 rcDeprecated := pkix.RevokedCertificate{
1242 SerialNumber: rce.SerialNumber,
1243 RevocationTime: rce.RevocationTime,
1244 Extensions: rce.Extensions,
1245 }
1246 rl.RevokedCertificates = append(rl.RevokedCertificates, rcDeprecated)
1247 }
1248 }
1249
1250 var extensions cryptobyte.String
1251 var present bool
1252 if !tbs.ReadOptionalASN1(&extensions, &present, cryptobyte_asn1.Tag(0).Constructed().ContextSpecific()) {
1253 return nil, errors.New("x509: malformed extensions")
1254 }
1255 if present {
1256 if !extensions.ReadASN1(&extensions, cryptobyte_asn1.SEQUENCE) {
1257 return nil, errors.New("x509: malformed extensions")
1258 }
1259 for !extensions.Empty() {
1260 var extension cryptobyte.String
1261 if !extensions.ReadASN1(&extension, cryptobyte_asn1.SEQUENCE) {
1262 return nil, errors.New("x509: malformed extension")
1263 }
1264 ext, err := parseExtension(extension)
1265 if err != nil {
1266 return nil, err
1267 }
1268 if ext.Id.Equal(oidExtensionAuthorityKeyId) {
1269 rl.AuthorityKeyId, err = parseAuthorityKeyIdentifier(ext)
1270 if err != nil {
1271 return nil, err
1272 }
1273 } else if ext.Id.Equal(oidExtensionCRLNumber) {
1274 value := cryptobyte.String(ext.Value)
1275 rl.Number = new(big.Int)
1276 if !value.ReadASN1Integer(rl.Number) {
1277 return nil, errors.New("x509: malformed crl number")
1278 }
1279 }
1280 rl.Extensions = append(rl.Extensions, ext)
1281 }
1282 }
1283
1284 return rl, nil
1285 }
1286
View as plain text