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