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