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.
22 type InvalidReason int
25 // NotAuthorizedToSign results when a certificate is signed by another
26 // which isn't marked as a CA certificate.
27 NotAuthorizedToSign InvalidReason = iota
28 // Expired results when a certificate has expired, based on the time
29 // given in the VerifyOptions.
31 // CANotAuthorizedForThisName results when an intermediate or root
32 // certificate has a name constraint which doesn't permit a DNS or
33 // other name (including IP address) in the leaf certificate.
34 CANotAuthorizedForThisName
35 // TooManyIntermediates results when a path length constraint is
38 // IncompatibleUsage results when the certificate's key usage indicates
39 // that it may only be used for a different purpose.
41 // NameMismatch results when the subject name of a parent certificate
42 // does not match the issuer name in the child.
44 // NameConstraintsWithoutSANs is a legacy error and is no longer returned.
45 NameConstraintsWithoutSANs
46 // UnconstrainedName results when a CA certificate contains permitted
47 // name constraints, but leaf certificate contains a name of an
48 // unsupported or unconstrained type.
50 // TooManyConstraints results when the number of comparison operations
51 // needed to check a certificate exceeds the limit set by
52 // VerifyOptions.MaxConstraintComparisions. This limit exists to
53 // prevent pathological certificates can consuming excessive amounts of
54 // CPU time to verify.
56 // CANotAuthorizedForExtKeyUsage results when an intermediate or root
57 // certificate does not permit a requested extended key usage.
58 CANotAuthorizedForExtKeyUsage
61 // CertificateInvalidError results when an odd error occurs. Users of this
62 // library probably want to handle all these errors uniformly.
63 type CertificateInvalidError struct {
69 func (e CertificateInvalidError) Error() string {
71 case NotAuthorizedToSign:
72 return "x509: certificate is not authorized to sign other certificates"
74 return "x509: certificate has expired or is not yet valid: " + e.Detail
75 case CANotAuthorizedForThisName:
76 return "x509: a root or intermediate certificate is not authorized to sign for this name: " + e.Detail
77 case CANotAuthorizedForExtKeyUsage:
78 return "x509: a root or intermediate certificate is not authorized for an extended key usage: " + e.Detail
79 case TooManyIntermediates:
80 return "x509: too many intermediates for path length constraint"
81 case IncompatibleUsage:
82 return "x509: certificate specifies an incompatible key usage"
84 return "x509: issuer name does not match subject from issuing certificate"
85 case NameConstraintsWithoutSANs:
86 return "x509: issuer has name constraints but leaf doesn't have a SAN extension"
87 case UnconstrainedName:
88 return "x509: issuer has name constraints but leaf contains unknown or unconstrained name: " + e.Detail
90 return "x509: unknown error"
93 // HostnameError results when the set of authorized names doesn't match the
95 type HostnameError struct {
96 Certificate *Certificate
100 func (h HostnameError) Error() string {
103 if !c.hasSANExtension() && matchHostnames(c.Subject.CommonName, h.Host) {
104 return "x509: certificate relies on legacy Common Name field, use SANs instead"
108 if ip := net.ParseIP(h.Host); ip != nil {
109 // Trying to validate an IP
110 if len(c.IPAddresses) == 0 {
111 return "x509: cannot validate certificate for " + h.Host + " because it doesn't contain any IP SANs"
113 for _, san := range c.IPAddresses {
117 valid += san.String()
120 valid = strings.Join(c.DNSNames, ", ")
124 return "x509: certificate is not valid for any names, but wanted to match " + h.Host
126 return "x509: certificate is valid for " + valid + ", not " + h.Host
129 // UnknownAuthorityError results when the certificate issuer is unknown
130 type UnknownAuthorityError struct {
132 // hintErr contains an error that may be helpful in determining why an
133 // authority wasn't found.
135 // hintCert contains a possible authority certificate that was rejected
136 // because of the error in hintErr.
137 hintCert *Certificate
140 func (e UnknownAuthorityError) Error() string {
141 s := "x509: certificate signed by unknown authority"
142 if e.hintErr != nil {
143 certName := e.hintCert.Subject.CommonName
144 if len(certName) == 0 {
145 if len(e.hintCert.Subject.Organization) > 0 {
146 certName = e.hintCert.Subject.Organization[0]
148 certName = "serial:" + e.hintCert.SerialNumber.String()
151 s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName)
156 // SystemRootsError results when we fail to load the system root certificates.
157 type SystemRootsError struct {
161 func (se SystemRootsError) Error() string {
162 msg := "x509: failed to load system roots and no roots provided"
164 return msg + "; " + se.Err.Error()
169 func (se SystemRootsError) Unwrap() error { return se.Err }
171 // errNotParsed is returned when a certificate without ASN.1 contents is
172 // verified. Platform-specific verification needs the ASN.1 contents.
173 var errNotParsed = errors.New("x509: missing ASN.1 contents; use ParseCertificate")
175 // VerifyOptions contains parameters for Certificate.Verify.
176 type VerifyOptions struct {
177 // DNSName, if set, is checked against the leaf certificate with
178 // Certificate.VerifyHostname or the platform verifier.
181 // Intermediates is an optional pool of certificates that are not trust
182 // anchors, but can be used to form a chain from the leaf certificate to a
184 Intermediates *CertPool
185 // Roots is the set of trusted root certificates the leaf certificate needs
186 // to chain up to. If nil, the system roots or the platform verifier are used.
189 // CurrentTime is used to check the validity of all certificates in the
190 // chain. If zero, the current time is used.
191 CurrentTime time.Time
193 // KeyUsages specifies which Extended Key Usage values are acceptable. A
194 // chain is accepted if it allows any of the listed values. An empty list
195 // means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny.
196 KeyUsages []ExtKeyUsage
198 // MaxConstraintComparisions is the maximum number of comparisons to
199 // perform when checking a given certificate's name constraints. If
200 // zero, a sensible default is used. This limit prevents pathological
201 // certificates from consuming excessive amounts of CPU time when
202 // validating. It does not apply to the platform verifier.
203 MaxConstraintComparisions int
207 leafCertificate = iota
208 intermediateCertificate
212 // rfc2821Mailbox represents a “mailbox” (which is an email address to most
213 // people) by breaking it into the “local” (i.e. before the '@') and “domain”
215 type rfc2821Mailbox struct {
219 // parseRFC2821Mailbox parses an email address into local and domain parts,
220 // based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
221 // Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
222 // format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
223 func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
225 return mailbox, false
228 localPartBytes := make([]byte, 0, len(in)/2)
231 // Quoted-string = DQUOTE *qcontent DQUOTE
232 // non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
233 // qcontent = qtext / quoted-pair
234 // qtext = non-whitespace-control /
235 // %d33 / %d35-91 / %d93-126
236 // quoted-pair = ("\" text) / obs-qp
237 // text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
239 // (Names beginning with “obs-” are the obsolete syntax from RFC 2822,
240 // Section 4. Since it has been 16 years, we no longer accept that.)
245 return mailbox, false
257 return mailbox, false
261 (1 <= in[0] && in[0] <= 9) ||
262 (14 <= in[0] && in[0] <= 127) {
263 localPartBytes = append(localPartBytes, in[0])
266 return mailbox, false
271 // Space (char 32) is not allowed based on the
272 // BNF, but RFC 3696 gives an example that
273 // assumes that it is. Several “verified”
274 // errata continue to argue about this point.
275 // We choose to accept it.
279 (1 <= c && c <= 8) ||
280 (14 <= c && c <= 31) ||
281 (35 <= c && c <= 91) ||
282 (93 <= c && c <= 126):
284 localPartBytes = append(localPartBytes, c)
287 return mailbox, false
294 // atext from RFC 2822, Section 3.2.4
299 // Examples given in RFC 3696 suggest that
300 // escaped characters can appear outside of a
301 // quoted string. Several “verified” errata
302 // continue to argue the point. We choose to
306 return mailbox, false
310 case ('0' <= c && c <= '9') ||
311 ('a' <= c && c <= 'z') ||
312 ('A' <= c && c <= 'Z') ||
313 c == '!' || c == '#' || c == '$' || c == '%' ||
314 c == '&' || c == '\'' || c == '*' || c == '+' ||
315 c == '-' || c == '/' || c == '=' || c == '?' ||
316 c == '^' || c == '_' || c == '`' || c == '{' ||
317 c == '|' || c == '}' || c == '~' || c == '.':
318 localPartBytes = append(localPartBytes, in[0])
326 if len(localPartBytes) == 0 {
327 return mailbox, false
330 // From RFC 3696, Section 3:
331 // “period (".") may also appear, but may not be used to start
332 // or end the local part, nor may two or more consecutive
334 twoDots := []byte{'.', '.'}
335 if localPartBytes[0] == '.' ||
336 localPartBytes[len(localPartBytes)-1] == '.' ||
337 bytes.Contains(localPartBytes, twoDots) {
338 return mailbox, false
342 if len(in) == 0 || in[0] != '@' {
343 return mailbox, false
347 // The RFC species a format for domains, but that's known to be
348 // violated in practice so we accept that anything after an '@' is the
350 if _, ok := domainToReverseLabels(in); !ok {
351 return mailbox, false
354 mailbox.local = string(localPartBytes)
359 // domainToReverseLabels converts a textual domain name like foo.example.com to
360 // the list of labels in reverse order, e.g. ["com", "example", "foo"].
361 func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
362 for len(domain) > 0 {
363 if i := strings.LastIndexByte(domain, '.'); i == -1 {
364 reverseLabels = append(reverseLabels, domain)
367 reverseLabels = append(reverseLabels, domain[i+1:])
372 if len(reverseLabels) > 0 && len(reverseLabels[0]) == 0 {
373 // An empty label at the end indicates an absolute value.
377 for _, label := range reverseLabels {
379 // Empty labels are otherwise invalid.
383 for _, c := range label {
384 if c < 33 || c > 126 {
385 // Invalid character.
391 return reverseLabels, true
394 func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
395 // If the constraint contains an @, then it specifies an exact mailbox
397 if strings.Contains(constraint, "@") {
398 constraintMailbox, ok := parseRFC2821Mailbox(constraint)
400 return false, fmt.Errorf("x509: internal error: cannot parse constraint %q", constraint)
402 return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
405 // Otherwise the constraint is like a DNS constraint of the domain part
407 return matchDomainConstraint(mailbox.domain, constraint)
410 func matchURIConstraint(uri *url.URL, constraint string) (bool, error) {
411 // From RFC 5280, Section 4.2.1.10:
412 // “a uniformResourceIdentifier that does not include an authority
413 // component with a host name specified as a fully qualified domain
414 // name (e.g., if the URI either does not include an authority
415 // component or includes an authority component in which the host name
416 // is specified as an IP address), then the application MUST reject the
421 return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
424 if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
426 host, _, err = net.SplitHostPort(uri.Host)
432 if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") ||
433 net.ParseIP(host) != nil {
434 return false, fmt.Errorf("URI with IP (%q) cannot be matched against constraints", uri.String())
437 return matchDomainConstraint(host, constraint)
440 func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
441 if len(ip) != len(constraint.IP) {
446 if mask := constraint.Mask[i]; ip[i]&mask != constraint.IP[i]&mask {
454 func matchDomainConstraint(domain, constraint string) (bool, error) {
455 // The meaning of zero length constraints is not specified, but this
456 // code follows NSS and accepts them as matching everything.
457 if len(constraint) == 0 {
461 domainLabels, ok := domainToReverseLabels(domain)
463 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", domain)
466 // RFC 5280 says that a leading period in a domain name means that at
467 // least one label must be prepended, but only for URI and email
468 // constraints, not DNS constraints. The code also supports that
469 // behaviour for DNS constraints.
471 mustHaveSubdomains := false
472 if constraint[0] == '.' {
473 mustHaveSubdomains = true
474 constraint = constraint[1:]
477 constraintLabels, ok := domainToReverseLabels(constraint)
479 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", constraint)
482 if len(domainLabels) < len(constraintLabels) ||
483 (mustHaveSubdomains && len(domainLabels) == len(constraintLabels)) {
487 for i, constraintLabel := range constraintLabels {
488 if !strings.EqualFold(constraintLabel, domainLabels[i]) {
496 // checkNameConstraints checks that c permits a child certificate to claim the
497 // given name, of type nameType. The argument parsedName contains the parsed
498 // form of name, suitable for passing to the match function. The total number
499 // of comparisons is tracked in the given count and should not exceed the given
501 func (c *Certificate) checkNameConstraints(count *int,
502 maxConstraintComparisons int,
506 match func(parsedName, constraint any) (match bool, err error),
507 permitted, excluded any) error {
509 excludedValue := reflect.ValueOf(excluded)
511 *count += excludedValue.Len()
512 if *count > maxConstraintComparisons {
513 return CertificateInvalidError{c, TooManyConstraints, ""}
516 for i := 0; i < excludedValue.Len(); i++ {
517 constraint := excludedValue.Index(i).Interface()
518 match, err := match(parsedName, constraint)
520 return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
524 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint)}
528 permittedValue := reflect.ValueOf(permitted)
530 *count += permittedValue.Len()
531 if *count > maxConstraintComparisons {
532 return CertificateInvalidError{c, TooManyConstraints, ""}
536 for i := 0; i < permittedValue.Len(); i++ {
537 constraint := permittedValue.Index(i).Interface()
540 if ok, err = match(parsedName, constraint); err != nil {
541 return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
550 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name)}
556 // isValid performs validity checks on c given that it is a candidate to append
557 // to the chain in currentChain.
558 func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
559 if len(c.UnhandledCriticalExtensions) > 0 {
560 return UnhandledCriticalExtension{}
563 if len(currentChain) > 0 {
564 child := currentChain[len(currentChain)-1]
565 if !bytes.Equal(child.RawIssuer, c.RawSubject) {
566 return CertificateInvalidError{c, NameMismatch, ""}
570 now := opts.CurrentTime
574 if now.Before(c.NotBefore) {
575 return CertificateInvalidError{
578 Detail: fmt.Sprintf("current time %s is before %s", now.Format(time.RFC3339), c.NotBefore.Format(time.RFC3339)),
580 } else if now.After(c.NotAfter) {
581 return CertificateInvalidError{
584 Detail: fmt.Sprintf("current time %s is after %s", now.Format(time.RFC3339), c.NotAfter.Format(time.RFC3339)),
588 maxConstraintComparisons := opts.MaxConstraintComparisions
589 if maxConstraintComparisons == 0 {
590 maxConstraintComparisons = 250000
594 var leaf *Certificate
595 if certType == intermediateCertificate || certType == rootCertificate {
596 if len(currentChain) == 0 {
597 return errors.New("x509: internal error: empty chain when appending CA cert")
599 leaf = currentChain[0]
602 if (certType == intermediateCertificate || certType == rootCertificate) &&
603 c.hasNameConstraints() {
604 toCheck := []*Certificate{}
605 if leaf.hasSANExtension() {
606 toCheck = append(toCheck, leaf)
608 if c.hasSANExtension() {
609 toCheck = append(toCheck, c)
611 for _, sanCert := range toCheck {
612 err := forEachSAN(sanCert.getSANExtension(), func(tag int, data []byte) error {
616 mailbox, ok := parseRFC2821Mailbox(name)
618 return fmt.Errorf("x509: cannot parse rfc822Name %q", mailbox)
621 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "email address", name, mailbox,
622 func(parsedName, constraint any) (bool, error) {
623 return matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string))
624 }, c.PermittedEmailAddresses, c.ExcludedEmailAddresses); err != nil {
630 if _, ok := domainToReverseLabels(name); !ok {
631 return fmt.Errorf("x509: cannot parse dnsName %q", name)
634 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "DNS name", name, name,
635 func(parsedName, constraint any) (bool, error) {
636 return matchDomainConstraint(parsedName.(string), constraint.(string))
637 }, c.PermittedDNSDomains, c.ExcludedDNSDomains); err != nil {
643 uri, err := url.Parse(name)
645 return fmt.Errorf("x509: internal error: URI SAN %q failed to parse", name)
648 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "URI", name, uri,
649 func(parsedName, constraint any) (bool, error) {
650 return matchURIConstraint(parsedName.(*url.URL), constraint.(string))
651 }, c.PermittedURIDomains, c.ExcludedURIDomains); err != nil {
657 if l := len(ip); l != net.IPv4len && l != net.IPv6len {
658 return fmt.Errorf("x509: internal error: IP SAN %x failed to parse", data)
661 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "IP address", ip.String(), ip,
662 func(parsedName, constraint any) (bool, error) {
663 return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet))
664 }, c.PermittedIPRanges, c.ExcludedIPRanges); err != nil {
669 // Unknown SAN types are ignored.
681 // KeyUsage status flags are ignored. From Engineering Security, Peter
682 // Gutmann: A European government CA marked its signing certificates as
683 // being valid for encryption only, but no-one noticed. Another
684 // European CA marked its signature keys as not being valid for
685 // signatures. A different CA marked its own trusted root certificate
686 // as being invalid for certificate signing. Another national CA
687 // distributed a certificate to be used to encrypt data for the
688 // country’s tax authority that was marked as only being usable for
689 // digital signatures but not for encryption. Yet another CA reversed
690 // the order of the bit flags in the keyUsage due to confusion over
691 // encoding endianness, essentially setting a random keyUsage in
692 // certificates that it issued. Another CA created a self-invalidating
693 // certificate by adding a certificate policy statement stipulating
694 // that the certificate had to be used strictly as specified in the
695 // keyUsage, and a keyUsage containing a flag indicating that the RSA
696 // encryption key could only be used for Diffie-Hellman key agreement.
698 if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
699 return CertificateInvalidError{c, NotAuthorizedToSign, ""}
702 if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
703 numIntermediates := len(currentChain) - 1
704 if numIntermediates > c.MaxPathLen {
705 return CertificateInvalidError{c, TooManyIntermediates, ""}
709 if !boringAllowCert(c) {
710 // IncompatibleUsage is not quite right here,
711 // but it's also the "no chains found" error
712 // and is close enough.
713 return CertificateInvalidError{c, IncompatibleUsage, ""}
719 // Verify attempts to verify c by building one or more chains from c to a
720 // certificate in opts.Roots, using certificates in opts.Intermediates if
721 // needed. If successful, it returns one or more chains where the first
722 // element of the chain is c and the last element is from opts.Roots.
724 // If opts.Roots is nil, the platform verifier might be used, and
725 // verification details might differ from what is described below. If system
726 // roots are unavailable the returned error will be of type SystemRootsError.
728 // Name constraints in the intermediates will be applied to all names claimed
729 // in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim
730 // example.com if an intermediate doesn't permit it, even if example.com is not
731 // the name being validated. Note that DirectoryName constraints are not
734 // Name constraint validation follows the rules from RFC 5280, with the
735 // addition that DNS name constraints may use the leading period format
736 // defined for emails and URIs. When a constraint has a leading period
737 // it indicates that at least one additional label must be prepended to
738 // the constrained name to be considered valid.
740 // Extended Key Usage values are enforced nested down a chain, so an intermediate
741 // or root that enumerates EKUs prevents a leaf from asserting an EKU not in that
742 // list. (While this is not specified, it is common practice in order to limit
743 // the types of certificates a CA can issue.)
745 // Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not supported,
746 // and will not be used to build chains.
748 // Certificates other than c in the returned chains should not be modified.
750 // WARNING: this function doesn't do any revocation checking.
751 func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) {
752 // Platform-specific verification needs the ASN.1 contents so
753 // this makes the behavior consistent across platforms.
755 return nil, errNotParsed
757 for i := 0; i < opts.Intermediates.len(); i++ {
758 c, err := opts.Intermediates.cert(i)
760 return nil, fmt.Errorf("crypto/x509: error fetching intermediate: %w", err)
763 return nil, errNotParsed
767 // Use platform verifiers, where available, if Roots is from SystemCertPool.
768 if runtime.GOOS == "windows" || runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
769 // Don't use the system verifier if the system pool was replaced with a non-system pool,
770 // i.e. if SetFallbackRoots was called with x509usefallbackroots=1.
771 systemPool := systemRootsPool()
772 if opts.Roots == nil && (systemPool == nil || systemPool.systemPool) {
773 return c.systemVerify(&opts)
775 if opts.Roots != nil && opts.Roots.systemPool {
776 platformChains, err := c.systemVerify(&opts)
777 // If the platform verifier succeeded, or there are no additional
778 // roots, return the platform verifier result. Otherwise, continue
779 // with the Go verifier.
780 if err == nil || opts.Roots.len() == 0 {
781 return platformChains, err
786 if opts.Roots == nil {
787 opts.Roots = systemRootsPool()
788 if opts.Roots == nil {
789 return nil, SystemRootsError{systemRootsErr}
793 err = c.isValid(leafCertificate, nil, &opts)
798 if len(opts.DNSName) > 0 {
799 err = c.VerifyHostname(opts.DNSName)
805 var candidateChains [][]*Certificate
806 if opts.Roots.contains(c) {
807 candidateChains = [][]*Certificate{{c}}
809 candidateChains, err = c.buildChains([]*Certificate{c}, nil, &opts)
815 if len(opts.KeyUsages) == 0 {
816 opts.KeyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
819 for _, eku := range opts.KeyUsages {
820 if eku == ExtKeyUsageAny {
821 // If any key usage is acceptable, no need to check the chain for
823 return candidateChains, nil
827 chains = make([][]*Certificate, 0, len(candidateChains))
828 for _, candidate := range candidateChains {
829 if checkChainForKeyUsage(candidate, opts.KeyUsages) {
830 chains = append(chains, candidate)
834 if len(chains) == 0 {
835 return nil, CertificateInvalidError{c, IncompatibleUsage, ""}
841 func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate {
842 n := make([]*Certificate, len(chain)+1)
848 // alreadyInChain checks whether a candidate certificate is present in a chain.
849 // Rather than doing a direct byte for byte equivalency check, we check if the
850 // subject, public key, and SAN, if present, are equal. This prevents loops that
851 // are created by mutual cross-signatures, or other cross-signature bridge
853 func alreadyInChain(candidate *Certificate, chain []*Certificate) bool {
854 type pubKeyEqual interface {
855 Equal(crypto.PublicKey) bool
858 var candidateSAN *pkix.Extension
859 for _, ext := range candidate.Extensions {
860 if ext.Id.Equal(oidExtensionSubjectAltName) {
866 for _, cert := range chain {
867 if !bytes.Equal(candidate.RawSubject, cert.RawSubject) {
870 if !candidate.PublicKey.(pubKeyEqual).Equal(cert.PublicKey) {
873 var certSAN *pkix.Extension
874 for _, ext := range cert.Extensions {
875 if ext.Id.Equal(oidExtensionSubjectAltName) {
880 if candidateSAN == nil && certSAN == nil {
882 } else if candidateSAN == nil || certSAN == nil {
885 if bytes.Equal(candidateSAN.Value, certSAN.Value) {
892 // maxChainSignatureChecks is the maximum number of CheckSignatureFrom calls
893 // that an invocation of buildChains will (transitively) make. Most chains are
894 // less than 15 certificates long, so this leaves space for multiple chains and
895 // for failed checks due to different intermediates having the same Subject.
896 const maxChainSignatureChecks = 100
898 func (c *Certificate) buildChains(currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error) {
901 hintCert *Certificate
904 considerCandidate := func(certType int, candidate *Certificate) {
905 if alreadyInChain(candidate, currentChain) {
909 if sigChecks == nil {
913 if *sigChecks > maxChainSignatureChecks {
914 err = errors.New("x509: signature check attempts limit reached while verifying certificate chain")
918 if err := c.CheckSignatureFrom(candidate); err != nil {
926 err = candidate.isValid(certType, currentChain, opts)
932 case rootCertificate:
933 chains = append(chains, appendToFreshChain(currentChain, candidate))
934 case intermediateCertificate:
935 var childChains [][]*Certificate
936 childChains, err = candidate.buildChains(appendToFreshChain(currentChain, candidate), sigChecks, opts)
937 chains = append(chains, childChains...)
941 for _, root := range opts.Roots.findPotentialParents(c) {
942 considerCandidate(rootCertificate, root)
944 for _, intermediate := range opts.Intermediates.findPotentialParents(c) {
945 considerCandidate(intermediateCertificate, intermediate)
951 if len(chains) == 0 && err == nil {
952 err = UnknownAuthorityError{c, hintErr, hintCert}
958 func validHostnamePattern(host string) bool { return validHostname(host, true) }
959 func validHostnameInput(host string) bool { return validHostname(host, false) }
961 // validHostname reports whether host is a valid hostname that can be matched or
962 // matched against according to RFC 6125 2.2, with some leniency to accommodate
964 func validHostname(host string, isPattern bool) bool {
966 host = strings.TrimSuffix(host, ".")
972 for i, part := range strings.Split(host, ".") {
977 if isPattern && i == 0 && part == "*" {
978 // Only allow full left-most wildcards, as those are the only ones
979 // we match, and matching literal '*' characters is probably never
980 // the expected behavior.
983 for j, c := range part {
984 if 'a' <= c && c <= 'z' {
987 if '0' <= c && c <= '9' {
990 if 'A' <= c && c <= 'Z' {
993 if c == '-' && j != 0 {
997 // Not a valid character in hostnames, but commonly
998 // found in deployments outside the WebPKI.
1008 func matchExactly(hostA, hostB string) bool {
1009 if hostA == "" || hostA == "." || hostB == "" || hostB == "." {
1012 return toLowerCaseASCII(hostA) == toLowerCaseASCII(hostB)
1015 func matchHostnames(pattern, host string) bool {
1016 pattern = toLowerCaseASCII(pattern)
1017 host = toLowerCaseASCII(strings.TrimSuffix(host, "."))
1019 if len(pattern) == 0 || len(host) == 0 {
1023 patternParts := strings.Split(pattern, ".")
1024 hostParts := strings.Split(host, ".")
1026 if len(patternParts) != len(hostParts) {
1030 for i, patternPart := range patternParts {
1031 if i == 0 && patternPart == "*" {
1034 if patternPart != hostParts[i] {
1042 // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
1043 // an explicitly ASCII function to avoid any sharp corners resulting from
1044 // performing Unicode operations on DNS labels.
1045 func toLowerCaseASCII(in string) string {
1046 // If the string is already lower-case then there's nothing to do.
1047 isAlreadyLowerCase := true
1048 for _, c := range in {
1049 if c == utf8.RuneError {
1050 // If we get a UTF-8 error then there might be
1051 // upper-case ASCII bytes in the invalid sequence.
1052 isAlreadyLowerCase = false
1055 if 'A' <= c && c <= 'Z' {
1056 isAlreadyLowerCase = false
1061 if isAlreadyLowerCase {
1066 for i, c := range out {
1067 if 'A' <= c && c <= 'Z' {
1074 // VerifyHostname returns nil if c is a valid certificate for the named host.
1075 // Otherwise it returns an error describing the mismatch.
1077 // IP addresses can be optionally enclosed in square brackets and are checked
1078 // against the IPAddresses field. Other names are checked case insensitively
1079 // against the DNSNames field. If the names are valid hostnames, the certificate
1080 // fields can have a wildcard as the left-most label.
1082 // Note that the legacy Common Name field is ignored.
1083 func (c *Certificate) VerifyHostname(h string) error {
1084 // IP addresses may be written in [ ].
1086 if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
1087 candidateIP = h[1 : len(h)-1]
1089 if ip := net.ParseIP(candidateIP); ip != nil {
1090 // We only match IP addresses against IP SANs.
1091 // See RFC 6125, Appendix B.2.
1092 for _, candidate := range c.IPAddresses {
1093 if ip.Equal(candidate) {
1097 return HostnameError{c, candidateIP}
1100 candidateName := toLowerCaseASCII(h) // Save allocations inside the loop.
1101 validCandidateName := validHostnameInput(candidateName)
1103 for _, match := range c.DNSNames {
1104 // Ideally, we'd only match valid hostnames according to RFC 6125 like
1105 // browsers (more or less) do, but in practice Go is used in a wider
1106 // array of contexts and can't even assume DNS resolution. Instead,
1107 // always allow perfect matches, and only apply wildcard and trailing
1108 // dot processing to valid hostnames.
1109 if validCandidateName && validHostnamePattern(match) {
1110 if matchHostnames(match, candidateName) {
1114 if matchExactly(match, candidateName) {
1120 return HostnameError{c, h}
1123 func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
1124 usages := make([]ExtKeyUsage, len(keyUsages))
1125 copy(usages, keyUsages)
1127 if len(chain) == 0 {
1131 usagesRemaining := len(usages)
1133 // We walk down the list and cross out any usages that aren't supported
1134 // by each certificate. If we cross out all the usages, then the chain
1138 for i := len(chain) - 1; i >= 0; i-- {
1140 if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
1141 // The certificate doesn't have any extended key usage specified.
1145 for _, usage := range cert.ExtKeyUsage {
1146 if usage == ExtKeyUsageAny {
1147 // The certificate is explicitly good for any usage.
1152 const invalidUsage ExtKeyUsage = -1
1155 for i, requestedUsage := range usages {
1156 if requestedUsage == invalidUsage {
1160 for _, usage := range cert.ExtKeyUsage {
1161 if requestedUsage == usage {
1162 continue NextRequestedUsage
1166 usages[i] = invalidUsage
1168 if usagesRemaining == 0 {