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.
20 type InvalidReason int
23 // NotAuthorizedToSign results when a certificate is signed by another
24 // which isn't marked as a CA certificate.
25 NotAuthorizedToSign InvalidReason = iota
26 // Expired results when a certificate has expired, based on the time
27 // given in the VerifyOptions.
29 // CANotAuthorizedForThisName results when an intermediate or root
30 // certificate has a name constraint which doesn't permit a DNS or
31 // other name (including IP address) in the leaf certificate.
32 CANotAuthorizedForThisName
33 // TooManyIntermediates results when a path length constraint is
36 // IncompatibleUsage results when the certificate's key usage indicates
37 // that it may only be used for a different purpose.
39 // NameMismatch results when the subject name of a parent certificate
40 // does not match the issuer name in the child.
42 // NameConstraintsWithoutSANs is a legacy error and is no longer returned.
43 NameConstraintsWithoutSANs
44 // UnconstrainedName results when a CA certificate contains permitted
45 // name constraints, but leaf certificate contains a name of an
46 // unsupported or unconstrained type.
48 // TooManyConstraints results when the number of comparison operations
49 // needed to check a certificate exceeds the limit set by
50 // VerifyOptions.MaxConstraintComparisions. This limit exists to
51 // prevent pathological certificates can consuming excessive amounts of
52 // CPU time to verify.
54 // CANotAuthorizedForExtKeyUsage results when an intermediate or root
55 // certificate does not permit a requested extended key usage.
56 CANotAuthorizedForExtKeyUsage
59 // CertificateInvalidError results when an odd error occurs. Users of this
60 // library probably want to handle all these errors uniformly.
61 type CertificateInvalidError struct {
67 func (e CertificateInvalidError) Error() string {
69 case NotAuthorizedToSign:
70 return "x509: certificate is not authorized to sign other certificates"
72 return "x509: certificate has expired or is not yet valid: " + e.Detail
73 case CANotAuthorizedForThisName:
74 return "x509: a root or intermediate certificate is not authorized to sign for this name: " + e.Detail
75 case CANotAuthorizedForExtKeyUsage:
76 return "x509: a root or intermediate certificate is not authorized for an extended key usage: " + e.Detail
77 case TooManyIntermediates:
78 return "x509: too many intermediates for path length constraint"
79 case IncompatibleUsage:
80 return "x509: certificate specifies an incompatible key usage"
82 return "x509: issuer name does not match subject from issuing certificate"
83 case NameConstraintsWithoutSANs:
84 return "x509: issuer has name constraints but leaf doesn't have a SAN extension"
85 case UnconstrainedName:
86 return "x509: issuer has name constraints but leaf contains unknown or unconstrained name: " + e.Detail
88 return "x509: unknown error"
91 // HostnameError results when the set of authorized names doesn't match the
93 type HostnameError struct {
94 Certificate *Certificate
98 func (h HostnameError) Error() string {
101 if !c.hasSANExtension() && matchHostnames(c.Subject.CommonName, h.Host) {
102 return "x509: certificate relies on legacy Common Name field, use SANs instead"
106 if ip := net.ParseIP(h.Host); ip != nil {
107 // Trying to validate an IP
108 if len(c.IPAddresses) == 0 {
109 return "x509: cannot validate certificate for " + h.Host + " because it doesn't contain any IP SANs"
111 for _, san := range c.IPAddresses {
115 valid += san.String()
118 valid = strings.Join(c.DNSNames, ", ")
122 return "x509: certificate is not valid for any names, but wanted to match " + h.Host
124 return "x509: certificate is valid for " + valid + ", not " + h.Host
127 // UnknownAuthorityError results when the certificate issuer is unknown
128 type UnknownAuthorityError struct {
130 // hintErr contains an error that may be helpful in determining why an
131 // authority wasn't found.
133 // hintCert contains a possible authority certificate that was rejected
134 // because of the error in hintErr.
135 hintCert *Certificate
138 func (e UnknownAuthorityError) Error() string {
139 s := "x509: certificate signed by unknown authority"
140 if e.hintErr != nil {
141 certName := e.hintCert.Subject.CommonName
142 if len(certName) == 0 {
143 if len(e.hintCert.Subject.Organization) > 0 {
144 certName = e.hintCert.Subject.Organization[0]
146 certName = "serial:" + e.hintCert.SerialNumber.String()
149 s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName)
154 // SystemRootsError results when we fail to load the system root certificates.
155 type SystemRootsError struct {
159 func (se SystemRootsError) Error() string {
160 msg := "x509: failed to load system roots and no roots provided"
162 return msg + "; " + se.Err.Error()
167 func (se SystemRootsError) Unwrap() error { return se.Err }
169 // errNotParsed is returned when a certificate without ASN.1 contents is
170 // verified. Platform-specific verification needs the ASN.1 contents.
171 var errNotParsed = errors.New("x509: missing ASN.1 contents; use ParseCertificate")
173 // VerifyOptions contains parameters for Certificate.Verify.
174 type VerifyOptions struct {
175 // IsBoring is a validity check for BoringCrypto.
176 // If not nil, it will be called to check whether a given certificate
177 // can be used for constructing verification chains.
178 IsBoring func(*Certificate) bool
180 // DNSName, if set, is checked against the leaf certificate with
181 // Certificate.VerifyHostname or the platform verifier.
184 // Intermediates is an optional pool of certificates that are not trust
185 // anchors, but can be used to form a chain from the leaf certificate to a
187 Intermediates *CertPool
188 // Roots is the set of trusted root certificates the leaf certificate needs
189 // to chain up to. If nil, the system roots or the platform verifier are used.
192 // CurrentTime is used to check the validity of all certificates in the
193 // chain. If zero, the current time is used.
194 CurrentTime time.Time
196 // KeyUsages specifies which Extended Key Usage values are acceptable. A
197 // chain is accepted if it allows any of the listed values. An empty list
198 // means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny.
199 KeyUsages []ExtKeyUsage
201 // MaxConstraintComparisions is the maximum number of comparisons to
202 // perform when checking a given certificate's name constraints. If
203 // zero, a sensible default is used. This limit prevents pathological
204 // certificates from consuming excessive amounts of CPU time when
205 // validating. It does not apply to the platform verifier.
206 MaxConstraintComparisions int
210 leafCertificate = iota
211 intermediateCertificate
215 // rfc2821Mailbox represents a “mailbox” (which is an email address to most
216 // people) by breaking it into the “local” (i.e. before the '@') and “domain”
218 type rfc2821Mailbox struct {
222 // parseRFC2821Mailbox parses an email address into local and domain parts,
223 // based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
224 // Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
225 // format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
226 func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
228 return mailbox, false
231 localPartBytes := make([]byte, 0, len(in)/2)
234 // Quoted-string = DQUOTE *qcontent DQUOTE
235 // non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
236 // qcontent = qtext / quoted-pair
237 // qtext = non-whitespace-control /
238 // %d33 / %d35-91 / %d93-126
239 // quoted-pair = ("\" text) / obs-qp
240 // text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
242 // (Names beginning with “obs-” are the obsolete syntax from RFC 2822,
243 // Section 4. Since it has been 16 years, we no longer accept that.)
248 return mailbox, false
260 return mailbox, false
264 (1 <= in[0] && in[0] <= 9) ||
265 (14 <= in[0] && in[0] <= 127) {
266 localPartBytes = append(localPartBytes, in[0])
269 return mailbox, false
274 // Space (char 32) is not allowed based on the
275 // BNF, but RFC 3696 gives an example that
276 // assumes that it is. Several “verified”
277 // errata continue to argue about this point.
278 // We choose to accept it.
282 (1 <= c && c <= 8) ||
283 (14 <= c && c <= 31) ||
284 (35 <= c && c <= 91) ||
285 (93 <= c && c <= 126):
287 localPartBytes = append(localPartBytes, c)
290 return mailbox, false
297 // atext from RFC 2822, Section 3.2.4
302 // Examples given in RFC 3696 suggest that
303 // escaped characters can appear outside of a
304 // quoted string. Several “verified” errata
305 // continue to argue the point. We choose to
309 return mailbox, false
313 case ('0' <= c && c <= '9') ||
314 ('a' <= c && c <= 'z') ||
315 ('A' <= c && c <= 'Z') ||
316 c == '!' || c == '#' || c == '$' || c == '%' ||
317 c == '&' || c == '\'' || c == '*' || c == '+' ||
318 c == '-' || c == '/' || c == '=' || c == '?' ||
319 c == '^' || c == '_' || c == '`' || c == '{' ||
320 c == '|' || c == '}' || c == '~' || c == '.':
321 localPartBytes = append(localPartBytes, in[0])
329 if len(localPartBytes) == 0 {
330 return mailbox, false
333 // From RFC 3696, Section 3:
334 // “period (".") may also appear, but may not be used to start
335 // or end the local part, nor may two or more consecutive
337 twoDots := []byte{'.', '.'}
338 if localPartBytes[0] == '.' ||
339 localPartBytes[len(localPartBytes)-1] == '.' ||
340 bytes.Contains(localPartBytes, twoDots) {
341 return mailbox, false
345 if len(in) == 0 || in[0] != '@' {
346 return mailbox, false
350 // The RFC species a format for domains, but that's known to be
351 // violated in practice so we accept that anything after an '@' is the
353 if _, ok := domainToReverseLabels(in); !ok {
354 return mailbox, false
357 mailbox.local = string(localPartBytes)
362 // domainToReverseLabels converts a textual domain name like foo.example.com to
363 // the list of labels in reverse order, e.g. ["com", "example", "foo"].
364 func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
365 for len(domain) > 0 {
366 if i := strings.LastIndexByte(domain, '.'); i == -1 {
367 reverseLabels = append(reverseLabels, domain)
370 reverseLabels = append(reverseLabels, domain[i+1:])
375 if len(reverseLabels) > 0 && len(reverseLabels[0]) == 0 {
376 // An empty label at the end indicates an absolute value.
380 for _, label := range reverseLabels {
382 // Empty labels are otherwise invalid.
386 for _, c := range label {
387 if c < 33 || c > 126 {
388 // Invalid character.
394 return reverseLabels, true
397 func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
398 // If the constraint contains an @, then it specifies an exact mailbox
400 if strings.Contains(constraint, "@") {
401 constraintMailbox, ok := parseRFC2821Mailbox(constraint)
403 return false, fmt.Errorf("x509: internal error: cannot parse constraint %q", constraint)
405 return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
408 // Otherwise the constraint is like a DNS constraint of the domain part
410 return matchDomainConstraint(mailbox.domain, constraint)
413 func matchURIConstraint(uri *url.URL, constraint string) (bool, error) {
414 // From RFC 5280, Section 4.2.1.10:
415 // “a uniformResourceIdentifier that does not include an authority
416 // component with a host name specified as a fully qualified domain
417 // name (e.g., if the URI either does not include an authority
418 // component or includes an authority component in which the host name
419 // is specified as an IP address), then the application MUST reject the
424 return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
427 if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
429 host, _, err = net.SplitHostPort(uri.Host)
435 if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") ||
436 net.ParseIP(host) != nil {
437 return false, fmt.Errorf("URI with IP (%q) cannot be matched against constraints", uri.String())
440 return matchDomainConstraint(host, constraint)
443 func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
444 if len(ip) != len(constraint.IP) {
449 if mask := constraint.Mask[i]; ip[i]&mask != constraint.IP[i]&mask {
457 func matchDomainConstraint(domain, constraint string) (bool, error) {
458 // The meaning of zero length constraints is not specified, but this
459 // code follows NSS and accepts them as matching everything.
460 if len(constraint) == 0 {
464 domainLabels, ok := domainToReverseLabels(domain)
466 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", domain)
469 // RFC 5280 says that a leading period in a domain name means that at
470 // least one label must be prepended, but only for URI and email
471 // constraints, not DNS constraints. The code also supports that
472 // behaviour for DNS constraints.
474 mustHaveSubdomains := false
475 if constraint[0] == '.' {
476 mustHaveSubdomains = true
477 constraint = constraint[1:]
480 constraintLabels, ok := domainToReverseLabels(constraint)
482 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", constraint)
485 if len(domainLabels) < len(constraintLabels) ||
486 (mustHaveSubdomains && len(domainLabels) == len(constraintLabels)) {
490 for i, constraintLabel := range constraintLabels {
491 if !strings.EqualFold(constraintLabel, domainLabels[i]) {
499 // checkNameConstraints checks that c permits a child certificate to claim the
500 // given name, of type nameType. The argument parsedName contains the parsed
501 // form of name, suitable for passing to the match function. The total number
502 // of comparisons is tracked in the given count and should not exceed the given
504 func (c *Certificate) checkNameConstraints(count *int,
505 maxConstraintComparisons int,
509 match func(parsedName, constraint any) (match bool, err error),
510 permitted, excluded any) error {
512 excludedValue := reflect.ValueOf(excluded)
514 *count += excludedValue.Len()
515 if *count > maxConstraintComparisons {
516 return CertificateInvalidError{c, TooManyConstraints, ""}
519 for i := 0; i < excludedValue.Len(); i++ {
520 constraint := excludedValue.Index(i).Interface()
521 match, err := match(parsedName, constraint)
523 return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
527 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint)}
531 permittedValue := reflect.ValueOf(permitted)
533 *count += permittedValue.Len()
534 if *count > maxConstraintComparisons {
535 return CertificateInvalidError{c, TooManyConstraints, ""}
539 for i := 0; i < permittedValue.Len(); i++ {
540 constraint := permittedValue.Index(i).Interface()
543 if ok, err = match(parsedName, constraint); err != nil {
544 return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
553 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name)}
559 // isValid performs validity checks on c given that it is a candidate to append
560 // to the chain in currentChain.
561 func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
562 if len(c.UnhandledCriticalExtensions) > 0 {
563 return UnhandledCriticalExtension{}
566 if len(currentChain) > 0 {
567 child := currentChain[len(currentChain)-1]
568 if !bytes.Equal(child.RawIssuer, c.RawSubject) {
569 return CertificateInvalidError{c, NameMismatch, ""}
573 now := opts.CurrentTime
577 if now.Before(c.NotBefore) {
578 return CertificateInvalidError{
581 Detail: fmt.Sprintf("current time %s is before %s", now.Format(time.RFC3339), c.NotBefore.Format(time.RFC3339)),
583 } else if now.After(c.NotAfter) {
584 return CertificateInvalidError{
587 Detail: fmt.Sprintf("current time %s is after %s", now.Format(time.RFC3339), c.NotAfter.Format(time.RFC3339)),
591 maxConstraintComparisons := opts.MaxConstraintComparisions
592 if maxConstraintComparisons == 0 {
593 maxConstraintComparisons = 250000
597 var leaf *Certificate
598 if certType == intermediateCertificate || certType == rootCertificate {
599 if len(currentChain) == 0 {
600 return errors.New("x509: internal error: empty chain when appending CA cert")
602 leaf = currentChain[0]
605 if (certType == intermediateCertificate || certType == rootCertificate) &&
606 c.hasNameConstraints() && leaf.hasSANExtension() {
607 err := forEachSAN(leaf.getSANExtension(), func(tag int, data []byte) error {
611 mailbox, ok := parseRFC2821Mailbox(name)
613 return fmt.Errorf("x509: cannot parse rfc822Name %q", mailbox)
616 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "email address", name, mailbox,
617 func(parsedName, constraint any) (bool, error) {
618 return matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string))
619 }, c.PermittedEmailAddresses, c.ExcludedEmailAddresses); err != nil {
625 if _, ok := domainToReverseLabels(name); !ok {
626 return fmt.Errorf("x509: cannot parse dnsName %q", name)
629 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "DNS name", name, name,
630 func(parsedName, constraint any) (bool, error) {
631 return matchDomainConstraint(parsedName.(string), constraint.(string))
632 }, c.PermittedDNSDomains, c.ExcludedDNSDomains); err != nil {
638 uri, err := url.Parse(name)
640 return fmt.Errorf("x509: internal error: URI SAN %q failed to parse", name)
643 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "URI", name, uri,
644 func(parsedName, constraint any) (bool, error) {
645 return matchURIConstraint(parsedName.(*url.URL), constraint.(string))
646 }, c.PermittedURIDomains, c.ExcludedURIDomains); err != nil {
652 if l := len(ip); l != net.IPv4len && l != net.IPv6len {
653 return fmt.Errorf("x509: internal error: IP SAN %x failed to parse", data)
656 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "IP address", ip.String(), ip,
657 func(parsedName, constraint any) (bool, error) {
658 return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet))
659 }, c.PermittedIPRanges, c.ExcludedIPRanges); err != nil {
664 // Unknown SAN types are ignored.
675 // KeyUsage status flags are ignored. From Engineering Security, Peter
676 // Gutmann: A European government CA marked its signing certificates as
677 // being valid for encryption only, but no-one noticed. Another
678 // European CA marked its signature keys as not being valid for
679 // signatures. A different CA marked its own trusted root certificate
680 // as being invalid for certificate signing. Another national CA
681 // distributed a certificate to be used to encrypt data for the
682 // country’s tax authority that was marked as only being usable for
683 // digital signatures but not for encryption. Yet another CA reversed
684 // the order of the bit flags in the keyUsage due to confusion over
685 // encoding endianness, essentially setting a random keyUsage in
686 // certificates that it issued. Another CA created a self-invalidating
687 // certificate by adding a certificate policy statement stipulating
688 // that the certificate had to be used strictly as specified in the
689 // keyUsage, and a keyUsage containing a flag indicating that the RSA
690 // encryption key could only be used for Diffie-Hellman key agreement.
692 if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
693 return CertificateInvalidError{c, NotAuthorizedToSign, ""}
696 if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
697 numIntermediates := len(currentChain) - 1
698 if numIntermediates > c.MaxPathLen {
699 return CertificateInvalidError{c, TooManyIntermediates, ""}
703 if opts.IsBoring != nil && !opts.IsBoring(c) {
704 // IncompatibleUsage is not quite right here,
705 // but it's also the "no chains found" error
706 // and is close enough.
707 return CertificateInvalidError{c, IncompatibleUsage, ""}
713 // Verify attempts to verify c by building one or more chains from c to a
714 // certificate in opts.Roots, using certificates in opts.Intermediates if
715 // needed. If successful, it returns one or more chains where the first
716 // element of the chain is c and the last element is from opts.Roots.
718 // If opts.Roots is nil, the platform verifier might be used, and
719 // verification details might differ from what is described below. If system
720 // roots are unavailable the returned error will be of type SystemRootsError.
722 // Name constraints in the intermediates will be applied to all names claimed
723 // in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim
724 // example.com if an intermediate doesn't permit it, even if example.com is not
725 // the name being validated. Note that DirectoryName constraints are not
728 // Name constraint validation follows the rules from RFC 5280, with the
729 // addition that DNS name constraints may use the leading period format
730 // defined for emails and URIs. When a constraint has a leading period
731 // it indicates that at least one additional label must be prepended to
732 // the constrained name to be considered valid.
734 // Extended Key Usage values are enforced nested down a chain, so an intermediate
735 // or root that enumerates EKUs prevents a leaf from asserting an EKU not in that
736 // list. (While this is not specified, it is common practice in order to limit
737 // the types of certificates a CA can issue.)
739 // WARNING: this function doesn't do any revocation checking.
740 func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) {
741 // Platform-specific verification needs the ASN.1 contents so
742 // this makes the behavior consistent across platforms.
744 return nil, errNotParsed
746 for i := 0; i < opts.Intermediates.len(); i++ {
747 c, err := opts.Intermediates.cert(i)
749 return nil, fmt.Errorf("crypto/x509: error fetching intermediate: %w", err)
752 return nil, errNotParsed
756 // Use platform verifiers, where available, if Roots is from SystemCertPool.
757 if runtime.GOOS == "windows" || runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
758 if opts.Roots == nil {
759 return c.systemVerify(&opts)
761 if opts.Roots != nil && opts.Roots.systemPool {
762 platformChains, err := c.systemVerify(&opts)
763 // If the platform verifier succeeded, or there are no additional
764 // roots, return the platform verifier result. Otherwise, continue
765 // with the Go verifier.
766 if err == nil || opts.Roots.len() == 0 {
767 return platformChains, err
772 if opts.Roots == nil {
773 opts.Roots = systemRootsPool()
774 if opts.Roots == nil {
775 return nil, SystemRootsError{systemRootsErr}
779 err = c.isValid(leafCertificate, nil, &opts)
784 if len(opts.DNSName) > 0 {
785 err = c.VerifyHostname(opts.DNSName)
791 var candidateChains [][]*Certificate
792 if opts.Roots.contains(c) {
793 candidateChains = append(candidateChains, []*Certificate{c})
795 if candidateChains, err = c.buildChains(nil, []*Certificate{c}, nil, &opts); err != nil {
800 keyUsages := opts.KeyUsages
801 if len(keyUsages) == 0 {
802 keyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
805 // If any key usage is acceptable then we're done.
806 for _, usage := range keyUsages {
807 if usage == ExtKeyUsageAny {
808 return candidateChains, nil
812 for _, candidate := range candidateChains {
813 if checkChainForKeyUsage(candidate, keyUsages) {
814 chains = append(chains, candidate)
818 if len(chains) == 0 {
819 return nil, CertificateInvalidError{c, IncompatibleUsage, ""}
825 func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate {
826 n := make([]*Certificate, len(chain)+1)
832 // maxChainSignatureChecks is the maximum number of CheckSignatureFrom calls
833 // that an invocation of buildChains will (transitively) make. Most chains are
834 // less than 15 certificates long, so this leaves space for multiple chains and
835 // for failed checks due to different intermediates having the same Subject.
836 const maxChainSignatureChecks = 100
838 func (c *Certificate) buildChains(cache map[*Certificate][][]*Certificate, currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error) {
841 hintCert *Certificate
844 considerCandidate := func(certType int, candidate *Certificate) {
845 for _, cert := range currentChain {
846 if cert.Equal(candidate) {
851 if sigChecks == nil {
855 if *sigChecks > maxChainSignatureChecks {
856 err = errors.New("x509: signature check attempts limit reached while verifying certificate chain")
860 if err := c.CheckSignatureFrom(candidate); err != nil {
868 err = candidate.isValid(certType, currentChain, opts)
874 case rootCertificate:
875 chains = append(chains, appendToFreshChain(currentChain, candidate))
876 case intermediateCertificate:
878 cache = make(map[*Certificate][][]*Certificate)
880 childChains, ok := cache[candidate]
882 childChains, err = candidate.buildChains(cache, appendToFreshChain(currentChain, candidate), sigChecks, opts)
883 cache[candidate] = childChains
885 chains = append(chains, childChains...)
889 for _, root := range opts.Roots.findPotentialParents(c) {
890 considerCandidate(rootCertificate, root)
892 for _, intermediate := range opts.Intermediates.findPotentialParents(c) {
893 considerCandidate(intermediateCertificate, intermediate)
899 if len(chains) == 0 && err == nil {
900 err = UnknownAuthorityError{c, hintErr, hintCert}
906 func validHostnamePattern(host string) bool { return validHostname(host, true) }
907 func validHostnameInput(host string) bool { return validHostname(host, false) }
909 // validHostname reports whether host is a valid hostname that can be matched or
910 // matched against according to RFC 6125 2.2, with some leniency to accommodate
912 func validHostname(host string, isPattern bool) bool {
914 host = strings.TrimSuffix(host, ".")
920 for i, part := range strings.Split(host, ".") {
925 if isPattern && i == 0 && part == "*" {
926 // Only allow full left-most wildcards, as those are the only ones
927 // we match, and matching literal '*' characters is probably never
928 // the expected behavior.
931 for j, c := range part {
932 if 'a' <= c && c <= 'z' {
935 if '0' <= c && c <= '9' {
938 if 'A' <= c && c <= 'Z' {
941 if c == '-' && j != 0 {
945 // Not a valid character in hostnames, but commonly
946 // found in deployments outside the WebPKI.
956 func matchExactly(hostA, hostB string) bool {
957 if hostA == "" || hostA == "." || hostB == "" || hostB == "." {
960 return toLowerCaseASCII(hostA) == toLowerCaseASCII(hostB)
963 func matchHostnames(pattern, host string) bool {
964 pattern = toLowerCaseASCII(pattern)
965 host = toLowerCaseASCII(strings.TrimSuffix(host, "."))
967 if len(pattern) == 0 || len(host) == 0 {
971 patternParts := strings.Split(pattern, ".")
972 hostParts := strings.Split(host, ".")
974 if len(patternParts) != len(hostParts) {
978 for i, patternPart := range patternParts {
979 if i == 0 && patternPart == "*" {
982 if patternPart != hostParts[i] {
990 // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
991 // an explicitly ASCII function to avoid any sharp corners resulting from
992 // performing Unicode operations on DNS labels.
993 func toLowerCaseASCII(in string) string {
994 // If the string is already lower-case then there's nothing to do.
995 isAlreadyLowerCase := true
996 for _, c := range in {
997 if c == utf8.RuneError {
998 // If we get a UTF-8 error then there might be
999 // upper-case ASCII bytes in the invalid sequence.
1000 isAlreadyLowerCase = false
1003 if 'A' <= c && c <= 'Z' {
1004 isAlreadyLowerCase = false
1009 if isAlreadyLowerCase {
1014 for i, c := range out {
1015 if 'A' <= c && c <= 'Z' {
1022 // VerifyHostname returns nil if c is a valid certificate for the named host.
1023 // Otherwise it returns an error describing the mismatch.
1025 // IP addresses can be optionally enclosed in square brackets and are checked
1026 // against the IPAddresses field. Other names are checked case insensitively
1027 // against the DNSNames field. If the names are valid hostnames, the certificate
1028 // fields can have a wildcard as the left-most label.
1030 // Note that the legacy Common Name field is ignored.
1031 func (c *Certificate) VerifyHostname(h string) error {
1032 // IP addresses may be written in [ ].
1034 if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
1035 candidateIP = h[1 : len(h)-1]
1037 if ip := net.ParseIP(candidateIP); ip != nil {
1038 // We only match IP addresses against IP SANs.
1039 // See RFC 6125, Appendix B.2.
1040 for _, candidate := range c.IPAddresses {
1041 if ip.Equal(candidate) {
1045 return HostnameError{c, candidateIP}
1048 candidateName := toLowerCaseASCII(h) // Save allocations inside the loop.
1049 validCandidateName := validHostnameInput(candidateName)
1051 for _, match := range c.DNSNames {
1052 // Ideally, we'd only match valid hostnames according to RFC 6125 like
1053 // browsers (more or less) do, but in practice Go is used in a wider
1054 // array of contexts and can't even assume DNS resolution. Instead,
1055 // always allow perfect matches, and only apply wildcard and trailing
1056 // dot processing to valid hostnames.
1057 if validCandidateName && validHostnamePattern(match) {
1058 if matchHostnames(match, candidateName) {
1062 if matchExactly(match, candidateName) {
1068 return HostnameError{c, h}
1071 func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
1072 usages := make([]ExtKeyUsage, len(keyUsages))
1073 copy(usages, keyUsages)
1075 if len(chain) == 0 {
1079 usagesRemaining := len(usages)
1081 // We walk down the list and cross out any usages that aren't supported
1082 // by each certificate. If we cross out all the usages, then the chain
1086 for i := len(chain) - 1; i >= 0; i-- {
1088 if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
1089 // The certificate doesn't have any extended key usage specified.
1093 for _, usage := range cert.ExtKeyUsage {
1094 if usage == ExtKeyUsageAny {
1095 // The certificate is explicitly good for any usage.
1100 const invalidUsage ExtKeyUsage = -1
1103 for i, requestedUsage := range usages {
1104 if requestedUsage == invalidUsage {
1108 for _, usage := range cert.ExtKeyUsage {
1109 if requestedUsage == usage {
1110 continue NextRequestedUsage
1114 usages[i] = invalidUsage
1116 if usagesRemaining == 0 {