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 results when a leaf certificate doesn't
45 // contain a Subject Alternative Name extension, but a CA certificate
46 // contains name constraints.
47 NameConstraintsWithoutSANs
48 // UnconstrainedName results when a CA certificate contains permitted
49 // name constraints, but leaf certificate contains a name of an
50 // unsupported or unconstrained type.
52 // TooManyConstraints results when the number of comparison operations
53 // needed to check a certificate exceeds the limit set by
54 // VerifyOptions.MaxConstraintComparisions. This limit exists to
55 // prevent pathological certificates can consuming excessive amounts of
56 // CPU time to verify.
58 // CANotAuthorizedForExtKeyUsage results when an intermediate or root
59 // certificate does not permit a requested extended key usage.
60 CANotAuthorizedForExtKeyUsage
63 // CertificateInvalidError results when an odd error occurs. Users of this
64 // library probably want to handle all these errors uniformly.
65 type CertificateInvalidError struct {
71 func (e CertificateInvalidError) Error() string {
73 case NotAuthorizedToSign:
74 return "x509: certificate is not authorized to sign other certificates"
76 return "x509: certificate has expired or is not yet valid"
77 case CANotAuthorizedForThisName:
78 return "x509: a root or intermediate certificate is not authorized to sign for this name: " + e.Detail
79 case CANotAuthorizedForExtKeyUsage:
80 return "x509: a root or intermediate certificate is not authorized for an extended key usage: " + e.Detail
81 case TooManyIntermediates:
82 return "x509: too many intermediates for path length constraint"
83 case IncompatibleUsage:
84 return "x509: certificate specifies an incompatible key usage"
86 return "x509: issuer name does not match subject from issuing certificate"
87 case NameConstraintsWithoutSANs:
88 return "x509: issuer has name constraints but leaf doesn't have a SAN extension"
89 case UnconstrainedName:
90 return "x509: issuer has name constraints but leaf contains unknown or unconstrained name: " + e.Detail
92 return "x509: unknown error"
95 // HostnameError results when the set of authorized names doesn't match the
97 type HostnameError struct {
98 Certificate *Certificate
102 func (h HostnameError) Error() string {
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 if c.hasSANExtension() {
119 valid = strings.Join(c.DNSNames, ", ")
121 valid = c.Subject.CommonName
126 return "x509: certificate is not valid for any names, but wanted to match " + h.Host
128 return "x509: certificate is valid for " + valid + ", not " + h.Host
131 // UnknownAuthorityError results when the certificate issuer is unknown
132 type UnknownAuthorityError struct {
134 // hintErr contains an error that may be helpful in determining why an
135 // authority wasn't found.
137 // hintCert contains a possible authority certificate that was rejected
138 // because of the error in hintErr.
139 hintCert *Certificate
142 func (e UnknownAuthorityError) Error() string {
143 s := "x509: certificate signed by unknown authority"
144 if e.hintErr != nil {
145 certName := e.hintCert.Subject.CommonName
146 if len(certName) == 0 {
147 if len(e.hintCert.Subject.Organization) > 0 {
148 certName = e.hintCert.Subject.Organization[0]
150 certName = "serial:" + e.hintCert.SerialNumber.String()
153 s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName)
158 // SystemRootsError results when we fail to load the system root certificates.
159 type SystemRootsError struct {
163 func (se SystemRootsError) Error() string {
164 msg := "x509: failed to load system roots and no roots provided"
166 return msg + "; " + se.Err.Error()
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. It's a structure
176 // because other PKIX verification APIs have ended up needing many options.
177 type VerifyOptions struct {
178 // IsBoring is a validity check for BoringCrypto.
179 // If not nil, it will be called to check whether a given certificate
180 // can be used for constructing verification chains.
181 IsBoring func(*Certificate) bool
184 Intermediates *CertPool
185 Roots *CertPool // if nil, the system roots are used
186 CurrentTime time.Time // if zero, the current time is used
187 // KeyUsage specifies which Extended Key Usage values are acceptable. A leaf
188 // certificate is accepted if it contains any of the listed values. An empty
189 // list means ExtKeyUsageServerAuth. To accept any key usage, include
192 // Certificate chains are required to nest these extended key usage values.
193 // (This matches the Windows CryptoAPI behavior, but not the spec.)
194 KeyUsages []ExtKeyUsage
195 // MaxConstraintComparisions is the maximum number of comparisons to
196 // perform when checking a given certificate's name constraints. If
197 // zero, a sensible default is used. This limit prevents pathological
198 // certificates from consuming excessive amounts of CPU time when
200 MaxConstraintComparisions int
204 leafCertificate = iota
205 intermediateCertificate
209 // rfc2821Mailbox represents a “mailbox” (which is an email address to most
210 // people) by breaking it into the “local” (i.e. before the '@') and “domain”
212 type rfc2821Mailbox struct {
216 // parseRFC2821Mailbox parses an email address into local and domain parts,
217 // based on the ABNF for a “Mailbox” from RFC 2821. According to
218 // https://tools.ietf.org/html/rfc5280#section-4.2.1.6 that's correct for an
219 // rfc822Name from a certificate: “The format of an rfc822Name is a "Mailbox"
220 // as defined in https://tools.ietf.org/html/rfc2821#section-4.1.2”.
221 func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
223 return mailbox, false
226 localPartBytes := make([]byte, 0, len(in)/2)
229 // Quoted-string = DQUOTE *qcontent DQUOTE
230 // non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
231 // qcontent = qtext / quoted-pair
232 // qtext = non-whitespace-control /
233 // %d33 / %d35-91 / %d93-126
234 // quoted-pair = ("\" text) / obs-qp
235 // text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
237 // (Names beginning with “obs-” are the obsolete syntax from
238 // https://tools.ietf.org/html/rfc2822#section-4. Since it has
239 // been 16 years, we no longer accept that.)
244 return mailbox, false
256 return mailbox, false
260 (1 <= in[0] && in[0] <= 9) ||
261 (14 <= in[0] && in[0] <= 127) {
262 localPartBytes = append(localPartBytes, in[0])
265 return mailbox, false
270 // Space (char 32) is not allowed based on the
271 // BNF, but RFC 3696 gives an example that
272 // assumes that it is. Several “verified”
273 // errata continue to argue about this point.
274 // We choose to accept it.
278 (1 <= c && c <= 8) ||
279 (14 <= c && c <= 31) ||
280 (35 <= c && c <= 91) ||
281 (93 <= c && c <= 126):
283 localPartBytes = append(localPartBytes, c)
286 return mailbox, false
293 // atext from https://tools.ietf.org/html/rfc2822#section-3.2.4
298 // Examples given in RFC 3696 suggest that
299 // escaped characters can appear outside of a
300 // quoted string. Several “verified” errata
301 // continue to argue the point. We choose to
305 return mailbox, false
309 case ('0' <= c && c <= '9') ||
310 ('a' <= c && c <= 'z') ||
311 ('A' <= c && c <= 'Z') ||
312 c == '!' || c == '#' || c == '$' || c == '%' ||
313 c == '&' || c == '\'' || c == '*' || c == '+' ||
314 c == '-' || c == '/' || c == '=' || c == '?' ||
315 c == '^' || c == '_' || c == '`' || c == '{' ||
316 c == '|' || c == '}' || c == '~' || c == '.':
317 localPartBytes = append(localPartBytes, in[0])
325 if len(localPartBytes) == 0 {
326 return mailbox, false
329 // https://tools.ietf.org/html/rfc3696#section-3
330 // “period (".") may also appear, but may not be used to start
331 // or end the local part, nor may two or more consecutive
333 twoDots := []byte{'.', '.'}
334 if localPartBytes[0] == '.' ||
335 localPartBytes[len(localPartBytes)-1] == '.' ||
336 bytes.Contains(localPartBytes, twoDots) {
337 return mailbox, false
341 if len(in) == 0 || in[0] != '@' {
342 return mailbox, false
346 // The RFC species a format for domains, but that's known to be
347 // violated in practice so we accept that anything after an '@' is the
349 if _, ok := domainToReverseLabels(in); !ok {
350 return mailbox, false
353 mailbox.local = string(localPartBytes)
358 // domainToReverseLabels converts a textual domain name like foo.example.com to
359 // the list of labels in reverse order, e.g. ["com", "example", "foo"].
360 func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
361 for len(domain) > 0 {
362 if i := strings.LastIndexByte(domain, '.'); i == -1 {
363 reverseLabels = append(reverseLabels, domain)
366 reverseLabels = append(reverseLabels, domain[i+1:len(domain)])
371 if len(reverseLabels) > 0 && len(reverseLabels[0]) == 0 {
372 // An empty label at the end indicates an absolute value.
376 for _, label := range reverseLabels {
378 // Empty labels are otherwise invalid.
382 for _, c := range label {
383 if c < 33 || c > 126 {
384 // Invalid character.
390 return reverseLabels, true
393 func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
394 // If the constraint contains an @, then it specifies an exact mailbox
396 if strings.Contains(constraint, "@") {
397 constraintMailbox, ok := parseRFC2821Mailbox(constraint)
399 return false, fmt.Errorf("x509: internal error: cannot parse constraint %q", constraint)
401 return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
404 // Otherwise the constraint is like a DNS constraint of the domain part
406 return matchDomainConstraint(mailbox.domain, constraint)
409 func matchURIConstraint(uri *url.URL, constraint string) (bool, error) {
410 // https://tools.ietf.org/html/rfc5280#section-4.2.1.10
411 // “a uniformResourceIdentifier that does not include an authority
412 // component with a host name specified as a fully qualified domain
413 // name (e.g., if the URI either does not include an authority
414 // component or includes an authority component in which the host name
415 // is specified as an IP address), then the application MUST reject the
420 return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
423 if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
425 host, _, err = net.SplitHostPort(uri.Host)
431 if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") ||
432 net.ParseIP(host) != nil {
433 return false, fmt.Errorf("URI with IP (%q) cannot be matched against constraints", uri.String())
436 return matchDomainConstraint(host, constraint)
439 func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
440 if len(ip) != len(constraint.IP) {
445 if mask := constraint.Mask[i]; ip[i]&mask != constraint.IP[i]&mask {
453 func matchDomainConstraint(domain, constraint string) (bool, error) {
454 // The meaning of zero length constraints is not specified, but this
455 // code follows NSS and accepts them as matching everything.
456 if len(constraint) == 0 {
460 domainLabels, ok := domainToReverseLabels(domain)
462 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", domain)
465 // RFC 5280 says that a leading period in a domain name means that at
466 // least one label must be prepended, but only for URI and email
467 // constraints, not DNS constraints. The code also supports that
468 // behaviour for DNS constraints.
470 mustHaveSubdomains := false
471 if constraint[0] == '.' {
472 mustHaveSubdomains = true
473 constraint = constraint[1:]
476 constraintLabels, ok := domainToReverseLabels(constraint)
478 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", constraint)
481 if len(domainLabels) < len(constraintLabels) ||
482 (mustHaveSubdomains && len(domainLabels) == len(constraintLabels)) {
486 for i, constraintLabel := range constraintLabels {
487 if !strings.EqualFold(constraintLabel, domainLabels[i]) {
495 // checkNameConstraints checks that c permits a child certificate to claim the
496 // given name, of type nameType. The argument parsedName contains the parsed
497 // form of name, suitable for passing to the match function. The total number
498 // of comparisons is tracked in the given count and should not exceed the given
500 func (c *Certificate) checkNameConstraints(count *int,
501 maxConstraintComparisons int,
504 parsedName interface{},
505 match func(parsedName, constraint interface{}) (match bool, err error),
506 permitted, excluded interface{}) error {
508 excludedValue := reflect.ValueOf(excluded)
510 *count += excludedValue.Len()
511 if *count > maxConstraintComparisons {
512 return CertificateInvalidError{c, TooManyConstraints, ""}
515 for i := 0; i < excludedValue.Len(); i++ {
516 constraint := excludedValue.Index(i).Interface()
517 match, err := match(parsedName, constraint)
519 return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
523 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint)}
527 permittedValue := reflect.ValueOf(permitted)
529 *count += permittedValue.Len()
530 if *count > maxConstraintComparisons {
531 return CertificateInvalidError{c, TooManyConstraints, ""}
535 for i := 0; i < permittedValue.Len(); i++ {
536 constraint := permittedValue.Index(i).Interface()
539 if ok, err = match(parsedName, constraint); err != nil {
540 return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
549 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name)}
555 // isValid performs validity checks on c given that it is a candidate to append
556 // to the chain in currentChain.
557 func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
558 if len(c.UnhandledCriticalExtensions) > 0 {
559 return UnhandledCriticalExtension{}
562 if len(currentChain) > 0 {
563 child := currentChain[len(currentChain)-1]
564 if !bytes.Equal(child.RawIssuer, c.RawSubject) {
565 return CertificateInvalidError{c, NameMismatch, ""}
569 now := opts.CurrentTime
573 if now.Before(c.NotBefore) || now.After(c.NotAfter) {
574 return CertificateInvalidError{c, Expired, ""}
577 maxConstraintComparisons := opts.MaxConstraintComparisions
578 if maxConstraintComparisons == 0 {
579 maxConstraintComparisons = 250000
583 var leaf *Certificate
584 if certType == intermediateCertificate || certType == rootCertificate {
585 if len(currentChain) == 0 {
586 return errors.New("x509: internal error: empty chain when appending CA cert")
588 leaf = currentChain[0]
591 if (certType == intermediateCertificate || certType == rootCertificate) && c.hasNameConstraints() {
592 sanExtension, ok := leaf.getSANExtension()
594 // This is the deprecated, legacy case of depending on
595 // the CN as a hostname. Chains modern enough to be
596 // using name constraints should not be depending on
598 return CertificateInvalidError{c, NameConstraintsWithoutSANs, ""}
601 err := forEachSAN(sanExtension, func(tag int, data []byte) error {
605 mailbox, ok := parseRFC2821Mailbox(name)
607 return fmt.Errorf("x509: cannot parse rfc822Name %q", mailbox)
610 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "email address", name, mailbox,
611 func(parsedName, constraint interface{}) (bool, error) {
612 return matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string))
613 }, c.PermittedEmailAddresses, c.ExcludedEmailAddresses); err != nil {
619 if _, ok := domainToReverseLabels(name); !ok {
620 return fmt.Errorf("x509: cannot parse dnsName %q", name)
623 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "DNS name", name, name,
624 func(parsedName, constraint interface{}) (bool, error) {
625 return matchDomainConstraint(parsedName.(string), constraint.(string))
626 }, c.PermittedDNSDomains, c.ExcludedDNSDomains); err != nil {
632 uri, err := url.Parse(name)
634 return fmt.Errorf("x509: internal error: URI SAN %q failed to parse", name)
637 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "URI", name, uri,
638 func(parsedName, constraint interface{}) (bool, error) {
639 return matchURIConstraint(parsedName.(*url.URL), constraint.(string))
640 }, c.PermittedURIDomains, c.ExcludedURIDomains); err != nil {
646 if l := len(ip); l != net.IPv4len && l != net.IPv6len {
647 return fmt.Errorf("x509: internal error: IP SAN %x failed to parse", data)
650 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "IP address", ip.String(), ip,
651 func(parsedName, constraint interface{}) (bool, error) {
652 return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet))
653 }, c.PermittedIPRanges, c.ExcludedIPRanges); err != nil {
658 // Unknown SAN types are ignored.
669 // KeyUsage status flags are ignored. From Engineering Security, Peter
670 // Gutmann: A European government CA marked its signing certificates as
671 // being valid for encryption only, but no-one noticed. Another
672 // European CA marked its signature keys as not being valid for
673 // signatures. A different CA marked its own trusted root certificate
674 // as being invalid for certificate signing. Another national CA
675 // distributed a certificate to be used to encrypt data for the
676 // country’s tax authority that was marked as only being usable for
677 // digital signatures but not for encryption. Yet another CA reversed
678 // the order of the bit flags in the keyUsage due to confusion over
679 // encoding endianness, essentially setting a random keyUsage in
680 // certificates that it issued. Another CA created a self-invalidating
681 // certificate by adding a certificate policy statement stipulating
682 // that the certificate had to be used strictly as specified in the
683 // keyUsage, and a keyUsage containing a flag indicating that the RSA
684 // encryption key could only be used for Diffie-Hellman key agreement.
686 if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
687 return CertificateInvalidError{c, NotAuthorizedToSign, ""}
690 if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
691 numIntermediates := len(currentChain) - 1
692 if numIntermediates > c.MaxPathLen {
693 return CertificateInvalidError{c, TooManyIntermediates, ""}
697 if opts.IsBoring != nil && !opts.IsBoring(c) {
698 // IncompatibleUsage is not quite right here,
699 // but it's also the "no chains found" error
700 // and is close enough.
701 return CertificateInvalidError{c, IncompatibleUsage, ""}
707 // formatOID formats an ASN.1 OBJECT IDENTIFER in the common, dotted style.
708 func formatOID(oid asn1.ObjectIdentifier) string {
710 for i, v := range oid {
714 ret += strconv.Itoa(v)
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 and system roots are unavailable the returned error
725 // will be of type SystemRootsError.
727 // Name constraints in the intermediates will be applied to all names claimed
728 // in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim
729 // example.com if an intermediate doesn't permit it, even if example.com is not
730 // the name being validated. Note that DirectoryName constraints are not
733 // Extended Key Usage values are enforced down a chain, so an intermediate or
734 // root that enumerates EKUs prevents a leaf from asserting an EKU not in that
737 // WARNING: this function doesn't do any revocation checking.
738 func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) {
739 // Platform-specific verification needs the ASN.1 contents so
740 // this makes the behavior consistent across platforms.
742 return nil, errNotParsed
744 if opts.Intermediates != nil {
745 for _, intermediate := range opts.Intermediates.certs {
746 if len(intermediate.Raw) == 0 {
747 return nil, errNotParsed
752 // Use Windows's own verification and chain building.
753 if opts.Roots == nil && runtime.GOOS == "windows" {
754 return c.systemVerify(&opts)
757 if opts.Roots == nil {
758 opts.Roots = systemRootsPool()
759 if opts.Roots == nil {
760 return nil, SystemRootsError{systemRootsErr}
764 err = c.isValid(leafCertificate, nil, &opts)
769 if len(opts.DNSName) > 0 {
770 err = c.VerifyHostname(opts.DNSName)
776 var candidateChains [][]*Certificate
777 if opts.Roots.contains(c) {
778 candidateChains = append(candidateChains, []*Certificate{c})
780 if candidateChains, err = c.buildChains(make(map[int][][]*Certificate), []*Certificate{c}, &opts); err != nil {
785 keyUsages := opts.KeyUsages
786 if len(keyUsages) == 0 {
787 keyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
790 // If any key usage is acceptable then we're done.
791 for _, usage := range keyUsages {
792 if usage == ExtKeyUsageAny {
793 return candidateChains, nil
797 for _, candidate := range candidateChains {
798 if checkChainForKeyUsage(candidate, keyUsages) {
799 chains = append(chains, candidate)
803 if len(chains) == 0 {
804 return nil, CertificateInvalidError{c, IncompatibleUsage, ""}
810 func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate {
811 n := make([]*Certificate, len(chain)+1)
817 func (c *Certificate) buildChains(cache map[int][][]*Certificate, currentChain []*Certificate, opts *VerifyOptions) (chains [][]*Certificate, err error) {
818 possibleRoots, failedRoot, rootErr := opts.Roots.findVerifiedParents(c)
820 for _, rootNum := range possibleRoots {
821 root := opts.Roots.certs[rootNum]
823 for _, cert := range currentChain {
824 if cert.Equal(root) {
829 err = root.isValid(rootCertificate, currentChain, opts)
833 chains = append(chains, appendToFreshChain(currentChain, root))
836 possibleIntermediates, failedIntermediate, intermediateErr := opts.Intermediates.findVerifiedParents(c)
838 for _, intermediateNum := range possibleIntermediates {
839 intermediate := opts.Intermediates.certs[intermediateNum]
840 for _, cert := range currentChain {
841 if cert.Equal(intermediate) {
842 continue nextIntermediate
845 err = intermediate.isValid(intermediateCertificate, currentChain, opts)
849 var childChains [][]*Certificate
850 childChains, ok := cache[intermediateNum]
852 childChains, err = intermediate.buildChains(cache, appendToFreshChain(currentChain, intermediate), opts)
853 cache[intermediateNum] = childChains
855 chains = append(chains, childChains...)
862 if len(chains) == 0 && err == nil {
864 hintCert := failedRoot
866 hintErr = intermediateErr
867 hintCert = failedIntermediate
869 err = UnknownAuthorityError{c, hintErr, hintCert}
875 func matchHostnames(pattern, host string) bool {
876 host = strings.TrimSuffix(host, ".")
877 pattern = strings.TrimSuffix(pattern, ".")
879 if len(pattern) == 0 || len(host) == 0 {
883 patternParts := strings.Split(pattern, ".")
884 hostParts := strings.Split(host, ".")
886 if len(patternParts) != len(hostParts) {
890 for i, patternPart := range patternParts {
891 if i == 0 && patternPart == "*" {
894 if patternPart != hostParts[i] {
902 // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
903 // an explicitly ASCII function to avoid any sharp corners resulting from
904 // performing Unicode operations on DNS labels.
905 func toLowerCaseASCII(in string) string {
906 // If the string is already lower-case then there's nothing to do.
907 isAlreadyLowerCase := true
908 for _, c := range in {
909 if c == utf8.RuneError {
910 // If we get a UTF-8 error then there might be
911 // upper-case ASCII bytes in the invalid sequence.
912 isAlreadyLowerCase = false
915 if 'A' <= c && c <= 'Z' {
916 isAlreadyLowerCase = false
921 if isAlreadyLowerCase {
926 for i, c := range out {
927 if 'A' <= c && c <= 'Z' {
934 // VerifyHostname returns nil if c is a valid certificate for the named host.
935 // Otherwise it returns an error describing the mismatch.
936 func (c *Certificate) VerifyHostname(h string) error {
937 // IP addresses may be written in [ ].
939 if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
940 candidateIP = h[1 : len(h)-1]
942 if ip := net.ParseIP(candidateIP); ip != nil {
943 // We only match IP addresses against IP SANs.
944 // https://tools.ietf.org/html/rfc6125#appendix-B.2
945 for _, candidate := range c.IPAddresses {
946 if ip.Equal(candidate) {
950 return HostnameError{c, candidateIP}
953 lowered := toLowerCaseASCII(h)
955 if c.hasSANExtension() {
956 for _, match := range c.DNSNames {
957 if matchHostnames(toLowerCaseASCII(match), lowered) {
961 // If Subject Alt Name is given, we ignore the common name.
962 } else if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) {
966 return HostnameError{c, h}
969 func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
970 usages := make([]ExtKeyUsage, len(keyUsages))
971 copy(usages, keyUsages)
977 usagesRemaining := len(usages)
979 // We walk down the list and cross out any usages that aren't supported
980 // by each certificate. If we cross out all the usages, then the chain
984 for i := len(chain) - 1; i >= 0; i-- {
986 if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
987 // The certificate doesn't have any extended key usage specified.
991 for _, usage := range cert.ExtKeyUsage {
992 if usage == ExtKeyUsageAny {
993 // The certificate is explicitly good for any usage.
998 const invalidUsage ExtKeyUsage = -1
1001 for i, requestedUsage := range usages {
1002 if requestedUsage == invalidUsage {
1006 for _, usage := range cert.ExtKeyUsage {
1007 if requestedUsage == usage {
1008 continue NextRequestedUsage
1009 } else if requestedUsage == ExtKeyUsageServerAuth &&
1010 (usage == ExtKeyUsageNetscapeServerGatedCrypto ||
1011 usage == ExtKeyUsageMicrosoftServerGatedCrypto) {
1012 // In order to support COMODO
1013 // certificate chains, we have to
1014 // accept Netscape or Microsoft SGC
1015 // usages as equal to ServerAuth.
1016 continue NextRequestedUsage
1020 usages[i] = invalidUsage
1022 if usagesRemaining == 0 {