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