Source file src/crypto/x509/verify.go

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package x509
     6  
     7  import (
     8  	"bytes"
     9  	"crypto"
    10  	"crypto/x509/pkix"
    11  	"errors"
    12  	"fmt"
    13  	"iter"
    14  	"maps"
    15  	"net"
    16  	"net/netip"
    17  	"net/url"
    18  	"reflect"
    19  	"runtime"
    20  	"strings"
    21  	"time"
    22  	"unicode/utf8"
    23  )
    24  
    25  type InvalidReason int
    26  
    27  const (
    28  	// NotAuthorizedToSign results when a certificate is signed by another
    29  	// which isn't marked as a CA certificate.
    30  	NotAuthorizedToSign InvalidReason = iota
    31  	// Expired results when a certificate has expired, based on the time
    32  	// given in the VerifyOptions.
    33  	Expired
    34  	// CANotAuthorizedForThisName results when an intermediate or root
    35  	// certificate has a name constraint which doesn't permit a DNS or
    36  	// other name (including IP address) in the leaf certificate.
    37  	CANotAuthorizedForThisName
    38  	// TooManyIntermediates results when a path length constraint is
    39  	// violated.
    40  	TooManyIntermediates
    41  	// IncompatibleUsage results when the certificate's key usage indicates
    42  	// that it may only be used for a different purpose.
    43  	IncompatibleUsage
    44  	// NameMismatch results when the subject name of a parent certificate
    45  	// does not match the issuer name in the child.
    46  	NameMismatch
    47  	// NameConstraintsWithoutSANs is a legacy error and is no longer returned.
    48  	NameConstraintsWithoutSANs
    49  	// UnconstrainedName results when a CA certificate contains permitted
    50  	// name constraints, but leaf certificate contains a name of an
    51  	// unsupported or unconstrained type.
    52  	UnconstrainedName
    53  	// TooManyConstraints results when the number of comparison operations
    54  	// needed to check a certificate exceeds the limit set by
    55  	// VerifyOptions.MaxConstraintComparisions. This limit exists to
    56  	// prevent pathological certificates can consuming excessive amounts of
    57  	// CPU time to verify.
    58  	TooManyConstraints
    59  	// CANotAuthorizedForExtKeyUsage results when an intermediate or root
    60  	// certificate does not permit a requested extended key usage.
    61  	CANotAuthorizedForExtKeyUsage
    62  	// NoValidChains results when there are no valid chains to return.
    63  	NoValidChains
    64  )
    65  
    66  // CertificateInvalidError results when an odd error occurs. Users of this
    67  // library probably want to handle all these errors uniformly.
    68  type CertificateInvalidError struct {
    69  	Cert   *Certificate
    70  	Reason InvalidReason
    71  	Detail string
    72  }
    73  
    74  func (e CertificateInvalidError) Error() string {
    75  	switch e.Reason {
    76  	case NotAuthorizedToSign:
    77  		return "x509: certificate is not authorized to sign other certificates"
    78  	case Expired:
    79  		return "x509: certificate has expired or is not yet valid: " + e.Detail
    80  	case CANotAuthorizedForThisName:
    81  		return "x509: a root or intermediate certificate is not authorized to sign for this name: " + e.Detail
    82  	case CANotAuthorizedForExtKeyUsage:
    83  		return "x509: a root or intermediate certificate is not authorized for an extended key usage: " + e.Detail
    84  	case TooManyIntermediates:
    85  		return "x509: too many intermediates for path length constraint"
    86  	case IncompatibleUsage:
    87  		return "x509: certificate specifies an incompatible key usage"
    88  	case NameMismatch:
    89  		return "x509: issuer name does not match subject from issuing certificate"
    90  	case NameConstraintsWithoutSANs:
    91  		return "x509: issuer has name constraints but leaf doesn't have a SAN extension"
    92  	case UnconstrainedName:
    93  		return "x509: issuer has name constraints but leaf contains unknown or unconstrained name: " + e.Detail
    94  	case NoValidChains:
    95  		s := "x509: no valid chains built"
    96  		if e.Detail != "" {
    97  			s = fmt.Sprintf("%s: %s", s, e.Detail)
    98  		}
    99  		return s
   100  	}
   101  	return "x509: unknown error"
   102  }
   103  
   104  // HostnameError results when the set of authorized names doesn't match the
   105  // requested name.
   106  type HostnameError struct {
   107  	Certificate *Certificate
   108  	Host        string
   109  }
   110  
   111  func (h HostnameError) Error() string {
   112  	c := h.Certificate
   113  	maxNamesIncluded := 100
   114  
   115  	if !c.hasSANExtension() && matchHostnames(c.Subject.CommonName, h.Host) {
   116  		return "x509: certificate relies on legacy Common Name field, use SANs instead"
   117  	}
   118  
   119  	var valid strings.Builder
   120  	if ip := net.ParseIP(h.Host); ip != nil {
   121  		// Trying to validate an IP
   122  		if len(c.IPAddresses) == 0 {
   123  			return "x509: cannot validate certificate for " + h.Host + " because it doesn't contain any IP SANs"
   124  		}
   125  		if len(c.IPAddresses) >= maxNamesIncluded {
   126  			return fmt.Sprintf("x509: certificate is valid for %d IP SANs, but none matched %s", len(c.IPAddresses), h.Host)
   127  		}
   128  		for _, san := range c.IPAddresses {
   129  			if valid.Len() > 0 {
   130  				valid.WriteString(", ")
   131  			}
   132  			valid.WriteString(san.String())
   133  		}
   134  	} else {
   135  		if len(c.DNSNames) >= maxNamesIncluded {
   136  			return fmt.Sprintf("x509: certificate is valid for %d names, but none matched %s", len(c.DNSNames), h.Host)
   137  		}
   138  		valid.WriteString(strings.Join(c.DNSNames, ", "))
   139  	}
   140  
   141  	if valid.Len() == 0 {
   142  		return "x509: certificate is not valid for any names, but wanted to match " + h.Host
   143  	}
   144  	return "x509: certificate is valid for " + valid.String() + ", not " + h.Host
   145  }
   146  
   147  // UnknownAuthorityError results when the certificate issuer is unknown
   148  type UnknownAuthorityError struct {
   149  	Cert *Certificate
   150  	// hintErr contains an error that may be helpful in determining why an
   151  	// authority wasn't found.
   152  	hintErr error
   153  	// hintCert contains a possible authority certificate that was rejected
   154  	// because of the error in hintErr.
   155  	hintCert *Certificate
   156  }
   157  
   158  func (e UnknownAuthorityError) Error() string {
   159  	s := "x509: certificate signed by unknown authority"
   160  	if e.hintErr != nil {
   161  		certName := e.hintCert.Subject.CommonName
   162  		if len(certName) == 0 {
   163  			if len(e.hintCert.Subject.Organization) > 0 {
   164  				certName = e.hintCert.Subject.Organization[0]
   165  			} else {
   166  				certName = "serial:" + e.hintCert.SerialNumber.String()
   167  			}
   168  		}
   169  		s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName)
   170  	}
   171  	return s
   172  }
   173  
   174  // SystemRootsError results when we fail to load the system root certificates.
   175  type SystemRootsError struct {
   176  	Err error
   177  }
   178  
   179  func (se SystemRootsError) Error() string {
   180  	msg := "x509: failed to load system roots and no roots provided"
   181  	if se.Err != nil {
   182  		return msg + "; " + se.Err.Error()
   183  	}
   184  	return msg
   185  }
   186  
   187  func (se SystemRootsError) Unwrap() error { return se.Err }
   188  
   189  // errNotParsed is returned when a certificate without ASN.1 contents is
   190  // verified. Platform-specific verification needs the ASN.1 contents.
   191  var errNotParsed = errors.New("x509: missing ASN.1 contents; use ParseCertificate")
   192  
   193  // VerifyOptions contains parameters for Certificate.Verify.
   194  type VerifyOptions struct {
   195  	// DNSName, if set, is checked against the leaf certificate with
   196  	// Certificate.VerifyHostname or the platform verifier.
   197  	DNSName string
   198  
   199  	// Intermediates is an optional pool of certificates that are not trust
   200  	// anchors, but can be used to form a chain from the leaf certificate to a
   201  	// root certificate.
   202  	Intermediates *CertPool
   203  	// Roots is the set of trusted root certificates the leaf certificate needs
   204  	// to chain up to. If nil, the system roots or the platform verifier are used.
   205  	Roots *CertPool
   206  
   207  	// CurrentTime is used to check the validity of all certificates in the
   208  	// chain. If zero, the current time is used.
   209  	CurrentTime time.Time
   210  
   211  	// KeyUsages specifies which Extended Key Usage values are acceptable. A
   212  	// chain is accepted if it allows any of the listed values. An empty list
   213  	// means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny.
   214  	KeyUsages []ExtKeyUsage
   215  
   216  	// MaxConstraintComparisions is the maximum number of comparisons to
   217  	// perform when checking a given certificate's name constraints. If
   218  	// zero, a sensible default is used. This limit prevents pathological
   219  	// certificates from consuming excessive amounts of CPU time when
   220  	// validating. It does not apply to the platform verifier.
   221  	MaxConstraintComparisions int
   222  
   223  	// CertificatePolicies specifies which certificate policy OIDs are
   224  	// acceptable during policy validation. An empty CertificatePolices
   225  	// field implies any valid policy is acceptable.
   226  	CertificatePolicies []OID
   227  
   228  	// The following policy fields are unexported, because we do not expect
   229  	// users to actually need to use them, but are useful for testing the
   230  	// policy validation code.
   231  
   232  	// inhibitPolicyMapping indicates if policy mapping should be allowed
   233  	// during path validation.
   234  	inhibitPolicyMapping bool
   235  
   236  	// requireExplicitPolicy indidicates if explicit policies must be present
   237  	// for each certificate being validated.
   238  	requireExplicitPolicy bool
   239  
   240  	// inhibitAnyPolicy indicates if the anyPolicy policy should be
   241  	// processed if present in a certificate being validated.
   242  	inhibitAnyPolicy bool
   243  }
   244  
   245  const (
   246  	leafCertificate = iota
   247  	intermediateCertificate
   248  	rootCertificate
   249  )
   250  
   251  // rfc2821Mailbox represents a “mailbox” (which is an email address to most
   252  // people) by breaking it into the “local” (i.e. before the '@') and “domain”
   253  // parts.
   254  type rfc2821Mailbox struct {
   255  	local, domain string
   256  }
   257  
   258  // parseRFC2821Mailbox parses an email address into local and domain parts,
   259  // based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
   260  // Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
   261  // format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
   262  func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
   263  	if len(in) == 0 {
   264  		return mailbox, false
   265  	}
   266  
   267  	localPartBytes := make([]byte, 0, len(in)/2)
   268  
   269  	if in[0] == '"' {
   270  		// Quoted-string = DQUOTE *qcontent DQUOTE
   271  		// non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
   272  		// qcontent = qtext / quoted-pair
   273  		// qtext = non-whitespace-control /
   274  		//         %d33 / %d35-91 / %d93-126
   275  		// quoted-pair = ("\" text) / obs-qp
   276  		// text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
   277  		//
   278  		// (Names beginning with “obs-” are the obsolete syntax from RFC 2822,
   279  		// Section 4. Since it has been 16 years, we no longer accept that.)
   280  		in = in[1:]
   281  	QuotedString:
   282  		for {
   283  			if len(in) == 0 {
   284  				return mailbox, false
   285  			}
   286  			c := in[0]
   287  			in = in[1:]
   288  
   289  			switch {
   290  			case c == '"':
   291  				break QuotedString
   292  
   293  			case c == '\\':
   294  				// quoted-pair
   295  				if len(in) == 0 {
   296  					return mailbox, false
   297  				}
   298  				if in[0] == 11 ||
   299  					in[0] == 12 ||
   300  					(1 <= in[0] && in[0] <= 9) ||
   301  					(14 <= in[0] && in[0] <= 127) {
   302  					localPartBytes = append(localPartBytes, in[0])
   303  					in = in[1:]
   304  				} else {
   305  					return mailbox, false
   306  				}
   307  
   308  			case c == 11 ||
   309  				c == 12 ||
   310  				// Space (char 32) is not allowed based on the
   311  				// BNF, but RFC 3696 gives an example that
   312  				// assumes that it is. Several “verified”
   313  				// errata continue to argue about this point.
   314  				// We choose to accept it.
   315  				c == 32 ||
   316  				c == 33 ||
   317  				c == 127 ||
   318  				(1 <= c && c <= 8) ||
   319  				(14 <= c && c <= 31) ||
   320  				(35 <= c && c <= 91) ||
   321  				(93 <= c && c <= 126):
   322  				// qtext
   323  				localPartBytes = append(localPartBytes, c)
   324  
   325  			default:
   326  				return mailbox, false
   327  			}
   328  		}
   329  	} else {
   330  		// Atom ("." Atom)*
   331  	NextChar:
   332  		for len(in) > 0 {
   333  			// atext from RFC 2822, Section 3.2.4
   334  			c := in[0]
   335  
   336  			switch {
   337  			case c == '\\':
   338  				// Examples given in RFC 3696 suggest that
   339  				// escaped characters can appear outside of a
   340  				// quoted string. Several “verified” errata
   341  				// continue to argue the point. We choose to
   342  				// accept it.
   343  				in = in[1:]
   344  				if len(in) == 0 {
   345  					return mailbox, false
   346  				}
   347  				fallthrough
   348  
   349  			case ('0' <= c && c <= '9') ||
   350  				('a' <= c && c <= 'z') ||
   351  				('A' <= c && c <= 'Z') ||
   352  				c == '!' || c == '#' || c == '$' || c == '%' ||
   353  				c == '&' || c == '\'' || c == '*' || c == '+' ||
   354  				c == '-' || c == '/' || c == '=' || c == '?' ||
   355  				c == '^' || c == '_' || c == '`' || c == '{' ||
   356  				c == '|' || c == '}' || c == '~' || c == '.':
   357  				localPartBytes = append(localPartBytes, in[0])
   358  				in = in[1:]
   359  
   360  			default:
   361  				break NextChar
   362  			}
   363  		}
   364  
   365  		if len(localPartBytes) == 0 {
   366  			return mailbox, false
   367  		}
   368  
   369  		// From RFC 3696, Section 3:
   370  		// “period (".") may also appear, but may not be used to start
   371  		// or end the local part, nor may two or more consecutive
   372  		// periods appear.”
   373  		twoDots := []byte{'.', '.'}
   374  		if localPartBytes[0] == '.' ||
   375  			localPartBytes[len(localPartBytes)-1] == '.' ||
   376  			bytes.Contains(localPartBytes, twoDots) {
   377  			return mailbox, false
   378  		}
   379  	}
   380  
   381  	if len(in) == 0 || in[0] != '@' {
   382  		return mailbox, false
   383  	}
   384  	in = in[1:]
   385  
   386  	// The RFC species a format for domains, but that's known to be
   387  	// violated in practice so we accept that anything after an '@' is the
   388  	// domain part.
   389  	if _, ok := domainToReverseLabels(in); !ok {
   390  		return mailbox, false
   391  	}
   392  
   393  	mailbox.local = string(localPartBytes)
   394  	mailbox.domain = in
   395  	return mailbox, true
   396  }
   397  
   398  // domainToReverseLabels converts a textual domain name like foo.example.com to
   399  // the list of labels in reverse order, e.g. ["com", "example", "foo"].
   400  func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
   401  	reverseLabels = make([]string, 0, strings.Count(domain, ".")+1)
   402  	for len(domain) > 0 {
   403  		if i := strings.LastIndexByte(domain, '.'); i == -1 {
   404  			reverseLabels = append(reverseLabels, domain)
   405  			domain = ""
   406  		} else {
   407  			reverseLabels = append(reverseLabels, domain[i+1:])
   408  			domain = domain[:i]
   409  			if i == 0 { // domain == ""
   410  				// domain is prefixed with an empty label, append an empty
   411  				// string to reverseLabels to indicate this.
   412  				reverseLabels = append(reverseLabels, "")
   413  			}
   414  		}
   415  	}
   416  
   417  	if len(reverseLabels) > 0 && len(reverseLabels[0]) == 0 {
   418  		// An empty label at the end indicates an absolute value.
   419  		return nil, false
   420  	}
   421  
   422  	for _, label := range reverseLabels {
   423  		if len(label) == 0 {
   424  			// Empty labels are otherwise invalid.
   425  			return nil, false
   426  		}
   427  
   428  		for _, c := range label {
   429  			if c < 33 || c > 126 {
   430  				// Invalid character.
   431  				return nil, false
   432  			}
   433  		}
   434  	}
   435  
   436  	return reverseLabels, true
   437  }
   438  
   439  func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string, excluded bool, reversedDomainsCache map[string][]string, reversedConstraintsCache map[string][]string) (bool, error) {
   440  	// If the constraint contains an @, then it specifies an exact mailbox
   441  	// name.
   442  	if strings.Contains(constraint, "@") {
   443  		constraintMailbox, ok := parseRFC2821Mailbox(constraint)
   444  		if !ok {
   445  			return false, fmt.Errorf("x509: internal error: cannot parse constraint %q", constraint)
   446  		}
   447  		return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
   448  	}
   449  
   450  	// Otherwise the constraint is like a DNS constraint of the domain part
   451  	// of the mailbox.
   452  	return matchDomainConstraint(mailbox.domain, constraint, excluded, reversedDomainsCache, reversedConstraintsCache)
   453  }
   454  
   455  func matchURIConstraint(uri *url.URL, constraint string, excluded bool, reversedDomainsCache map[string][]string, reversedConstraintsCache map[string][]string) (bool, error) {
   456  	// From RFC 5280, Section 4.2.1.10:
   457  	// “a uniformResourceIdentifier that does not include an authority
   458  	// component with a host name specified as a fully qualified domain
   459  	// name (e.g., if the URI either does not include an authority
   460  	// component or includes an authority component in which the host name
   461  	// is specified as an IP address), then the application MUST reject the
   462  	// certificate.”
   463  
   464  	host := uri.Host
   465  	if len(host) == 0 {
   466  		return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
   467  	}
   468  
   469  	if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
   470  		var err error
   471  		host, _, err = net.SplitHostPort(uri.Host)
   472  		if err != nil {
   473  			return false, err
   474  		}
   475  	}
   476  
   477  	// netip.ParseAddr will reject the URI IPv6 literal form "[...]", so we
   478  	// check if _either_ the string parses as an IP, or if it is enclosed in
   479  	// square brackets.
   480  	if _, err := netip.ParseAddr(host); err == nil || (strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]")) {
   481  		return false, fmt.Errorf("URI with IP (%q) cannot be matched against constraints", uri.String())
   482  	}
   483  
   484  	return matchDomainConstraint(host, constraint, excluded, reversedDomainsCache, reversedConstraintsCache)
   485  }
   486  
   487  func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
   488  	if len(ip) != len(constraint.IP) {
   489  		return false, nil
   490  	}
   491  
   492  	for i := range ip {
   493  		if mask := constraint.Mask[i]; ip[i]&mask != constraint.IP[i]&mask {
   494  			return false, nil
   495  		}
   496  	}
   497  
   498  	return true, nil
   499  }
   500  
   501  func matchDomainConstraint(domain, constraint string, excluded bool, reversedDomainsCache map[string][]string, reversedConstraintsCache map[string][]string) (bool, error) {
   502  	// The meaning of zero length constraints is not specified, but this
   503  	// code follows NSS and accepts them as matching everything.
   504  	if len(constraint) == 0 {
   505  		return true, nil
   506  	}
   507  
   508  	domainLabels, found := reversedDomainsCache[domain]
   509  	if !found {
   510  		var ok bool
   511  		domainLabels, ok = domainToReverseLabels(domain)
   512  		if !ok {
   513  			return false, fmt.Errorf("x509: internal error: cannot parse domain %q", domain)
   514  		}
   515  		reversedDomainsCache[domain] = domainLabels
   516  	}
   517  
   518  	wildcardDomain := false
   519  	if len(domain) > 0 && domain[0] == '*' {
   520  		wildcardDomain = true
   521  	}
   522  
   523  	// RFC 5280 says that a leading period in a domain name means that at
   524  	// least one label must be prepended, but only for URI and email
   525  	// constraints, not DNS constraints. The code also supports that
   526  	// behaviour for DNS constraints.
   527  
   528  	mustHaveSubdomains := false
   529  	if constraint[0] == '.' {
   530  		mustHaveSubdomains = true
   531  		constraint = constraint[1:]
   532  	}
   533  
   534  	constraintLabels, found := reversedConstraintsCache[constraint]
   535  	if !found {
   536  		var ok bool
   537  		constraintLabels, ok = domainToReverseLabels(constraint)
   538  		if !ok {
   539  			return false, fmt.Errorf("x509: internal error: cannot parse domain %q", constraint)
   540  		}
   541  		reversedConstraintsCache[constraint] = constraintLabels
   542  	}
   543  
   544  	if len(domainLabels) < len(constraintLabels) ||
   545  		(mustHaveSubdomains && len(domainLabels) == len(constraintLabels)) {
   546  		return false, nil
   547  	}
   548  
   549  	if excluded && wildcardDomain && len(domainLabels) > 1 && len(constraintLabels) > 0 {
   550  		domainLabels = domainLabels[:len(domainLabels)-1]
   551  		constraintLabels = constraintLabels[:len(constraintLabels)-1]
   552  	}
   553  
   554  	for i, constraintLabel := range constraintLabels {
   555  		if !strings.EqualFold(constraintLabel, domainLabels[i]) {
   556  			return false, nil
   557  		}
   558  	}
   559  
   560  	return true, nil
   561  }
   562  
   563  // checkNameConstraints checks that c permits a child certificate to claim the
   564  // given name, of type nameType. The argument parsedName contains the parsed
   565  // form of name, suitable for passing to the match function. The total number
   566  // of comparisons is tracked in the given count and should not exceed the given
   567  // limit.
   568  func (c *Certificate) checkNameConstraints(count *int,
   569  	maxConstraintComparisons int,
   570  	nameType string,
   571  	name string,
   572  	parsedName any,
   573  	match func(parsedName, constraint any, excluded bool) (match bool, err error),
   574  	permitted, excluded any) error {
   575  
   576  	excludedValue := reflect.ValueOf(excluded)
   577  
   578  	*count += excludedValue.Len()
   579  	if *count > maxConstraintComparisons {
   580  		return CertificateInvalidError{c, TooManyConstraints, ""}
   581  	}
   582  
   583  	for i := 0; i < excludedValue.Len(); i++ {
   584  		constraint := excludedValue.Index(i).Interface()
   585  		match, err := match(parsedName, constraint, true)
   586  		if err != nil {
   587  			return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
   588  		}
   589  
   590  		if match {
   591  			return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint)}
   592  		}
   593  	}
   594  
   595  	permittedValue := reflect.ValueOf(permitted)
   596  
   597  	*count += permittedValue.Len()
   598  	if *count > maxConstraintComparisons {
   599  		return CertificateInvalidError{c, TooManyConstraints, ""}
   600  	}
   601  
   602  	ok := true
   603  	for i := 0; i < permittedValue.Len(); i++ {
   604  		constraint := permittedValue.Index(i).Interface()
   605  
   606  		var err error
   607  		if ok, err = match(parsedName, constraint, false); err != nil {
   608  			return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
   609  		}
   610  
   611  		if ok {
   612  			break
   613  		}
   614  	}
   615  
   616  	if !ok {
   617  		return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name)}
   618  	}
   619  
   620  	return nil
   621  }
   622  
   623  // isValid performs validity checks on c given that it is a candidate to append
   624  // to the chain in currentChain.
   625  func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
   626  	if len(c.UnhandledCriticalExtensions) > 0 {
   627  		return UnhandledCriticalExtension{}
   628  	}
   629  
   630  	if len(currentChain) > 0 {
   631  		child := currentChain[len(currentChain)-1]
   632  		if !bytes.Equal(child.RawIssuer, c.RawSubject) {
   633  			return CertificateInvalidError{c, NameMismatch, ""}
   634  		}
   635  	}
   636  
   637  	now := opts.CurrentTime
   638  	if now.IsZero() {
   639  		now = time.Now()
   640  	}
   641  	if now.Before(c.NotBefore) {
   642  		return CertificateInvalidError{
   643  			Cert:   c,
   644  			Reason: Expired,
   645  			Detail: fmt.Sprintf("current time %s is before %s", now.Format(time.RFC3339), c.NotBefore.Format(time.RFC3339)),
   646  		}
   647  	} else if now.After(c.NotAfter) {
   648  		return CertificateInvalidError{
   649  			Cert:   c,
   650  			Reason: Expired,
   651  			Detail: fmt.Sprintf("current time %s is after %s", now.Format(time.RFC3339), c.NotAfter.Format(time.RFC3339)),
   652  		}
   653  	}
   654  
   655  	maxConstraintComparisons := opts.MaxConstraintComparisions
   656  	if maxConstraintComparisons == 0 {
   657  		maxConstraintComparisons = 250000
   658  	}
   659  	comparisonCount := 0
   660  
   661  	if certType == intermediateCertificate || certType == rootCertificate {
   662  		if len(currentChain) == 0 {
   663  			return errors.New("x509: internal error: empty chain when appending CA cert")
   664  		}
   665  	}
   666  
   667  	// Each time we do constraint checking, we need to check the constraints in
   668  	// the current certificate against all of the names that preceded it. We
   669  	// reverse these names using domainToReverseLabels, which is a relatively
   670  	// expensive operation. Since we check each name against each constraint,
   671  	// this requires us to do N*C calls to domainToReverseLabels (where N is the
   672  	// total number of names that preceed the certificate, and C is the total
   673  	// number of constraints in the certificate). By caching the results of
   674  	// calling domainToReverseLabels, we can reduce that to N+C calls at the
   675  	// cost of keeping all of the parsed names and constraints in memory until
   676  	// we return from isValid.
   677  	reversedDomainsCache := map[string][]string{}
   678  	reversedConstraintsCache := map[string][]string{}
   679  
   680  	if (certType == intermediateCertificate || certType == rootCertificate) &&
   681  		c.hasNameConstraints() {
   682  		toCheck := []*Certificate{}
   683  		for _, c := range currentChain {
   684  			if c.hasSANExtension() {
   685  				toCheck = append(toCheck, c)
   686  			}
   687  		}
   688  		for _, sanCert := range toCheck {
   689  			err := forEachSAN(sanCert.getSANExtension(), func(tag int, data []byte) error {
   690  				switch tag {
   691  				case nameTypeEmail:
   692  					name := string(data)
   693  					mailbox, ok := parseRFC2821Mailbox(name)
   694  					if !ok {
   695  						return fmt.Errorf("x509: cannot parse rfc822Name %q", mailbox)
   696  					}
   697  
   698  					if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "email address", name, mailbox,
   699  						func(parsedName, constraint any, excluded bool) (bool, error) {
   700  							return matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string), excluded, reversedDomainsCache, reversedConstraintsCache)
   701  						}, c.PermittedEmailAddresses, c.ExcludedEmailAddresses); err != nil {
   702  						return err
   703  					}
   704  
   705  				case nameTypeDNS:
   706  					name := string(data)
   707  					if !domainNameValid(name, false) {
   708  						return fmt.Errorf("x509: cannot parse dnsName %q", name)
   709  					}
   710  
   711  					if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "DNS name", name, name,
   712  						func(parsedName, constraint any, excluded bool) (bool, error) {
   713  							return matchDomainConstraint(parsedName.(string), constraint.(string), excluded, reversedDomainsCache, reversedConstraintsCache)
   714  						}, c.PermittedDNSDomains, c.ExcludedDNSDomains); err != nil {
   715  						return err
   716  					}
   717  
   718  				case nameTypeURI:
   719  					name := string(data)
   720  					uri, err := url.Parse(name)
   721  					if err != nil {
   722  						return fmt.Errorf("x509: internal error: URI SAN %q failed to parse", name)
   723  					}
   724  
   725  					if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "URI", name, uri,
   726  						func(parsedName, constraint any, excluded bool) (bool, error) {
   727  							return matchURIConstraint(parsedName.(*url.URL), constraint.(string), excluded, reversedDomainsCache, reversedConstraintsCache)
   728  						}, c.PermittedURIDomains, c.ExcludedURIDomains); err != nil {
   729  						return err
   730  					}
   731  
   732  				case nameTypeIP:
   733  					ip := net.IP(data)
   734  					if l := len(ip); l != net.IPv4len && l != net.IPv6len {
   735  						return fmt.Errorf("x509: internal error: IP SAN %x failed to parse", data)
   736  					}
   737  
   738  					if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "IP address", ip.String(), ip,
   739  						func(parsedName, constraint any, _ bool) (bool, error) {
   740  							return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet))
   741  						}, c.PermittedIPRanges, c.ExcludedIPRanges); err != nil {
   742  						return err
   743  					}
   744  
   745  				default:
   746  					// Unknown SAN types are ignored.
   747  				}
   748  
   749  				return nil
   750  			})
   751  
   752  			if err != nil {
   753  				return err
   754  			}
   755  		}
   756  	}
   757  
   758  	// KeyUsage status flags are ignored. From Engineering Security, Peter
   759  	// Gutmann: A European government CA marked its signing certificates as
   760  	// being valid for encryption only, but no-one noticed. Another
   761  	// European CA marked its signature keys as not being valid for
   762  	// signatures. A different CA marked its own trusted root certificate
   763  	// as being invalid for certificate signing. Another national CA
   764  	// distributed a certificate to be used to encrypt data for the
   765  	// country’s tax authority that was marked as only being usable for
   766  	// digital signatures but not for encryption. Yet another CA reversed
   767  	// the order of the bit flags in the keyUsage due to confusion over
   768  	// encoding endianness, essentially setting a random keyUsage in
   769  	// certificates that it issued. Another CA created a self-invalidating
   770  	// certificate by adding a certificate policy statement stipulating
   771  	// that the certificate had to be used strictly as specified in the
   772  	// keyUsage, and a keyUsage containing a flag indicating that the RSA
   773  	// encryption key could only be used for Diffie-Hellman key agreement.
   774  
   775  	if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
   776  		return CertificateInvalidError{c, NotAuthorizedToSign, ""}
   777  	}
   778  
   779  	if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
   780  		numIntermediates := len(currentChain) - 1
   781  		if numIntermediates > c.MaxPathLen {
   782  			return CertificateInvalidError{c, TooManyIntermediates, ""}
   783  		}
   784  	}
   785  
   786  	return nil
   787  }
   788  
   789  // Verify attempts to verify c by building one or more chains from c to a
   790  // certificate in opts.Roots, using certificates in opts.Intermediates if
   791  // needed. If successful, it returns one or more chains where the first
   792  // element of the chain is c and the last element is from opts.Roots.
   793  //
   794  // If opts.Roots is nil, the platform verifier might be used, and
   795  // verification details might differ from what is described below. If system
   796  // roots are unavailable the returned error will be of type SystemRootsError.
   797  //
   798  // Name constraints in the intermediates will be applied to all names claimed
   799  // in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim
   800  // example.com if an intermediate doesn't permit it, even if example.com is not
   801  // the name being validated. Note that DirectoryName constraints are not
   802  // supported.
   803  //
   804  // Name constraint validation follows the rules from RFC 5280, with the
   805  // addition that DNS name constraints may use the leading period format
   806  // defined for emails and URIs. When a constraint has a leading period
   807  // it indicates that at least one additional label must be prepended to
   808  // the constrained name to be considered valid.
   809  //
   810  // Extended Key Usage values are enforced nested down a chain, so an intermediate
   811  // or root that enumerates EKUs prevents a leaf from asserting an EKU not in that
   812  // list. (While this is not specified, it is common practice in order to limit
   813  // the types of certificates a CA can issue.)
   814  //
   815  // Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not supported,
   816  // and will not be used to build chains.
   817  //
   818  // Certificates other than c in the returned chains should not be modified.
   819  //
   820  // WARNING: this function doesn't do any revocation checking.
   821  func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) {
   822  	// Platform-specific verification needs the ASN.1 contents so
   823  	// this makes the behavior consistent across platforms.
   824  	if len(c.Raw) == 0 {
   825  		return nil, errNotParsed
   826  	}
   827  	for i := 0; i < opts.Intermediates.len(); i++ {
   828  		c, _, err := opts.Intermediates.cert(i)
   829  		if err != nil {
   830  			return nil, fmt.Errorf("crypto/x509: error fetching intermediate: %w", err)
   831  		}
   832  		if len(c.Raw) == 0 {
   833  			return nil, errNotParsed
   834  		}
   835  	}
   836  
   837  	// Use platform verifiers, where available, if Roots is from SystemCertPool.
   838  	if runtime.GOOS == "windows" || runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
   839  		// Don't use the system verifier if the system pool was replaced with a non-system pool,
   840  		// i.e. if SetFallbackRoots was called with x509usefallbackroots=1.
   841  		systemPool := systemRootsPool()
   842  		if opts.Roots == nil && (systemPool == nil || systemPool.systemPool) {
   843  			return c.systemVerify(&opts)
   844  		}
   845  		if opts.Roots != nil && opts.Roots.systemPool {
   846  			platformChains, err := c.systemVerify(&opts)
   847  			// If the platform verifier succeeded, or there are no additional
   848  			// roots, return the platform verifier result. Otherwise, continue
   849  			// with the Go verifier.
   850  			if err == nil || opts.Roots.len() == 0 {
   851  				return platformChains, err
   852  			}
   853  		}
   854  	}
   855  
   856  	if opts.Roots == nil {
   857  		opts.Roots = systemRootsPool()
   858  		if opts.Roots == nil {
   859  			return nil, SystemRootsError{systemRootsErr}
   860  		}
   861  	}
   862  
   863  	err = c.isValid(leafCertificate, nil, &opts)
   864  	if err != nil {
   865  		return
   866  	}
   867  
   868  	if len(opts.DNSName) > 0 {
   869  		err = c.VerifyHostname(opts.DNSName)
   870  		if err != nil {
   871  			return
   872  		}
   873  	}
   874  
   875  	var candidateChains [][]*Certificate
   876  	if opts.Roots.contains(c) {
   877  		candidateChains = [][]*Certificate{{c}}
   878  	} else {
   879  		candidateChains, err = c.buildChains([]*Certificate{c}, nil, &opts)
   880  		if err != nil {
   881  			return nil, err
   882  		}
   883  	}
   884  
   885  	chains = make([][]*Certificate, 0, len(candidateChains))
   886  
   887  	var invalidPoliciesChains int
   888  	for _, candidate := range candidateChains {
   889  		if !policiesValid(candidate, opts) {
   890  			invalidPoliciesChains++
   891  			continue
   892  		}
   893  		chains = append(chains, candidate)
   894  	}
   895  
   896  	if len(chains) == 0 {
   897  		return nil, CertificateInvalidError{c, NoValidChains, "all candidate chains have invalid policies"}
   898  	}
   899  
   900  	for _, eku := range opts.KeyUsages {
   901  		if eku == ExtKeyUsageAny {
   902  			// If any key usage is acceptable, no need to check the chain for
   903  			// key usages.
   904  			return chains, nil
   905  		}
   906  	}
   907  
   908  	if len(opts.KeyUsages) == 0 {
   909  		opts.KeyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
   910  	}
   911  
   912  	candidateChains = chains
   913  	chains = chains[:0]
   914  
   915  	var incompatibleKeyUsageChains int
   916  	for _, candidate := range candidateChains {
   917  		if !checkChainForKeyUsage(candidate, opts.KeyUsages) {
   918  			incompatibleKeyUsageChains++
   919  			continue
   920  		}
   921  		chains = append(chains, candidate)
   922  	}
   923  
   924  	if len(chains) == 0 {
   925  		var details []string
   926  		if incompatibleKeyUsageChains > 0 {
   927  			if invalidPoliciesChains == 0 {
   928  				return nil, CertificateInvalidError{c, IncompatibleUsage, ""}
   929  			}
   930  			details = append(details, fmt.Sprintf("%d chains with incompatible key usage", incompatibleKeyUsageChains))
   931  		}
   932  		if invalidPoliciesChains > 0 {
   933  			details = append(details, fmt.Sprintf("%d chains with invalid policies", invalidPoliciesChains))
   934  		}
   935  		err = CertificateInvalidError{c, NoValidChains, strings.Join(details, ", ")}
   936  		return nil, err
   937  	}
   938  
   939  	return chains, nil
   940  }
   941  
   942  func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate {
   943  	n := make([]*Certificate, len(chain)+1)
   944  	copy(n, chain)
   945  	n[len(chain)] = cert
   946  	return n
   947  }
   948  
   949  // alreadyInChain checks whether a candidate certificate is present in a chain.
   950  // Rather than doing a direct byte for byte equivalency check, we check if the
   951  // subject, public key, and SAN, if present, are equal. This prevents loops that
   952  // are created by mutual cross-signatures, or other cross-signature bridge
   953  // oddities.
   954  func alreadyInChain(candidate *Certificate, chain []*Certificate) bool {
   955  	type pubKeyEqual interface {
   956  		Equal(crypto.PublicKey) bool
   957  	}
   958  
   959  	var candidateSAN *pkix.Extension
   960  	for _, ext := range candidate.Extensions {
   961  		if ext.Id.Equal(oidExtensionSubjectAltName) {
   962  			candidateSAN = &ext
   963  			break
   964  		}
   965  	}
   966  
   967  	for _, cert := range chain {
   968  		if !bytes.Equal(candidate.RawSubject, cert.RawSubject) {
   969  			continue
   970  		}
   971  		// We enforce the canonical encoding of SPKI (by only allowing the
   972  		// correct AI paremeter encodings in parseCertificate), so it's safe to
   973  		// directly compare the raw bytes.
   974  		if !bytes.Equal(candidate.RawSubjectPublicKeyInfo, cert.RawSubjectPublicKeyInfo) {
   975  			continue
   976  		}
   977  		var certSAN *pkix.Extension
   978  		for _, ext := range cert.Extensions {
   979  			if ext.Id.Equal(oidExtensionSubjectAltName) {
   980  				certSAN = &ext
   981  				break
   982  			}
   983  		}
   984  		if candidateSAN == nil && certSAN == nil {
   985  			return true
   986  		} else if candidateSAN == nil || certSAN == nil {
   987  			return false
   988  		}
   989  		if bytes.Equal(candidateSAN.Value, certSAN.Value) {
   990  			return true
   991  		}
   992  	}
   993  	return false
   994  }
   995  
   996  // maxChainSignatureChecks is the maximum number of CheckSignatureFrom calls
   997  // that an invocation of buildChains will (transitively) make. Most chains are
   998  // less than 15 certificates long, so this leaves space for multiple chains and
   999  // for failed checks due to different intermediates having the same Subject.
  1000  const maxChainSignatureChecks = 100
  1001  
  1002  func (c *Certificate) buildChains(currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error) {
  1003  	var (
  1004  		hintErr  error
  1005  		hintCert *Certificate
  1006  	)
  1007  
  1008  	considerCandidate := func(certType int, candidate potentialParent) {
  1009  		if candidate.cert.PublicKey == nil || alreadyInChain(candidate.cert, currentChain) {
  1010  			return
  1011  		}
  1012  
  1013  		if sigChecks == nil {
  1014  			sigChecks = new(int)
  1015  		}
  1016  		*sigChecks++
  1017  		if *sigChecks > maxChainSignatureChecks {
  1018  			err = errors.New("x509: signature check attempts limit reached while verifying certificate chain")
  1019  			return
  1020  		}
  1021  
  1022  		if err := c.CheckSignatureFrom(candidate.cert); err != nil {
  1023  			if hintErr == nil {
  1024  				hintErr = err
  1025  				hintCert = candidate.cert
  1026  			}
  1027  			return
  1028  		}
  1029  
  1030  		err = candidate.cert.isValid(certType, currentChain, opts)
  1031  		if err != nil {
  1032  			if hintErr == nil {
  1033  				hintErr = err
  1034  				hintCert = candidate.cert
  1035  			}
  1036  			return
  1037  		}
  1038  
  1039  		if candidate.constraint != nil {
  1040  			if err := candidate.constraint(currentChain); err != nil {
  1041  				if hintErr == nil {
  1042  					hintErr = err
  1043  					hintCert = candidate.cert
  1044  				}
  1045  				return
  1046  			}
  1047  		}
  1048  
  1049  		switch certType {
  1050  		case rootCertificate:
  1051  			chains = append(chains, appendToFreshChain(currentChain, candidate.cert))
  1052  		case intermediateCertificate:
  1053  			var childChains [][]*Certificate
  1054  			childChains, err = candidate.cert.buildChains(appendToFreshChain(currentChain, candidate.cert), sigChecks, opts)
  1055  			chains = append(chains, childChains...)
  1056  		}
  1057  	}
  1058  
  1059  	for _, root := range opts.Roots.findPotentialParents(c) {
  1060  		considerCandidate(rootCertificate, root)
  1061  	}
  1062  	for _, intermediate := range opts.Intermediates.findPotentialParents(c) {
  1063  		considerCandidate(intermediateCertificate, intermediate)
  1064  	}
  1065  
  1066  	if len(chains) > 0 {
  1067  		err = nil
  1068  	}
  1069  	if len(chains) == 0 && err == nil {
  1070  		err = UnknownAuthorityError{c, hintErr, hintCert}
  1071  	}
  1072  
  1073  	return
  1074  }
  1075  
  1076  func validHostnamePattern(host string) bool { return validHostname(host, true) }
  1077  func validHostnameInput(host string) bool   { return validHostname(host, false) }
  1078  
  1079  // validHostname reports whether host is a valid hostname that can be matched or
  1080  // matched against according to RFC 6125 2.2, with some leniency to accommodate
  1081  // legacy values.
  1082  func validHostname(host string, isPattern bool) bool {
  1083  	if !isPattern {
  1084  		host = strings.TrimSuffix(host, ".")
  1085  	}
  1086  	if len(host) == 0 {
  1087  		return false
  1088  	}
  1089  	if host == "*" {
  1090  		// Bare wildcards are not allowed, they are not valid DNS names,
  1091  		// nor are they allowed per RFC 6125.
  1092  		return false
  1093  	}
  1094  
  1095  	for i, part := range strings.Split(host, ".") {
  1096  		if part == "" {
  1097  			// Empty label.
  1098  			return false
  1099  		}
  1100  		if isPattern && i == 0 && part == "*" {
  1101  			// Only allow full left-most wildcards, as those are the only ones
  1102  			// we match, and matching literal '*' characters is probably never
  1103  			// the expected behavior.
  1104  			continue
  1105  		}
  1106  		for j, c := range part {
  1107  			if 'a' <= c && c <= 'z' {
  1108  				continue
  1109  			}
  1110  			if '0' <= c && c <= '9' {
  1111  				continue
  1112  			}
  1113  			if 'A' <= c && c <= 'Z' {
  1114  				continue
  1115  			}
  1116  			if c == '-' && j != 0 {
  1117  				continue
  1118  			}
  1119  			if c == '_' {
  1120  				// Not a valid character in hostnames, but commonly
  1121  				// found in deployments outside the WebPKI.
  1122  				continue
  1123  			}
  1124  			return false
  1125  		}
  1126  	}
  1127  
  1128  	return true
  1129  }
  1130  
  1131  func matchExactly(hostA, hostB string) bool {
  1132  	if hostA == "" || hostA == "." || hostB == "" || hostB == "." {
  1133  		return false
  1134  	}
  1135  	return toLowerCaseASCII(hostA) == toLowerCaseASCII(hostB)
  1136  }
  1137  
  1138  func matchHostnames(pattern, host string) bool {
  1139  	pattern = toLowerCaseASCII(pattern)
  1140  	host = toLowerCaseASCII(strings.TrimSuffix(host, "."))
  1141  
  1142  	if len(pattern) == 0 || len(host) == 0 {
  1143  		return false
  1144  	}
  1145  
  1146  	patternParts := strings.Split(pattern, ".")
  1147  	hostParts := strings.Split(host, ".")
  1148  
  1149  	if len(patternParts) != len(hostParts) {
  1150  		return false
  1151  	}
  1152  
  1153  	for i, patternPart := range patternParts {
  1154  		if i == 0 && patternPart == "*" {
  1155  			continue
  1156  		}
  1157  		if patternPart != hostParts[i] {
  1158  			return false
  1159  		}
  1160  	}
  1161  
  1162  	return true
  1163  }
  1164  
  1165  // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
  1166  // an explicitly ASCII function to avoid any sharp corners resulting from
  1167  // performing Unicode operations on DNS labels.
  1168  func toLowerCaseASCII(in string) string {
  1169  	// If the string is already lower-case then there's nothing to do.
  1170  	isAlreadyLowerCase := true
  1171  	for _, c := range in {
  1172  		if c == utf8.RuneError {
  1173  			// If we get a UTF-8 error then there might be
  1174  			// upper-case ASCII bytes in the invalid sequence.
  1175  			isAlreadyLowerCase = false
  1176  			break
  1177  		}
  1178  		if 'A' <= c && c <= 'Z' {
  1179  			isAlreadyLowerCase = false
  1180  			break
  1181  		}
  1182  	}
  1183  
  1184  	if isAlreadyLowerCase {
  1185  		return in
  1186  	}
  1187  
  1188  	out := []byte(in)
  1189  	for i, c := range out {
  1190  		if 'A' <= c && c <= 'Z' {
  1191  			out[i] += 'a' - 'A'
  1192  		}
  1193  	}
  1194  	return string(out)
  1195  }
  1196  
  1197  // VerifyHostname returns nil if c is a valid certificate for the named host.
  1198  // Otherwise it returns an error describing the mismatch.
  1199  //
  1200  // IP addresses can be optionally enclosed in square brackets and are checked
  1201  // against the IPAddresses field. Other names are checked case insensitively
  1202  // against the DNSNames field. If the names are valid hostnames, the certificate
  1203  // fields can have a wildcard as the complete left-most label (e.g. *.example.com).
  1204  //
  1205  // Note that the legacy Common Name field is ignored.
  1206  func (c *Certificate) VerifyHostname(h string) error {
  1207  	// IP addresses may be written in [ ].
  1208  	candidateIP := h
  1209  	if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
  1210  		candidateIP = h[1 : len(h)-1]
  1211  	}
  1212  	if ip := net.ParseIP(candidateIP); ip != nil {
  1213  		// We only match IP addresses against IP SANs.
  1214  		// See RFC 6125, Appendix B.2.
  1215  		for _, candidate := range c.IPAddresses {
  1216  			if ip.Equal(candidate) {
  1217  				return nil
  1218  			}
  1219  		}
  1220  		return HostnameError{c, candidateIP}
  1221  	}
  1222  
  1223  	candidateName := toLowerCaseASCII(h) // Save allocations inside the loop.
  1224  	validCandidateName := validHostnameInput(candidateName)
  1225  
  1226  	for _, match := range c.DNSNames {
  1227  		// Ideally, we'd only match valid hostnames according to RFC 6125 like
  1228  		// browsers (more or less) do, but in practice Go is used in a wider
  1229  		// array of contexts and can't even assume DNS resolution. Instead,
  1230  		// always allow perfect matches, and only apply wildcard and trailing
  1231  		// dot processing to valid hostnames.
  1232  		if validCandidateName && validHostnamePattern(match) {
  1233  			if matchHostnames(match, candidateName) {
  1234  				return nil
  1235  			}
  1236  		} else {
  1237  			if matchExactly(match, candidateName) {
  1238  				return nil
  1239  			}
  1240  		}
  1241  	}
  1242  
  1243  	return HostnameError{c, h}
  1244  }
  1245  
  1246  func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
  1247  	usages := make([]ExtKeyUsage, len(keyUsages))
  1248  	copy(usages, keyUsages)
  1249  
  1250  	if len(chain) == 0 {
  1251  		return false
  1252  	}
  1253  
  1254  	usagesRemaining := len(usages)
  1255  
  1256  	// We walk down the list and cross out any usages that aren't supported
  1257  	// by each certificate. If we cross out all the usages, then the chain
  1258  	// is unacceptable.
  1259  
  1260  NextCert:
  1261  	for i := len(chain) - 1; i >= 0; i-- {
  1262  		cert := chain[i]
  1263  		if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
  1264  			// The certificate doesn't have any extended key usage specified.
  1265  			continue
  1266  		}
  1267  
  1268  		for _, usage := range cert.ExtKeyUsage {
  1269  			if usage == ExtKeyUsageAny {
  1270  				// The certificate is explicitly good for any usage.
  1271  				continue NextCert
  1272  			}
  1273  		}
  1274  
  1275  		const invalidUsage ExtKeyUsage = -1
  1276  
  1277  	NextRequestedUsage:
  1278  		for i, requestedUsage := range usages {
  1279  			if requestedUsage == invalidUsage {
  1280  				continue
  1281  			}
  1282  
  1283  			for _, usage := range cert.ExtKeyUsage {
  1284  				if requestedUsage == usage {
  1285  					continue NextRequestedUsage
  1286  				}
  1287  			}
  1288  
  1289  			usages[i] = invalidUsage
  1290  			usagesRemaining--
  1291  			if usagesRemaining == 0 {
  1292  				return false
  1293  			}
  1294  		}
  1295  	}
  1296  
  1297  	return true
  1298  }
  1299  
  1300  func mustNewOIDFromInts(ints []uint64) OID {
  1301  	oid, err := OIDFromInts(ints)
  1302  	if err != nil {
  1303  		panic(fmt.Sprintf("OIDFromInts(%v) unexpected error: %v", ints, err))
  1304  	}
  1305  	return oid
  1306  }
  1307  
  1308  type policyGraphNode struct {
  1309  	validPolicy       OID
  1310  	expectedPolicySet []OID
  1311  	// we do not implement qualifiers, so we don't track qualifier_set
  1312  
  1313  	parents  map[*policyGraphNode]bool
  1314  	children map[*policyGraphNode]bool
  1315  }
  1316  
  1317  func newPolicyGraphNode(valid OID, parents []*policyGraphNode) *policyGraphNode {
  1318  	n := &policyGraphNode{
  1319  		validPolicy:       valid,
  1320  		expectedPolicySet: []OID{valid},
  1321  		children:          map[*policyGraphNode]bool{},
  1322  		parents:           map[*policyGraphNode]bool{},
  1323  	}
  1324  	for _, p := range parents {
  1325  		p.children[n] = true
  1326  		n.parents[p] = true
  1327  	}
  1328  	return n
  1329  }
  1330  
  1331  type policyGraph struct {
  1332  	strata []map[string]*policyGraphNode
  1333  	// map of OID -> nodes at strata[depth-1] with OID in their expectedPolicySet
  1334  	parentIndex map[string][]*policyGraphNode
  1335  	depth       int
  1336  }
  1337  
  1338  var anyPolicyOID = mustNewOIDFromInts([]uint64{2, 5, 29, 32, 0})
  1339  
  1340  func newPolicyGraph() *policyGraph {
  1341  	root := policyGraphNode{
  1342  		validPolicy:       anyPolicyOID,
  1343  		expectedPolicySet: []OID{anyPolicyOID},
  1344  		children:          map[*policyGraphNode]bool{},
  1345  		parents:           map[*policyGraphNode]bool{},
  1346  	}
  1347  	return &policyGraph{
  1348  		depth:  0,
  1349  		strata: []map[string]*policyGraphNode{{string(anyPolicyOID.der): &root}},
  1350  	}
  1351  }
  1352  
  1353  func (pg *policyGraph) insert(n *policyGraphNode) {
  1354  	pg.strata[pg.depth][string(n.validPolicy.der)] = n
  1355  }
  1356  
  1357  func (pg *policyGraph) parentsWithExpected(expected OID) []*policyGraphNode {
  1358  	if pg.depth == 0 {
  1359  		return nil
  1360  	}
  1361  	return pg.parentIndex[string(expected.der)]
  1362  }
  1363  
  1364  func (pg *policyGraph) parentWithAnyPolicy() *policyGraphNode {
  1365  	if pg.depth == 0 {
  1366  		return nil
  1367  	}
  1368  	return pg.strata[pg.depth-1][string(anyPolicyOID.der)]
  1369  }
  1370  
  1371  func (pg *policyGraph) parents() iter.Seq[*policyGraphNode] {
  1372  	if pg.depth == 0 {
  1373  		return nil
  1374  	}
  1375  	return maps.Values(pg.strata[pg.depth-1])
  1376  }
  1377  
  1378  func (pg *policyGraph) leaves() map[string]*policyGraphNode {
  1379  	return pg.strata[pg.depth]
  1380  }
  1381  
  1382  func (pg *policyGraph) leafWithPolicy(policy OID) *policyGraphNode {
  1383  	return pg.strata[pg.depth][string(policy.der)]
  1384  }
  1385  
  1386  func (pg *policyGraph) deleteLeaf(policy OID) {
  1387  	n := pg.strata[pg.depth][string(policy.der)]
  1388  	if n == nil {
  1389  		return
  1390  	}
  1391  	for p := range n.parents {
  1392  		delete(p.children, n)
  1393  	}
  1394  	for c := range n.children {
  1395  		delete(c.parents, n)
  1396  	}
  1397  	delete(pg.strata[pg.depth], string(policy.der))
  1398  }
  1399  
  1400  func (pg *policyGraph) validPolicyNodes() []*policyGraphNode {
  1401  	var validNodes []*policyGraphNode
  1402  	for i := pg.depth; i >= 0; i-- {
  1403  		for _, n := range pg.strata[i] {
  1404  			if n.validPolicy.Equal(anyPolicyOID) {
  1405  				continue
  1406  			}
  1407  
  1408  			if len(n.parents) == 1 {
  1409  				for p := range n.parents {
  1410  					if p.validPolicy.Equal(anyPolicyOID) {
  1411  						validNodes = append(validNodes, n)
  1412  					}
  1413  				}
  1414  			}
  1415  		}
  1416  	}
  1417  	return validNodes
  1418  }
  1419  
  1420  func (pg *policyGraph) prune() {
  1421  	for i := pg.depth - 1; i > 0; i-- {
  1422  		for _, n := range pg.strata[i] {
  1423  			if len(n.children) == 0 {
  1424  				for p := range n.parents {
  1425  					delete(p.children, n)
  1426  				}
  1427  				delete(pg.strata[i], string(n.validPolicy.der))
  1428  			}
  1429  		}
  1430  	}
  1431  }
  1432  
  1433  func (pg *policyGraph) incrDepth() {
  1434  	pg.parentIndex = map[string][]*policyGraphNode{}
  1435  	for _, n := range pg.strata[pg.depth] {
  1436  		for _, e := range n.expectedPolicySet {
  1437  			pg.parentIndex[string(e.der)] = append(pg.parentIndex[string(e.der)], n)
  1438  		}
  1439  	}
  1440  
  1441  	pg.depth++
  1442  	pg.strata = append(pg.strata, map[string]*policyGraphNode{})
  1443  }
  1444  
  1445  func policiesValid(chain []*Certificate, opts VerifyOptions) bool {
  1446  	// The following code implements the policy verification algorithm as
  1447  	// specified in RFC 5280 and updated by RFC 9618. In particular the
  1448  	// following sections are replaced by RFC 9618:
  1449  	//	* 6.1.2 (a)
  1450  	//	* 6.1.3 (d)
  1451  	//	* 6.1.3 (e)
  1452  	//	* 6.1.3 (f)
  1453  	//	* 6.1.4 (b)
  1454  	//	* 6.1.5 (g)
  1455  
  1456  	if len(chain) == 1 {
  1457  		return true
  1458  	}
  1459  
  1460  	// n is the length of the chain minus the trust anchor
  1461  	n := len(chain) - 1
  1462  
  1463  	pg := newPolicyGraph()
  1464  	var inhibitAnyPolicy, explicitPolicy, policyMapping int
  1465  	if !opts.inhibitAnyPolicy {
  1466  		inhibitAnyPolicy = n + 1
  1467  	}
  1468  	if !opts.requireExplicitPolicy {
  1469  		explicitPolicy = n + 1
  1470  	}
  1471  	if !opts.inhibitPolicyMapping {
  1472  		policyMapping = n + 1
  1473  	}
  1474  
  1475  	initialUserPolicySet := map[string]bool{}
  1476  	for _, p := range opts.CertificatePolicies {
  1477  		initialUserPolicySet[string(p.der)] = true
  1478  	}
  1479  	// If the user does not pass any policies, we consider
  1480  	// that equivalent to passing anyPolicyOID.
  1481  	if len(initialUserPolicySet) == 0 {
  1482  		initialUserPolicySet[string(anyPolicyOID.der)] = true
  1483  	}
  1484  
  1485  	for i := n - 1; i >= 0; i-- {
  1486  		cert := chain[i]
  1487  
  1488  		isSelfSigned := bytes.Equal(cert.RawIssuer, cert.RawSubject)
  1489  
  1490  		// 6.1.3 (e) -- as updated by RFC 9618
  1491  		if len(cert.Policies) == 0 {
  1492  			pg = nil
  1493  		}
  1494  
  1495  		// 6.1.3 (f) -- as updated by RFC 9618
  1496  		if explicitPolicy == 0 && pg == nil {
  1497  			return false
  1498  		}
  1499  
  1500  		if pg != nil {
  1501  			pg.incrDepth()
  1502  
  1503  			policies := map[string]bool{}
  1504  
  1505  			// 6.1.3 (d) (1) -- as updated by RFC 9618
  1506  			for _, policy := range cert.Policies {
  1507  				policies[string(policy.der)] = true
  1508  
  1509  				if policy.Equal(anyPolicyOID) {
  1510  					continue
  1511  				}
  1512  
  1513  				// 6.1.3 (d) (1) (i) -- as updated by RFC 9618
  1514  				parents := pg.parentsWithExpected(policy)
  1515  				if len(parents) == 0 {
  1516  					// 6.1.3 (d) (1) (ii) -- as updated by RFC 9618
  1517  					if anyParent := pg.parentWithAnyPolicy(); anyParent != nil {
  1518  						parents = []*policyGraphNode{anyParent}
  1519  					}
  1520  				}
  1521  				if len(parents) > 0 {
  1522  					pg.insert(newPolicyGraphNode(policy, parents))
  1523  				}
  1524  			}
  1525  
  1526  			// 6.1.3 (d) (2) -- as updated by RFC 9618
  1527  			// NOTE: in the check "n-i < n" our i is different from the i in the specification.
  1528  			// In the specification chains go from the trust anchor to the leaf, whereas our
  1529  			// chains go from the leaf to the trust anchor, so our i's our inverted. Our
  1530  			// check here matches the check "i < n" in the specification.
  1531  			if policies[string(anyPolicyOID.der)] && (inhibitAnyPolicy > 0 || (n-i < n && isSelfSigned)) {
  1532  				missing := map[string][]*policyGraphNode{}
  1533  				leaves := pg.leaves()
  1534  				for p := range pg.parents() {
  1535  					for _, expected := range p.expectedPolicySet {
  1536  						if leaves[string(expected.der)] == nil {
  1537  							missing[string(expected.der)] = append(missing[string(expected.der)], p)
  1538  						}
  1539  					}
  1540  				}
  1541  
  1542  				for oidStr, parents := range missing {
  1543  					pg.insert(newPolicyGraphNode(OID{der: []byte(oidStr)}, parents))
  1544  				}
  1545  			}
  1546  
  1547  			// 6.1.3 (d) (3) -- as updated by RFC 9618
  1548  			pg.prune()
  1549  
  1550  			if i != 0 {
  1551  				// 6.1.4 (b) -- as updated by RFC 9618
  1552  				if len(cert.PolicyMappings) > 0 {
  1553  					// collect map of issuer -> []subject
  1554  					mappings := map[string][]OID{}
  1555  
  1556  					for _, mapping := range cert.PolicyMappings {
  1557  						if policyMapping > 0 {
  1558  							if mapping.IssuerDomainPolicy.Equal(anyPolicyOID) || mapping.SubjectDomainPolicy.Equal(anyPolicyOID) {
  1559  								// Invalid mapping
  1560  								return false
  1561  							}
  1562  							mappings[string(mapping.IssuerDomainPolicy.der)] = append(mappings[string(mapping.IssuerDomainPolicy.der)], mapping.SubjectDomainPolicy)
  1563  						} else {
  1564  							// 6.1.4 (b) (3) (i) -- as updated by RFC 9618
  1565  							pg.deleteLeaf(mapping.IssuerDomainPolicy)
  1566  
  1567  							// 6.1.4 (b) (3) (ii) -- as updated by RFC 9618
  1568  							pg.prune()
  1569  						}
  1570  					}
  1571  
  1572  					for issuerStr, subjectPolicies := range mappings {
  1573  						// 6.1.4 (b) (1) -- as updated by RFC 9618
  1574  						if matching := pg.leafWithPolicy(OID{der: []byte(issuerStr)}); matching != nil {
  1575  							matching.expectedPolicySet = subjectPolicies
  1576  						} else if matching := pg.leafWithPolicy(anyPolicyOID); matching != nil {
  1577  							// 6.1.4 (b) (2) -- as updated by RFC 9618
  1578  							n := newPolicyGraphNode(OID{der: []byte(issuerStr)}, []*policyGraphNode{matching})
  1579  							n.expectedPolicySet = subjectPolicies
  1580  							pg.insert(n)
  1581  						}
  1582  					}
  1583  				}
  1584  			}
  1585  		}
  1586  
  1587  		if i != 0 {
  1588  			// 6.1.4 (h)
  1589  			if !isSelfSigned {
  1590  				if explicitPolicy > 0 {
  1591  					explicitPolicy--
  1592  				}
  1593  				if policyMapping > 0 {
  1594  					policyMapping--
  1595  				}
  1596  				if inhibitAnyPolicy > 0 {
  1597  					inhibitAnyPolicy--
  1598  				}
  1599  			}
  1600  
  1601  			// 6.1.4 (i)
  1602  			if (cert.RequireExplicitPolicy > 0 || cert.RequireExplicitPolicyZero) && cert.RequireExplicitPolicy < explicitPolicy {
  1603  				explicitPolicy = cert.RequireExplicitPolicy
  1604  			}
  1605  			if (cert.InhibitPolicyMapping > 0 || cert.InhibitPolicyMappingZero) && cert.InhibitPolicyMapping < policyMapping {
  1606  				policyMapping = cert.InhibitPolicyMapping
  1607  			}
  1608  			// 6.1.4 (j)
  1609  			if (cert.InhibitAnyPolicy > 0 || cert.InhibitAnyPolicyZero) && cert.InhibitAnyPolicy < inhibitAnyPolicy {
  1610  				inhibitAnyPolicy = cert.InhibitAnyPolicy
  1611  			}
  1612  		}
  1613  	}
  1614  
  1615  	// 6.1.5 (a)
  1616  	if explicitPolicy > 0 {
  1617  		explicitPolicy--
  1618  	}
  1619  
  1620  	// 6.1.5 (b)
  1621  	if chain[0].RequireExplicitPolicyZero {
  1622  		explicitPolicy = 0
  1623  	}
  1624  
  1625  	// 6.1.5 (g) (1) -- as updated by RFC 9618
  1626  	var validPolicyNodeSet []*policyGraphNode
  1627  	// 6.1.5 (g) (2) -- as updated by RFC 9618
  1628  	if pg != nil {
  1629  		validPolicyNodeSet = pg.validPolicyNodes()
  1630  		// 6.1.5 (g) (3) -- as updated by RFC 9618
  1631  		if currentAny := pg.leafWithPolicy(anyPolicyOID); currentAny != nil {
  1632  			validPolicyNodeSet = append(validPolicyNodeSet, currentAny)
  1633  		}
  1634  	}
  1635  
  1636  	// 6.1.5 (g) (4) -- as updated by RFC 9618
  1637  	authorityConstrainedPolicySet := map[string]bool{}
  1638  	for _, n := range validPolicyNodeSet {
  1639  		authorityConstrainedPolicySet[string(n.validPolicy.der)] = true
  1640  	}
  1641  	// 6.1.5 (g) (5) -- as updated by RFC 9618
  1642  	userConstrainedPolicySet := maps.Clone(authorityConstrainedPolicySet)
  1643  	// 6.1.5 (g) (6) -- as updated by RFC 9618
  1644  	if len(initialUserPolicySet) != 1 || !initialUserPolicySet[string(anyPolicyOID.der)] {
  1645  		// 6.1.5 (g) (6) (i) -- as updated by RFC 9618
  1646  		for p := range userConstrainedPolicySet {
  1647  			if !initialUserPolicySet[p] {
  1648  				delete(userConstrainedPolicySet, p)
  1649  			}
  1650  		}
  1651  		// 6.1.5 (g) (6) (ii) -- as updated by RFC 9618
  1652  		if authorityConstrainedPolicySet[string(anyPolicyOID.der)] {
  1653  			for policy := range initialUserPolicySet {
  1654  				userConstrainedPolicySet[policy] = true
  1655  			}
  1656  		}
  1657  	}
  1658  
  1659  	if explicitPolicy == 0 && len(userConstrainedPolicySet) == 0 {
  1660  		return false
  1661  	}
  1662  
  1663  	return true
  1664  }
  1665  

View as plain text