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