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