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.
21 // ignoreCN disables interpreting Common Name as a hostname. See issue 24151.
22 var ignoreCN = strings.Contains(os.Getenv("GODEBUG"), "x509ignoreCN=1")
24 type InvalidReason int
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.
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
40 // IncompatibleUsage results when the certificate's key usage indicates
41 // that it may only be used for a different purpose.
43 // NameMismatch results when the subject name of a parent certificate
44 // does not match the issuer name in the child.
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
51 // You can avoid this error by setting the experimental GODEBUG environment
52 // variable to "x509ignoreCN=1", disabling Common Name matching entirely.
53 // This behavior might become the default in the future.
54 NameConstraintsWithoutSANs
55 // UnconstrainedName results when a CA certificate contains permitted
56 // name constraints, but leaf certificate contains a name of an
57 // unsupported or unconstrained type.
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.
65 // CANotAuthorizedForExtKeyUsage results when an intermediate or root
66 // certificate does not permit a requested extended key usage.
67 CANotAuthorizedForExtKeyUsage
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 {
78 func (e CertificateInvalidError) Error() string {
80 case NotAuthorizedToSign:
81 return "x509: certificate is not authorized to sign other certificates"
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"
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
99 return "x509: unknown error"
102 // HostnameError results when the set of authorized names doesn't match the
104 type HostnameError struct {
105 Certificate *Certificate
109 func (h HostnameError) Error() string {
112 if !c.hasSANExtension() && !validHostname(c.Subject.CommonName) &&
113 matchHostnames(toLowerCaseASCII(c.Subject.CommonName), toLowerCaseASCII(h.Host)) {
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
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"
124 for _, san := range c.IPAddresses {
128 valid += san.String()
131 if c.commonNameAsHostname() {
132 valid = c.Subject.CommonName
134 valid = strings.Join(c.DNSNames, ", ")
139 return "x509: certificate is not valid for any names, but wanted to match " + h.Host
141 return "x509: certificate is valid for " + valid + ", not " + h.Host
144 // UnknownAuthorityError results when the certificate issuer is unknown
145 type UnknownAuthorityError struct {
147 // hintErr contains an error that may be helpful in determining why an
148 // authority wasn't found.
150 // hintCert contains a possible authority certificate that was rejected
151 // because of the error in hintErr.
152 hintCert *Certificate
155 func (e UnknownAuthorityError) Error() string {
156 s := "x509: certificate signed by unknown authority"
157 if e.hintErr != nil {
158 certName := e.hintCert.Subject.CommonName
159 if len(certName) == 0 {
160 if len(e.hintCert.Subject.Organization) > 0 {
161 certName = e.hintCert.Subject.Organization[0]
163 certName = "serial:" + e.hintCert.SerialNumber.String()
166 s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName)
171 // SystemRootsError results when we fail to load the system root certificates.
172 type SystemRootsError struct {
176 func (se SystemRootsError) Error() string {
177 msg := "x509: failed to load system roots and no roots provided"
179 return msg + "; " + se.Err.Error()
184 // errNotParsed is returned when a certificate without ASN.1 contents is
185 // verified. Platform-specific verification needs the ASN.1 contents.
186 var errNotParsed = errors.New("x509: missing ASN.1 contents; use ParseCertificate")
188 // VerifyOptions contains parameters for Certificate.Verify. It's a structure
189 // because other PKIX verification APIs have ended up needing many options.
190 type VerifyOptions struct {
191 // IsBoring is a validity check for BoringCrypto.
192 // If not nil, it will be called to check whether a given certificate
193 // can be used for constructing verification chains.
194 IsBoring func(*Certificate) bool
197 Intermediates *CertPool
198 Roots *CertPool // if nil, the system roots are used
199 CurrentTime time.Time // if zero, the current time is used
200 // KeyUsage specifies which Extended Key Usage values are acceptable. A leaf
201 // certificate is accepted if it contains any of the listed values. An empty
202 // list means ExtKeyUsageServerAuth. To accept any key usage, include
205 // Certificate chains are required to nest these extended key usage values.
206 // (This matches the Windows CryptoAPI behavior, but not the spec.)
207 KeyUsages []ExtKeyUsage
208 // MaxConstraintComparisions is the maximum number of comparisons to
209 // perform when checking a given certificate's name constraints. If
210 // zero, a sensible default is used. This limit prevents pathological
211 // certificates from consuming excessive amounts of CPU time when
213 MaxConstraintComparisions int
217 leafCertificate = iota
218 intermediateCertificate
222 // rfc2821Mailbox represents a “mailbox” (which is an email address to most
223 // people) by breaking it into the “local” (i.e. before the '@') and “domain”
225 type rfc2821Mailbox struct {
229 // parseRFC2821Mailbox parses an email address into local and domain parts,
230 // based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
231 // Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
232 // format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
233 func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
235 return mailbox, false
238 localPartBytes := make([]byte, 0, len(in)/2)
241 // Quoted-string = DQUOTE *qcontent DQUOTE
242 // non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
243 // qcontent = qtext / quoted-pair
244 // qtext = non-whitespace-control /
245 // %d33 / %d35-91 / %d93-126
246 // quoted-pair = ("\" text) / obs-qp
247 // text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
249 // (Names beginning with “obs-” are the obsolete syntax from RFC 2822,
250 // Section 4. Since it has been 16 years, we no longer accept that.)
255 return mailbox, false
267 return mailbox, false
271 (1 <= in[0] && in[0] <= 9) ||
272 (14 <= in[0] && in[0] <= 127) {
273 localPartBytes = append(localPartBytes, in[0])
276 return mailbox, false
281 // Space (char 32) is not allowed based on the
282 // BNF, but RFC 3696 gives an example that
283 // assumes that it is. Several “verified”
284 // errata continue to argue about this point.
285 // We choose to accept it.
289 (1 <= c && c <= 8) ||
290 (14 <= c && c <= 31) ||
291 (35 <= c && c <= 91) ||
292 (93 <= c && c <= 126):
294 localPartBytes = append(localPartBytes, c)
297 return mailbox, false
304 // atext from RFC 2822, Section 3.2.4
309 // Examples given in RFC 3696 suggest that
310 // escaped characters can appear outside of a
311 // quoted string. Several “verified” errata
312 // continue to argue the point. We choose to
316 return mailbox, false
320 case ('0' <= c && c <= '9') ||
321 ('a' <= c && c <= 'z') ||
322 ('A' <= c && c <= 'Z') ||
323 c == '!' || c == '#' || c == '$' || c == '%' ||
324 c == '&' || c == '\'' || c == '*' || c == '+' ||
325 c == '-' || c == '/' || c == '=' || c == '?' ||
326 c == '^' || c == '_' || c == '`' || c == '{' ||
327 c == '|' || c == '}' || c == '~' || c == '.':
328 localPartBytes = append(localPartBytes, in[0])
336 if len(localPartBytes) == 0 {
337 return mailbox, false
340 // From RFC 3696, Section 3:
341 // “period (".") may also appear, but may not be used to start
342 // or end the local part, nor may two or more consecutive
344 twoDots := []byte{'.', '.'}
345 if localPartBytes[0] == '.' ||
346 localPartBytes[len(localPartBytes)-1] == '.' ||
347 bytes.Contains(localPartBytes, twoDots) {
348 return mailbox, false
352 if len(in) == 0 || in[0] != '@' {
353 return mailbox, false
357 // The RFC species a format for domains, but that's known to be
358 // violated in practice so we accept that anything after an '@' is the
360 if _, ok := domainToReverseLabels(in); !ok {
361 return mailbox, false
364 mailbox.local = string(localPartBytes)
369 // domainToReverseLabels converts a textual domain name like foo.example.com to
370 // the list of labels in reverse order, e.g. ["com", "example", "foo"].
371 func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
372 for len(domain) > 0 {
373 if i := strings.LastIndexByte(domain, '.'); i == -1 {
374 reverseLabels = append(reverseLabels, domain)
377 reverseLabels = append(reverseLabels, domain[i+1:])
382 if len(reverseLabels) > 0 && len(reverseLabels[0]) == 0 {
383 // An empty label at the end indicates an absolute value.
387 for _, label := range reverseLabels {
389 // Empty labels are otherwise invalid.
393 for _, c := range label {
394 if c < 33 || c > 126 {
395 // Invalid character.
401 return reverseLabels, true
404 func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
405 // If the constraint contains an @, then it specifies an exact mailbox
407 if strings.Contains(constraint, "@") {
408 constraintMailbox, ok := parseRFC2821Mailbox(constraint)
410 return false, fmt.Errorf("x509: internal error: cannot parse constraint %q", constraint)
412 return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
415 // Otherwise the constraint is like a DNS constraint of the domain part
417 return matchDomainConstraint(mailbox.domain, constraint)
420 func matchURIConstraint(uri *url.URL, constraint string) (bool, error) {
421 // From RFC 5280, Section 4.2.1.10:
422 // “a uniformResourceIdentifier that does not include an authority
423 // component with a host name specified as a fully qualified domain
424 // name (e.g., if the URI either does not include an authority
425 // component or includes an authority component in which the host name
426 // is specified as an IP address), then the application MUST reject the
431 return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
434 if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
436 host, _, err = net.SplitHostPort(uri.Host)
442 if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") ||
443 net.ParseIP(host) != nil {
444 return false, fmt.Errorf("URI with IP (%q) cannot be matched against constraints", uri.String())
447 return matchDomainConstraint(host, constraint)
450 func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
451 if len(ip) != len(constraint.IP) {
456 if mask := constraint.Mask[i]; ip[i]&mask != constraint.IP[i]&mask {
464 func matchDomainConstraint(domain, constraint string) (bool, error) {
465 // The meaning of zero length constraints is not specified, but this
466 // code follows NSS and accepts them as matching everything.
467 if len(constraint) == 0 {
471 domainLabels, ok := domainToReverseLabels(domain)
473 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", domain)
476 // RFC 5280 says that a leading period in a domain name means that at
477 // least one label must be prepended, but only for URI and email
478 // constraints, not DNS constraints. The code also supports that
479 // behaviour for DNS constraints.
481 mustHaveSubdomains := false
482 if constraint[0] == '.' {
483 mustHaveSubdomains = true
484 constraint = constraint[1:]
487 constraintLabels, ok := domainToReverseLabels(constraint)
489 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", constraint)
492 if len(domainLabels) < len(constraintLabels) ||
493 (mustHaveSubdomains && len(domainLabels) == len(constraintLabels)) {
497 for i, constraintLabel := range constraintLabels {
498 if !strings.EqualFold(constraintLabel, domainLabels[i]) {
506 // checkNameConstraints checks that c permits a child certificate to claim the
507 // given name, of type nameType. The argument parsedName contains the parsed
508 // form of name, suitable for passing to the match function. The total number
509 // of comparisons is tracked in the given count and should not exceed the given
511 func (c *Certificate) checkNameConstraints(count *int,
512 maxConstraintComparisons int,
515 parsedName interface{},
516 match func(parsedName, constraint interface{}) (match bool, err error),
517 permitted, excluded interface{}) error {
519 excludedValue := reflect.ValueOf(excluded)
521 *count += excludedValue.Len()
522 if *count > maxConstraintComparisons {
523 return CertificateInvalidError{c, TooManyConstraints, ""}
526 for i := 0; i < excludedValue.Len(); i++ {
527 constraint := excludedValue.Index(i).Interface()
528 match, err := match(parsedName, constraint)
530 return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
534 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint)}
538 permittedValue := reflect.ValueOf(permitted)
540 *count += permittedValue.Len()
541 if *count > maxConstraintComparisons {
542 return CertificateInvalidError{c, TooManyConstraints, ""}
546 for i := 0; i < permittedValue.Len(); i++ {
547 constraint := permittedValue.Index(i).Interface()
550 if ok, err = match(parsedName, constraint); err != nil {
551 return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
560 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name)}
566 // isValid performs validity checks on c given that it is a candidate to append
567 // to the chain in currentChain.
568 func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
569 if len(c.UnhandledCriticalExtensions) > 0 {
570 return UnhandledCriticalExtension{}
573 if len(currentChain) > 0 {
574 child := currentChain[len(currentChain)-1]
575 if !bytes.Equal(child.RawIssuer, c.RawSubject) {
576 return CertificateInvalidError{c, NameMismatch, ""}
580 now := opts.CurrentTime
584 if now.Before(c.NotBefore) {
585 return CertificateInvalidError{
588 Detail: fmt.Sprintf("current time %s is before %s", now.Format(time.RFC3339), c.NotBefore.Format(time.RFC3339)),
590 } else if now.After(c.NotAfter) {
591 return CertificateInvalidError{
594 Detail: fmt.Sprintf("current time %s is after %s", now.Format(time.RFC3339), c.NotAfter.Format(time.RFC3339)),
598 maxConstraintComparisons := opts.MaxConstraintComparisions
599 if maxConstraintComparisons == 0 {
600 maxConstraintComparisons = 250000
604 var leaf *Certificate
605 if certType == intermediateCertificate || certType == rootCertificate {
606 if len(currentChain) == 0 {
607 return errors.New("x509: internal error: empty chain when appending CA cert")
609 leaf = currentChain[0]
612 checkNameConstraints := (certType == intermediateCertificate || certType == rootCertificate) && c.hasNameConstraints()
613 if checkNameConstraints && leaf.commonNameAsHostname() {
614 // This is the deprecated, legacy case of depending on the commonName as
615 // a hostname. We don't enforce name constraints against the CN, but
616 // VerifyHostname will look for hostnames in there if there are no SANs.
617 // In order to ensure VerifyHostname will not accept an unchecked name,
618 // return an error here.
619 return CertificateInvalidError{c, NameConstraintsWithoutSANs, ""}
620 } else if checkNameConstraints && leaf.hasSANExtension() {
621 err := forEachSAN(leaf.getSANExtension(), func(tag int, data []byte) error {
625 mailbox, ok := parseRFC2821Mailbox(name)
627 return fmt.Errorf("x509: cannot parse rfc822Name %q", mailbox)
630 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "email address", name, mailbox,
631 func(parsedName, constraint interface{}) (bool, error) {
632 return matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string))
633 }, c.PermittedEmailAddresses, c.ExcludedEmailAddresses); err != nil {
639 if _, ok := domainToReverseLabels(name); !ok {
640 return fmt.Errorf("x509: cannot parse dnsName %q", name)
643 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "DNS name", name, name,
644 func(parsedName, constraint interface{}) (bool, error) {
645 return matchDomainConstraint(parsedName.(string), constraint.(string))
646 }, c.PermittedDNSDomains, c.ExcludedDNSDomains); err != nil {
652 uri, err := url.Parse(name)
654 return fmt.Errorf("x509: internal error: URI SAN %q failed to parse", name)
657 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "URI", name, uri,
658 func(parsedName, constraint interface{}) (bool, error) {
659 return matchURIConstraint(parsedName.(*url.URL), constraint.(string))
660 }, c.PermittedURIDomains, c.ExcludedURIDomains); err != nil {
666 if l := len(ip); l != net.IPv4len && l != net.IPv6len {
667 return fmt.Errorf("x509: internal error: IP SAN %x failed to parse", data)
670 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "IP address", ip.String(), ip,
671 func(parsedName, constraint interface{}) (bool, error) {
672 return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet))
673 }, c.PermittedIPRanges, c.ExcludedIPRanges); err != nil {
678 // Unknown SAN types are ignored.
689 // KeyUsage status flags are ignored. From Engineering Security, Peter
690 // Gutmann: A European government CA marked its signing certificates as
691 // being valid for encryption only, but no-one noticed. Another
692 // European CA marked its signature keys as not being valid for
693 // signatures. A different CA marked its own trusted root certificate
694 // as being invalid for certificate signing. Another national CA
695 // distributed a certificate to be used to encrypt data for the
696 // country’s tax authority that was marked as only being usable for
697 // digital signatures but not for encryption. Yet another CA reversed
698 // the order of the bit flags in the keyUsage due to confusion over
699 // encoding endianness, essentially setting a random keyUsage in
700 // certificates that it issued. Another CA created a self-invalidating
701 // certificate by adding a certificate policy statement stipulating
702 // that the certificate had to be used strictly as specified in the
703 // keyUsage, and a keyUsage containing a flag indicating that the RSA
704 // encryption key could only be used for Diffie-Hellman key agreement.
706 if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
707 return CertificateInvalidError{c, NotAuthorizedToSign, ""}
710 if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
711 numIntermediates := len(currentChain) - 1
712 if numIntermediates > c.MaxPathLen {
713 return CertificateInvalidError{c, TooManyIntermediates, ""}
717 if opts.IsBoring != nil && !opts.IsBoring(c) {
718 // IncompatibleUsage is not quite right here,
719 // but it's also the "no chains found" error
720 // and is close enough.
721 return CertificateInvalidError{c, IncompatibleUsage, ""}
727 // Verify attempts to verify c by building one or more chains from c to a
728 // certificate in opts.Roots, using certificates in opts.Intermediates if
729 // needed. If successful, it returns one or more chains where the first
730 // element of the chain is c and the last element is from opts.Roots.
732 // If opts.Roots is nil and system roots are unavailable the returned error
733 // will be of type SystemRootsError.
735 // Name constraints in the intermediates will be applied to all names claimed
736 // in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim
737 // example.com if an intermediate doesn't permit it, even if example.com is not
738 // the name being validated. Note that DirectoryName constraints are not
741 // Extended Key Usage values are enforced down a chain, so an intermediate or
742 // root that enumerates EKUs prevents a leaf from asserting an EKU not in that
745 // WARNING: this function doesn't do any revocation checking.
746 func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) {
747 // Platform-specific verification needs the ASN.1 contents so
748 // this makes the behavior consistent across platforms.
750 return nil, errNotParsed
752 if opts.Intermediates != nil {
753 for _, intermediate := range opts.Intermediates.certs {
754 if len(intermediate.Raw) == 0 {
755 return nil, errNotParsed
760 // Use Windows's own verification and chain building.
761 if opts.Roots == nil && runtime.GOOS == "windows" {
762 return c.systemVerify(&opts)
765 if opts.Roots == nil {
766 opts.Roots = systemRootsPool()
767 if opts.Roots == nil {
768 return nil, SystemRootsError{systemRootsErr}
772 err = c.isValid(leafCertificate, nil, &opts)
777 if len(opts.DNSName) > 0 {
778 err = c.VerifyHostname(opts.DNSName)
784 var candidateChains [][]*Certificate
785 if opts.Roots.contains(c) {
786 candidateChains = append(candidateChains, []*Certificate{c})
788 if candidateChains, err = c.buildChains(nil, []*Certificate{c}, nil, &opts); err != nil {
793 keyUsages := opts.KeyUsages
794 if len(keyUsages) == 0 {
795 keyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
798 // If any key usage is acceptable then we're done.
799 for _, usage := range keyUsages {
800 if usage == ExtKeyUsageAny {
801 return candidateChains, nil
805 for _, candidate := range candidateChains {
806 if checkChainForKeyUsage(candidate, keyUsages) {
807 chains = append(chains, candidate)
811 if len(chains) == 0 {
812 return nil, CertificateInvalidError{c, IncompatibleUsage, ""}
818 func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate {
819 n := make([]*Certificate, len(chain)+1)
825 // maxChainSignatureChecks is the maximum number of CheckSignatureFrom calls
826 // that an invocation of buildChains will (tranistively) make. Most chains are
827 // less than 15 certificates long, so this leaves space for multiple chains and
828 // for failed checks due to different intermediates having the same Subject.
829 const maxChainSignatureChecks = 100
831 func (c *Certificate) buildChains(cache map[*Certificate][][]*Certificate, currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error) {
834 hintCert *Certificate
837 considerCandidate := func(certType int, candidate *Certificate) {
838 for _, cert := range currentChain {
839 if cert.Equal(candidate) {
844 if sigChecks == nil {
848 if *sigChecks > maxChainSignatureChecks {
849 err = errors.New("x509: signature check attempts limit reached while verifying certificate chain")
853 if err := c.CheckSignatureFrom(candidate); err != nil {
861 err = candidate.isValid(certType, currentChain, opts)
867 case rootCertificate:
868 chains = append(chains, appendToFreshChain(currentChain, candidate))
869 case intermediateCertificate:
871 cache = make(map[*Certificate][][]*Certificate)
873 childChains, ok := cache[candidate]
875 childChains, err = candidate.buildChains(cache, appendToFreshChain(currentChain, candidate), sigChecks, opts)
876 cache[candidate] = childChains
878 chains = append(chains, childChains...)
882 for _, rootNum := range opts.Roots.findPotentialParents(c) {
883 considerCandidate(rootCertificate, opts.Roots.certs[rootNum])
885 for _, intermediateNum := range opts.Intermediates.findPotentialParents(c) {
886 considerCandidate(intermediateCertificate, opts.Intermediates.certs[intermediateNum])
892 if len(chains) == 0 && err == nil {
893 err = UnknownAuthorityError{c, hintErr, hintCert}
899 // validHostname reports whether host is a valid hostname that can be matched or
900 // matched against according to RFC 6125 2.2, with some leniency to accommodate
902 func validHostname(host string) bool {
903 host = strings.TrimSuffix(host, ".")
909 for i, part := range strings.Split(host, ".") {
914 if i == 0 && part == "*" {
915 // Only allow full left-most wildcards, as those are the only ones
916 // we match, and matching literal '*' characters is probably never
917 // the expected behavior.
920 for j, c := range part {
921 if 'a' <= c && c <= 'z' {
924 if '0' <= c && c <= '9' {
927 if 'A' <= c && c <= 'Z' {
930 if c == '-' && j != 0 {
933 if c == '_' || c == ':' {
934 // Not valid characters in hostnames, but commonly
935 // found in deployments outside the WebPKI.
945 // commonNameAsHostname reports whether the Common Name field should be
946 // considered the hostname that the certificate is valid for. This is a legacy
947 // behavior, disabled if the Subject Alt Name extension is present.
949 // It applies the strict validHostname check to the Common Name field, so that
950 // certificates without SANs can still be validated against CAs with name
951 // constraints if there is no risk the CN would be matched as a hostname.
952 // See NameConstraintsWithoutSANs and issue 24151.
953 func (c *Certificate) commonNameAsHostname() bool {
954 return !ignoreCN && !c.hasSANExtension() && validHostname(c.Subject.CommonName)
957 func matchHostnames(pattern, host string) bool {
958 host = strings.TrimSuffix(host, ".")
959 pattern = strings.TrimSuffix(pattern, ".")
961 if len(pattern) == 0 || len(host) == 0 {
965 patternParts := strings.Split(pattern, ".")
966 hostParts := strings.Split(host, ".")
968 if len(patternParts) != len(hostParts) {
972 for i, patternPart := range patternParts {
973 if i == 0 && patternPart == "*" {
976 if patternPart != hostParts[i] {
984 // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
985 // an explicitly ASCII function to avoid any sharp corners resulting from
986 // performing Unicode operations on DNS labels.
987 func toLowerCaseASCII(in string) string {
988 // If the string is already lower-case then there's nothing to do.
989 isAlreadyLowerCase := true
990 for _, c := range in {
991 if c == utf8.RuneError {
992 // If we get a UTF-8 error then there might be
993 // upper-case ASCII bytes in the invalid sequence.
994 isAlreadyLowerCase = false
997 if 'A' <= c && c <= 'Z' {
998 isAlreadyLowerCase = false
1003 if isAlreadyLowerCase {
1008 for i, c := range out {
1009 if 'A' <= c && c <= 'Z' {
1016 // VerifyHostname returns nil if c is a valid certificate for the named host.
1017 // Otherwise it returns an error describing the mismatch.
1018 func (c *Certificate) VerifyHostname(h string) error {
1019 // IP addresses may be written in [ ].
1021 if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
1022 candidateIP = h[1 : len(h)-1]
1024 if ip := net.ParseIP(candidateIP); ip != nil {
1025 // We only match IP addresses against IP SANs.
1026 // See RFC 6125, Appendix B.2.
1027 for _, candidate := range c.IPAddresses {
1028 if ip.Equal(candidate) {
1032 return HostnameError{c, candidateIP}
1035 lowered := toLowerCaseASCII(h)
1037 if c.commonNameAsHostname() {
1038 if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) {
1042 for _, match := range c.DNSNames {
1043 if matchHostnames(toLowerCaseASCII(match), lowered) {
1049 return HostnameError{c, h}
1052 func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
1053 usages := make([]ExtKeyUsage, len(keyUsages))
1054 copy(usages, keyUsages)
1056 if len(chain) == 0 {
1060 usagesRemaining := len(usages)
1062 // We walk down the list and cross out any usages that aren't supported
1063 // by each certificate. If we cross out all the usages, then the chain
1067 for i := len(chain) - 1; i >= 0; i-- {
1069 if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
1070 // The certificate doesn't have any extended key usage specified.
1074 for _, usage := range cert.ExtKeyUsage {
1075 if usage == ExtKeyUsageAny {
1076 // The certificate is explicitly good for any usage.
1081 const invalidUsage ExtKeyUsage = -1
1084 for i, requestedUsage := range usages {
1085 if requestedUsage == invalidUsage {
1089 for _, usage := range cert.ExtKeyUsage {
1090 if requestedUsage == usage {
1091 continue NextRequestedUsage
1092 } else if requestedUsage == ExtKeyUsageServerAuth &&
1093 (usage == ExtKeyUsageNetscapeServerGatedCrypto ||
1094 usage == ExtKeyUsageMicrosoftServerGatedCrypto) {
1095 // In order to support COMODO
1096 // certificate chains, we have to
1097 // accept Netscape or Microsoft SGC
1098 // usages as equal to ServerAuth.
1099 continue NextRequestedUsage
1103 usages[i] = invalidUsage
1105 if usagesRemaining == 0 {