]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/x509/verify.go
[dev.boringcrypto] all: merge master into dev.boringcrypto
[gostls13.git] / src / crypto / x509 / verify.go
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package x509
6
7 import (
8         "bytes"
9         "errors"
10         "fmt"
11         "net"
12         "net/url"
13         "os"
14         "reflect"
15         "runtime"
16         "strings"
17         "time"
18         "unicode/utf8"
19 )
20
21 // ignoreCN disables interpreting Common Name as a hostname. See issue 24151.
22 var ignoreCN = !strings.Contains(os.Getenv("GODEBUG"), "x509ignoreCN=0")
23
24 type InvalidReason int
25
26 const (
27         // NotAuthorizedToSign results when a certificate is signed by another
28         // which isn't marked as a CA certificate.
29         NotAuthorizedToSign InvalidReason = iota
30         // Expired results when a certificate has expired, based on the time
31         // given in the VerifyOptions.
32         Expired
33         // CANotAuthorizedForThisName results when an intermediate or root
34         // certificate has a name constraint which doesn't permit a DNS or
35         // other name (including IP address) in the leaf certificate.
36         CANotAuthorizedForThisName
37         // TooManyIntermediates results when a path length constraint is
38         // violated.
39         TooManyIntermediates
40         // IncompatibleUsage results when the certificate's key usage indicates
41         // that it may only be used for a different purpose.
42         IncompatibleUsage
43         // NameMismatch results when the subject name of a parent certificate
44         // does not match the issuer name in the child.
45         NameMismatch
46         // NameConstraintsWithoutSANs results when a leaf certificate doesn't
47         // contain a Subject Alternative Name extension, but a CA certificate
48         // contains name constraints, and the Common Name can be interpreted as
49         // a hostname.
50         //
51         // This error is only returned when legacy Common Name matching is enabled
52         // by setting the GODEBUG environment variable to "x509ignoreCN=1". This
53         // setting might be removed in the future.
54         NameConstraintsWithoutSANs
55         // UnconstrainedName results when a CA certificate contains permitted
56         // name constraints, but leaf certificate contains a name of an
57         // unsupported or unconstrained type.
58         UnconstrainedName
59         // TooManyConstraints results when the number of comparison operations
60         // needed to check a certificate exceeds the limit set by
61         // VerifyOptions.MaxConstraintComparisions. This limit exists to
62         // prevent pathological certificates can consuming excessive amounts of
63         // CPU time to verify.
64         TooManyConstraints
65         // CANotAuthorizedForExtKeyUsage results when an intermediate or root
66         // certificate does not permit a requested extended key usage.
67         CANotAuthorizedForExtKeyUsage
68 )
69
70 // CertificateInvalidError results when an odd error occurs. Users of this
71 // library probably want to handle all these errors uniformly.
72 type CertificateInvalidError struct {
73         Cert   *Certificate
74         Reason InvalidReason
75         Detail string
76 }
77
78 func (e CertificateInvalidError) Error() string {
79         switch e.Reason {
80         case NotAuthorizedToSign:
81                 return "x509: certificate is not authorized to sign other certificates"
82         case Expired:
83                 return "x509: certificate has expired or is not yet valid: " + e.Detail
84         case CANotAuthorizedForThisName:
85                 return "x509: a root or intermediate certificate is not authorized to sign for this name: " + e.Detail
86         case CANotAuthorizedForExtKeyUsage:
87                 return "x509: a root or intermediate certificate is not authorized for an extended key usage: " + e.Detail
88         case TooManyIntermediates:
89                 return "x509: too many intermediates for path length constraint"
90         case IncompatibleUsage:
91                 return "x509: certificate specifies an incompatible key usage"
92         case NameMismatch:
93                 return "x509: issuer name does not match subject from issuing certificate"
94         case NameConstraintsWithoutSANs:
95                 return "x509: issuer has name constraints but leaf doesn't have a SAN extension"
96         case UnconstrainedName:
97                 return "x509: issuer has name constraints but leaf contains unknown or unconstrained name: " + e.Detail
98         }
99         return "x509: unknown error"
100 }
101
102 // HostnameError results when the set of authorized names doesn't match the
103 // requested name.
104 type HostnameError struct {
105         Certificate *Certificate
106         Host        string
107 }
108
109 func (h HostnameError) Error() string {
110         c := h.Certificate
111
112         if !c.hasSANExtension() && matchHostnames(c.Subject.CommonName, h.Host) {
113                 if !ignoreCN && !validHostnamePattern(c.Subject.CommonName) {
114                         // This would have validated, if it weren't for the validHostname check on Common Name.
115                         return "x509: Common Name is not a valid hostname: " + c.Subject.CommonName
116                 }
117                 if ignoreCN && validHostnamePattern(c.Subject.CommonName) {
118                         // This would have validated if x509ignoreCN=0 were set.
119                         return "x509: certificate relies on legacy Common Name field, " +
120                                 "use SANs or temporarily enable Common Name matching with GODEBUG=x509ignoreCN=0"
121                 }
122         }
123
124         var valid string
125         if ip := net.ParseIP(h.Host); ip != nil {
126                 // Trying to validate an IP
127                 if len(c.IPAddresses) == 0 {
128                         return "x509: cannot validate certificate for " + h.Host + " because it doesn't contain any IP SANs"
129                 }
130                 for _, san := range c.IPAddresses {
131                         if len(valid) > 0 {
132                                 valid += ", "
133                         }
134                         valid += san.String()
135                 }
136         } else {
137                 if c.commonNameAsHostname() {
138                         valid = c.Subject.CommonName
139                 } else {
140                         valid = strings.Join(c.DNSNames, ", ")
141                 }
142         }
143
144         if len(valid) == 0 {
145                 return "x509: certificate is not valid for any names, but wanted to match " + h.Host
146         }
147         return "x509: certificate is valid for " + valid + ", not " + h.Host
148 }
149
150 // UnknownAuthorityError results when the certificate issuer is unknown
151 type UnknownAuthorityError struct {
152         Cert *Certificate
153         // hintErr contains an error that may be helpful in determining why an
154         // authority wasn't found.
155         hintErr error
156         // hintCert contains a possible authority certificate that was rejected
157         // because of the error in hintErr.
158         hintCert *Certificate
159 }
160
161 func (e UnknownAuthorityError) Error() string {
162         s := "x509: certificate signed by unknown authority"
163         if e.hintErr != nil {
164                 certName := e.hintCert.Subject.CommonName
165                 if len(certName) == 0 {
166                         if len(e.hintCert.Subject.Organization) > 0 {
167                                 certName = e.hintCert.Subject.Organization[0]
168                         } else {
169                                 certName = "serial:" + e.hintCert.SerialNumber.String()
170                         }
171                 }
172                 s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName)
173         }
174         return s
175 }
176
177 // SystemRootsError results when we fail to load the system root certificates.
178 type SystemRootsError struct {
179         Err error
180 }
181
182 func (se SystemRootsError) Error() string {
183         msg := "x509: failed to load system roots and no roots provided"
184         if se.Err != nil {
185                 return msg + "; " + se.Err.Error()
186         }
187         return msg
188 }
189
190 func (se SystemRootsError) Unwrap() error { return se.Err }
191
192 // errNotParsed is returned when a certificate without ASN.1 contents is
193 // verified. Platform-specific verification needs the ASN.1 contents.
194 var errNotParsed = errors.New("x509: missing ASN.1 contents; use ParseCertificate")
195
196 // VerifyOptions contains parameters for Certificate.Verify.
197 type VerifyOptions struct {
198         // IsBoring is a validity check for BoringCrypto.
199         // If not nil, it will be called to check whether a given certificate
200         // can be used for constructing verification chains.
201         IsBoring func(*Certificate) bool
202
203         // DNSName, if set, is checked against the leaf certificate with
204         // Certificate.VerifyHostname or the platform verifier.
205         DNSName string
206
207         // Intermediates is an optional pool of certificates that are not trust
208         // anchors, but can be used to form a chain from the leaf certificate to a
209         // root certificate.
210         Intermediates *CertPool
211         // Roots is the set of trusted root certificates the leaf certificate needs
212         // to chain up to. If nil, the system roots or the platform verifier are used.
213         Roots *CertPool
214
215         // CurrentTime is used to check the validity of all certificates in the
216         // chain. If zero, the current time is used.
217         CurrentTime time.Time
218
219         // KeyUsages specifies which Extended Key Usage values are acceptable. A
220         // chain is accepted if it allows any of the listed values. An empty list
221         // means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny.
222         KeyUsages []ExtKeyUsage
223
224         // MaxConstraintComparisions is the maximum number of comparisons to
225         // perform when checking a given certificate's name constraints. If
226         // zero, a sensible default is used. This limit prevents pathological
227         // certificates from consuming excessive amounts of CPU time when
228         // validating. It does not apply to the platform verifier.
229         MaxConstraintComparisions int
230 }
231
232 const (
233         leafCertificate = iota
234         intermediateCertificate
235         rootCertificate
236 )
237
238 // rfc2821Mailbox represents a “mailbox” (which is an email address to most
239 // people) by breaking it into the “local” (i.e. before the '@') and “domain”
240 // parts.
241 type rfc2821Mailbox struct {
242         local, domain string
243 }
244
245 // parseRFC2821Mailbox parses an email address into local and domain parts,
246 // based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
247 // Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
248 // format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
249 func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
250         if len(in) == 0 {
251                 return mailbox, false
252         }
253
254         localPartBytes := make([]byte, 0, len(in)/2)
255
256         if in[0] == '"' {
257                 // Quoted-string = DQUOTE *qcontent DQUOTE
258                 // non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
259                 // qcontent = qtext / quoted-pair
260                 // qtext = non-whitespace-control /
261                 //         %d33 / %d35-91 / %d93-126
262                 // quoted-pair = ("\" text) / obs-qp
263                 // text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
264                 //
265                 // (Names beginning with “obs-” are the obsolete syntax from RFC 2822,
266                 // Section 4. Since it has been 16 years, we no longer accept that.)
267                 in = in[1:]
268         QuotedString:
269                 for {
270                         if len(in) == 0 {
271                                 return mailbox, false
272                         }
273                         c := in[0]
274                         in = in[1:]
275
276                         switch {
277                         case c == '"':
278                                 break QuotedString
279
280                         case c == '\\':
281                                 // quoted-pair
282                                 if len(in) == 0 {
283                                         return mailbox, false
284                                 }
285                                 if in[0] == 11 ||
286                                         in[0] == 12 ||
287                                         (1 <= in[0] && in[0] <= 9) ||
288                                         (14 <= in[0] && in[0] <= 127) {
289                                         localPartBytes = append(localPartBytes, in[0])
290                                         in = in[1:]
291                                 } else {
292                                         return mailbox, false
293                                 }
294
295                         case c == 11 ||
296                                 c == 12 ||
297                                 // Space (char 32) is not allowed based on the
298                                 // BNF, but RFC 3696 gives an example that
299                                 // assumes that it is. Several “verified”
300                                 // errata continue to argue about this point.
301                                 // We choose to accept it.
302                                 c == 32 ||
303                                 c == 33 ||
304                                 c == 127 ||
305                                 (1 <= c && c <= 8) ||
306                                 (14 <= c && c <= 31) ||
307                                 (35 <= c && c <= 91) ||
308                                 (93 <= c && c <= 126):
309                                 // qtext
310                                 localPartBytes = append(localPartBytes, c)
311
312                         default:
313                                 return mailbox, false
314                         }
315                 }
316         } else {
317                 // Atom ("." Atom)*
318         NextChar:
319                 for len(in) > 0 {
320                         // atext from RFC 2822, Section 3.2.4
321                         c := in[0]
322
323                         switch {
324                         case c == '\\':
325                                 // Examples given in RFC 3696 suggest that
326                                 // escaped characters can appear outside of a
327                                 // quoted string. Several “verified” errata
328                                 // continue to argue the point. We choose to
329                                 // accept it.
330                                 in = in[1:]
331                                 if len(in) == 0 {
332                                         return mailbox, false
333                                 }
334                                 fallthrough
335
336                         case ('0' <= c && c <= '9') ||
337                                 ('a' <= c && c <= 'z') ||
338                                 ('A' <= c && c <= 'Z') ||
339                                 c == '!' || c == '#' || c == '$' || c == '%' ||
340                                 c == '&' || c == '\'' || c == '*' || c == '+' ||
341                                 c == '-' || c == '/' || c == '=' || c == '?' ||
342                                 c == '^' || c == '_' || c == '`' || c == '{' ||
343                                 c == '|' || c == '}' || c == '~' || c == '.':
344                                 localPartBytes = append(localPartBytes, in[0])
345                                 in = in[1:]
346
347                         default:
348                                 break NextChar
349                         }
350                 }
351
352                 if len(localPartBytes) == 0 {
353                         return mailbox, false
354                 }
355
356                 // From RFC 3696, Section 3:
357                 // “period (".") may also appear, but may not be used to start
358                 // or end the local part, nor may two or more consecutive
359                 // periods appear.”
360                 twoDots := []byte{'.', '.'}
361                 if localPartBytes[0] == '.' ||
362                         localPartBytes[len(localPartBytes)-1] == '.' ||
363                         bytes.Contains(localPartBytes, twoDots) {
364                         return mailbox, false
365                 }
366         }
367
368         if len(in) == 0 || in[0] != '@' {
369                 return mailbox, false
370         }
371         in = in[1:]
372
373         // The RFC species a format for domains, but that's known to be
374         // violated in practice so we accept that anything after an '@' is the
375         // domain part.
376         if _, ok := domainToReverseLabels(in); !ok {
377                 return mailbox, false
378         }
379
380         mailbox.local = string(localPartBytes)
381         mailbox.domain = in
382         return mailbox, true
383 }
384
385 // domainToReverseLabels converts a textual domain name like foo.example.com to
386 // the list of labels in reverse order, e.g. ["com", "example", "foo"].
387 func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
388         for len(domain) > 0 {
389                 if i := strings.LastIndexByte(domain, '.'); i == -1 {
390                         reverseLabels = append(reverseLabels, domain)
391                         domain = ""
392                 } else {
393                         reverseLabels = append(reverseLabels, domain[i+1:])
394                         domain = domain[:i]
395                 }
396         }
397
398         if len(reverseLabels) > 0 && len(reverseLabels[0]) == 0 {
399                 // An empty label at the end indicates an absolute value.
400                 return nil, false
401         }
402
403         for _, label := range reverseLabels {
404                 if len(label) == 0 {
405                         // Empty labels are otherwise invalid.
406                         return nil, false
407                 }
408
409                 for _, c := range label {
410                         if c < 33 || c > 126 {
411                                 // Invalid character.
412                                 return nil, false
413                         }
414                 }
415         }
416
417         return reverseLabels, true
418 }
419
420 func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
421         // If the constraint contains an @, then it specifies an exact mailbox
422         // name.
423         if strings.Contains(constraint, "@") {
424                 constraintMailbox, ok := parseRFC2821Mailbox(constraint)
425                 if !ok {
426                         return false, fmt.Errorf("x509: internal error: cannot parse constraint %q", constraint)
427                 }
428                 return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
429         }
430
431         // Otherwise the constraint is like a DNS constraint of the domain part
432         // of the mailbox.
433         return matchDomainConstraint(mailbox.domain, constraint)
434 }
435
436 func matchURIConstraint(uri *url.URL, constraint string) (bool, error) {
437         // From RFC 5280, Section 4.2.1.10:
438         // “a uniformResourceIdentifier that does not include an authority
439         // component with a host name specified as a fully qualified domain
440         // name (e.g., if the URI either does not include an authority
441         // component or includes an authority component in which the host name
442         // is specified as an IP address), then the application MUST reject the
443         // certificate.”
444
445         host := uri.Host
446         if len(host) == 0 {
447                 return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
448         }
449
450         if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
451                 var err error
452                 host, _, err = net.SplitHostPort(uri.Host)
453                 if err != nil {
454                         return false, err
455                 }
456         }
457
458         if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") ||
459                 net.ParseIP(host) != nil {
460                 return false, fmt.Errorf("URI with IP (%q) cannot be matched against constraints", uri.String())
461         }
462
463         return matchDomainConstraint(host, constraint)
464 }
465
466 func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
467         if len(ip) != len(constraint.IP) {
468                 return false, nil
469         }
470
471         for i := range ip {
472                 if mask := constraint.Mask[i]; ip[i]&mask != constraint.IP[i]&mask {
473                         return false, nil
474                 }
475         }
476
477         return true, nil
478 }
479
480 func matchDomainConstraint(domain, constraint string) (bool, error) {
481         // The meaning of zero length constraints is not specified, but this
482         // code follows NSS and accepts them as matching everything.
483         if len(constraint) == 0 {
484                 return true, nil
485         }
486
487         domainLabels, ok := domainToReverseLabels(domain)
488         if !ok {
489                 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", domain)
490         }
491
492         // RFC 5280 says that a leading period in a domain name means that at
493         // least one label must be prepended, but only for URI and email
494         // constraints, not DNS constraints. The code also supports that
495         // behaviour for DNS constraints.
496
497         mustHaveSubdomains := false
498         if constraint[0] == '.' {
499                 mustHaveSubdomains = true
500                 constraint = constraint[1:]
501         }
502
503         constraintLabels, ok := domainToReverseLabels(constraint)
504         if !ok {
505                 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", constraint)
506         }
507
508         if len(domainLabels) < len(constraintLabels) ||
509                 (mustHaveSubdomains && len(domainLabels) == len(constraintLabels)) {
510                 return false, nil
511         }
512
513         for i, constraintLabel := range constraintLabels {
514                 if !strings.EqualFold(constraintLabel, domainLabels[i]) {
515                         return false, nil
516                 }
517         }
518
519         return true, nil
520 }
521
522 // checkNameConstraints checks that c permits a child certificate to claim the
523 // given name, of type nameType. The argument parsedName contains the parsed
524 // form of name, suitable for passing to the match function. The total number
525 // of comparisons is tracked in the given count and should not exceed the given
526 // limit.
527 func (c *Certificate) checkNameConstraints(count *int,
528         maxConstraintComparisons int,
529         nameType string,
530         name string,
531         parsedName interface{},
532         match func(parsedName, constraint interface{}) (match bool, err error),
533         permitted, excluded interface{}) error {
534
535         excludedValue := reflect.ValueOf(excluded)
536
537         *count += excludedValue.Len()
538         if *count > maxConstraintComparisons {
539                 return CertificateInvalidError{c, TooManyConstraints, ""}
540         }
541
542         for i := 0; i < excludedValue.Len(); i++ {
543                 constraint := excludedValue.Index(i).Interface()
544                 match, err := match(parsedName, constraint)
545                 if err != nil {
546                         return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
547                 }
548
549                 if match {
550                         return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint)}
551                 }
552         }
553
554         permittedValue := reflect.ValueOf(permitted)
555
556         *count += permittedValue.Len()
557         if *count > maxConstraintComparisons {
558                 return CertificateInvalidError{c, TooManyConstraints, ""}
559         }
560
561         ok := true
562         for i := 0; i < permittedValue.Len(); i++ {
563                 constraint := permittedValue.Index(i).Interface()
564
565                 var err error
566                 if ok, err = match(parsedName, constraint); err != nil {
567                         return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
568                 }
569
570                 if ok {
571                         break
572                 }
573         }
574
575         if !ok {
576                 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name)}
577         }
578
579         return nil
580 }
581
582 // isValid performs validity checks on c given that it is a candidate to append
583 // to the chain in currentChain.
584 func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
585         if len(c.UnhandledCriticalExtensions) > 0 {
586                 return UnhandledCriticalExtension{}
587         }
588
589         if len(currentChain) > 0 {
590                 child := currentChain[len(currentChain)-1]
591                 if !bytes.Equal(child.RawIssuer, c.RawSubject) {
592                         return CertificateInvalidError{c, NameMismatch, ""}
593                 }
594         }
595
596         now := opts.CurrentTime
597         if now.IsZero() {
598                 now = time.Now()
599         }
600         if now.Before(c.NotBefore) {
601                 return CertificateInvalidError{
602                         Cert:   c,
603                         Reason: Expired,
604                         Detail: fmt.Sprintf("current time %s is before %s", now.Format(time.RFC3339), c.NotBefore.Format(time.RFC3339)),
605                 }
606         } else if now.After(c.NotAfter) {
607                 return CertificateInvalidError{
608                         Cert:   c,
609                         Reason: Expired,
610                         Detail: fmt.Sprintf("current time %s is after %s", now.Format(time.RFC3339), c.NotAfter.Format(time.RFC3339)),
611                 }
612         }
613
614         maxConstraintComparisons := opts.MaxConstraintComparisions
615         if maxConstraintComparisons == 0 {
616                 maxConstraintComparisons = 250000
617         }
618         comparisonCount := 0
619
620         var leaf *Certificate
621         if certType == intermediateCertificate || certType == rootCertificate {
622                 if len(currentChain) == 0 {
623                         return errors.New("x509: internal error: empty chain when appending CA cert")
624                 }
625                 leaf = currentChain[0]
626         }
627
628         checkNameConstraints := (certType == intermediateCertificate || certType == rootCertificate) && c.hasNameConstraints()
629         if checkNameConstraints && leaf.commonNameAsHostname() {
630                 // This is the deprecated, legacy case of depending on the commonName as
631                 // a hostname. We don't enforce name constraints against the CN, but
632                 // VerifyHostname will look for hostnames in there if there are no SANs.
633                 // In order to ensure VerifyHostname will not accept an unchecked name,
634                 // return an error here.
635                 return CertificateInvalidError{c, NameConstraintsWithoutSANs, ""}
636         } else if checkNameConstraints && leaf.hasSANExtension() {
637                 err := forEachSAN(leaf.getSANExtension(), func(tag int, data []byte) error {
638                         switch tag {
639                         case nameTypeEmail:
640                                 name := string(data)
641                                 mailbox, ok := parseRFC2821Mailbox(name)
642                                 if !ok {
643                                         return fmt.Errorf("x509: cannot parse rfc822Name %q", mailbox)
644                                 }
645
646                                 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "email address", name, mailbox,
647                                         func(parsedName, constraint interface{}) (bool, error) {
648                                                 return matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string))
649                                         }, c.PermittedEmailAddresses, c.ExcludedEmailAddresses); err != nil {
650                                         return err
651                                 }
652
653                         case nameTypeDNS:
654                                 name := string(data)
655                                 if _, ok := domainToReverseLabels(name); !ok {
656                                         return fmt.Errorf("x509: cannot parse dnsName %q", name)
657                                 }
658
659                                 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "DNS name", name, name,
660                                         func(parsedName, constraint interface{}) (bool, error) {
661                                                 return matchDomainConstraint(parsedName.(string), constraint.(string))
662                                         }, c.PermittedDNSDomains, c.ExcludedDNSDomains); err != nil {
663                                         return err
664                                 }
665
666                         case nameTypeURI:
667                                 name := string(data)
668                                 uri, err := url.Parse(name)
669                                 if err != nil {
670                                         return fmt.Errorf("x509: internal error: URI SAN %q failed to parse", name)
671                                 }
672
673                                 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "URI", name, uri,
674                                         func(parsedName, constraint interface{}) (bool, error) {
675                                                 return matchURIConstraint(parsedName.(*url.URL), constraint.(string))
676                                         }, c.PermittedURIDomains, c.ExcludedURIDomains); err != nil {
677                                         return err
678                                 }
679
680                         case nameTypeIP:
681                                 ip := net.IP(data)
682                                 if l := len(ip); l != net.IPv4len && l != net.IPv6len {
683                                         return fmt.Errorf("x509: internal error: IP SAN %x failed to parse", data)
684                                 }
685
686                                 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "IP address", ip.String(), ip,
687                                         func(parsedName, constraint interface{}) (bool, error) {
688                                                 return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet))
689                                         }, c.PermittedIPRanges, c.ExcludedIPRanges); err != nil {
690                                         return err
691                                 }
692
693                         default:
694                                 // Unknown SAN types are ignored.
695                         }
696
697                         return nil
698                 })
699
700                 if err != nil {
701                         return err
702                 }
703         }
704
705         // KeyUsage status flags are ignored. From Engineering Security, Peter
706         // Gutmann: A European government CA marked its signing certificates as
707         // being valid for encryption only, but no-one noticed. Another
708         // European CA marked its signature keys as not being valid for
709         // signatures. A different CA marked its own trusted root certificate
710         // as being invalid for certificate signing. Another national CA
711         // distributed a certificate to be used to encrypt data for the
712         // country’s tax authority that was marked as only being usable for
713         // digital signatures but not for encryption. Yet another CA reversed
714         // the order of the bit flags in the keyUsage due to confusion over
715         // encoding endianness, essentially setting a random keyUsage in
716         // certificates that it issued. Another CA created a self-invalidating
717         // certificate by adding a certificate policy statement stipulating
718         // that the certificate had to be used strictly as specified in the
719         // keyUsage, and a keyUsage containing a flag indicating that the RSA
720         // encryption key could only be used for Diffie-Hellman key agreement.
721
722         if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
723                 return CertificateInvalidError{c, NotAuthorizedToSign, ""}
724         }
725
726         if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
727                 numIntermediates := len(currentChain) - 1
728                 if numIntermediates > c.MaxPathLen {
729                         return CertificateInvalidError{c, TooManyIntermediates, ""}
730                 }
731         }
732
733         if opts.IsBoring != nil && !opts.IsBoring(c) {
734                 // IncompatibleUsage is not quite right here,
735                 // but it's also the "no chains found" error
736                 // and is close enough.
737                 return CertificateInvalidError{c, IncompatibleUsage, ""}
738         }
739
740         return nil
741 }
742
743 // Verify attempts to verify c by building one or more chains from c to a
744 // certificate in opts.Roots, using certificates in opts.Intermediates if
745 // needed. If successful, it returns one or more chains where the first
746 // element of the chain is c and the last element is from opts.Roots.
747 //
748 // If opts.Roots is nil, the platform verifier might be used, and
749 // verification details might differ from what is described below. If system
750 // roots are unavailable the returned error will be of type SystemRootsError.
751 //
752 // Name constraints in the intermediates will be applied to all names claimed
753 // in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim
754 // example.com if an intermediate doesn't permit it, even if example.com is not
755 // the name being validated. Note that DirectoryName constraints are not
756 // supported.
757 //
758 // Name constraint validation follows the rules from RFC 5280, with the
759 // addition that DNS name constraints may use the leading period format
760 // defined for emails and URIs. When a constraint has a leading period
761 // it indicates that at least one additional label must be prepended to
762 // the constrained name to be considered valid.
763 //
764 // Extended Key Usage values are enforced nested down a chain, so an intermediate
765 // or root that enumerates EKUs prevents a leaf from asserting an EKU not in that
766 // list. (While this is not specified, it is common practice in order to limit
767 // the types of certificates a CA can issue.)
768 //
769 // WARNING: this function doesn't do any revocation checking.
770 func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) {
771         // Platform-specific verification needs the ASN.1 contents so
772         // this makes the behavior consistent across platforms.
773         if len(c.Raw) == 0 {
774                 return nil, errNotParsed
775         }
776         for i := 0; i < opts.Intermediates.len(); i++ {
777                 c, err := opts.Intermediates.cert(i)
778                 if err != nil {
779                         return nil, fmt.Errorf("crypto/x509: error fetching intermediate: %w", err)
780                 }
781                 if len(c.Raw) == 0 {
782                         return nil, errNotParsed
783                 }
784         }
785
786         // Use Windows's own verification and chain building.
787         if opts.Roots == nil && runtime.GOOS == "windows" {
788                 return c.systemVerify(&opts)
789         }
790
791         if opts.Roots == nil {
792                 opts.Roots = systemRootsPool()
793                 if opts.Roots == nil {
794                         return nil, SystemRootsError{systemRootsErr}
795                 }
796         }
797
798         err = c.isValid(leafCertificate, nil, &opts)
799         if err != nil {
800                 return
801         }
802
803         if len(opts.DNSName) > 0 {
804                 err = c.VerifyHostname(opts.DNSName)
805                 if err != nil {
806                         return
807                 }
808         }
809
810         var candidateChains [][]*Certificate
811         if opts.Roots.contains(c) {
812                 candidateChains = append(candidateChains, []*Certificate{c})
813         } else {
814                 if candidateChains, err = c.buildChains(nil, []*Certificate{c}, nil, &opts); err != nil {
815                         return nil, err
816                 }
817         }
818
819         keyUsages := opts.KeyUsages
820         if len(keyUsages) == 0 {
821                 keyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
822         }
823
824         // If any key usage is acceptable then we're done.
825         for _, usage := range keyUsages {
826                 if usage == ExtKeyUsageAny {
827                         return candidateChains, nil
828                 }
829         }
830
831         for _, candidate := range candidateChains {
832                 if checkChainForKeyUsage(candidate, keyUsages) {
833                         chains = append(chains, candidate)
834                 }
835         }
836
837         if len(chains) == 0 {
838                 return nil, CertificateInvalidError{c, IncompatibleUsage, ""}
839         }
840
841         return chains, nil
842 }
843
844 func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate {
845         n := make([]*Certificate, len(chain)+1)
846         copy(n, chain)
847         n[len(chain)] = cert
848         return n
849 }
850
851 // maxChainSignatureChecks is the maximum number of CheckSignatureFrom calls
852 // that an invocation of buildChains will (tranistively) make. Most chains are
853 // less than 15 certificates long, so this leaves space for multiple chains and
854 // for failed checks due to different intermediates having the same Subject.
855 const maxChainSignatureChecks = 100
856
857 func (c *Certificate) buildChains(cache map[*Certificate][][]*Certificate, currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error) {
858         var (
859                 hintErr  error
860                 hintCert *Certificate
861         )
862
863         considerCandidate := func(certType int, candidate *Certificate) {
864                 for _, cert := range currentChain {
865                         if cert.Equal(candidate) {
866                                 return
867                         }
868                 }
869
870                 if sigChecks == nil {
871                         sigChecks = new(int)
872                 }
873                 *sigChecks++
874                 if *sigChecks > maxChainSignatureChecks {
875                         err = errors.New("x509: signature check attempts limit reached while verifying certificate chain")
876                         return
877                 }
878
879                 if err := c.CheckSignatureFrom(candidate); err != nil {
880                         if hintErr == nil {
881                                 hintErr = err
882                                 hintCert = candidate
883                         }
884                         return
885                 }
886
887                 err = candidate.isValid(certType, currentChain, opts)
888                 if err != nil {
889                         return
890                 }
891
892                 switch certType {
893                 case rootCertificate:
894                         chains = append(chains, appendToFreshChain(currentChain, candidate))
895                 case intermediateCertificate:
896                         if cache == nil {
897                                 cache = make(map[*Certificate][][]*Certificate)
898                         }
899                         childChains, ok := cache[candidate]
900                         if !ok {
901                                 childChains, err = candidate.buildChains(cache, appendToFreshChain(currentChain, candidate), sigChecks, opts)
902                                 cache[candidate] = childChains
903                         }
904                         chains = append(chains, childChains...)
905                 }
906         }
907
908         for _, root := range opts.Roots.findPotentialParents(c) {
909                 considerCandidate(rootCertificate, root)
910         }
911         for _, intermediate := range opts.Intermediates.findPotentialParents(c) {
912                 considerCandidate(intermediateCertificate, intermediate)
913         }
914
915         if len(chains) > 0 {
916                 err = nil
917         }
918         if len(chains) == 0 && err == nil {
919                 err = UnknownAuthorityError{c, hintErr, hintCert}
920         }
921
922         return
923 }
924
925 func validHostnamePattern(host string) bool { return validHostname(host, true) }
926 func validHostnameInput(host string) bool   { return validHostname(host, false) }
927
928 // validHostname reports whether host is a valid hostname that can be matched or
929 // matched against according to RFC 6125 2.2, with some leniency to accommodate
930 // legacy values.
931 func validHostname(host string, isPattern bool) bool {
932         if !isPattern {
933                 host = strings.TrimSuffix(host, ".")
934         }
935         if len(host) == 0 {
936                 return false
937         }
938
939         for i, part := range strings.Split(host, ".") {
940                 if part == "" {
941                         // Empty label.
942                         return false
943                 }
944                 if isPattern && i == 0 && part == "*" {
945                         // Only allow full left-most wildcards, as those are the only ones
946                         // we match, and matching literal '*' characters is probably never
947                         // the expected behavior.
948                         continue
949                 }
950                 for j, c := range part {
951                         if 'a' <= c && c <= 'z' {
952                                 continue
953                         }
954                         if '0' <= c && c <= '9' {
955                                 continue
956                         }
957                         if 'A' <= c && c <= 'Z' {
958                                 continue
959                         }
960                         if c == '-' && j != 0 {
961                                 continue
962                         }
963                         if c == '_' {
964                                 // Not a valid character in hostnames, but commonly
965                                 // found in deployments outside the WebPKI.
966                                 continue
967                         }
968                         return false
969                 }
970         }
971
972         return true
973 }
974
975 // commonNameAsHostname reports whether the Common Name field should be
976 // considered the hostname that the certificate is valid for. This is a legacy
977 // behavior, disabled by default or if the Subject Alt Name extension is present.
978 //
979 // It applies the strict validHostname check to the Common Name field, so that
980 // certificates without SANs can still be validated against CAs with name
981 // constraints if there is no risk the CN would be matched as a hostname.
982 // See NameConstraintsWithoutSANs and issue 24151.
983 func (c *Certificate) commonNameAsHostname() bool {
984         return !ignoreCN && !c.hasSANExtension() && validHostnamePattern(c.Subject.CommonName)
985 }
986
987 func matchExactly(hostA, hostB string) bool {
988         if hostA == "" || hostA == "." || hostB == "" || hostB == "." {
989                 return false
990         }
991         return toLowerCaseASCII(hostA) == toLowerCaseASCII(hostB)
992 }
993
994 func matchHostnames(pattern, host string) bool {
995         pattern = toLowerCaseASCII(pattern)
996         host = toLowerCaseASCII(strings.TrimSuffix(host, "."))
997
998         if len(pattern) == 0 || len(host) == 0 {
999                 return false
1000         }
1001
1002         patternParts := strings.Split(pattern, ".")
1003         hostParts := strings.Split(host, ".")
1004
1005         if len(patternParts) != len(hostParts) {
1006                 return false
1007         }
1008
1009         for i, patternPart := range patternParts {
1010                 if i == 0 && patternPart == "*" {
1011                         continue
1012                 }
1013                 if patternPart != hostParts[i] {
1014                         return false
1015                 }
1016         }
1017
1018         return true
1019 }
1020
1021 // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
1022 // an explicitly ASCII function to avoid any sharp corners resulting from
1023 // performing Unicode operations on DNS labels.
1024 func toLowerCaseASCII(in string) string {
1025         // If the string is already lower-case then there's nothing to do.
1026         isAlreadyLowerCase := true
1027         for _, c := range in {
1028                 if c == utf8.RuneError {
1029                         // If we get a UTF-8 error then there might be
1030                         // upper-case ASCII bytes in the invalid sequence.
1031                         isAlreadyLowerCase = false
1032                         break
1033                 }
1034                 if 'A' <= c && c <= 'Z' {
1035                         isAlreadyLowerCase = false
1036                         break
1037                 }
1038         }
1039
1040         if isAlreadyLowerCase {
1041                 return in
1042         }
1043
1044         out := []byte(in)
1045         for i, c := range out {
1046                 if 'A' <= c && c <= 'Z' {
1047                         out[i] += 'a' - 'A'
1048                 }
1049         }
1050         return string(out)
1051 }
1052
1053 // VerifyHostname returns nil if c is a valid certificate for the named host.
1054 // Otherwise it returns an error describing the mismatch.
1055 //
1056 // IP addresses can be optionally enclosed in square brackets and are checked
1057 // against the IPAddresses field. Other names are checked case insensitively
1058 // against the DNSNames field. If the names are valid hostnames, the certificate
1059 // fields can have a wildcard as the left-most label.
1060 //
1061 // The legacy Common Name field is ignored unless it's a valid hostname, the
1062 // certificate doesn't have any Subject Alternative Names, and the GODEBUG
1063 // environment variable is set to "x509ignoreCN=0". Support for Common Name is
1064 // deprecated will be entirely removed in the future.
1065 func (c *Certificate) VerifyHostname(h string) error {
1066         // IP addresses may be written in [ ].
1067         candidateIP := h
1068         if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
1069                 candidateIP = h[1 : len(h)-1]
1070         }
1071         if ip := net.ParseIP(candidateIP); ip != nil {
1072                 // We only match IP addresses against IP SANs.
1073                 // See RFC 6125, Appendix B.2.
1074                 for _, candidate := range c.IPAddresses {
1075                         if ip.Equal(candidate) {
1076                                 return nil
1077                         }
1078                 }
1079                 return HostnameError{c, candidateIP}
1080         }
1081
1082         names := c.DNSNames
1083         if c.commonNameAsHostname() {
1084                 names = []string{c.Subject.CommonName}
1085         }
1086
1087         candidateName := toLowerCaseASCII(h) // Save allocations inside the loop.
1088         validCandidateName := validHostnameInput(candidateName)
1089
1090         for _, match := range names {
1091                 // Ideally, we'd only match valid hostnames according to RFC 6125 like
1092                 // browsers (more or less) do, but in practice Go is used in a wider
1093                 // array of contexts and can't even assume DNS resolution. Instead,
1094                 // always allow perfect matches, and only apply wildcard and trailing
1095                 // dot processing to valid hostnames.
1096                 if validCandidateName && validHostnamePattern(match) {
1097                         if matchHostnames(match, candidateName) {
1098                                 return nil
1099                         }
1100                 } else {
1101                         if matchExactly(match, candidateName) {
1102                                 return nil
1103                         }
1104                 }
1105         }
1106
1107         return HostnameError{c, h}
1108 }
1109
1110 func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
1111         usages := make([]ExtKeyUsage, len(keyUsages))
1112         copy(usages, keyUsages)
1113
1114         if len(chain) == 0 {
1115                 return false
1116         }
1117
1118         usagesRemaining := len(usages)
1119
1120         // We walk down the list and cross out any usages that aren't supported
1121         // by each certificate. If we cross out all the usages, then the chain
1122         // is unacceptable.
1123
1124 NextCert:
1125         for i := len(chain) - 1; i >= 0; i-- {
1126                 cert := chain[i]
1127                 if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
1128                         // The certificate doesn't have any extended key usage specified.
1129                         continue
1130                 }
1131
1132                 for _, usage := range cert.ExtKeyUsage {
1133                         if usage == ExtKeyUsageAny {
1134                                 // The certificate is explicitly good for any usage.
1135                                 continue NextCert
1136                         }
1137                 }
1138
1139                 const invalidUsage ExtKeyUsage = -1
1140
1141         NextRequestedUsage:
1142                 for i, requestedUsage := range usages {
1143                         if requestedUsage == invalidUsage {
1144                                 continue
1145                         }
1146
1147                         for _, usage := range cert.ExtKeyUsage {
1148                                 if requestedUsage == usage {
1149                                         continue NextRequestedUsage
1150                                 } else if requestedUsage == ExtKeyUsageServerAuth &&
1151                                         (usage == ExtKeyUsageNetscapeServerGatedCrypto ||
1152                                                 usage == ExtKeyUsageMicrosoftServerGatedCrypto) {
1153                                         // In order to support COMODO
1154                                         // certificate chains, we have to
1155                                         // accept Netscape or Microsoft SGC
1156                                         // usages as equal to ServerAuth.
1157                                         continue NextRequestedUsage
1158                                 }
1159                         }
1160
1161                         usages[i] = invalidUsage
1162                         usagesRemaining--
1163                         if usagesRemaining == 0 {
1164                                 return false
1165                         }
1166                 }
1167         }
1168
1169         return true
1170 }