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