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