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