Black Lives Matter. Support the Equal Justice Initiative.

Source file src/crypto/x509/verify.go

Documentation: crypto/x509

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

View as plain text