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