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