]> 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"
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. It's a structure
189 // because other PKIX verification APIs have ended up needing many options.
190 type VerifyOptions struct {
191         // IsBoring is a validity check for BoringCrypto.
192         // If not nil, it will be called to check whether a given certificate
193         // can be used for constructing verification chains.
194         IsBoring func(*Certificate) bool
195
196         DNSName       string
197         Intermediates *CertPool
198         Roots         *CertPool // if nil, the system roots are used
199         CurrentTime   time.Time // if zero, the current time is used
200         // KeyUsage specifies which Extended Key Usage values are acceptable. A leaf
201         // certificate is accepted if it contains any of the listed values. An empty
202         // list means ExtKeyUsageServerAuth. To accept any key usage, include
203         // ExtKeyUsageAny.
204         //
205         // Certificate chains are required to nest these extended key usage values.
206         // (This matches the Windows CryptoAPI behavior, but not the spec.)
207         KeyUsages []ExtKeyUsage
208         // MaxConstraintComparisions is the maximum number of comparisons to
209         // perform when checking a given certificate's name constraints. If
210         // zero, a sensible default is used. This limit prevents pathological
211         // certificates from consuming excessive amounts of CPU time when
212         // validating.
213         MaxConstraintComparisions int
214 }
215
216 const (
217         leafCertificate = iota
218         intermediateCertificate
219         rootCertificate
220 )
221
222 // rfc2821Mailbox represents a “mailbox” (which is an email address to most
223 // people) by breaking it into the “local” (i.e. before the '@') and “domain”
224 // parts.
225 type rfc2821Mailbox struct {
226         local, domain string
227 }
228
229 // parseRFC2821Mailbox parses an email address into local and domain parts,
230 // based on the ABNF for a “Mailbox” from RFC 2821. According to
231 // https://tools.ietf.org/html/rfc5280#section-4.2.1.6 that's correct for an
232 // rfc822Name from a certificate: “The format of an rfc822Name is a "Mailbox"
233 // as defined in https://tools.ietf.org/html/rfc2821#section-4.1.2”.
234 func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
235         if len(in) == 0 {
236                 return mailbox, false
237         }
238
239         localPartBytes := make([]byte, 0, len(in)/2)
240
241         if in[0] == '"' {
242                 // Quoted-string = DQUOTE *qcontent DQUOTE
243                 // non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
244                 // qcontent = qtext / quoted-pair
245                 // qtext = non-whitespace-control /
246                 //         %d33 / %d35-91 / %d93-126
247                 // quoted-pair = ("\" text) / obs-qp
248                 // text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
249                 //
250                 // (Names beginning with “obs-” are the obsolete syntax from
251                 // https://tools.ietf.org/html/rfc2822#section-4. Since it has
252                 // been 16 years, we no longer accept that.)
253                 in = in[1:]
254         QuotedString:
255                 for {
256                         if len(in) == 0 {
257                                 return mailbox, false
258                         }
259                         c := in[0]
260                         in = in[1:]
261
262                         switch {
263                         case c == '"':
264                                 break QuotedString
265
266                         case c == '\\':
267                                 // quoted-pair
268                                 if len(in) == 0 {
269                                         return mailbox, false
270                                 }
271                                 if in[0] == 11 ||
272                                         in[0] == 12 ||
273                                         (1 <= in[0] && in[0] <= 9) ||
274                                         (14 <= in[0] && in[0] <= 127) {
275                                         localPartBytes = append(localPartBytes, in[0])
276                                         in = in[1:]
277                                 } else {
278                                         return mailbox, false
279                                 }
280
281                         case c == 11 ||
282                                 c == 12 ||
283                                 // Space (char 32) is not allowed based on the
284                                 // BNF, but RFC 3696 gives an example that
285                                 // assumes that it is. Several “verified”
286                                 // errata continue to argue about this point.
287                                 // We choose to accept it.
288                                 c == 32 ||
289                                 c == 33 ||
290                                 c == 127 ||
291                                 (1 <= c && c <= 8) ||
292                                 (14 <= c && c <= 31) ||
293                                 (35 <= c && c <= 91) ||
294                                 (93 <= c && c <= 126):
295                                 // qtext
296                                 localPartBytes = append(localPartBytes, c)
297
298                         default:
299                                 return mailbox, false
300                         }
301                 }
302         } else {
303                 // Atom ("." Atom)*
304         NextChar:
305                 for len(in) > 0 {
306                         // atext from https://tools.ietf.org/html/rfc2822#section-3.2.4
307                         c := in[0]
308
309                         switch {
310                         case c == '\\':
311                                 // Examples given in RFC 3696 suggest that
312                                 // escaped characters can appear outside of a
313                                 // quoted string. Several “verified” errata
314                                 // continue to argue the point. We choose to
315                                 // accept it.
316                                 in = in[1:]
317                                 if len(in) == 0 {
318                                         return mailbox, false
319                                 }
320                                 fallthrough
321
322                         case ('0' <= c && c <= '9') ||
323                                 ('a' <= c && c <= 'z') ||
324                                 ('A' <= c && c <= 'Z') ||
325                                 c == '!' || c == '#' || c == '$' || c == '%' ||
326                                 c == '&' || c == '\'' || c == '*' || c == '+' ||
327                                 c == '-' || c == '/' || c == '=' || c == '?' ||
328                                 c == '^' || c == '_' || c == '`' || c == '{' ||
329                                 c == '|' || c == '}' || c == '~' || c == '.':
330                                 localPartBytes = append(localPartBytes, in[0])
331                                 in = in[1:]
332
333                         default:
334                                 break NextChar
335                         }
336                 }
337
338                 if len(localPartBytes) == 0 {
339                         return mailbox, false
340                 }
341
342                 // https://tools.ietf.org/html/rfc3696#section-3
343                 // “period (".") may also appear, but may not be used to start
344                 // or end the local part, nor may two or more consecutive
345                 // periods appear.”
346                 twoDots := []byte{'.', '.'}
347                 if localPartBytes[0] == '.' ||
348                         localPartBytes[len(localPartBytes)-1] == '.' ||
349                         bytes.Contains(localPartBytes, twoDots) {
350                         return mailbox, false
351                 }
352         }
353
354         if len(in) == 0 || in[0] != '@' {
355                 return mailbox, false
356         }
357         in = in[1:]
358
359         // The RFC species a format for domains, but that's known to be
360         // violated in practice so we accept that anything after an '@' is the
361         // domain part.
362         if _, ok := domainToReverseLabels(in); !ok {
363                 return mailbox, false
364         }
365
366         mailbox.local = string(localPartBytes)
367         mailbox.domain = in
368         return mailbox, true
369 }
370
371 // domainToReverseLabels converts a textual domain name like foo.example.com to
372 // the list of labels in reverse order, e.g. ["com", "example", "foo"].
373 func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
374         for len(domain) > 0 {
375                 if i := strings.LastIndexByte(domain, '.'); i == -1 {
376                         reverseLabels = append(reverseLabels, domain)
377                         domain = ""
378                 } else {
379                         reverseLabels = append(reverseLabels, domain[i+1:len(domain)])
380                         domain = domain[:i]
381                 }
382         }
383
384         if len(reverseLabels) > 0 && len(reverseLabels[0]) == 0 {
385                 // An empty label at the end indicates an absolute value.
386                 return nil, false
387         }
388
389         for _, label := range reverseLabels {
390                 if len(label) == 0 {
391                         // Empty labels are otherwise invalid.
392                         return nil, false
393                 }
394
395                 for _, c := range label {
396                         if c < 33 || c > 126 {
397                                 // Invalid character.
398                                 return nil, false
399                         }
400                 }
401         }
402
403         return reverseLabels, true
404 }
405
406 func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
407         // If the constraint contains an @, then it specifies an exact mailbox
408         // name.
409         if strings.Contains(constraint, "@") {
410                 constraintMailbox, ok := parseRFC2821Mailbox(constraint)
411                 if !ok {
412                         return false, fmt.Errorf("x509: internal error: cannot parse constraint %q", constraint)
413                 }
414                 return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
415         }
416
417         // Otherwise the constraint is like a DNS constraint of the domain part
418         // of the mailbox.
419         return matchDomainConstraint(mailbox.domain, constraint)
420 }
421
422 func matchURIConstraint(uri *url.URL, constraint string) (bool, error) {
423         // https://tools.ietf.org/html/rfc5280#section-4.2.1.10
424         // “a uniformResourceIdentifier that does not include an authority
425         // component with a host name specified as a fully qualified domain
426         // name (e.g., if the URI either does not include an authority
427         // component or includes an authority component in which the host name
428         // is specified as an IP address), then the application MUST reject the
429         // certificate.”
430
431         host := uri.Host
432         if len(host) == 0 {
433                 return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
434         }
435
436         if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
437                 var err error
438                 host, _, err = net.SplitHostPort(uri.Host)
439                 if err != nil {
440                         return false, err
441                 }
442         }
443
444         if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") ||
445                 net.ParseIP(host) != nil {
446                 return false, fmt.Errorf("URI with IP (%q) cannot be matched against constraints", uri.String())
447         }
448
449         return matchDomainConstraint(host, constraint)
450 }
451
452 func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
453         if len(ip) != len(constraint.IP) {
454                 return false, nil
455         }
456
457         for i := range ip {
458                 if mask := constraint.Mask[i]; ip[i]&mask != constraint.IP[i]&mask {
459                         return false, nil
460                 }
461         }
462
463         return true, nil
464 }
465
466 func matchDomainConstraint(domain, constraint string) (bool, error) {
467         // The meaning of zero length constraints is not specified, but this
468         // code follows NSS and accepts them as matching everything.
469         if len(constraint) == 0 {
470                 return true, nil
471         }
472
473         domainLabels, ok := domainToReverseLabels(domain)
474         if !ok {
475                 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", domain)
476         }
477
478         // RFC 5280 says that a leading period in a domain name means that at
479         // least one label must be prepended, but only for URI and email
480         // constraints, not DNS constraints. The code also supports that
481         // behaviour for DNS constraints.
482
483         mustHaveSubdomains := false
484         if constraint[0] == '.' {
485                 mustHaveSubdomains = true
486                 constraint = constraint[1:]
487         }
488
489         constraintLabels, ok := domainToReverseLabels(constraint)
490         if !ok {
491                 return false, fmt.Errorf("x509: internal error: cannot parse domain %q", constraint)
492         }
493
494         if len(domainLabels) < len(constraintLabels) ||
495                 (mustHaveSubdomains && len(domainLabels) == len(constraintLabels)) {
496                 return false, nil
497         }
498
499         for i, constraintLabel := range constraintLabels {
500                 if !strings.EqualFold(constraintLabel, domainLabels[i]) {
501                         return false, nil
502                 }
503         }
504
505         return true, nil
506 }
507
508 // checkNameConstraints checks that c permits a child certificate to claim the
509 // given name, of type nameType. The argument parsedName contains the parsed
510 // form of name, suitable for passing to the match function. The total number
511 // of comparisons is tracked in the given count and should not exceed the given
512 // limit.
513 func (c *Certificate) checkNameConstraints(count *int,
514         maxConstraintComparisons int,
515         nameType string,
516         name string,
517         parsedName interface{},
518         match func(parsedName, constraint interface{}) (match bool, err error),
519         permitted, excluded interface{}) error {
520
521         excludedValue := reflect.ValueOf(excluded)
522
523         *count += excludedValue.Len()
524         if *count > maxConstraintComparisons {
525                 return CertificateInvalidError{c, TooManyConstraints, ""}
526         }
527
528         for i := 0; i < excludedValue.Len(); i++ {
529                 constraint := excludedValue.Index(i).Interface()
530                 match, err := match(parsedName, constraint)
531                 if err != nil {
532                         return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
533                 }
534
535                 if match {
536                         return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint)}
537                 }
538         }
539
540         permittedValue := reflect.ValueOf(permitted)
541
542         *count += permittedValue.Len()
543         if *count > maxConstraintComparisons {
544                 return CertificateInvalidError{c, TooManyConstraints, ""}
545         }
546
547         ok := true
548         for i := 0; i < permittedValue.Len(); i++ {
549                 constraint := permittedValue.Index(i).Interface()
550
551                 var err error
552                 if ok, err = match(parsedName, constraint); err != nil {
553                         return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
554                 }
555
556                 if ok {
557                         break
558                 }
559         }
560
561         if !ok {
562                 return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name)}
563         }
564
565         return nil
566 }
567
568 // isValid performs validity checks on c given that it is a candidate to append
569 // to the chain in currentChain.
570 func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
571         if len(c.UnhandledCriticalExtensions) > 0 {
572                 return UnhandledCriticalExtension{}
573         }
574
575         if len(currentChain) > 0 {
576                 child := currentChain[len(currentChain)-1]
577                 if !bytes.Equal(child.RawIssuer, c.RawSubject) {
578                         return CertificateInvalidError{c, NameMismatch, ""}
579                 }
580         }
581
582         now := opts.CurrentTime
583         if now.IsZero() {
584                 now = time.Now()
585         }
586         if now.Before(c.NotBefore) || now.After(c.NotAfter) {
587                 return CertificateInvalidError{c, Expired, ""}
588         }
589
590         maxConstraintComparisons := opts.MaxConstraintComparisions
591         if maxConstraintComparisons == 0 {
592                 maxConstraintComparisons = 250000
593         }
594         comparisonCount := 0
595
596         var leaf *Certificate
597         if certType == intermediateCertificate || certType == rootCertificate {
598                 if len(currentChain) == 0 {
599                         return errors.New("x509: internal error: empty chain when appending CA cert")
600                 }
601                 leaf = currentChain[0]
602         }
603
604         checkNameConstraints := (certType == intermediateCertificate || certType == rootCertificate) && c.hasNameConstraints()
605         if checkNameConstraints && leaf.commonNameAsHostname() {
606                 // This is the deprecated, legacy case of depending on the commonName as
607                 // a hostname. We don't enforce name constraints against the CN, but
608                 // VerifyHostname will look for hostnames in there if there are no SANs.
609                 // In order to ensure VerifyHostname will not accept an unchecked name,
610                 // return an error here.
611                 return CertificateInvalidError{c, NameConstraintsWithoutSANs, ""}
612         } else if checkNameConstraints && leaf.hasSANExtension() {
613                 err := forEachSAN(leaf.getSANExtension(), func(tag int, data []byte) error {
614                         switch tag {
615                         case nameTypeEmail:
616                                 name := string(data)
617                                 mailbox, ok := parseRFC2821Mailbox(name)
618                                 if !ok {
619                                         return fmt.Errorf("x509: cannot parse rfc822Name %q", mailbox)
620                                 }
621
622                                 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "email address", name, mailbox,
623                                         func(parsedName, constraint interface{}) (bool, error) {
624                                                 return matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string))
625                                         }, c.PermittedEmailAddresses, c.ExcludedEmailAddresses); err != nil {
626                                         return err
627                                 }
628
629                         case nameTypeDNS:
630                                 name := string(data)
631                                 if _, ok := domainToReverseLabels(name); !ok {
632                                         return fmt.Errorf("x509: cannot parse dnsName %q", name)
633                                 }
634
635                                 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "DNS name", name, name,
636                                         func(parsedName, constraint interface{}) (bool, error) {
637                                                 return matchDomainConstraint(parsedName.(string), constraint.(string))
638                                         }, c.PermittedDNSDomains, c.ExcludedDNSDomains); err != nil {
639                                         return err
640                                 }
641
642                         case nameTypeURI:
643                                 name := string(data)
644                                 uri, err := url.Parse(name)
645                                 if err != nil {
646                                         return fmt.Errorf("x509: internal error: URI SAN %q failed to parse", name)
647                                 }
648
649                                 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "URI", name, uri,
650                                         func(parsedName, constraint interface{}) (bool, error) {
651                                                 return matchURIConstraint(parsedName.(*url.URL), constraint.(string))
652                                         }, c.PermittedURIDomains, c.ExcludedURIDomains); err != nil {
653                                         return err
654                                 }
655
656                         case nameTypeIP:
657                                 ip := net.IP(data)
658                                 if l := len(ip); l != net.IPv4len && l != net.IPv6len {
659                                         return fmt.Errorf("x509: internal error: IP SAN %x failed to parse", data)
660                                 }
661
662                                 if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "IP address", ip.String(), ip,
663                                         func(parsedName, constraint interface{}) (bool, error) {
664                                                 return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet))
665                                         }, c.PermittedIPRanges, c.ExcludedIPRanges); err != nil {
666                                         return err
667                                 }
668
669                         default:
670                                 // Unknown SAN types are ignored.
671                         }
672
673                         return nil
674                 })
675
676                 if err != nil {
677                         return err
678                 }
679         }
680
681         // KeyUsage status flags are ignored. From Engineering Security, Peter
682         // Gutmann: A European government CA marked its signing certificates as
683         // being valid for encryption only, but no-one noticed. Another
684         // European CA marked its signature keys as not being valid for
685         // signatures. A different CA marked its own trusted root certificate
686         // as being invalid for certificate signing. Another national CA
687         // distributed a certificate to be used to encrypt data for the
688         // country’s tax authority that was marked as only being usable for
689         // digital signatures but not for encryption. Yet another CA reversed
690         // the order of the bit flags in the keyUsage due to confusion over
691         // encoding endianness, essentially setting a random keyUsage in
692         // certificates that it issued. Another CA created a self-invalidating
693         // certificate by adding a certificate policy statement stipulating
694         // that the certificate had to be used strictly as specified in the
695         // keyUsage, and a keyUsage containing a flag indicating that the RSA
696         // encryption key could only be used for Diffie-Hellman key agreement.
697
698         if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
699                 return CertificateInvalidError{c, NotAuthorizedToSign, ""}
700         }
701
702         if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
703                 numIntermediates := len(currentChain) - 1
704                 if numIntermediates > c.MaxPathLen {
705                         return CertificateInvalidError{c, TooManyIntermediates, ""}
706                 }
707         }
708
709         if opts.IsBoring != nil && !opts.IsBoring(c) {
710                 // IncompatibleUsage is not quite right here,
711                 // but it's also the "no chains found" error
712                 // and is close enough.
713                 return CertificateInvalidError{c, IncompatibleUsage, ""}
714         }
715
716         return nil
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 // validHostname returns whether host is a valid hostname that can be matched or
876 // matched against according to RFC 6125 2.2, with some leniency to accommodate
877 // legacy values.
878 func validHostname(host string) bool {
879         host = strings.TrimSuffix(host, ".")
880
881         if len(host) == 0 {
882                 return false
883         }
884
885         for i, part := range strings.Split(host, ".") {
886                 if part == "" {
887                         // Empty label.
888                         return false
889                 }
890                 if i == 0 && part == "*" {
891                         // Only allow full left-most wildcards, as those are the only ones
892                         // we match, and matching literal '*' characters is probably never
893                         // the expected behavior.
894                         continue
895                 }
896                 for j, c := range part {
897                         if 'a' <= c && c <= 'z' {
898                                 continue
899                         }
900                         if '0' <= c && c <= '9' {
901                                 continue
902                         }
903                         if 'A' <= c && c <= 'Z' {
904                                 continue
905                         }
906                         if c == '-' && j != 0 {
907                                 continue
908                         }
909                         if c == '_' {
910                                 // _ is not a valid character in hostnames, but it's commonly
911                                 // found in deployments outside the WebPKI.
912                                 continue
913                         }
914                         return false
915                 }
916         }
917
918         return true
919 }
920
921 // commonNameAsHostname reports whether the Common Name field should be
922 // considered the hostname that the certificate is valid for. This is a legacy
923 // behavior, disabled if the Subject Alt Name extension is present.
924 //
925 // It applies the strict validHostname check to the Common Name field, so that
926 // certificates without SANs can still be validated against CAs with name
927 // constraints if there is no risk the CN would be matched as a hostname.
928 // See NameConstraintsWithoutSANs and issue 24151.
929 func (c *Certificate) commonNameAsHostname() bool {
930         return !ignoreCN && !c.hasSANExtension() && validHostname(c.Subject.CommonName)
931 }
932
933 func matchHostnames(pattern, host string) bool {
934         host = strings.TrimSuffix(host, ".")
935         pattern = strings.TrimSuffix(pattern, ".")
936
937         if len(pattern) == 0 || len(host) == 0 {
938                 return false
939         }
940
941         patternParts := strings.Split(pattern, ".")
942         hostParts := strings.Split(host, ".")
943
944         if len(patternParts) != len(hostParts) {
945                 return false
946         }
947
948         for i, patternPart := range patternParts {
949                 if i == 0 && patternPart == "*" {
950                         continue
951                 }
952                 if patternPart != hostParts[i] {
953                         return false
954                 }
955         }
956
957         return true
958 }
959
960 // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
961 // an explicitly ASCII function to avoid any sharp corners resulting from
962 // performing Unicode operations on DNS labels.
963 func toLowerCaseASCII(in string) string {
964         // If the string is already lower-case then there's nothing to do.
965         isAlreadyLowerCase := true
966         for _, c := range in {
967                 if c == utf8.RuneError {
968                         // If we get a UTF-8 error then there might be
969                         // upper-case ASCII bytes in the invalid sequence.
970                         isAlreadyLowerCase = false
971                         break
972                 }
973                 if 'A' <= c && c <= 'Z' {
974                         isAlreadyLowerCase = false
975                         break
976                 }
977         }
978
979         if isAlreadyLowerCase {
980                 return in
981         }
982
983         out := []byte(in)
984         for i, c := range out {
985                 if 'A' <= c && c <= 'Z' {
986                         out[i] += 'a' - 'A'
987                 }
988         }
989         return string(out)
990 }
991
992 // VerifyHostname returns nil if c is a valid certificate for the named host.
993 // Otherwise it returns an error describing the mismatch.
994 func (c *Certificate) VerifyHostname(h string) error {
995         // IP addresses may be written in [ ].
996         candidateIP := h
997         if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
998                 candidateIP = h[1 : len(h)-1]
999         }
1000         if ip := net.ParseIP(candidateIP); ip != nil {
1001                 // We only match IP addresses against IP SANs.
1002                 // https://tools.ietf.org/html/rfc6125#appendix-B.2
1003                 for _, candidate := range c.IPAddresses {
1004                         if ip.Equal(candidate) {
1005                                 return nil
1006                         }
1007                 }
1008                 return HostnameError{c, candidateIP}
1009         }
1010
1011         lowered := toLowerCaseASCII(h)
1012
1013         if c.commonNameAsHostname() {
1014                 if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) {
1015                         return nil
1016                 }
1017         } else {
1018                 for _, match := range c.DNSNames {
1019                         if matchHostnames(toLowerCaseASCII(match), lowered) {
1020                                 return nil
1021                         }
1022                 }
1023         }
1024
1025         return HostnameError{c, h}
1026 }
1027
1028 func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
1029         usages := make([]ExtKeyUsage, len(keyUsages))
1030         copy(usages, keyUsages)
1031
1032         if len(chain) == 0 {
1033                 return false
1034         }
1035
1036         usagesRemaining := len(usages)
1037
1038         // We walk down the list and cross out any usages that aren't supported
1039         // by each certificate. If we cross out all the usages, then the chain
1040         // is unacceptable.
1041
1042 NextCert:
1043         for i := len(chain) - 1; i >= 0; i-- {
1044                 cert := chain[i]
1045                 if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
1046                         // The certificate doesn't have any extended key usage specified.
1047                         continue
1048                 }
1049
1050                 for _, usage := range cert.ExtKeyUsage {
1051                         if usage == ExtKeyUsageAny {
1052                                 // The certificate is explicitly good for any usage.
1053                                 continue NextCert
1054                         }
1055                 }
1056
1057                 const invalidUsage ExtKeyUsage = -1
1058
1059         NextRequestedUsage:
1060                 for i, requestedUsage := range usages {
1061                         if requestedUsage == invalidUsage {
1062                                 continue
1063                         }
1064
1065                         for _, usage := range cert.ExtKeyUsage {
1066                                 if requestedUsage == usage {
1067                                         continue NextRequestedUsage
1068                                 } else if requestedUsage == ExtKeyUsageServerAuth &&
1069                                         (usage == ExtKeyUsageNetscapeServerGatedCrypto ||
1070                                                 usage == ExtKeyUsageMicrosoftServerGatedCrypto) {
1071                                         // In order to support COMODO
1072                                         // certificate chains, we have to
1073                                         // accept Netscape or Microsoft SGC
1074                                         // usages as equal to ServerAuth.
1075                                         continue NextRequestedUsage
1076                                 }
1077                         }
1078
1079                         usages[i] = invalidUsage
1080                         usagesRemaining--
1081                         if usagesRemaining == 0 {
1082                                 return false
1083                         }
1084                 }
1085         }
1086
1087         return true
1088 }