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 type InvalidReason int
24 // NotAuthorizedToSign results when a certificate is signed by another
25 // which isn't marked as a CA certificate.
26 NotAuthorizedToSign InvalidReason = iota
27 // Expired results when a certificate has expired, based on the time
28 // given in the VerifyOptions.
30 // CANotAuthorizedForThisName results when an intermediate or root
31 // certificate has a name constraint which doesn't permit a DNS or
32 // other name (including IP address) in the leaf certificate.
33 CANotAuthorizedForThisName
34 // TooManyIntermediates results when a path length constraint is
37 // IncompatibleUsage results when the certificate's key usage indicates
38 // that it may only be used for a different purpose.
40 // NameMismatch results when the subject name of a parent certificate
41 // does not match the issuer name in the child.
43 // NameConstraintsWithoutSANs is a legacy error and is no longer returned.
44 NameConstraintsWithoutSANs
45 // UnconstrainedName results when a CA certificate contains permitted
46 // name constraints, but leaf certificate contains a name of an
47 // unsupported or unconstrained type.
49 // TooManyConstraints results when the number of comparison operations
50 // needed to check a certificate exceeds the limit set by
51 // VerifyOptions.MaxConstraintComparisions. This limit exists to
52 // prevent pathological certificates can consuming excessive amounts of
53 // CPU time to verify.
55 // CANotAuthorizedForExtKeyUsage results when an intermediate or root
56 // certificate does not permit a requested extended key usage.
57 CANotAuthorizedForExtKeyUsage
60 // CertificateInvalidError results when an odd error occurs. Users of this
61 // library probably want to handle all these errors uniformly.
62 type CertificateInvalidError struct {
68 func (e CertificateInvalidError) Error() string {
70 case NotAuthorizedToSign:
71 return "x509: certificate is not authorized to sign other certificates"
73 return "x509: certificate has expired or is not yet valid: " + e.Detail
74 case CANotAuthorizedForThisName:
75 return "x509: a root or intermediate certificate is not authorized to sign for this name: " + e.Detail
76 case CANotAuthorizedForExtKeyUsage:
77 return "x509: a root or intermediate certificate is not authorized for an extended key usage: " + e.Detail
78 case TooManyIntermediates:
79 return "x509: too many intermediates for path length constraint"
80 case IncompatibleUsage:
81 return "x509: certificate specifies an incompatible key usage"
83 return "x509: issuer name does not match subject from issuing certificate"
84 case NameConstraintsWithoutSANs:
85 return "x509: issuer has name constraints but leaf doesn't have a SAN extension"
86 case UnconstrainedName:
87 return "x509: issuer has name constraints but leaf contains unknown or unconstrained name: " + e.Detail
89 return "x509: unknown error"
92 // HostnameError results when the set of authorized names doesn't match the
94 type HostnameError struct {
95 Certificate *Certificate
99 func (h HostnameError) Error() string {
102 if !c.hasSANExtension() && matchHostnames(c.Subject.CommonName, h.Host) {
103 return "x509: certificate relies on legacy Common Name field, use SANs instead"
107 if ip := net.ParseIP(h.Host); ip != nil {
108 // Trying to validate an IP
109 if len(c.IPAddresses) == 0 {
110 return "x509: cannot validate certificate for " + h.Host + " because it doesn't contain any IP SANs"
112 for _, san := range c.IPAddresses {
116 valid += san.String()
119 valid = strings.Join(c.DNSNames, ", ")
123 return "x509: certificate is not valid for any names, but wanted to match " + h.Host
125 return "x509: certificate is valid for " + valid + ", not " + h.Host
128 // UnknownAuthorityError results when the certificate issuer is unknown
129 type UnknownAuthorityError struct {
131 // hintErr contains an error that may be helpful in determining why an
132 // authority wasn't found.
134 // hintCert contains a possible authority certificate that was rejected
135 // because of the error in hintErr.
136 hintCert *Certificate
139 func (e UnknownAuthorityError) Error() string {
140 s := "x509: certificate signed by unknown authority"
141 if e.hintErr != nil {
142 certName := e.hintCert.Subject.CommonName
143 if len(certName) == 0 {
144 if len(e.hintCert.Subject.Organization) > 0 {
145 certName = e.hintCert.Subject.Organization[0]
147 certName = "serial:" + e.hintCert.SerialNumber.String()
150 s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName)
155 // SystemRootsError results when we fail to load the system root certificates.
156 type SystemRootsError struct {
160 func (se SystemRootsError) Error() string {
161 msg := "x509: failed to load system roots and no roots provided"
163 return msg + "; " + se.Err.Error()
168 func (se SystemRootsError) Unwrap() error { return se.Err }
170 // errNotParsed is returned when a certificate without ASN.1 contents is
171 // verified. Platform-specific verification needs the ASN.1 contents.
172 var errNotParsed = errors.New("x509: missing ASN.1 contents; use ParseCertificate")
174 // VerifyOptions contains parameters for Certificate.Verify.
175 type VerifyOptions struct {
176 // IsBoring is a validity check for BoringCrypto.
177 // If not nil, it will be called to check whether a given certificate
178 // can be used for constructing verification chains.
179 IsBoring func(*Certificate) bool
181 // DNSName, if set, is checked against the leaf certificate with
182 // Certificate.VerifyHostname or the platform verifier.
185 // Intermediates is an optional pool of certificates that are not trust
186 // anchors, but can be used to form a chain from the leaf certificate to a
188 Intermediates *CertPool
189 // Roots is the set of trusted root certificates the leaf certificate needs
190 // to chain up to. If nil, the system roots or the platform verifier are used.
193 // CurrentTime is used to check the validity of all certificates in the
194 // chain. If zero, the current time is used.
195 CurrentTime time.Time
197 // KeyUsages specifies which Extended Key Usage values are acceptable. A
198 // chain is accepted if it allows any of the listed values. An empty list
199 // means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny.
200 KeyUsages []ExtKeyUsage
202 // MaxConstraintComparisions is the maximum number of comparisons to
203 // perform when checking a given certificate's name constraints. If
204 // zero, a sensible default is used. This limit prevents pathological
205 // certificates from consuming excessive amounts of CPU time when
206 // validating. It does not apply to the platform verifier.
207 MaxConstraintComparisions int
211 leafCertificate = iota
212 intermediateCertificate
216 // rfc2821Mailbox represents a “mailbox” (which is an email address to most
217 // people) by breaking it into the “local” (i.e. before the '@') and “domain”
219 type rfc2821Mailbox struct {
223 // parseRFC2821Mailbox parses an email address into local and domain parts,
224 // based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
225 // Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
226 // format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
227 func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
229 return mailbox, false
232 localPartBytes := make([]byte, 0, len(in)/2)
235 // Quoted-string = DQUOTE *qcontent DQUOTE
236 // non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
237 // qcontent = qtext / quoted-pair
238 // qtext = non-whitespace-control /
239 // %d33 / %d35-91 / %d93-126
240 // quoted-pair = ("\" text) / obs-qp
241 // text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
243 // (Names beginning with “obs-” are the obsolete syntax from RFC 2822,
244 // Section 4. Since it has been 16 years, we no longer accept that.)
249 return mailbox, false
261 return mailbox, false
265 (1 <= in[0] && in[0] <= 9) ||
266 (14 <= in[0] && in[0] <= 127) {
267 localPartBytes = append(localPartBytes, in[0])
270 return mailbox, false
275 // Space (char 32) is not allowed based on the
276 // BNF, but RFC 3696 gives an example that
277 // assumes that it is. Several “verified”
278 // errata continue to argue about this point.
279 // We choose to accept it.
283 (1 <= c && c <= 8) ||
284 (14 <= c && c <= 31) ||
285 (35 <= c && c <= 91) ||
286 (93 <= c && c <= 126):
288 localPartBytes = append(localPartBytes, c)
291 return mailbox, false
298 // atext from RFC 2822, Section 3.2.4
303 // Examples given in RFC 3696 suggest that
304 // escaped characters can appear outside of a
305 // quoted string. Several “verified” errata
306 // continue to argue the point. We choose to
310 return mailbox, false
314 case ('0' <= c && c <= '9') ||
315 ('a' <= c && c <= 'z') ||
316 ('A' <= c && c <= 'Z') ||
317 c == '!' || c == '#' || c == '$' || c == '%' ||
318 c == '&' || c == '\'' || c == '*' || c == '+' ||
319 c == '-' || c == '/' || c == '=' || c == '?' ||
320 c == '^' || c == '_' || c == '`' || c == '{' ||
321 c == '|' || c == '}' || c == '~' || c == '.':
322 localPartBytes = append(localPartBytes, in[0])
330 if len(localPartBytes) == 0 {
331 return mailbox, false
334 // From RFC 3696, Section 3:
335 // “period (".") may also appear, but may not be used to start
336 // or end the local part, nor may two or more consecutive
338 twoDots := []byte{'.', '.'}
339 if localPartBytes[0] == '.' ||
340 localPartBytes[len(localPartBytes)-1] == '.' ||
341 bytes.Contains(localPartBytes, twoDots) {
342 return mailbox, false
346 if len(in) == 0 || in[0] != '@' {
347 return mailbox, false
351 // The RFC species a format for domains, but that's known to be
352 // violated in practice so we accept that anything after an '@' is the
354 if _, ok := domainToReverseLabels(in); !ok {
355 return mailbox, false
358 mailbox.local = string(localPartBytes)
363 // domainToReverseLabels converts a textual domain name like foo.example.com to
364 // the list of labels in reverse order, e.g. ["com", "example", "foo"].
365 func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
366 for len(domain) > 0 {
367 if i := strings.LastIndexByte(domain, '.'); i == -1 {
368 reverseLabels = append(reverseLabels, domain)
371 reverseLabels = append(reverseLabels, domain[i+1:])
376 if len(reverseLabels) > 0 && len(reverseLabels[0]) == 0 {
377 // An empty label at the end indicates an absolute value.
381 for _, label := range reverseLabels {
383 // Empty labels are otherwise invalid.
387 for _, c := range label {
388 if c < 33 || c > 126 {
389 // Invalid character.
395 return reverseLabels, true
398 func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
399 // If the constraint contains an @, then it specifies an exact mailbox
401 if strings.Contains(constraint, "@") {
402 constraintMailbox, ok := parseRFC2821Mailbox(constraint)
404 return false, fmt.Errorf("x509: internal error: cannot parse constraint %q", constraint)
406 return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
409 // Otherwise the constraint is like a DNS constraint of the domain part
411 return matchDomainConstraint(mailbox.domain, constraint)
414 func matchURIConstraint(uri *url.URL, constraint string) (bool, error) {
415 // From RFC 5280, Section 4.2.1.10:
416 // “a uniformResourceIdentifier that does not include an authority
417 // component with a host name specified as a fully qualified domain
418 // name (e.g., if the URI either does not include an authority
419 // component or includes an authority component in which the host name
420 // is specified as an IP address), then the application MUST reject the
425 return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
428 if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
430 host, _, err = net.SplitHostPort(uri.Host)
436 if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") ||
437 net.ParseIP(host) != nil {
438 return false, fmt.Errorf("URI with IP (%q) cannot be matched against constraints", uri.String())
441 return matchDomainConstraint(host, constraint)
444 func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
445 if len(ip) != len(constraint.IP) {
450 if mask := constraint.Mask[i]; ip[i]&mask != constraint.IP[i]&mask {
458 func matchDomainConstraint(domain, constraint string) (bool, error) {
459 // The meaning of zero length constraints is not specified, but this
460 // code follows NSS and accepts them as matching everything.
461 if len(constraint) == 0 {
465 domainLabels, ok := domainToReverseLabels(domain)
467 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", domain)
470 // RFC 5280 says that a leading period in a domain name means that at
471 // least one label must be prepended, but only for URI and email
472 // constraints, not DNS constraints. The code also supports that
473 // behaviour for DNS constraints.
475 mustHaveSubdomains := false
476 if constraint[0] == '.' {
477 mustHaveSubdomains = true
478 constraint = constraint[1:]
481 constraintLabels, ok := domainToReverseLabels(constraint)
483 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", constraint)
486 if len(domainLabels) < len(constraintLabels) ||
487 (mustHaveSubdomains && len(domainLabels) == len(constraintLabels)) {
491 for i, constraintLabel := range constraintLabels {
492 if !strings.EqualFold(constraintLabel, domainLabels[i]) {
500 // checkNameConstraints checks that c permits a child certificate to claim the
501 // given name, of type nameType. The argument parsedName contains the parsed
502 // form of name, suitable for passing to the match function. The total number
503 // of comparisons is tracked in the given count and should not exceed the given
505 func (c *Certificate) checkNameConstraints(count *int,
506 maxConstraintComparisons int,
510 match func(parsedName, constraint any) (match bool, err error),
511 permitted, excluded any) error {
513 excludedValue := reflect.ValueOf(excluded)
515 *count += excludedValue.Len()
516 if *count > maxConstraintComparisons {
517 return CertificateInvalidError{c, TooManyConstraints, ""}
520 for i := 0; i < excludedValue.Len(); i++ {
521 constraint := excludedValue.Index(i).Interface()
522 match, err := match(parsedName, constraint)
524 return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
528 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint)}
532 permittedValue := reflect.ValueOf(permitted)
534 *count += permittedValue.Len()
535 if *count > maxConstraintComparisons {
536 return CertificateInvalidError{c, TooManyConstraints, ""}
540 for i := 0; i < permittedValue.Len(); i++ {
541 constraint := permittedValue.Index(i).Interface()
544 if ok, err = match(parsedName, constraint); err != nil {
545 return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
554 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name)}
560 // isValid performs validity checks on c given that it is a candidate to append
561 // to the chain in currentChain.
562 func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
563 if len(c.UnhandledCriticalExtensions) > 0 {
564 return UnhandledCriticalExtension{}
567 if len(currentChain) > 0 {
568 child := currentChain[len(currentChain)-1]
569 if !bytes.Equal(child.RawIssuer, c.RawSubject) {
570 return CertificateInvalidError{c, NameMismatch, ""}
574 now := opts.CurrentTime
578 if now.Before(c.NotBefore) {
579 return CertificateInvalidError{
582 Detail: fmt.Sprintf("current time %s is before %s", now.Format(time.RFC3339), c.NotBefore.Format(time.RFC3339)),
584 } else if now.After(c.NotAfter) {
585 return CertificateInvalidError{
588 Detail: fmt.Sprintf("current time %s is after %s", now.Format(time.RFC3339), c.NotAfter.Format(time.RFC3339)),
592 maxConstraintComparisons := opts.MaxConstraintComparisions
593 if maxConstraintComparisons == 0 {
594 maxConstraintComparisons = 250000
598 var leaf *Certificate
599 if certType == intermediateCertificate || certType == rootCertificate {
600 if len(currentChain) == 0 {
601 return errors.New("x509: internal error: empty chain when appending CA cert")
603 leaf = currentChain[0]
606 if (len(c.ExtKeyUsage) > 0 || len(c.UnknownExtKeyUsage) > 0) && len(opts.KeyUsages) > 0 {
607 acceptableUsage := false
608 um := make(map[ExtKeyUsage]bool, len(opts.KeyUsages))
609 for _, u := range opts.KeyUsages {
612 if !um[ExtKeyUsageAny] {
613 for _, u := range c.ExtKeyUsage {
614 if u == ExtKeyUsageAny || um[u] {
615 acceptableUsage = true
619 if !acceptableUsage {
620 return CertificateInvalidError{c, IncompatibleUsage, ""}
625 if (certType == intermediateCertificate || certType == rootCertificate) &&
626 c.hasNameConstraints() {
627 toCheck := []*Certificate{}
628 if leaf.hasSANExtension() {
629 toCheck = append(toCheck, leaf)
631 if c.hasSANExtension() {
632 toCheck = append(toCheck, c)
634 for _, sanCert := range toCheck {
635 err := forEachSAN(sanCert.getSANExtension(), func(tag int, data []byte) error {
639 mailbox, ok := parseRFC2821Mailbox(name)
641 return fmt.Errorf("x509: cannot parse rfc822Name %q", mailbox)
644 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "email address", name, mailbox,
645 func(parsedName, constraint any) (bool, error) {
646 return matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string))
647 }, c.PermittedEmailAddresses, c.ExcludedEmailAddresses); err != nil {
653 if _, ok := domainToReverseLabels(name); !ok {
654 return fmt.Errorf("x509: cannot parse dnsName %q", name)
657 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "DNS name", name, name,
658 func(parsedName, constraint any) (bool, error) {
659 return matchDomainConstraint(parsedName.(string), constraint.(string))
660 }, c.PermittedDNSDomains, c.ExcludedDNSDomains); err != nil {
666 uri, err := url.Parse(name)
668 return fmt.Errorf("x509: internal error: URI SAN %q failed to parse", name)
671 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "URI", name, uri,
672 func(parsedName, constraint any) (bool, error) {
673 return matchURIConstraint(parsedName.(*url.URL), constraint.(string))
674 }, c.PermittedURIDomains, c.ExcludedURIDomains); err != nil {
680 if l := len(ip); l != net.IPv4len && l != net.IPv6len {
681 return fmt.Errorf("x509: internal error: IP SAN %x failed to parse", data)
684 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "IP address", ip.String(), ip,
685 func(parsedName, constraint any) (bool, error) {
686 return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet))
687 }, c.PermittedIPRanges, c.ExcludedIPRanges); err != nil {
692 // Unknown SAN types are ignored.
704 // KeyUsage status flags are ignored. From Engineering Security, Peter
705 // Gutmann: A European government CA marked its signing certificates as
706 // being valid for encryption only, but no-one noticed. Another
707 // European CA marked its signature keys as not being valid for
708 // signatures. A different CA marked its own trusted root certificate
709 // as being invalid for certificate signing. Another national CA
710 // distributed a certificate to be used to encrypt data for the
711 // country’s tax authority that was marked as only being usable for
712 // digital signatures but not for encryption. Yet another CA reversed
713 // the order of the bit flags in the keyUsage due to confusion over
714 // encoding endianness, essentially setting a random keyUsage in
715 // certificates that it issued. Another CA created a self-invalidating
716 // certificate by adding a certificate policy statement stipulating
717 // that the certificate had to be used strictly as specified in the
718 // keyUsage, and a keyUsage containing a flag indicating that the RSA
719 // encryption key could only be used for Diffie-Hellman key agreement.
721 if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
722 return CertificateInvalidError{c, NotAuthorizedToSign, ""}
725 if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
726 numIntermediates := len(currentChain) - 1
727 if numIntermediates > c.MaxPathLen {
728 return CertificateInvalidError{c, TooManyIntermediates, ""}
732 if opts.IsBoring != nil && !opts.IsBoring(c) {
733 // IncompatibleUsage is not quite right here,
734 // but it's also the "no chains found" error
735 // and is close enough.
736 return CertificateInvalidError{c, IncompatibleUsage, ""}
742 // Verify attempts to verify c by building one or more chains from c to a
743 // certificate in opts.Roots, using certificates in opts.Intermediates if
744 // needed. If successful, it returns one or more chains where the first
745 // element of the chain is c and the last element is from opts.Roots.
747 // If opts.Roots is nil, the platform verifier might be used, and
748 // verification details might differ from what is described below. If system
749 // roots are unavailable the returned error will be of type SystemRootsError.
751 // Name constraints in the intermediates will be applied to all names claimed
752 // in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim
753 // example.com if an intermediate doesn't permit it, even if example.com is not
754 // the name being validated. Note that DirectoryName constraints are not
757 // Name constraint validation follows the rules from RFC 5280, with the
758 // addition that DNS name constraints may use the leading period format
759 // defined for emails and URIs. When a constraint has a leading period
760 // it indicates that at least one additional label must be prepended to
761 // the constrained name to be considered valid.
763 // Extended Key Usage values are enforced nested down a chain, so an intermediate
764 // or root that enumerates EKUs prevents a leaf from asserting an EKU not in that
765 // list. (While this is not specified, it is common practice in order to limit
766 // the types of certificates a CA can issue.)
768 // Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not supported,
769 // and will not be used to build chains.
771 // WARNING: this function doesn't do any revocation checking.
772 func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) {
773 // Platform-specific verification needs the ASN.1 contents so
774 // this makes the behavior consistent across platforms.
776 return nil, errNotParsed
778 for i := 0; i < opts.Intermediates.len(); i++ {
779 c, err := opts.Intermediates.cert(i)
781 return nil, fmt.Errorf("crypto/x509: error fetching intermediate: %w", err)
784 return nil, errNotParsed
788 // Use platform verifiers, where available, if Roots is from SystemCertPool.
789 if runtime.GOOS == "windows" || runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
790 if opts.Roots == nil {
791 return c.systemVerify(&opts)
793 if opts.Roots != nil && opts.Roots.systemPool {
794 platformChains, err := c.systemVerify(&opts)
795 // If the platform verifier succeeded, or there are no additional
796 // roots, return the platform verifier result. Otherwise, continue
797 // with the Go verifier.
798 if err == nil || opts.Roots.len() == 0 {
799 return platformChains, err
804 if opts.Roots == nil {
805 opts.Roots = systemRootsPool()
806 if opts.Roots == nil {
807 return nil, SystemRootsError{systemRootsErr}
811 if len(opts.KeyUsages) == 0 {
812 opts.KeyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
815 err = c.isValid(leafCertificate, nil, &opts)
820 if len(opts.DNSName) > 0 {
821 err = c.VerifyHostname(opts.DNSName)
827 if opts.Roots.contains(c) {
828 return [][]*Certificate{{c}}, nil
830 return c.buildChains([]*Certificate{c}, nil, &opts)
833 func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate {
834 n := make([]*Certificate, len(chain)+1)
840 // maxChainSignatureChecks is the maximum number of CheckSignatureFrom calls
841 // that an invocation of buildChains will (transitively) make. Most chains are
842 // less than 15 certificates long, so this leaves space for multiple chains and
843 // for failed checks due to different intermediates having the same Subject.
844 const maxChainSignatureChecks = 100
846 func (c *Certificate) buildChains(currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error) {
849 hintCert *Certificate
852 type pubKeyEqual interface {
853 Equal(crypto.PublicKey) bool
856 considerCandidate := func(certType int, candidate *Certificate) {
857 for _, cert := range currentChain {
858 // If a certificate already appeared in the chain we've built, don't
859 // reconsider it. This prevents loops, for isntance those created by
860 // mutual cross-signatures, or other cross-signature bridges oddities.
861 if bytes.Equal(cert.RawSubject, candidate.RawSubject) && cert.PublicKey.(pubKeyEqual).Equal(candidate.PublicKey) {
866 if sigChecks == nil {
870 if *sigChecks > maxChainSignatureChecks {
871 err = errors.New("x509: signature check attempts limit reached while verifying certificate chain")
875 if err := c.CheckSignatureFrom(candidate); err != nil {
883 err = candidate.isValid(certType, currentChain, opts)
889 case rootCertificate:
890 chains = append(chains, appendToFreshChain(currentChain, candidate))
891 case intermediateCertificate:
892 var childChains [][]*Certificate
893 childChains, err = candidate.buildChains(appendToFreshChain(currentChain, candidate), sigChecks, opts)
894 chains = append(chains, childChains...)
898 for _, root := range opts.Roots.findPotentialParents(c) {
899 considerCandidate(rootCertificate, root)
901 for _, intermediate := range opts.Intermediates.findPotentialParents(c) {
902 considerCandidate(intermediateCertificate, intermediate)
908 if len(chains) == 0 && err == nil {
909 err = UnknownAuthorityError{c, hintErr, hintCert}
915 func validHostnamePattern(host string) bool { return validHostname(host, true) }
916 func validHostnameInput(host string) bool { return validHostname(host, false) }
918 // validHostname reports whether host is a valid hostname that can be matched or
919 // matched against according to RFC 6125 2.2, with some leniency to accommodate
921 func validHostname(host string, isPattern bool) bool {
923 host = strings.TrimSuffix(host, ".")
929 for i, part := range strings.Split(host, ".") {
934 if isPattern && i == 0 && part == "*" {
935 // Only allow full left-most wildcards, as those are the only ones
936 // we match, and matching literal '*' characters is probably never
937 // the expected behavior.
940 for j, c := range part {
941 if 'a' <= c && c <= 'z' {
944 if '0' <= c && c <= '9' {
947 if 'A' <= c && c <= 'Z' {
950 if c == '-' && j != 0 {
954 // Not a valid character in hostnames, but commonly
955 // found in deployments outside the WebPKI.
965 func matchExactly(hostA, hostB string) bool {
966 if hostA == "" || hostA == "." || hostB == "" || hostB == "." {
969 return toLowerCaseASCII(hostA) == toLowerCaseASCII(hostB)
972 func matchHostnames(pattern, host string) bool {
973 pattern = toLowerCaseASCII(pattern)
974 host = toLowerCaseASCII(strings.TrimSuffix(host, "."))
976 if len(pattern) == 0 || len(host) == 0 {
980 patternParts := strings.Split(pattern, ".")
981 hostParts := strings.Split(host, ".")
983 if len(patternParts) != len(hostParts) {
987 for i, patternPart := range patternParts {
988 if i == 0 && patternPart == "*" {
991 if patternPart != hostParts[i] {
999 // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
1000 // an explicitly ASCII function to avoid any sharp corners resulting from
1001 // performing Unicode operations on DNS labels.
1002 func toLowerCaseASCII(in string) string {
1003 // If the string is already lower-case then there's nothing to do.
1004 isAlreadyLowerCase := true
1005 for _, c := range in {
1006 if c == utf8.RuneError {
1007 // If we get a UTF-8 error then there might be
1008 // upper-case ASCII bytes in the invalid sequence.
1009 isAlreadyLowerCase = false
1012 if 'A' <= c && c <= 'Z' {
1013 isAlreadyLowerCase = false
1018 if isAlreadyLowerCase {
1023 for i, c := range out {
1024 if 'A' <= c && c <= 'Z' {
1031 // VerifyHostname returns nil if c is a valid certificate for the named host.
1032 // Otherwise it returns an error describing the mismatch.
1034 // IP addresses can be optionally enclosed in square brackets and are checked
1035 // against the IPAddresses field. Other names are checked case insensitively
1036 // against the DNSNames field. If the names are valid hostnames, the certificate
1037 // fields can have a wildcard as the left-most label.
1039 // Note that the legacy Common Name field is ignored.
1040 func (c *Certificate) VerifyHostname(h string) error {
1041 // IP addresses may be written in [ ].
1043 if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
1044 candidateIP = h[1 : len(h)-1]
1046 if ip := net.ParseIP(candidateIP); ip != nil {
1047 // We only match IP addresses against IP SANs.
1048 // See RFC 6125, Appendix B.2.
1049 for _, candidate := range c.IPAddresses {
1050 if ip.Equal(candidate) {
1054 return HostnameError{c, candidateIP}
1057 candidateName := toLowerCaseASCII(h) // Save allocations inside the loop.
1058 validCandidateName := validHostnameInput(candidateName)
1060 for _, match := range c.DNSNames {
1061 // Ideally, we'd only match valid hostnames according to RFC 6125 like
1062 // browsers (more or less) do, but in practice Go is used in a wider
1063 // array of contexts and can't even assume DNS resolution. Instead,
1064 // always allow perfect matches, and only apply wildcard and trailing
1065 // dot processing to valid hostnames.
1066 if validCandidateName && validHostnamePattern(match) {
1067 if matchHostnames(match, candidateName) {
1071 if matchExactly(match, candidateName) {
1077 return HostnameError{c, h}
1080 func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
1081 usages := make([]ExtKeyUsage, len(keyUsages))
1082 copy(usages, keyUsages)
1084 if len(chain) == 0 {
1088 usagesRemaining := len(usages)
1090 // We walk down the list and cross out any usages that aren't supported
1091 // by each certificate. If we cross out all the usages, then the chain
1095 for i := len(chain) - 1; i >= 0; i-- {
1097 if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
1098 // The certificate doesn't have any extended key usage specified.
1102 for _, usage := range cert.ExtKeyUsage {
1103 if usage == ExtKeyUsageAny {
1104 // The certificate is explicitly good for any usage.
1109 const invalidUsage ExtKeyUsage = -1
1112 for i, requestedUsage := range usages {
1113 if requestedUsage == invalidUsage {
1117 for _, usage := range cert.ExtKeyUsage {
1118 if requestedUsage == usage {
1119 continue NextRequestedUsage
1123 usages[i] = invalidUsage
1125 if usagesRemaining == 0 {