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