github.com/insolar/x-crypto@v0.0.0-20191031140942-75fab8a325f6/x509/verify.go (about)

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