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

View as plain text