]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/x509/verify.go
[dev.boringcrypto] all: merge master into dev.boringcrypto
[gostls13.git] / src / crypto / x509 / verify.go
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.
4
5 package x509
6
7 import (
8         "bytes"
9         "errors"
10         "fmt"
11         "net"
12         "net/url"
13         "os"
14         "reflect"
15         "runtime"
16         "strings"
17         "time"
18         "unicode/utf8"
19 )
20
21 // ignoreCN disables interpreting Common Name as a hostname. See issue 24151.
22 var ignoreCN = !strings.Contains(os.Getenv("GODEBUG"), "x509ignoreCN=0")
23
24 type InvalidReason int
25
26 const (
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.
32         Expired
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
38         // violated.
39         TooManyIntermediates
40         // IncompatibleUsage results when the certificate's key usage indicates
41         // that it may only be used for a different purpose.
42         IncompatibleUsage
43         // NameMismatch results when the subject name of a parent certificate
44         // does not match the issuer name in the child.
45         NameMismatch
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
49         // a hostname.
50         //
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.
58         UnconstrainedName
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.
64         TooManyConstraints
65         // CANotAuthorizedForExtKeyUsage results when an intermediate or root
66         // certificate does not permit a requested extended key usage.
67         CANotAuthorizedForExtKeyUsage
68 )
69
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 {
73         Cert   *Certificate
74         Reason InvalidReason
75         Detail string
76 }
77
78 func (e CertificateInvalidError) Error() string {
79         switch e.Reason {
80         case NotAuthorizedToSign:
81                 return "x509: certificate is not authorized to sign other certificates"
82         case Expired:
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"
92         case NameMismatch:
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
98         }
99         return "x509: unknown error"
100 }
101
102 // HostnameError results when the set of authorized names doesn't match the
103 // requested name.
104 type HostnameError struct {
105         Certificate *Certificate
106         Host        string
107 }
108
109 func (h HostnameError) Error() string {
110         c := h.Certificate
111
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
116                 }
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"
121                 }
122         }
123
124         var valid string
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"
129                 }
130                 for _, san := range c.IPAddresses {
131                         if len(valid) > 0 {
132                                 valid += ", "
133                         }
134                         valid += san.String()
135                 }
136         } else {
137                 if c.commonNameAsHostname() {
138                         valid = c.Subject.CommonName
139                 } else {
140                         valid = strings.Join(c.DNSNames, ", ")
141                 }
142         }
143
144         if len(valid) == 0 {
145                 return "x509: certificate is not valid for any names, but wanted to match " + h.Host
146         }
147         return "x509: certificate is valid for " + valid + ", not " + h.Host
148 }
149
150 // UnknownAuthorityError results when the certificate issuer is unknown
151 type UnknownAuthorityError struct {
152         Cert *Certificate
153         // hintErr contains an error that may be helpful in determining why an
154         // authority wasn't found.
155         hintErr error
156         // hintCert contains a possible authority certificate that was rejected
157         // because of the error in hintErr.
158         hintCert *Certificate
159 }
160
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]
168                         } else {
169                                 certName = "serial:" + e.hintCert.SerialNumber.String()
170                         }
171                 }
172                 s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName)
173         }
174         return s
175 }
176
177 // SystemRootsError results when we fail to load the system root certificates.
178 type SystemRootsError struct {
179         Err error
180 }
181
182 func (se SystemRootsError) Error() string {
183         msg := "x509: failed to load system roots and no roots provided"
184         if se.Err != nil {
185                 return msg + "; " + se.Err.Error()
186         }
187         return msg
188 }
189
190 // errNotParsed is returned when a certificate without ASN.1 contents is
191 // verified. Platform-specific verification needs the ASN.1 contents.
192 var errNotParsed = errors.New("x509: missing ASN.1 contents; use ParseCertificate")
193
194 // VerifyOptions contains parameters for Certificate.Verify.
195 type VerifyOptions struct {
196         // IsBoring is a validity check for BoringCrypto.
197         // If not nil, it will be called to check whether a given certificate
198         // can be used for constructing verification chains.
199         IsBoring func(*Certificate) bool
200
201         // DNSName, if set, is checked against the leaf certificate with
202         // Certificate.VerifyHostname.
203         DNSName string
204
205         // Intermediates is an optional pool of certificates that are not trust
206         // anchors, but can be used to form a chain from the leaf certificate to a
207         // root certificate.
208         Intermediates *CertPool
209         // Roots is the set of trusted root certificates the leaf certificate needs
210         // to chain up to. If nil, the system roots or the platform verifier are used.
211         Roots *CertPool
212
213         // CurrentTime is used to check the validity of all certificates in the
214         // chain. If zero, the current time is used.
215         CurrentTime time.Time
216
217         // KeyUsage specifies which Extended Key Usage values are acceptable. A leaf
218         // certificate is accepted if it contains any of the listed values. An empty
219         // list means ExtKeyUsageServerAuth. To accept any key usage, include
220         // ExtKeyUsageAny.
221         //
222         // Certificate chains are required to nest these extended key usage values.
223         // (This matches the Windows CryptoAPI behavior, but not the spec.)
224         KeyUsages []ExtKeyUsage
225
226         // MaxConstraintComparisions is the maximum number of comparisons to
227         // perform when checking a given certificate's name constraints. If
228         // zero, a sensible default is used. This limit prevents pathological
229         // certificates from consuming excessive amounts of CPU time when
230         // validating.
231         MaxConstraintComparisions int
232 }
233
234 const (
235         leafCertificate = iota
236         intermediateCertificate
237         rootCertificate
238 )
239
240 // rfc2821Mailbox represents a “mailbox” (which is an email address to most
241 // people) by breaking it into the “local” (i.e. before the '@') and “domain”
242 // parts.
243 type rfc2821Mailbox struct {
244         local, domain string
245 }
246
247 // parseRFC2821Mailbox parses an email address into local and domain parts,
248 // based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
249 // Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
250 // format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
251 func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
252         if len(in) == 0 {
253                 return mailbox, false
254         }
255
256         localPartBytes := make([]byte, 0, len(in)/2)
257
258         if in[0] == '"' {
259                 // Quoted-string = DQUOTE *qcontent DQUOTE
260                 // non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
261                 // qcontent = qtext / quoted-pair
262                 // qtext = non-whitespace-control /
263                 //         %d33 / %d35-91 / %d93-126
264                 // quoted-pair = ("\" text) / obs-qp
265                 // text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
266                 //
267                 // (Names beginning with “obs-” are the obsolete syntax from RFC 2822,
268                 // Section 4. Since it has been 16 years, we no longer accept that.)
269                 in = in[1:]
270         QuotedString:
271                 for {
272                         if len(in) == 0 {
273                                 return mailbox, false
274                         }
275                         c := in[0]
276                         in = in[1:]
277
278                         switch {
279                         case c == '"':
280                                 break QuotedString
281
282                         case c == '\\':
283                                 // quoted-pair
284                                 if len(in) == 0 {
285                                         return mailbox, false
286                                 }
287                                 if in[0] == 11 ||
288                                         in[0] == 12 ||
289                                         (1 <= in[0] && in[0] <= 9) ||
290                                         (14 <= in[0] && in[0] <= 127) {
291                                         localPartBytes = append(localPartBytes, in[0])
292                                         in = in[1:]
293                                 } else {
294                                         return mailbox, false
295                                 }
296
297                         case c == 11 ||
298                                 c == 12 ||
299                                 // Space (char 32) is not allowed based on the
300                                 // BNF, but RFC 3696 gives an example that
301                                 // assumes that it is. Several “verified”
302                                 // errata continue to argue about this point.
303                                 // We choose to accept it.
304                                 c == 32 ||
305                                 c == 33 ||
306                                 c == 127 ||
307                                 (1 <= c && c <= 8) ||
308                                 (14 <= c && c <= 31) ||
309                                 (35 <= c && c <= 91) ||
310                                 (93 <= c && c <= 126):
311                                 // qtext
312                                 localPartBytes = append(localPartBytes, c)
313
314                         default:
315                                 return mailbox, false
316                         }
317                 }
318         } else {
319                 // Atom ("." Atom)*
320         NextChar:
321                 for len(in) > 0 {
322                         // atext from RFC 2822, Section 3.2.4
323                         c := in[0]
324
325                         switch {
326                         case c == '\\':
327                                 // Examples given in RFC 3696 suggest that
328                                 // escaped characters can appear outside of a
329                                 // quoted string. Several “verified” errata
330                                 // continue to argue the point. We choose to
331                                 // accept it.
332                                 in = in[1:]
333                                 if len(in) == 0 {
334                                         return mailbox, false
335                                 }
336                                 fallthrough
337
338                         case ('0' <= c && c <= '9') ||
339                                 ('a' <= c && c <= 'z') ||
340                                 ('A' <= c && c <= 'Z') ||
341                                 c == '!' || c == '#' || c == '$' || c == '%' ||
342                                 c == '&' || c == '\'' || c == '*' || c == '+' ||
343                                 c == '-' || c == '/' || c == '=' || c == '?' ||
344                                 c == '^' || c == '_' || c == '`' || c == '{' ||
345                                 c == '|' || c == '}' || c == '~' || c == '.':
346                                 localPartBytes = append(localPartBytes, in[0])
347                                 in = in[1:]
348
349                         default:
350                                 break NextChar
351                         }
352                 }
353
354                 if len(localPartBytes) == 0 {
355                         return mailbox, false
356                 }
357
358                 // From RFC 3696, Section 3:
359                 // “period (".") may also appear, but may not be used to start
360                 // or end the local part, nor may two or more consecutive
361                 // periods appear.”
362                 twoDots := []byte{'.', '.'}
363                 if localPartBytes[0] == '.' ||
364                         localPartBytes[len(localPartBytes)-1] == '.' ||
365                         bytes.Contains(localPartBytes, twoDots) {
366                         return mailbox, false
367                 }
368         }
369
370         if len(in) == 0 || in[0] != '@' {
371                 return mailbox, false
372         }
373         in = in[1:]
374
375         // The RFC species a format for domains, but that's known to be
376         // violated in practice so we accept that anything after an '@' is the
377         // domain part.
378         if _, ok := domainToReverseLabels(in); !ok {
379                 return mailbox, false
380         }
381
382         mailbox.local = string(localPartBytes)
383         mailbox.domain = in
384         return mailbox, true
385 }
386
387 // domainToReverseLabels converts a textual domain name like foo.example.com to
388 // the list of labels in reverse order, e.g. ["com", "example", "foo"].
389 func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
390         for len(domain) > 0 {
391                 if i := strings.LastIndexByte(domain, '.'); i == -1 {
392                         reverseLabels = append(reverseLabels, domain)
393                         domain = ""
394                 } else {
395                         reverseLabels = append(reverseLabels, domain[i+1:])
396                         domain = domain[:i]
397                 }
398         }
399
400         if len(reverseLabels) > 0 && len(reverseLabels[0]) == 0 {
401                 // An empty label at the end indicates an absolute value.
402                 return nil, false
403         }
404
405         for _, label := range reverseLabels {
406                 if len(label) == 0 {
407                         // Empty labels are otherwise invalid.
408                         return nil, false
409                 }
410
411                 for _, c := range label {
412                         if c < 33 || c > 126 {
413                                 // Invalid character.
414                                 return nil, false
415                         }
416                 }
417         }
418
419         return reverseLabels, true
420 }
421
422 func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
423         // If the constraint contains an @, then it specifies an exact mailbox
424         // name.
425         if strings.Contains(constraint, "@") {
426                 constraintMailbox, ok := parseRFC2821Mailbox(constraint)
427                 if !ok {
428                         return false, fmt.Errorf("x509: internal error: cannot parse constraint %q", constraint)
429                 }
430                 return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
431         }
432
433         // Otherwise the constraint is like a DNS constraint of the domain part
434         // of the mailbox.
435         return matchDomainConstraint(mailbox.domain, constraint)
436 }
437
438 func matchURIConstraint(uri *url.URL, constraint string) (bool, error) {
439         // From RFC 5280, Section 4.2.1.10:
440         // “a uniformResourceIdentifier that does not include an authority
441         // component with a host name specified as a fully qualified domain
442         // name (e.g., if the URI either does not include an authority
443         // component or includes an authority component in which the host name
444         // is specified as an IP address), then the application MUST reject the
445         // certificate.”
446
447         host := uri.Host
448         if len(host) == 0 {
449                 return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
450         }
451
452         if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
453                 var err error
454                 host, _, err = net.SplitHostPort(uri.Host)
455                 if err != nil {
456                         return false, err
457                 }
458         }
459
460         if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") ||
461                 net.ParseIP(host) != nil {
462                 return false, fmt.Errorf("URI with IP (%q) cannot be matched against constraints", uri.String())
463         }
464
465         return matchDomainConstraint(host, constraint)
466 }
467
468 func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
469         if len(ip) != len(constraint.IP) {
470                 return false, nil
471         }
472
473         for i := range ip {
474                 if mask := constraint.Mask[i]; ip[i]&mask != constraint.IP[i]&mask {
475                         return false, nil
476                 }
477         }
478
479         return true, nil
480 }
481
482 func matchDomainConstraint(domain, constraint string) (bool, error) {
483         // The meaning of zero length constraints is not specified, but this
484         // code follows NSS and accepts them as matching everything.
485         if len(constraint) == 0 {
486                 return true, nil
487         }
488
489         domainLabels, ok := domainToReverseLabels(domain)
490         if !ok {
491                 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", domain)
492         }
493
494         // RFC 5280 says that a leading period in a domain name means that at
495         // least one label must be prepended, but only for URI and email
496         // constraints, not DNS constraints. The code also supports that
497         // behaviour for DNS constraints.
498
499         mustHaveSubdomains := false
500         if constraint[0] == '.' {
501                 mustHaveSubdomains = true
502                 constraint = constraint[1:]
503         }
504
505         constraintLabels, ok := domainToReverseLabels(constraint)
506         if !ok {
507                 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", constraint)
508         }
509
510         if len(domainLabels) < len(constraintLabels) ||
511                 (mustHaveSubdomains && len(domainLabels) == len(constraintLabels)) {
512                 return false, nil
513         }
514
515         for i, constraintLabel := range constraintLabels {
516                 if !strings.EqualFold(constraintLabel, domainLabels[i]) {
517                         return false, nil
518                 }
519         }
520
521         return true, nil
522 }
523
524 // checkNameConstraints checks that c permits a child certificate to claim the
525 // given name, of type nameType. The argument parsedName contains the parsed
526 // form of name, suitable for passing to the match function. The total number
527 // of comparisons is tracked in the given count and should not exceed the given
528 // limit.
529 func (c *Certificate) checkNameConstraints(count *int,
530         maxConstraintComparisons int,
531         nameType string,
532         name string,
533         parsedName interface{},
534         match func(parsedName, constraint interface{}) (match bool, err error),
535         permitted, excluded interface{}) error {
536
537         excludedValue := reflect.ValueOf(excluded)
538
539         *count += excludedValue.Len()
540         if *count > maxConstraintComparisons {
541                 return CertificateInvalidError{c, TooManyConstraints, ""}
542         }
543
544         for i := 0; i < excludedValue.Len(); i++ {
545                 constraint := excludedValue.Index(i).Interface()
546                 match, err := match(parsedName, constraint)
547                 if err != nil {
548                         return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
549                 }
550
551                 if match {
552                         return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint)}
553                 }
554         }
555
556         permittedValue := reflect.ValueOf(permitted)
557
558         *count += permittedValue.Len()
559         if *count > maxConstraintComparisons {
560                 return CertificateInvalidError{c, TooManyConstraints, ""}
561         }
562
563         ok := true
564         for i := 0; i < permittedValue.Len(); i++ {
565                 constraint := permittedValue.Index(i).Interface()
566
567                 var err error
568                 if ok, err = match(parsedName, constraint); err != nil {
569                         return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
570                 }
571
572                 if ok {
573                         break
574                 }
575         }
576
577         if !ok {
578                 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name)}
579         }
580
581         return nil
582 }
583
584 // isValid performs validity checks on c given that it is a candidate to append
585 // to the chain in currentChain.
586 func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
587         if len(c.UnhandledCriticalExtensions) > 0 {
588                 return UnhandledCriticalExtension{}
589         }
590
591         if len(currentChain) > 0 {
592                 child := currentChain[len(currentChain)-1]
593                 if !bytes.Equal(child.RawIssuer, c.RawSubject) {
594                         return CertificateInvalidError{c, NameMismatch, ""}
595                 }
596         }
597
598         now := opts.CurrentTime
599         if now.IsZero() {
600                 now = time.Now()
601         }
602         if now.Before(c.NotBefore) {
603                 return CertificateInvalidError{
604                         Cert:   c,
605                         Reason: Expired,
606                         Detail: fmt.Sprintf("current time %s is before %s", now.Format(time.RFC3339), c.NotBefore.Format(time.RFC3339)),
607                 }
608         } else if now.After(c.NotAfter) {
609                 return CertificateInvalidError{
610                         Cert:   c,
611                         Reason: Expired,
612                         Detail: fmt.Sprintf("current time %s is after %s", now.Format(time.RFC3339), c.NotAfter.Format(time.RFC3339)),
613                 }
614         }
615
616         maxConstraintComparisons := opts.MaxConstraintComparisions
617         if maxConstraintComparisons == 0 {
618                 maxConstraintComparisons = 250000
619         }
620         comparisonCount := 0
621
622         var leaf *Certificate
623         if certType == intermediateCertificate || certType == rootCertificate {
624                 if len(currentChain) == 0 {
625                         return errors.New("x509: internal error: empty chain when appending CA cert")
626                 }
627                 leaf = currentChain[0]
628         }
629
630         checkNameConstraints := (certType == intermediateCertificate || certType == rootCertificate) && c.hasNameConstraints()
631         if checkNameConstraints && leaf.commonNameAsHostname() {
632                 // This is the deprecated, legacy case of depending on the commonName as
633                 // a hostname. We don't enforce name constraints against the CN, but
634                 // VerifyHostname will look for hostnames in there if there are no SANs.
635                 // In order to ensure VerifyHostname will not accept an unchecked name,
636                 // return an error here.
637                 return CertificateInvalidError{c, NameConstraintsWithoutSANs, ""}
638         } else if checkNameConstraints && leaf.hasSANExtension() {
639                 err := forEachSAN(leaf.getSANExtension(), func(tag int, data []byte) error {
640                         switch tag {
641                         case nameTypeEmail:
642                                 name := string(data)
643                                 mailbox, ok := parseRFC2821Mailbox(name)
644                                 if !ok {
645                                         return fmt.Errorf("x509: cannot parse rfc822Name %q", mailbox)
646                                 }
647
648                                 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "email address", name, mailbox,
649                                         func(parsedName, constraint interface{}) (bool, error) {
650                                                 return matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string))
651                                         }, c.PermittedEmailAddresses, c.ExcludedEmailAddresses); err != nil {
652                                         return err
653                                 }
654
655                         case nameTypeDNS:
656                                 name := string(data)
657                                 if _, ok := domainToReverseLabels(name); !ok {
658                                         return fmt.Errorf("x509: cannot parse dnsName %q", name)
659                                 }
660
661                                 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "DNS name", name, name,
662                                         func(parsedName, constraint interface{}) (bool, error) {
663                                                 return matchDomainConstraint(parsedName.(string), constraint.(string))
664                                         }, c.PermittedDNSDomains, c.ExcludedDNSDomains); err != nil {
665                                         return err
666                                 }
667
668                         case nameTypeURI:
669                                 name := string(data)
670                                 uri, err := url.Parse(name)
671                                 if err != nil {
672                                         return fmt.Errorf("x509: internal error: URI SAN %q failed to parse", name)
673                                 }
674
675                                 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "URI", name, uri,
676                                         func(parsedName, constraint interface{}) (bool, error) {
677                                                 return matchURIConstraint(parsedName.(*url.URL), constraint.(string))
678                                         }, c.PermittedURIDomains, c.ExcludedURIDomains); err != nil {
679                                         return err
680                                 }
681
682                         case nameTypeIP:
683                                 ip := net.IP(data)
684                                 if l := len(ip); l != net.IPv4len && l != net.IPv6len {
685                                         return fmt.Errorf("x509: internal error: IP SAN %x failed to parse", data)
686                                 }
687
688                                 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "IP address", ip.String(), ip,
689                                         func(parsedName, constraint interface{}) (bool, error) {
690                                                 return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet))
691                                         }, c.PermittedIPRanges, c.ExcludedIPRanges); err != nil {
692                                         return err
693                                 }
694
695                         default:
696                                 // Unknown SAN types are ignored.
697                         }
698
699                         return nil
700                 })
701
702                 if err != nil {
703                         return err
704                 }
705         }
706
707         // KeyUsage status flags are ignored. From Engineering Security, Peter
708         // Gutmann: A European government CA marked its signing certificates as
709         // being valid for encryption only, but no-one noticed. Another
710         // European CA marked its signature keys as not being valid for
711         // signatures. A different CA marked its own trusted root certificate
712         // as being invalid for certificate signing. Another national CA
713         // distributed a certificate to be used to encrypt data for the
714         // country’s tax authority that was marked as only being usable for
715         // digital signatures but not for encryption. Yet another CA reversed
716         // the order of the bit flags in the keyUsage due to confusion over
717         // encoding endianness, essentially setting a random keyUsage in
718         // certificates that it issued. Another CA created a self-invalidating
719         // certificate by adding a certificate policy statement stipulating
720         // that the certificate had to be used strictly as specified in the
721         // keyUsage, and a keyUsage containing a flag indicating that the RSA
722         // encryption key could only be used for Diffie-Hellman key agreement.
723
724         if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
725                 return CertificateInvalidError{c, NotAuthorizedToSign, ""}
726         }
727
728         if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
729                 numIntermediates := len(currentChain) - 1
730                 if numIntermediates > c.MaxPathLen {
731                         return CertificateInvalidError{c, TooManyIntermediates, ""}
732                 }
733         }
734
735         if opts.IsBoring != nil && !opts.IsBoring(c) {
736                 // IncompatibleUsage is not quite right here,
737                 // but it's also the "no chains found" error
738                 // and is close enough.
739                 return CertificateInvalidError{c, IncompatibleUsage, ""}
740         }
741
742         return nil
743 }
744
745 // Verify attempts to verify c by building one or more chains from c to a
746 // certificate in opts.Roots, using certificates in opts.Intermediates if
747 // needed. If successful, it returns one or more chains where the first
748 // element of the chain is c and the last element is from opts.Roots.
749 //
750 // If opts.Roots is nil and system roots are unavailable the returned error
751 // will be of type SystemRootsError.
752 //
753 // Name constraints in the intermediates will be applied to all names claimed
754 // in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim
755 // example.com if an intermediate doesn't permit it, even if example.com is not
756 // the name being validated. Note that DirectoryName constraints are not
757 // supported.
758 //
759 // Name constraint validation follows the rules from RFC 5280, with the
760 // addition that DNS name constraints may use the leading period format
761 // defined for emails and URIs. When a constraint has a leading period
762 // it indicates that at least one additional label must be prepended to
763 // the constrained name to be considered valid.
764 //
765 // Extended Key Usage values are enforced down a chain, so an intermediate or
766 // root that enumerates EKUs prevents a leaf from asserting an EKU not in that
767 // list.
768 //
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.
773         if len(c.Raw) == 0 {
774                 return nil, errNotParsed
775         }
776         if opts.Intermediates != nil {
777                 for _, intermediate := range opts.Intermediates.certs {
778                         if len(intermediate.Raw) == 0 {
779                                 return nil, errNotParsed
780                         }
781                 }
782         }
783
784         // Use Windows's own verification and chain building.
785         if opts.Roots == nil && runtime.GOOS == "windows" {
786                 return c.systemVerify(&opts)
787         }
788
789         if opts.Roots == nil {
790                 opts.Roots = systemRootsPool()
791                 if opts.Roots == nil {
792                         return nil, SystemRootsError{systemRootsErr}
793                 }
794         }
795
796         err = c.isValid(leafCertificate, nil, &opts)
797         if err != nil {
798                 return
799         }
800
801         if len(opts.DNSName) > 0 {
802                 err = c.VerifyHostname(opts.DNSName)
803                 if err != nil {
804                         return
805                 }
806         }
807
808         var candidateChains [][]*Certificate
809         if opts.Roots.contains(c) {
810                 candidateChains = append(candidateChains, []*Certificate{c})
811         } else {
812                 if candidateChains, err = c.buildChains(nil, []*Certificate{c}, nil, &opts); err != nil {
813                         return nil, err
814                 }
815         }
816
817         keyUsages := opts.KeyUsages
818         if len(keyUsages) == 0 {
819                 keyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
820         }
821
822         // If any key usage is acceptable then we're done.
823         for _, usage := range keyUsages {
824                 if usage == ExtKeyUsageAny {
825                         return candidateChains, nil
826                 }
827         }
828
829         for _, candidate := range candidateChains {
830                 if checkChainForKeyUsage(candidate, keyUsages) {
831                         chains = append(chains, candidate)
832                 }
833         }
834
835         if len(chains) == 0 {
836                 return nil, CertificateInvalidError{c, IncompatibleUsage, ""}
837         }
838
839         return chains, nil
840 }
841
842 func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate {
843         n := make([]*Certificate, len(chain)+1)
844         copy(n, chain)
845         n[len(chain)] = cert
846         return n
847 }
848
849 // maxChainSignatureChecks is the maximum number of CheckSignatureFrom calls
850 // that an invocation of buildChains will (tranistively) make. Most chains are
851 // less than 15 certificates long, so this leaves space for multiple chains and
852 // for failed checks due to different intermediates having the same Subject.
853 const maxChainSignatureChecks = 100
854
855 func (c *Certificate) buildChains(cache map[*Certificate][][]*Certificate, currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error) {
856         var (
857                 hintErr  error
858                 hintCert *Certificate
859         )
860
861         considerCandidate := func(certType int, candidate *Certificate) {
862                 for _, cert := range currentChain {
863                         if cert.Equal(candidate) {
864                                 return
865                         }
866                 }
867
868                 if sigChecks == nil {
869                         sigChecks = new(int)
870                 }
871                 *sigChecks++
872                 if *sigChecks > maxChainSignatureChecks {
873                         err = errors.New("x509: signature check attempts limit reached while verifying certificate chain")
874                         return
875                 }
876
877                 if err := c.CheckSignatureFrom(candidate); err != nil {
878                         if hintErr == nil {
879                                 hintErr = err
880                                 hintCert = candidate
881                         }
882                         return
883                 }
884
885                 err = candidate.isValid(certType, currentChain, opts)
886                 if err != nil {
887                         return
888                 }
889
890                 switch certType {
891                 case rootCertificate:
892                         chains = append(chains, appendToFreshChain(currentChain, candidate))
893                 case intermediateCertificate:
894                         if cache == nil {
895                                 cache = make(map[*Certificate][][]*Certificate)
896                         }
897                         childChains, ok := cache[candidate]
898                         if !ok {
899                                 childChains, err = candidate.buildChains(cache, appendToFreshChain(currentChain, candidate), sigChecks, opts)
900                                 cache[candidate] = childChains
901                         }
902                         chains = append(chains, childChains...)
903                 }
904         }
905
906         for _, rootNum := range opts.Roots.findPotentialParents(c) {
907                 considerCandidate(rootCertificate, opts.Roots.certs[rootNum])
908         }
909         for _, intermediateNum := range opts.Intermediates.findPotentialParents(c) {
910                 considerCandidate(intermediateCertificate, opts.Intermediates.certs[intermediateNum])
911         }
912
913         if len(chains) > 0 {
914                 err = nil
915         }
916         if len(chains) == 0 && err == nil {
917                 err = UnknownAuthorityError{c, hintErr, hintCert}
918         }
919
920         return
921 }
922
923 func validHostnamePattern(host string) bool { return validHostname(host, true) }
924 func validHostnameInput(host string) bool   { return validHostname(host, false) }
925
926 // validHostname reports whether host is a valid hostname that can be matched or
927 // matched against according to RFC 6125 2.2, with some leniency to accommodate
928 // legacy values.
929 func validHostname(host string, isPattern bool) bool {
930         if !isPattern {
931                 host = strings.TrimSuffix(host, ".")
932         }
933         if len(host) == 0 {
934                 return false
935         }
936
937         for i, part := range strings.Split(host, ".") {
938                 if part == "" {
939                         // Empty label.
940                         return false
941                 }
942                 if isPattern && i == 0 && part == "*" {
943                         // Only allow full left-most wildcards, as those are the only ones
944                         // we match, and matching literal '*' characters is probably never
945                         // the expected behavior.
946                         continue
947                 }
948                 for j, c := range part {
949                         if 'a' <= c && c <= 'z' {
950                                 continue
951                         }
952                         if '0' <= c && c <= '9' {
953                                 continue
954                         }
955                         if 'A' <= c && c <= 'Z' {
956                                 continue
957                         }
958                         if c == '-' && j != 0 {
959                                 continue
960                         }
961                         if c == '_' {
962                                 // Not a valid character in hostnames, but commonly
963                                 // found in deployments outside the WebPKI.
964                                 continue
965                         }
966                         return false
967                 }
968         }
969
970         return true
971 }
972
973 // commonNameAsHostname reports whether the Common Name field should be
974 // considered the hostname that the certificate is valid for. This is a legacy
975 // behavior, disabled by default or if the Subject Alt Name extension is present.
976 //
977 // It applies the strict validHostname check to the Common Name field, so that
978 // certificates without SANs can still be validated against CAs with name
979 // constraints if there is no risk the CN would be matched as a hostname.
980 // See NameConstraintsWithoutSANs and issue 24151.
981 func (c *Certificate) commonNameAsHostname() bool {
982         return !ignoreCN && !c.hasSANExtension() && validHostnamePattern(c.Subject.CommonName)
983 }
984
985 func matchExactly(hostA, hostB string) bool {
986         if hostA == "" || hostA == "." || hostB == "" || hostB == "." {
987                 return false
988         }
989         return toLowerCaseASCII(hostA) == toLowerCaseASCII(hostB)
990 }
991
992 func matchHostnames(pattern, host string) bool {
993         pattern = toLowerCaseASCII(pattern)
994         host = toLowerCaseASCII(strings.TrimSuffix(host, "."))
995
996         if len(pattern) == 0 || len(host) == 0 {
997                 return false
998         }
999
1000         patternParts := strings.Split(pattern, ".")
1001         hostParts := strings.Split(host, ".")
1002
1003         if len(patternParts) != len(hostParts) {
1004                 return false
1005         }
1006
1007         for i, patternPart := range patternParts {
1008                 if i == 0 && patternPart == "*" {
1009                         continue
1010                 }
1011                 if patternPart != hostParts[i] {
1012                         return false
1013                 }
1014         }
1015
1016         return true
1017 }
1018
1019 // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
1020 // an explicitly ASCII function to avoid any sharp corners resulting from
1021 // performing Unicode operations on DNS labels.
1022 func toLowerCaseASCII(in string) string {
1023         // If the string is already lower-case then there's nothing to do.
1024         isAlreadyLowerCase := true
1025         for _, c := range in {
1026                 if c == utf8.RuneError {
1027                         // If we get a UTF-8 error then there might be
1028                         // upper-case ASCII bytes in the invalid sequence.
1029                         isAlreadyLowerCase = false
1030                         break
1031                 }
1032                 if 'A' <= c && c <= 'Z' {
1033                         isAlreadyLowerCase = false
1034                         break
1035                 }
1036         }
1037
1038         if isAlreadyLowerCase {
1039                 return in
1040         }
1041
1042         out := []byte(in)
1043         for i, c := range out {
1044                 if 'A' <= c && c <= 'Z' {
1045                         out[i] += 'a' - 'A'
1046                 }
1047         }
1048         return string(out)
1049 }
1050
1051 // VerifyHostname returns nil if c is a valid certificate for the named host.
1052 // Otherwise it returns an error describing the mismatch.
1053 //
1054 // IP addresses can be optionally enclosed in square brackets and are checked
1055 // against the IPAddresses field. Other names are checked case insensitively
1056 // against the DNSNames field. If the names are valid hostnames, the certificate
1057 // fields can have a wildcard as the left-most label.
1058 //
1059 // The legacy Common Name field is ignored unless it's a valid hostname, the
1060 // certificate doesn't have any Subject Alternative Names, and the GODEBUG
1061 // environment variable is set to "x509ignoreCN=0". Support for Common Name is
1062 // deprecated will be entirely removed in the future.
1063 func (c *Certificate) VerifyHostname(h string) error {
1064         // IP addresses may be written in [ ].
1065         candidateIP := h
1066         if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
1067                 candidateIP = h[1 : len(h)-1]
1068         }
1069         if ip := net.ParseIP(candidateIP); ip != nil {
1070                 // We only match IP addresses against IP SANs.
1071                 // See RFC 6125, Appendix B.2.
1072                 for _, candidate := range c.IPAddresses {
1073                         if ip.Equal(candidate) {
1074                                 return nil
1075                         }
1076                 }
1077                 return HostnameError{c, candidateIP}
1078         }
1079
1080         names := c.DNSNames
1081         if c.commonNameAsHostname() {
1082                 names = []string{c.Subject.CommonName}
1083         }
1084
1085         candidateName := toLowerCaseASCII(h) // Save allocations inside the loop.
1086         validCandidateName := validHostnameInput(candidateName)
1087
1088         for _, match := range names {
1089                 // Ideally, we'd only match valid hostnames according to RFC 6125 like
1090                 // browsers (more or less) do, but in practice Go is used in a wider
1091                 // array of contexts and can't even assume DNS resolution. Instead,
1092                 // always allow perfect matches, and only apply wildcard and trailing
1093                 // dot processing to valid hostnames.
1094                 if validCandidateName && validHostnamePattern(match) {
1095                         if matchHostnames(match, candidateName) {
1096                                 return nil
1097                         }
1098                 } else {
1099                         if matchExactly(match, candidateName) {
1100                                 return nil
1101                         }
1102                 }
1103         }
1104
1105         return HostnameError{c, h}
1106 }
1107
1108 func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
1109         usages := make([]ExtKeyUsage, len(keyUsages))
1110         copy(usages, keyUsages)
1111
1112         if len(chain) == 0 {
1113                 return false
1114         }
1115
1116         usagesRemaining := len(usages)
1117
1118         // We walk down the list and cross out any usages that aren't supported
1119         // by each certificate. If we cross out all the usages, then the chain
1120         // is unacceptable.
1121
1122 NextCert:
1123         for i := len(chain) - 1; i >= 0; i-- {
1124                 cert := chain[i]
1125                 if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
1126                         // The certificate doesn't have any extended key usage specified.
1127                         continue
1128                 }
1129
1130                 for _, usage := range cert.ExtKeyUsage {
1131                         if usage == ExtKeyUsageAny {
1132                                 // The certificate is explicitly good for any usage.
1133                                 continue NextCert
1134                         }
1135                 }
1136
1137                 const invalidUsage ExtKeyUsage = -1
1138
1139         NextRequestedUsage:
1140                 for i, requestedUsage := range usages {
1141                         if requestedUsage == invalidUsage {
1142                                 continue
1143                         }
1144
1145                         for _, usage := range cert.ExtKeyUsage {
1146                                 if requestedUsage == usage {
1147                                         continue NextRequestedUsage
1148                                 } else if requestedUsage == ExtKeyUsageServerAuth &&
1149                                         (usage == ExtKeyUsageNetscapeServerGatedCrypto ||
1150                                                 usage == ExtKeyUsageMicrosoftServerGatedCrypto) {
1151                                         // In order to support COMODO
1152                                         // certificate chains, we have to
1153                                         // accept Netscape or Microsoft SGC
1154                                         // usages as equal to ServerAuth.
1155                                         continue NextRequestedUsage
1156                                 }
1157                         }
1158
1159                         usages[i] = invalidUsage
1160                         usagesRemaining--
1161                         if usagesRemaining == 0 {
1162                                 return false
1163                         }
1164                 }
1165         }
1166
1167         return true
1168 }