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