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