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