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