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

View as plain text