github.com/hellobchain/newcryptosm@v0.0.0-20221019060107-edb949a317e9/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  // Verify attempts to verify c by building one or more chains from c to a
   707  // certificate in opts.Roots, using certificates in opts.Intermediates if
   708  // needed. If successful, it returns one or more chains where the first
   709  // element of the chain is c and the last element is from opts.Roots.
   710  //
   711  // If opts.Roots is nil and system roots are unavailable the returned error
   712  // will be of type SystemRootsError.
   713  //
   714  // Name constraints in the intermediates will be applied to all names claimed
   715  // in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim
   716  // example.com if an intermediate doesn't permit it, even if example.com is not
   717  // the name being validated. Note that DirectoryName constraints are not
   718  // supported.
   719  //
   720  // Extended Key Usage values are enforced down a chain, so an intermediate or
   721  // root that enumerates EKUs prevents a leaf from asserting an EKU not in that
   722  // list.
   723  //
   724  // WARNING: this function doesn't do any revocation checking.
   725  func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) {
   726  	// Platform-specific verification needs the ASN.1 contents so
   727  	// this makes the behavior consistent across platforms.
   728  	if len(c.Raw) == 0 {
   729  		return nil, errNotParsed
   730  	}
   731  	if opts.Intermediates != nil {
   732  		for _, intermediate := range opts.Intermediates.certs {
   733  			if len(intermediate.Raw) == 0 {
   734  				return nil, errNotParsed
   735  			}
   736  		}
   737  	}
   738  
   739  	// Use Windows's own verification and chain building.
   740  	// if opts.Roots == nil && runtime.GOOS == "windows" {
   741  	// 	return c.systemVerify(&opts)
   742  	// }
   743  
   744  	// if opts.Roots == nil {
   745  	// 	opts.Roots = systemRootsPool()
   746  	// 	if opts.Roots == nil {
   747  	// 		return nil, SystemRootsError{systemRootsErr}
   748  	// 	}
   749  	// }
   750  
   751  	err = c.isValid(leafCertificate, nil, &opts)
   752  	if err != nil {
   753  		return
   754  	}
   755  
   756  	if len(opts.DNSName) > 0 {
   757  		err = c.VerifyHostname(opts.DNSName)
   758  		if err != nil {
   759  			return
   760  		}
   761  	}
   762  
   763  	var candidateChains [][]*Certificate
   764  	if opts.Roots.contains(c) {
   765  		candidateChains = append(candidateChains, []*Certificate{c})
   766  	} else {
   767  		if candidateChains, err = c.buildChains(make(map[int][][]*Certificate), []*Certificate{c}, &opts); err != nil {
   768  			return nil, err
   769  		}
   770  	}
   771  
   772  	keyUsages := opts.KeyUsages
   773  	if len(keyUsages) == 0 {
   774  		keyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
   775  	}
   776  
   777  	// If any key usage is acceptable then we're done.
   778  	for _, usage := range keyUsages {
   779  		if usage == ExtKeyUsageAny {
   780  			return candidateChains, nil
   781  		}
   782  	}
   783  
   784  	for _, candidate := range candidateChains {
   785  		if checkChainForKeyUsage(candidate, keyUsages) {
   786  			chains = append(chains, candidate)
   787  		}
   788  	}
   789  
   790  	if len(chains) == 0 {
   791  		return nil, CertificateInvalidError{c, IncompatibleUsage, ""}
   792  	}
   793  
   794  	return chains, nil
   795  }
   796  
   797  func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate {
   798  	n := make([]*Certificate, len(chain)+1)
   799  	copy(n, chain)
   800  	n[len(chain)] = cert
   801  	return n
   802  }
   803  
   804  func (c *Certificate) buildChains(cache map[int][][]*Certificate, currentChain []*Certificate, opts *VerifyOptions) (chains [][]*Certificate, err error) {
   805  	possibleRoots, failedRoot, rootErr := opts.Roots.findVerifiedParents(c)
   806  nextRoot:
   807  	for _, rootNum := range possibleRoots {
   808  		root := opts.Roots.certs[rootNum]
   809  
   810  		for _, cert := range currentChain {
   811  			if cert.Equal(root) {
   812  				continue nextRoot
   813  			}
   814  		}
   815  
   816  		err = root.isValid(rootCertificate, currentChain, opts)
   817  		if err != nil {
   818  			continue
   819  		}
   820  		chains = append(chains, appendToFreshChain(currentChain, root))
   821  	}
   822  
   823  	possibleIntermediates, failedIntermediate, intermediateErr := opts.Intermediates.findVerifiedParents(c)
   824  nextIntermediate:
   825  	for _, intermediateNum := range possibleIntermediates {
   826  		intermediate := opts.Intermediates.certs[intermediateNum]
   827  		for _, cert := range currentChain {
   828  			if cert.Equal(intermediate) {
   829  				continue nextIntermediate
   830  			}
   831  		}
   832  		err = intermediate.isValid(intermediateCertificate, currentChain, opts)
   833  		if err != nil {
   834  			continue
   835  		}
   836  		var childChains [][]*Certificate
   837  		childChains, ok := cache[intermediateNum]
   838  		if !ok {
   839  			childChains, err = intermediate.buildChains(cache, appendToFreshChain(currentChain, intermediate), opts)
   840  			cache[intermediateNum] = childChains
   841  		}
   842  		chains = append(chains, childChains...)
   843  	}
   844  
   845  	if len(chains) > 0 {
   846  		err = nil
   847  	}
   848  
   849  	if len(chains) == 0 && err == nil {
   850  		hintErr := rootErr
   851  		hintCert := failedRoot
   852  		if hintErr == nil {
   853  			hintErr = intermediateErr
   854  			hintCert = failedIntermediate
   855  		}
   856  		err = UnknownAuthorityError{c, hintErr, hintCert}
   857  	}
   858  
   859  	return
   860  }
   861  
   862  // validHostname returns whether host is a valid hostname that can be matched or
   863  // matched against according to RFC 6125 2.2, with some leniency to accomodate
   864  // legacy values.
   865  func validHostname(host string) bool {
   866  	host = strings.TrimSuffix(host, ".")
   867  
   868  	if len(host) == 0 {
   869  		return false
   870  	}
   871  
   872  	for i, part := range strings.Split(host, ".") {
   873  		if part == "" {
   874  			// Empty label.
   875  			return false
   876  		}
   877  		if i == 0 && part == "*" {
   878  			// Only allow full left-most wildcards, as those are the only ones
   879  			// we match, and matching literal '*' characters is probably never
   880  			// the expected behavior.
   881  			continue
   882  		}
   883  		for j, c := range part {
   884  			if 'a' <= c && c <= 'z' {
   885  				continue
   886  			}
   887  			if '0' <= c && c <= '9' {
   888  				continue
   889  			}
   890  			if 'A' <= c && c <= 'Z' {
   891  				continue
   892  			}
   893  			if c == '-' && j != 0 {
   894  				continue
   895  			}
   896  			if c == '_' {
   897  				// _ is not a valid character in hostnames, but it's commonly
   898  				// found in deployments outside the WebPKI.
   899  				continue
   900  			}
   901  			return false
   902  		}
   903  	}
   904  
   905  	return true
   906  }
   907  
   908  // commonNameAsHostname reports whether the Common Name field should be
   909  // considered the hostname that the certificate is valid for. This is a legacy
   910  // behavior, disabled if the Subject Alt Name extension is present.
   911  //
   912  // It applies the strict validHostname check to the Common Name field, so that
   913  // certificates without SANs can still be validated against CAs with name
   914  // constraints if there is no risk the CN would be matched as a hostname.
   915  // See NameConstraintsWithoutSANs and issue 24151.
   916  func (c *Certificate) commonNameAsHostname() bool {
   917  	return !ignoreCN && !c.hasSANExtension() && validHostname(c.Subject.CommonName)
   918  }
   919  
   920  func matchHostnames(pattern, host string) bool {
   921  	host = strings.TrimSuffix(host, ".")
   922  	pattern = strings.TrimSuffix(pattern, ".")
   923  
   924  	if len(pattern) == 0 || len(host) == 0 {
   925  		return false
   926  	}
   927  
   928  	patternParts := strings.Split(pattern, ".")
   929  	hostParts := strings.Split(host, ".")
   930  
   931  	if len(patternParts) != len(hostParts) {
   932  		return false
   933  	}
   934  
   935  	for i, patternPart := range patternParts {
   936  		if i == 0 && patternPart == "*" {
   937  			continue
   938  		}
   939  		if patternPart != hostParts[i] {
   940  			return false
   941  		}
   942  	}
   943  
   944  	return true
   945  }
   946  
   947  // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
   948  // an explicitly ASCII function to avoid any sharp corners resulting from
   949  // performing Unicode operations on DNS labels.
   950  func toLowerCaseASCII(in string) string {
   951  	// If the string is already lower-case then there's nothing to do.
   952  	isAlreadyLowerCase := true
   953  	for _, c := range in {
   954  		if c == utf8.RuneError {
   955  			// If we get a UTF-8 error then there might be
   956  			// upper-case ASCII bytes in the invalid sequence.
   957  			isAlreadyLowerCase = false
   958  			break
   959  		}
   960  		if 'A' <= c && c <= 'Z' {
   961  			isAlreadyLowerCase = false
   962  			break
   963  		}
   964  	}
   965  
   966  	if isAlreadyLowerCase {
   967  		return in
   968  	}
   969  
   970  	out := []byte(in)
   971  	for i, c := range out {
   972  		if 'A' <= c && c <= 'Z' {
   973  			out[i] += 'a' - 'A'
   974  		}
   975  	}
   976  	return string(out)
   977  }
   978  
   979  // VerifyHostname returns nil if c is a valid certificate for the named host.
   980  // Otherwise it returns an error describing the mismatch.
   981  func (c *Certificate) VerifyHostname(h string) error {
   982  	// IP addresses may be written in [ ].
   983  	candidateIP := h
   984  	if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
   985  		candidateIP = h[1 : len(h)-1]
   986  	}
   987  	if ip := net.ParseIP(candidateIP); ip != nil {
   988  		// We only match IP addresses against IP SANs.
   989  		// https://tools.ietf.org/html/rfc6125#appendix-B.2
   990  		for _, candidate := range c.IPAddresses {
   991  			if ip.Equal(candidate) {
   992  				return nil
   993  			}
   994  		}
   995  		return HostnameError{c, candidateIP}
   996  	}
   997  
   998  	lowered := toLowerCaseASCII(h)
   999  
  1000  	if c.commonNameAsHostname() {
  1001  		if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) {
  1002  			return nil
  1003  		}
  1004  	} else {
  1005  		for _, match := range c.DNSNames {
  1006  			if matchHostnames(toLowerCaseASCII(match), lowered) {
  1007  				return nil
  1008  			}
  1009  		}
  1010  	}
  1011  
  1012  	return HostnameError{c, h}
  1013  }
  1014  
  1015  func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
  1016  	usages := make([]ExtKeyUsage, len(keyUsages))
  1017  	copy(usages, keyUsages)
  1018  
  1019  	if len(chain) == 0 {
  1020  		return false
  1021  	}
  1022  
  1023  	usagesRemaining := len(usages)
  1024  
  1025  	// We walk down the list and cross out any usages that aren't supported
  1026  	// by each certificate. If we cross out all the usages, then the chain
  1027  	// is unacceptable.
  1028  
  1029  NextCert:
  1030  	for i := len(chain) - 1; i >= 0; i-- {
  1031  		cert := chain[i]
  1032  		if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
  1033  			// The certificate doesn't have any extended key usage specified.
  1034  			continue
  1035  		}
  1036  
  1037  		for _, usage := range cert.ExtKeyUsage {
  1038  			if usage == ExtKeyUsageAny {
  1039  				// The certificate is explicitly good for any usage.
  1040  				continue NextCert
  1041  			}
  1042  		}
  1043  
  1044  		const invalidUsage ExtKeyUsage = -1
  1045  
  1046  	NextRequestedUsage:
  1047  		for i, requestedUsage := range usages {
  1048  			if requestedUsage == invalidUsage {
  1049  				continue
  1050  			}
  1051  
  1052  			for _, usage := range cert.ExtKeyUsage {
  1053  				if requestedUsage == usage {
  1054  					continue NextRequestedUsage
  1055  				} else if requestedUsage == ExtKeyUsageServerAuth &&
  1056  					(usage == ExtKeyUsageNetscapeServerGatedCrypto ||
  1057  						usage == ExtKeyUsageMicrosoftServerGatedCrypto) {
  1058  					// In order to support COMODO
  1059  					// certificate chains, we have to
  1060  					// accept Netscape or Microsoft SGC
  1061  					// usages as equal to ServerAuth.
  1062  					continue NextRequestedUsage
  1063  				}
  1064  			}
  1065  
  1066  			usages[i] = invalidUsage
  1067  			usagesRemaining--
  1068  			if usagesRemaining == 0 {
  1069  				return false
  1070  			}
  1071  		}
  1072  	}
  1073  
  1074  	return true
  1075  }