1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
21 // ignoreCN disables interpreting Common Name as a hostname. See issue 24151.
22 var ignoreCN = !strings.Contains(os.Getenv("GODEBUG"), "x509ignoreCN=0")
24 type InvalidReason int
27 // NotAuthorizedToSign results when a certificate is signed by another
28 // which isn't marked as a CA certificate.
29 NotAuthorizedToSign InvalidReason = iota
30 // Expired results when a certificate has expired, based on the time
31 // given in the VerifyOptions.
33 // CANotAuthorizedForThisName results when an intermediate or root
34 // certificate has a name constraint which doesn't permit a DNS or
35 // other name (including IP address) in the leaf certificate.
36 CANotAuthorizedForThisName
37 // TooManyIntermediates results when a path length constraint is
40 // IncompatibleUsage results when the certificate's key usage indicates
41 // that it may only be used for a different purpose.
43 // NameMismatch results when the subject name of a parent certificate
44 // does not match the issuer name in the child.
46 // NameConstraintsWithoutSANs results when a leaf certificate doesn't
47 // contain a Subject Alternative Name extension, but a CA certificate
48 // contains name constraints, and the Common Name can be interpreted as
51 // This error is only returned when legacy Common Name matching is enabled
52 // by setting the GODEBUG environment variable to "x509ignoreCN=1". This
53 // setting might be removed in the future.
54 NameConstraintsWithoutSANs
55 // UnconstrainedName results when a CA certificate contains permitted
56 // name constraints, but leaf certificate contains a name of an
57 // unsupported or unconstrained type.
59 // TooManyConstraints results when the number of comparison operations
60 // needed to check a certificate exceeds the limit set by
61 // VerifyOptions.MaxConstraintComparisions. This limit exists to
62 // prevent pathological certificates can consuming excessive amounts of
63 // CPU time to verify.
65 // CANotAuthorizedForExtKeyUsage results when an intermediate or root
66 // certificate does not permit a requested extended key usage.
67 CANotAuthorizedForExtKeyUsage
70 // CertificateInvalidError results when an odd error occurs. Users of this
71 // library probably want to handle all these errors uniformly.
72 type CertificateInvalidError struct {
78 func (e CertificateInvalidError) Error() string {
80 case NotAuthorizedToSign:
81 return "x509: certificate is not authorized to sign other certificates"
83 return "x509: certificate has expired or is not yet valid: " + e.Detail
84 case CANotAuthorizedForThisName:
85 return "x509: a root or intermediate certificate is not authorized to sign for this name: " + e.Detail
86 case CANotAuthorizedForExtKeyUsage:
87 return "x509: a root or intermediate certificate is not authorized for an extended key usage: " + e.Detail
88 case TooManyIntermediates:
89 return "x509: too many intermediates for path length constraint"
90 case IncompatibleUsage:
91 return "x509: certificate specifies an incompatible key usage"
93 return "x509: issuer name does not match subject from issuing certificate"
94 case NameConstraintsWithoutSANs:
95 return "x509: issuer has name constraints but leaf doesn't have a SAN extension"
96 case UnconstrainedName:
97 return "x509: issuer has name constraints but leaf contains unknown or unconstrained name: " + e.Detail
99 return "x509: unknown error"
102 // HostnameError results when the set of authorized names doesn't match the
104 type HostnameError struct {
105 Certificate *Certificate
109 func (h HostnameError) Error() string {
112 if !c.hasSANExtension() && matchHostnames(c.Subject.CommonName, h.Host) {
113 if !ignoreCN && !validHostnamePattern(c.Subject.CommonName) {
114 // This would have validated, if it weren't for the validHostname check on Common Name.
115 return "x509: Common Name is not a valid hostname: " + c.Subject.CommonName
117 if ignoreCN && validHostnamePattern(c.Subject.CommonName) {
118 // This would have validated if x509ignoreCN=0 were set.
119 return "x509: certificate relies on legacy Common Name field, " +
120 "use SANs or temporarily enable Common Name matching with GODEBUG=x509ignoreCN=0"
125 if ip := net.ParseIP(h.Host); ip != nil {
126 // Trying to validate an IP
127 if len(c.IPAddresses) == 0 {
128 return "x509: cannot validate certificate for " + h.Host + " because it doesn't contain any IP SANs"
130 for _, san := range c.IPAddresses {
134 valid += san.String()
137 if c.commonNameAsHostname() {
138 valid = c.Subject.CommonName
140 valid = strings.Join(c.DNSNames, ", ")
145 return "x509: certificate is not valid for any names, but wanted to match " + h.Host
147 return "x509: certificate is valid for " + valid + ", not " + h.Host
150 // UnknownAuthorityError results when the certificate issuer is unknown
151 type UnknownAuthorityError struct {
153 // hintErr contains an error that may be helpful in determining why an
154 // authority wasn't found.
156 // hintCert contains a possible authority certificate that was rejected
157 // because of the error in hintErr.
158 hintCert *Certificate
161 func (e UnknownAuthorityError) Error() string {
162 s := "x509: certificate signed by unknown authority"
163 if e.hintErr != nil {
164 certName := e.hintCert.Subject.CommonName
165 if len(certName) == 0 {
166 if len(e.hintCert.Subject.Organization) > 0 {
167 certName = e.hintCert.Subject.Organization[0]
169 certName = "serial:" + e.hintCert.SerialNumber.String()
172 s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName)
177 // SystemRootsError results when we fail to load the system root certificates.
178 type SystemRootsError struct {
182 func (se SystemRootsError) Error() string {
183 msg := "x509: failed to load system roots and no roots provided"
185 return msg + "; " + se.Err.Error()
190 func (se SystemRootsError) Unwrap() error { return se.Err }
192 // errNotParsed is returned when a certificate without ASN.1 contents is
193 // verified. Platform-specific verification needs the ASN.1 contents.
194 var errNotParsed = errors.New("x509: missing ASN.1 contents; use ParseCertificate")
196 // VerifyOptions contains parameters for Certificate.Verify.
197 type VerifyOptions struct {
198 // IsBoring is a validity check for BoringCrypto.
199 // If not nil, it will be called to check whether a given certificate
200 // can be used for constructing verification chains.
201 IsBoring func(*Certificate) bool
203 // DNSName, if set, is checked against the leaf certificate with
204 // Certificate.VerifyHostname or the platform verifier.
207 // Intermediates is an optional pool of certificates that are not trust
208 // anchors, but can be used to form a chain from the leaf certificate to a
210 Intermediates *CertPool
211 // Roots is the set of trusted root certificates the leaf certificate needs
212 // to chain up to. If nil, the system roots or the platform verifier are used.
215 // CurrentTime is used to check the validity of all certificates in the
216 // chain. If zero, the current time is used.
217 CurrentTime time.Time
219 // KeyUsages specifies which Extended Key Usage values are acceptable. A
220 // chain is accepted if it allows any of the listed values. An empty list
221 // means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny.
222 KeyUsages []ExtKeyUsage
224 // MaxConstraintComparisions is the maximum number of comparisons to
225 // perform when checking a given certificate's name constraints. If
226 // zero, a sensible default is used. This limit prevents pathological
227 // certificates from consuming excessive amounts of CPU time when
228 // validating. It does not apply to the platform verifier.
229 MaxConstraintComparisions int
233 leafCertificate = iota
234 intermediateCertificate
238 // rfc2821Mailbox represents a “mailbox” (which is an email address to most
239 // people) by breaking it into the “local” (i.e. before the '@') and “domain”
241 type rfc2821Mailbox struct {
245 // parseRFC2821Mailbox parses an email address into local and domain parts,
246 // based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
247 // Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
248 // format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
249 func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
251 return mailbox, false
254 localPartBytes := make([]byte, 0, len(in)/2)
257 // Quoted-string = DQUOTE *qcontent DQUOTE
258 // non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
259 // qcontent = qtext / quoted-pair
260 // qtext = non-whitespace-control /
261 // %d33 / %d35-91 / %d93-126
262 // quoted-pair = ("\" text) / obs-qp
263 // text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
265 // (Names beginning with “obs-” are the obsolete syntax from RFC 2822,
266 // Section 4. Since it has been 16 years, we no longer accept that.)
271 return mailbox, false
283 return mailbox, false
287 (1 <= in[0] && in[0] <= 9) ||
288 (14 <= in[0] && in[0] <= 127) {
289 localPartBytes = append(localPartBytes, in[0])
292 return mailbox, false
297 // Space (char 32) is not allowed based on the
298 // BNF, but RFC 3696 gives an example that
299 // assumes that it is. Several “verified”
300 // errata continue to argue about this point.
301 // We choose to accept it.
305 (1 <= c && c <= 8) ||
306 (14 <= c && c <= 31) ||
307 (35 <= c && c <= 91) ||
308 (93 <= c && c <= 126):
310 localPartBytes = append(localPartBytes, c)
313 return mailbox, false
320 // atext from RFC 2822, Section 3.2.4
325 // Examples given in RFC 3696 suggest that
326 // escaped characters can appear outside of a
327 // quoted string. Several “verified” errata
328 // continue to argue the point. We choose to
332 return mailbox, false
336 case ('0' <= c && c <= '9') ||
337 ('a' <= c && c <= 'z') ||
338 ('A' <= c && c <= 'Z') ||
339 c == '!' || c == '#' || c == '$' || c == '%' ||
340 c == '&' || c == '\'' || c == '*' || c == '+' ||
341 c == '-' || c == '/' || c == '=' || c == '?' ||
342 c == '^' || c == '_' || c == '`' || c == '{' ||
343 c == '|' || c == '}' || c == '~' || c == '.':
344 localPartBytes = append(localPartBytes, in[0])
352 if len(localPartBytes) == 0 {
353 return mailbox, false
356 // From RFC 3696, Section 3:
357 // “period (".") may also appear, but may not be used to start
358 // or end the local part, nor may two or more consecutive
360 twoDots := []byte{'.', '.'}
361 if localPartBytes[0] == '.' ||
362 localPartBytes[len(localPartBytes)-1] == '.' ||
363 bytes.Contains(localPartBytes, twoDots) {
364 return mailbox, false
368 if len(in) == 0 || in[0] != '@' {
369 return mailbox, false
373 // The RFC species a format for domains, but that's known to be
374 // violated in practice so we accept that anything after an '@' is the
376 if _, ok := domainToReverseLabels(in); !ok {
377 return mailbox, false
380 mailbox.local = string(localPartBytes)
385 // domainToReverseLabels converts a textual domain name like foo.example.com to
386 // the list of labels in reverse order, e.g. ["com", "example", "foo"].
387 func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
388 for len(domain) > 0 {
389 if i := strings.LastIndexByte(domain, '.'); i == -1 {
390 reverseLabels = append(reverseLabels, domain)
393 reverseLabels = append(reverseLabels, domain[i+1:])
398 if len(reverseLabels) > 0 && len(reverseLabels[0]) == 0 {
399 // An empty label at the end indicates an absolute value.
403 for _, label := range reverseLabels {
405 // Empty labels are otherwise invalid.
409 for _, c := range label {
410 if c < 33 || c > 126 {
411 // Invalid character.
417 return reverseLabels, true
420 func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
421 // If the constraint contains an @, then it specifies an exact mailbox
423 if strings.Contains(constraint, "@") {
424 constraintMailbox, ok := parseRFC2821Mailbox(constraint)
426 return false, fmt.Errorf("x509: internal error: cannot parse constraint %q", constraint)
428 return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
431 // Otherwise the constraint is like a DNS constraint of the domain part
433 return matchDomainConstraint(mailbox.domain, constraint)
436 func matchURIConstraint(uri *url.URL, constraint string) (bool, error) {
437 // From RFC 5280, Section 4.2.1.10:
438 // “a uniformResourceIdentifier that does not include an authority
439 // component with a host name specified as a fully qualified domain
440 // name (e.g., if the URI either does not include an authority
441 // component or includes an authority component in which the host name
442 // is specified as an IP address), then the application MUST reject the
447 return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
450 if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
452 host, _, err = net.SplitHostPort(uri.Host)
458 if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") ||
459 net.ParseIP(host) != nil {
460 return false, fmt.Errorf("URI with IP (%q) cannot be matched against constraints", uri.String())
463 return matchDomainConstraint(host, constraint)
466 func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
467 if len(ip) != len(constraint.IP) {
472 if mask := constraint.Mask[i]; ip[i]&mask != constraint.IP[i]&mask {
480 func matchDomainConstraint(domain, constraint string) (bool, error) {
481 // The meaning of zero length constraints is not specified, but this
482 // code follows NSS and accepts them as matching everything.
483 if len(constraint) == 0 {
487 domainLabels, ok := domainToReverseLabels(domain)
489 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", domain)
492 // RFC 5280 says that a leading period in a domain name means that at
493 // least one label must be prepended, but only for URI and email
494 // constraints, not DNS constraints. The code also supports that
495 // behaviour for DNS constraints.
497 mustHaveSubdomains := false
498 if constraint[0] == '.' {
499 mustHaveSubdomains = true
500 constraint = constraint[1:]
503 constraintLabels, ok := domainToReverseLabels(constraint)
505 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", constraint)
508 if len(domainLabels) < len(constraintLabels) ||
509 (mustHaveSubdomains && len(domainLabels) == len(constraintLabels)) {
513 for i, constraintLabel := range constraintLabels {
514 if !strings.EqualFold(constraintLabel, domainLabels[i]) {
522 // checkNameConstraints checks that c permits a child certificate to claim the
523 // given name, of type nameType. The argument parsedName contains the parsed
524 // form of name, suitable for passing to the match function. The total number
525 // of comparisons is tracked in the given count and should not exceed the given
527 func (c *Certificate) checkNameConstraints(count *int,
528 maxConstraintComparisons int,
531 parsedName interface{},
532 match func(parsedName, constraint interface{}) (match bool, err error),
533 permitted, excluded interface{}) error {
535 excludedValue := reflect.ValueOf(excluded)
537 *count += excludedValue.Len()
538 if *count > maxConstraintComparisons {
539 return CertificateInvalidError{c, TooManyConstraints, ""}
542 for i := 0; i < excludedValue.Len(); i++ {
543 constraint := excludedValue.Index(i).Interface()
544 match, err := match(parsedName, constraint)
546 return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
550 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint)}
554 permittedValue := reflect.ValueOf(permitted)
556 *count += permittedValue.Len()
557 if *count > maxConstraintComparisons {
558 return CertificateInvalidError{c, TooManyConstraints, ""}
562 for i := 0; i < permittedValue.Len(); i++ {
563 constraint := permittedValue.Index(i).Interface()
566 if ok, err = match(parsedName, constraint); err != nil {
567 return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
576 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name)}
582 // isValid performs validity checks on c given that it is a candidate to append
583 // to the chain in currentChain.
584 func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
585 if len(c.UnhandledCriticalExtensions) > 0 {
586 return UnhandledCriticalExtension{}
589 if len(currentChain) > 0 {
590 child := currentChain[len(currentChain)-1]
591 if !bytes.Equal(child.RawIssuer, c.RawSubject) {
592 return CertificateInvalidError{c, NameMismatch, ""}
596 now := opts.CurrentTime
600 if now.Before(c.NotBefore) {
601 return CertificateInvalidError{
604 Detail: fmt.Sprintf("current time %s is before %s", now.Format(time.RFC3339), c.NotBefore.Format(time.RFC3339)),
606 } else if now.After(c.NotAfter) {
607 return CertificateInvalidError{
610 Detail: fmt.Sprintf("current time %s is after %s", now.Format(time.RFC3339), c.NotAfter.Format(time.RFC3339)),
614 maxConstraintComparisons := opts.MaxConstraintComparisions
615 if maxConstraintComparisons == 0 {
616 maxConstraintComparisons = 250000
620 var leaf *Certificate
621 if certType == intermediateCertificate || certType == rootCertificate {
622 if len(currentChain) == 0 {
623 return errors.New("x509: internal error: empty chain when appending CA cert")
625 leaf = currentChain[0]
628 checkNameConstraints := (certType == intermediateCertificate || certType == rootCertificate) && c.hasNameConstraints()
629 if checkNameConstraints && leaf.commonNameAsHostname() {
630 // This is the deprecated, legacy case of depending on the commonName as
631 // a hostname. We don't enforce name constraints against the CN, but
632 // VerifyHostname will look for hostnames in there if there are no SANs.
633 // In order to ensure VerifyHostname will not accept an unchecked name,
634 // return an error here.
635 return CertificateInvalidError{c, NameConstraintsWithoutSANs, ""}
636 } else if checkNameConstraints && leaf.hasSANExtension() {
637 err := forEachSAN(leaf.getSANExtension(), func(tag int, data []byte) error {
641 mailbox, ok := parseRFC2821Mailbox(name)
643 return fmt.Errorf("x509: cannot parse rfc822Name %q", mailbox)
646 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "email address", name, mailbox,
647 func(parsedName, constraint interface{}) (bool, error) {
648 return matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string))
649 }, c.PermittedEmailAddresses, c.ExcludedEmailAddresses); err != nil {
655 if _, ok := domainToReverseLabels(name); !ok {
656 return fmt.Errorf("x509: cannot parse dnsName %q", name)
659 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "DNS name", name, name,
660 func(parsedName, constraint interface{}) (bool, error) {
661 return matchDomainConstraint(parsedName.(string), constraint.(string))
662 }, c.PermittedDNSDomains, c.ExcludedDNSDomains); err != nil {
668 uri, err := url.Parse(name)
670 return fmt.Errorf("x509: internal error: URI SAN %q failed to parse", name)
673 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "URI", name, uri,
674 func(parsedName, constraint interface{}) (bool, error) {
675 return matchURIConstraint(parsedName.(*url.URL), constraint.(string))
676 }, c.PermittedURIDomains, c.ExcludedURIDomains); err != nil {
682 if l := len(ip); l != net.IPv4len && l != net.IPv6len {
683 return fmt.Errorf("x509: internal error: IP SAN %x failed to parse", data)
686 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "IP address", ip.String(), ip,
687 func(parsedName, constraint interface{}) (bool, error) {
688 return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet))
689 }, c.PermittedIPRanges, c.ExcludedIPRanges); err != nil {
694 // Unknown SAN types are ignored.
705 // KeyUsage status flags are ignored. From Engineering Security, Peter
706 // Gutmann: A European government CA marked its signing certificates as
707 // being valid for encryption only, but no-one noticed. Another
708 // European CA marked its signature keys as not being valid for
709 // signatures. A different CA marked its own trusted root certificate
710 // as being invalid for certificate signing. Another national CA
711 // distributed a certificate to be used to encrypt data for the
712 // country’s tax authority that was marked as only being usable for
713 // digital signatures but not for encryption. Yet another CA reversed
714 // the order of the bit flags in the keyUsage due to confusion over
715 // encoding endianness, essentially setting a random keyUsage in
716 // certificates that it issued. Another CA created a self-invalidating
717 // certificate by adding a certificate policy statement stipulating
718 // that the certificate had to be used strictly as specified in the
719 // keyUsage, and a keyUsage containing a flag indicating that the RSA
720 // encryption key could only be used for Diffie-Hellman key agreement.
722 if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
723 return CertificateInvalidError{c, NotAuthorizedToSign, ""}
726 if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
727 numIntermediates := len(currentChain) - 1
728 if numIntermediates > c.MaxPathLen {
729 return CertificateInvalidError{c, TooManyIntermediates, ""}
733 if opts.IsBoring != nil && !opts.IsBoring(c) {
734 // IncompatibleUsage is not quite right here,
735 // but it's also the "no chains found" error
736 // and is close enough.
737 return CertificateInvalidError{c, IncompatibleUsage, ""}
743 // Verify attempts to verify c by building one or more chains from c to a
744 // certificate in opts.Roots, using certificates in opts.Intermediates if
745 // needed. If successful, it returns one or more chains where the first
746 // element of the chain is c and the last element is from opts.Roots.
748 // If opts.Roots is nil, the platform verifier might be used, and
749 // verification details might differ from what is described below. If system
750 // roots are unavailable the returned error will be of type SystemRootsError.
752 // Name constraints in the intermediates will be applied to all names claimed
753 // in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim
754 // example.com if an intermediate doesn't permit it, even if example.com is not
755 // the name being validated. Note that DirectoryName constraints are not
758 // Name constraint validation follows the rules from RFC 5280, with the
759 // addition that DNS name constraints may use the leading period format
760 // defined for emails and URIs. When a constraint has a leading period
761 // it indicates that at least one additional label must be prepended to
762 // the constrained name to be considered valid.
764 // Extended Key Usage values are enforced nested down a chain, so an intermediate
765 // or root that enumerates EKUs prevents a leaf from asserting an EKU not in that
766 // list. (While this is not specified, it is common practice in order to limit
767 // the types of certificates a CA can issue.)
769 // WARNING: this function doesn't do any revocation checking.
770 func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) {
771 // Platform-specific verification needs the ASN.1 contents so
772 // this makes the behavior consistent across platforms.
774 return nil, errNotParsed
776 for i := 0; i < opts.Intermediates.len(); i++ {
777 c, err := opts.Intermediates.cert(i)
779 return nil, fmt.Errorf("crypto/x509: error fetching intermediate: %w", err)
782 return nil, errNotParsed
786 // Use Windows's own verification and chain building.
787 if opts.Roots == nil && runtime.GOOS == "windows" {
788 return c.systemVerify(&opts)
791 if opts.Roots == nil {
792 opts.Roots = systemRootsPool()
793 if opts.Roots == nil {
794 return nil, SystemRootsError{systemRootsErr}
798 err = c.isValid(leafCertificate, nil, &opts)
803 if len(opts.DNSName) > 0 {
804 err = c.VerifyHostname(opts.DNSName)
810 var candidateChains [][]*Certificate
811 if opts.Roots.contains(c) {
812 candidateChains = append(candidateChains, []*Certificate{c})
814 if candidateChains, err = c.buildChains(nil, []*Certificate{c}, nil, &opts); err != nil {
819 keyUsages := opts.KeyUsages
820 if len(keyUsages) == 0 {
821 keyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
824 // If any key usage is acceptable then we're done.
825 for _, usage := range keyUsages {
826 if usage == ExtKeyUsageAny {
827 return candidateChains, nil
831 for _, candidate := range candidateChains {
832 if checkChainForKeyUsage(candidate, keyUsages) {
833 chains = append(chains, candidate)
837 if len(chains) == 0 {
838 return nil, CertificateInvalidError{c, IncompatibleUsage, ""}
844 func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate {
845 n := make([]*Certificate, len(chain)+1)
851 // maxChainSignatureChecks is the maximum number of CheckSignatureFrom calls
852 // that an invocation of buildChains will (tranistively) make. Most chains are
853 // less than 15 certificates long, so this leaves space for multiple chains and
854 // for failed checks due to different intermediates having the same Subject.
855 const maxChainSignatureChecks = 100
857 func (c *Certificate) buildChains(cache map[*Certificate][][]*Certificate, currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error) {
860 hintCert *Certificate
863 considerCandidate := func(certType int, candidate *Certificate) {
864 for _, cert := range currentChain {
865 if cert.Equal(candidate) {
870 if sigChecks == nil {
874 if *sigChecks > maxChainSignatureChecks {
875 err = errors.New("x509: signature check attempts limit reached while verifying certificate chain")
879 if err := c.CheckSignatureFrom(candidate); err != nil {
887 err = candidate.isValid(certType, currentChain, opts)
893 case rootCertificate:
894 chains = append(chains, appendToFreshChain(currentChain, candidate))
895 case intermediateCertificate:
897 cache = make(map[*Certificate][][]*Certificate)
899 childChains, ok := cache[candidate]
901 childChains, err = candidate.buildChains(cache, appendToFreshChain(currentChain, candidate), sigChecks, opts)
902 cache[candidate] = childChains
904 chains = append(chains, childChains...)
908 for _, root := range opts.Roots.findPotentialParents(c) {
909 considerCandidate(rootCertificate, root)
911 for _, intermediate := range opts.Intermediates.findPotentialParents(c) {
912 considerCandidate(intermediateCertificate, intermediate)
918 if len(chains) == 0 && err == nil {
919 err = UnknownAuthorityError{c, hintErr, hintCert}
925 func validHostnamePattern(host string) bool { return validHostname(host, true) }
926 func validHostnameInput(host string) bool { return validHostname(host, false) }
928 // validHostname reports whether host is a valid hostname that can be matched or
929 // matched against according to RFC 6125 2.2, with some leniency to accommodate
931 func validHostname(host string, isPattern bool) bool {
933 host = strings.TrimSuffix(host, ".")
939 for i, part := range strings.Split(host, ".") {
944 if isPattern && i == 0 && part == "*" {
945 // Only allow full left-most wildcards, as those are the only ones
946 // we match, and matching literal '*' characters is probably never
947 // the expected behavior.
950 for j, c := range part {
951 if 'a' <= c && c <= 'z' {
954 if '0' <= c && c <= '9' {
957 if 'A' <= c && c <= 'Z' {
960 if c == '-' && j != 0 {
964 // Not a valid character in hostnames, but commonly
965 // found in deployments outside the WebPKI.
975 // commonNameAsHostname reports whether the Common Name field should be
976 // considered the hostname that the certificate is valid for. This is a legacy
977 // behavior, disabled by default or if the Subject Alt Name extension is present.
979 // It applies the strict validHostname check to the Common Name field, so that
980 // certificates without SANs can still be validated against CAs with name
981 // constraints if there is no risk the CN would be matched as a hostname.
982 // See NameConstraintsWithoutSANs and issue 24151.
983 func (c *Certificate) commonNameAsHostname() bool {
984 return !ignoreCN && !c.hasSANExtension() && validHostnamePattern(c.Subject.CommonName)
987 func matchExactly(hostA, hostB string) bool {
988 if hostA == "" || hostA == "." || hostB == "" || hostB == "." {
991 return toLowerCaseASCII(hostA) == toLowerCaseASCII(hostB)
994 func matchHostnames(pattern, host string) bool {
995 pattern = toLowerCaseASCII(pattern)
996 host = toLowerCaseASCII(strings.TrimSuffix(host, "."))
998 if len(pattern) == 0 || len(host) == 0 {
1002 patternParts := strings.Split(pattern, ".")
1003 hostParts := strings.Split(host, ".")
1005 if len(patternParts) != len(hostParts) {
1009 for i, patternPart := range patternParts {
1010 if i == 0 && patternPart == "*" {
1013 if patternPart != hostParts[i] {
1021 // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
1022 // an explicitly ASCII function to avoid any sharp corners resulting from
1023 // performing Unicode operations on DNS labels.
1024 func toLowerCaseASCII(in string) string {
1025 // If the string is already lower-case then there's nothing to do.
1026 isAlreadyLowerCase := true
1027 for _, c := range in {
1028 if c == utf8.RuneError {
1029 // If we get a UTF-8 error then there might be
1030 // upper-case ASCII bytes in the invalid sequence.
1031 isAlreadyLowerCase = false
1034 if 'A' <= c && c <= 'Z' {
1035 isAlreadyLowerCase = false
1040 if isAlreadyLowerCase {
1045 for i, c := range out {
1046 if 'A' <= c && c <= 'Z' {
1053 // VerifyHostname returns nil if c is a valid certificate for the named host.
1054 // Otherwise it returns an error describing the mismatch.
1056 // IP addresses can be optionally enclosed in square brackets and are checked
1057 // against the IPAddresses field. Other names are checked case insensitively
1058 // against the DNSNames field. If the names are valid hostnames, the certificate
1059 // fields can have a wildcard as the left-most label.
1061 // The legacy Common Name field is ignored unless it's a valid hostname, the
1062 // certificate doesn't have any Subject Alternative Names, and the GODEBUG
1063 // environment variable is set to "x509ignoreCN=0". Support for Common Name is
1064 // deprecated will be entirely removed in the future.
1065 func (c *Certificate) VerifyHostname(h string) error {
1066 // IP addresses may be written in [ ].
1068 if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
1069 candidateIP = h[1 : len(h)-1]
1071 if ip := net.ParseIP(candidateIP); ip != nil {
1072 // We only match IP addresses against IP SANs.
1073 // See RFC 6125, Appendix B.2.
1074 for _, candidate := range c.IPAddresses {
1075 if ip.Equal(candidate) {
1079 return HostnameError{c, candidateIP}
1083 if c.commonNameAsHostname() {
1084 names = []string{c.Subject.CommonName}
1087 candidateName := toLowerCaseASCII(h) // Save allocations inside the loop.
1088 validCandidateName := validHostnameInput(candidateName)
1090 for _, match := range names {
1091 // Ideally, we'd only match valid hostnames according to RFC 6125 like
1092 // browsers (more or less) do, but in practice Go is used in a wider
1093 // array of contexts and can't even assume DNS resolution. Instead,
1094 // always allow perfect matches, and only apply wildcard and trailing
1095 // dot processing to valid hostnames.
1096 if validCandidateName && validHostnamePattern(match) {
1097 if matchHostnames(match, candidateName) {
1101 if matchExactly(match, candidateName) {
1107 return HostnameError{c, h}
1110 func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
1111 usages := make([]ExtKeyUsage, len(keyUsages))
1112 copy(usages, keyUsages)
1114 if len(chain) == 0 {
1118 usagesRemaining := len(usages)
1120 // We walk down the list and cross out any usages that aren't supported
1121 // by each certificate. If we cross out all the usages, then the chain
1125 for i := len(chain) - 1; i >= 0; i-- {
1127 if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
1128 // The certificate doesn't have any extended key usage specified.
1132 for _, usage := range cert.ExtKeyUsage {
1133 if usage == ExtKeyUsageAny {
1134 // The certificate is explicitly good for any usage.
1139 const invalidUsage ExtKeyUsage = -1
1142 for i, requestedUsage := range usages {
1143 if requestedUsage == invalidUsage {
1147 for _, usage := range cert.ExtKeyUsage {
1148 if requestedUsage == usage {
1149 continue NextRequestedUsage
1150 } else if requestedUsage == ExtKeyUsageServerAuth &&
1151 (usage == ExtKeyUsageNetscapeServerGatedCrypto ||
1152 usage == ExtKeyUsageMicrosoftServerGatedCrypto) {
1153 // In order to support COMODO
1154 // certificate chains, we have to
1155 // accept Netscape or Microsoft SGC
1156 // usages as equal to ServerAuth.
1157 continue NextRequestedUsage
1161 usages[i] = invalidUsage
1163 if usagesRemaining == 0 {