| |
| |
| |
|
|
| package x509 |
|
|
| import ( |
| "bytes" |
| "crypto" |
| "crypto/x509/pkix" |
| "errors" |
| "fmt" |
| "iter" |
| "maps" |
| "net" |
| "runtime" |
| "slices" |
| "strings" |
| "time" |
| "unicode/utf8" |
| ) |
|
|
| type InvalidReason int |
|
|
| const ( |
| |
| |
| NotAuthorizedToSign InvalidReason = iota |
| |
| |
| Expired |
| |
| |
| |
| CANotAuthorizedForThisName |
| |
| |
| TooManyIntermediates |
| |
| |
| IncompatibleUsage |
| |
| |
| NameMismatch |
| |
| NameConstraintsWithoutSANs |
| |
| |
| |
| UnconstrainedName |
| |
| |
| |
| |
| |
| TooManyConstraints |
| |
| |
| CANotAuthorizedForExtKeyUsage |
| |
| NoValidChains |
| ) |
|
|
| |
| |
| type CertificateInvalidError struct { |
| Cert *Certificate |
| Reason InvalidReason |
| Detail string |
| } |
|
|
| func (e CertificateInvalidError) Error() string { |
| switch e.Reason { |
| case NotAuthorizedToSign: |
| return "x509: certificate is not authorized to sign other certificates" |
| case Expired: |
| return "x509: certificate has expired or is not yet valid: " + e.Detail |
| case CANotAuthorizedForThisName: |
| return "x509: a root or intermediate certificate is not authorized to sign for this name: " + e.Detail |
| case CANotAuthorizedForExtKeyUsage: |
| return "x509: a root or intermediate certificate is not authorized for an extended key usage: " + e.Detail |
| case TooManyIntermediates: |
| return "x509: too many intermediates for path length constraint" |
| case IncompatibleUsage: |
| return "x509: certificate specifies an incompatible key usage" |
| case NameMismatch: |
| return "x509: issuer name does not match subject from issuing certificate" |
| case NameConstraintsWithoutSANs: |
| return "x509: issuer has name constraints but leaf doesn't have a SAN extension" |
| case UnconstrainedName: |
| return "x509: issuer has name constraints but leaf contains unknown or unconstrained name: " + e.Detail |
| case NoValidChains: |
| s := "x509: no valid chains built" |
| if e.Detail != "" { |
| s = fmt.Sprintf("%s: %s", s, e.Detail) |
| } |
| return s |
| } |
| return "x509: unknown error" |
| } |
|
|
| |
| |
| type HostnameError struct { |
| Certificate *Certificate |
| Host string |
| } |
|
|
| func (h HostnameError) Error() string { |
| c := h.Certificate |
| maxNamesIncluded := 100 |
|
|
| if !c.hasSANExtension() && matchHostnames(c.Subject.CommonName, h.Host) { |
| return "x509: certificate relies on legacy Common Name field, use SANs instead" |
| } |
|
|
| var valid strings.Builder |
| if ip := net.ParseIP(h.Host); ip != nil { |
| |
| if len(c.IPAddresses) == 0 { |
| return "x509: cannot validate certificate for " + h.Host + " because it doesn't contain any IP SANs" |
| } |
| if len(c.IPAddresses) >= maxNamesIncluded { |
| return fmt.Sprintf("x509: certificate is valid for %d IP SANs, but none matched %s", len(c.IPAddresses), h.Host) |
| } |
| for _, san := range c.IPAddresses { |
| if valid.Len() > 0 { |
| valid.WriteString(", ") |
| } |
| valid.WriteString(san.String()) |
| } |
| } else { |
| if len(c.DNSNames) >= maxNamesIncluded { |
| return fmt.Sprintf("x509: certificate is valid for %d names, but none matched %s", len(c.DNSNames), h.Host) |
| } |
| valid.WriteString(strings.Join(c.DNSNames, ", ")) |
| } |
|
|
| if valid.Len() == 0 { |
| return "x509: certificate is not valid for any names, but wanted to match " + h.Host |
| } |
| return "x509: certificate is valid for " + valid.String() + ", not " + h.Host |
| } |
|
|
| |
| type UnknownAuthorityError struct { |
| Cert *Certificate |
| |
| |
| hintErr error |
| |
| |
| hintCert *Certificate |
| } |
|
|
| func (e UnknownAuthorityError) Error() string { |
| s := "x509: certificate signed by unknown authority" |
| if e.hintErr != nil { |
| certName := e.hintCert.Subject.CommonName |
| if len(certName) == 0 { |
| if len(e.hintCert.Subject.Organization) > 0 { |
| certName = e.hintCert.Subject.Organization[0] |
| } else { |
| certName = "serial:" + e.hintCert.SerialNumber.String() |
| } |
| } |
| s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName) |
| } |
| return s |
| } |
|
|
| |
| type SystemRootsError struct { |
| Err error |
| } |
|
|
| func (se SystemRootsError) Error() string { |
| msg := "x509: failed to load system roots and no roots provided" |
| if se.Err != nil { |
| return msg + "; " + se.Err.Error() |
| } |
| return msg |
| } |
|
|
| func (se SystemRootsError) Unwrap() error { return se.Err } |
|
|
| |
| |
| var errNotParsed = errors.New("x509: missing ASN.1 contents; use ParseCertificate") |
|
|
| |
| type VerifyOptions struct { |
| |
| |
| DNSName string |
|
|
| |
| |
| |
| Intermediates *CertPool |
| |
| |
| Roots *CertPool |
|
|
| |
| |
| CurrentTime time.Time |
|
|
| |
| |
| |
| KeyUsages []ExtKeyUsage |
|
|
| |
| |
| |
| |
| |
| MaxConstraintComparisions int |
|
|
| |
| |
| |
| CertificatePolicies []OID |
|
|
| |
| |
| |
|
|
| |
| |
| inhibitPolicyMapping bool |
|
|
| |
| |
| requireExplicitPolicy bool |
|
|
| |
| |
| inhibitAnyPolicy bool |
| } |
|
|
| const ( |
| leafCertificate = iota |
| intermediateCertificate |
| rootCertificate |
| ) |
|
|
| |
| |
| |
| type rfc2821Mailbox struct { |
| local, domain string |
| } |
|
|
| func (s rfc2821Mailbox) String() string { |
| return fmt.Sprintf("%s@%s", s.local, s.domain) |
| } |
|
|
| |
| |
| |
| |
| func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) { |
| if len(in) == 0 { |
| return mailbox, false |
| } |
|
|
| localPartBytes := make([]byte, 0, len(in)/2) |
|
|
| if in[0] == '"' { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| in = in[1:] |
| QuotedString: |
| for { |
| if len(in) == 0 { |
| return mailbox, false |
| } |
| c := in[0] |
| in = in[1:] |
|
|
| switch { |
| case c == '"': |
| break QuotedString |
|
|
| case c == '\\': |
| |
| if len(in) == 0 { |
| return mailbox, false |
| } |
| if in[0] == 11 || |
| in[0] == 12 || |
| (1 <= in[0] && in[0] <= 9) || |
| (14 <= in[0] && in[0] <= 127) { |
| localPartBytes = append(localPartBytes, in[0]) |
| in = in[1:] |
| } else { |
| return mailbox, false |
| } |
|
|
| case c == 11 || |
| c == 12 || |
| |
| |
| |
| |
| |
| c == 32 || |
| c == 33 || |
| c == 127 || |
| (1 <= c && c <= 8) || |
| (14 <= c && c <= 31) || |
| (35 <= c && c <= 91) || |
| (93 <= c && c <= 126): |
| |
| localPartBytes = append(localPartBytes, c) |
|
|
| default: |
| return mailbox, false |
| } |
| } |
| } else { |
| |
| NextChar: |
| for len(in) > 0 { |
| |
| c := in[0] |
|
|
| switch { |
| case c == '\\': |
| |
| |
| |
| |
| |
| in = in[1:] |
| if len(in) == 0 { |
| return mailbox, false |
| } |
| fallthrough |
|
|
| case ('0' <= c && c <= '9') || |
| ('a' <= c && c <= 'z') || |
| ('A' <= c && c <= 'Z') || |
| c == '!' || c == '#' || c == '$' || c == '%' || |
| c == '&' || c == '\'' || c == '*' || c == '+' || |
| c == '-' || c == '/' || c == '=' || c == '?' || |
| c == '^' || c == '_' || c == '`' || c == '{' || |
| c == '|' || c == '}' || c == '~' || c == '.': |
| localPartBytes = append(localPartBytes, in[0]) |
| in = in[1:] |
|
|
| default: |
| break NextChar |
| } |
| } |
|
|
| if len(localPartBytes) == 0 { |
| return mailbox, false |
| } |
|
|
| |
| |
| |
| |
| twoDots := []byte{'.', '.'} |
| if localPartBytes[0] == '.' || |
| localPartBytes[len(localPartBytes)-1] == '.' || |
| bytes.Contains(localPartBytes, twoDots) { |
| return mailbox, false |
| } |
| } |
|
|
| if len(in) == 0 || in[0] != '@' { |
| return mailbox, false |
| } |
| in = in[1:] |
|
|
| |
| |
| |
| if _, ok := domainToReverseLabels(in); !ok { |
| return mailbox, false |
| } |
|
|
| mailbox.local = string(localPartBytes) |
| mailbox.domain = in |
| return mailbox, true |
| } |
|
|
| |
| |
| func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) { |
| reverseLabels = make([]string, 0, strings.Count(domain, ".")+1) |
| for len(domain) > 0 { |
| if i := strings.LastIndexByte(domain, '.'); i == -1 { |
| reverseLabels = append(reverseLabels, domain) |
| domain = "" |
| } else { |
| reverseLabels = append(reverseLabels, domain[i+1:]) |
| domain = domain[:i] |
| if i == 0 { |
| |
| |
| reverseLabels = append(reverseLabels, "") |
| } |
| } |
| } |
|
|
| if len(reverseLabels) > 0 && len(reverseLabels[0]) == 0 { |
| |
| return nil, false |
| } |
|
|
| for _, label := range reverseLabels { |
| if len(label) == 0 { |
| |
| return nil, false |
| } |
|
|
| for _, c := range label { |
| if c < 33 || c > 126 { |
| |
| return nil, false |
| } |
| } |
| } |
|
|
| return reverseLabels, true |
| } |
|
|
| |
| |
| func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error { |
| if len(c.UnhandledCriticalExtensions) > 0 { |
| return UnhandledCriticalExtension{} |
| } |
|
|
| if len(currentChain) > 0 { |
| child := currentChain[len(currentChain)-1] |
| if !bytes.Equal(child.RawIssuer, c.RawSubject) { |
| return CertificateInvalidError{c, NameMismatch, ""} |
| } |
| } |
|
|
| now := opts.CurrentTime |
| if now.IsZero() { |
| now = time.Now() |
| } |
| if now.Before(c.NotBefore) { |
| return CertificateInvalidError{ |
| Cert: c, |
| Reason: Expired, |
| Detail: fmt.Sprintf("current time %s is before %s", now.Format(time.RFC3339), c.NotBefore.Format(time.RFC3339)), |
| } |
| } else if now.After(c.NotAfter) { |
| return CertificateInvalidError{ |
| Cert: c, |
| Reason: Expired, |
| Detail: fmt.Sprintf("current time %s is after %s", now.Format(time.RFC3339), c.NotAfter.Format(time.RFC3339)), |
| } |
| } |
|
|
| if certType == intermediateCertificate || certType == rootCertificate { |
| if len(currentChain) == 0 { |
| return errors.New("x509: internal error: empty chain when appending CA cert") |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) { |
| return CertificateInvalidError{c, NotAuthorizedToSign, ""} |
| } |
|
|
| if c.BasicConstraintsValid && c.MaxPathLen >= 0 { |
| numIntermediates := len(currentChain) - 1 |
| if numIntermediates > c.MaxPathLen { |
| return CertificateInvalidError{c, TooManyIntermediates, ""} |
| } |
| } |
|
|
| return nil |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| func (c *Certificate) Verify(opts VerifyOptions) ([][]*Certificate, error) { |
| |
| |
| if len(c.Raw) == 0 { |
| return nil, errNotParsed |
| } |
| for i := 0; i < opts.Intermediates.len(); i++ { |
| c, _, err := opts.Intermediates.cert(i) |
| if err != nil { |
| return nil, fmt.Errorf("crypto/x509: error fetching intermediate: %w", err) |
| } |
| if len(c.Raw) == 0 { |
| return nil, errNotParsed |
| } |
| } |
|
|
| |
| if runtime.GOOS == "windows" || runtime.GOOS == "darwin" || runtime.GOOS == "ios" { |
| |
| |
| systemPool := systemRootsPool() |
| if opts.Roots == nil && (systemPool == nil || systemPool.systemPool) { |
| return c.systemVerify(&opts) |
| } |
| if opts.Roots != nil && opts.Roots.systemPool { |
| platformChains, err := c.systemVerify(&opts) |
| |
| |
| |
| if err == nil || opts.Roots.len() == 0 { |
| return platformChains, err |
| } |
| } |
| } |
|
|
| if opts.Roots == nil { |
| opts.Roots = systemRootsPool() |
| if opts.Roots == nil { |
| return nil, SystemRootsError{systemRootsErr} |
| } |
| } |
|
|
| err := c.isValid(leafCertificate, nil, &opts) |
| if err != nil { |
| return nil, err |
| } |
|
|
| if len(opts.DNSName) > 0 { |
| err = c.VerifyHostname(opts.DNSName) |
| if err != nil { |
| return nil, err |
| } |
| } |
|
|
| var candidateChains [][]*Certificate |
| if opts.Roots.contains(c) { |
| candidateChains = [][]*Certificate{{c}} |
| } else { |
| candidateChains, err = c.buildChains([]*Certificate{c}, nil, &opts) |
| if err != nil { |
| return nil, err |
| } |
| } |
|
|
| anyKeyUsage := false |
| for _, eku := range opts.KeyUsages { |
| if eku == ExtKeyUsageAny { |
| |
| anyKeyUsage = true |
| break |
| } |
| } |
|
|
| if len(opts.KeyUsages) == 0 { |
| opts.KeyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth} |
| } |
|
|
| var invalidPoliciesChains int |
| var incompatibleKeyUsageChains int |
| var constraintsHintErr error |
| candidateChains = slices.DeleteFunc(candidateChains, func(chain []*Certificate) bool { |
| if !policiesValid(chain, opts) { |
| invalidPoliciesChains++ |
| return true |
| } |
| |
| |
| if !anyKeyUsage && !checkChainForKeyUsage(chain, opts.KeyUsages) { |
| incompatibleKeyUsageChains++ |
| return true |
| } |
| if err := checkChainConstraints(chain); err != nil { |
| if constraintsHintErr == nil { |
| constraintsHintErr = CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()} |
| } |
| return true |
| } |
| return false |
| }) |
|
|
| if len(candidateChains) == 0 { |
| if constraintsHintErr != nil { |
| return nil, constraintsHintErr |
| } |
| var details []string |
| if incompatibleKeyUsageChains > 0 { |
| if invalidPoliciesChains == 0 { |
| return nil, CertificateInvalidError{c, IncompatibleUsage, ""} |
| } |
| details = append(details, fmt.Sprintf("%d candidate chains with incompatible key usage", incompatibleKeyUsageChains)) |
| } |
| if invalidPoliciesChains > 0 { |
| details = append(details, fmt.Sprintf("%d candidate chains with invalid policies", invalidPoliciesChains)) |
| } |
| err = CertificateInvalidError{c, NoValidChains, strings.Join(details, ", ")} |
| return nil, err |
| } |
|
|
| return candidateChains, nil |
| } |
|
|
| func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate { |
| n := make([]*Certificate, len(chain)+1) |
| copy(n, chain) |
| n[len(chain)] = cert |
| return n |
| } |
|
|
| |
| |
| |
| |
| |
| func alreadyInChain(candidate *Certificate, chain []*Certificate) bool { |
| type pubKeyEqual interface { |
| Equal(crypto.PublicKey) bool |
| } |
|
|
| var candidateSAN *pkix.Extension |
| for _, ext := range candidate.Extensions { |
| if ext.Id.Equal(oidExtensionSubjectAltName) { |
| candidateSAN = &ext |
| break |
| } |
| } |
|
|
| for _, cert := range chain { |
| if !bytes.Equal(candidate.RawSubject, cert.RawSubject) { |
| continue |
| } |
| |
| |
| |
| if !bytes.Equal(candidate.RawSubjectPublicKeyInfo, cert.RawSubjectPublicKeyInfo) { |
| continue |
| } |
| var certSAN *pkix.Extension |
| for _, ext := range cert.Extensions { |
| if ext.Id.Equal(oidExtensionSubjectAltName) { |
| certSAN = &ext |
| break |
| } |
| } |
| if candidateSAN == nil && certSAN == nil { |
| return true |
| } else if candidateSAN == nil || certSAN == nil { |
| return false |
| } |
| if bytes.Equal(candidateSAN.Value, certSAN.Value) { |
| return true |
| } |
| } |
| return false |
| } |
|
|
| |
| |
| |
| |
| const maxChainSignatureChecks = 100 |
|
|
| var errSignatureLimit = errors.New("x509: signature check attempts limit reached while verifying certificate chain") |
|
|
| func (c *Certificate) buildChains(currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error) { |
| var ( |
| hintErr error |
| hintCert *Certificate |
| ) |
|
|
| considerCandidate := func(certType int, candidate potentialParent) { |
| if sigChecks == nil { |
| sigChecks = new(int) |
| } |
| *sigChecks++ |
| if *sigChecks > maxChainSignatureChecks { |
| err = errSignatureLimit |
| return |
| } |
|
|
| if candidate.cert.PublicKey == nil || alreadyInChain(candidate.cert, currentChain) { |
| return |
| } |
|
|
| if err := c.CheckSignatureFrom(candidate.cert); err != nil { |
| if hintErr == nil { |
| hintErr = err |
| hintCert = candidate.cert |
| } |
| return |
| } |
|
|
| err = candidate.cert.isValid(certType, currentChain, opts) |
| if err != nil { |
| if hintErr == nil { |
| hintErr = err |
| hintCert = candidate.cert |
| } |
| return |
| } |
|
|
| if candidate.constraint != nil { |
| if err := candidate.constraint(currentChain); err != nil { |
| if hintErr == nil { |
| hintErr = err |
| hintCert = candidate.cert |
| } |
| return |
| } |
| } |
|
|
| switch certType { |
| case rootCertificate: |
| chains = append(chains, appendToFreshChain(currentChain, candidate.cert)) |
| case intermediateCertificate: |
| var childChains [][]*Certificate |
| childChains, err = candidate.cert.buildChains(appendToFreshChain(currentChain, candidate.cert), sigChecks, opts) |
| chains = append(chains, childChains...) |
| } |
| } |
|
|
| candidateLoop: |
| for _, parents := range []struct { |
| certType int |
| potentials []potentialParent |
| }{ |
| {rootCertificate, opts.Roots.findPotentialParents(c)}, |
| {intermediateCertificate, opts.Intermediates.findPotentialParents(c)}, |
| } { |
| for _, parent := range parents.potentials { |
| considerCandidate(parents.certType, parent) |
| if err == errSignatureLimit { |
| break candidateLoop |
| } |
| } |
| } |
|
|
| if len(chains) > 0 { |
| err = nil |
| } |
| if len(chains) == 0 && err == nil { |
| err = UnknownAuthorityError{c, hintErr, hintCert} |
| } |
|
|
| return |
| } |
|
|
| func validHostnamePattern(host string) bool { return validHostname(host, true) } |
| func validHostnameInput(host string) bool { return validHostname(host, false) } |
|
|
| |
| |
| |
| func validHostname(host string, isPattern bool) bool { |
| if !isPattern { |
| host = strings.TrimSuffix(host, ".") |
| } |
| if len(host) == 0 { |
| return false |
| } |
| if host == "*" { |
| |
| |
| return false |
| } |
|
|
| for i, part := range strings.Split(host, ".") { |
| if part == "" { |
| |
| return false |
| } |
| if isPattern && i == 0 && part == "*" { |
| |
| |
| |
| continue |
| } |
| for j, c := range part { |
| if 'a' <= c && c <= 'z' { |
| continue |
| } |
| if '0' <= c && c <= '9' { |
| continue |
| } |
| if 'A' <= c && c <= 'Z' { |
| continue |
| } |
| if c == '-' && j != 0 { |
| continue |
| } |
| if c == '_' { |
| |
| |
| continue |
| } |
| return false |
| } |
| } |
|
|
| return true |
| } |
|
|
| func matchExactly(hostA, hostB string) bool { |
| if hostA == "" || hostA == "." || hostB == "" || hostB == "." { |
| return false |
| } |
| return toLowerCaseASCII(hostA) == toLowerCaseASCII(hostB) |
| } |
|
|
| func matchHostnames(pattern, host string) bool { |
| pattern = toLowerCaseASCII(pattern) |
| host = toLowerCaseASCII(strings.TrimSuffix(host, ".")) |
|
|
| if len(pattern) == 0 || len(host) == 0 { |
| return false |
| } |
|
|
| patternParts := strings.Split(pattern, ".") |
| hostParts := strings.Split(host, ".") |
|
|
| if len(patternParts) != len(hostParts) { |
| return false |
| } |
|
|
| for i, patternPart := range patternParts { |
| if i == 0 && patternPart == "*" { |
| continue |
| } |
| if patternPart != hostParts[i] { |
| return false |
| } |
| } |
|
|
| return true |
| } |
|
|
| |
| |
| |
| func toLowerCaseASCII(in string) string { |
| |
| isAlreadyLowerCase := true |
| for _, c := range in { |
| if c == utf8.RuneError { |
| |
| |
| isAlreadyLowerCase = false |
| break |
| } |
| if 'A' <= c && c <= 'Z' { |
| isAlreadyLowerCase = false |
| break |
| } |
| } |
|
|
| if isAlreadyLowerCase { |
| return in |
| } |
|
|
| out := []byte(in) |
| for i, c := range out { |
| if 'A' <= c && c <= 'Z' { |
| out[i] += 'a' - 'A' |
| } |
| } |
| return string(out) |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| func (c *Certificate) VerifyHostname(h string) error { |
| |
| candidateIP := h |
| if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' { |
| candidateIP = h[1 : len(h)-1] |
| } |
| if ip := net.ParseIP(candidateIP); ip != nil { |
| |
| |
| for _, candidate := range c.IPAddresses { |
| if ip.Equal(candidate) { |
| return nil |
| } |
| } |
| return HostnameError{c, candidateIP} |
| } |
|
|
| candidateName := toLowerCaseASCII(h) |
| validCandidateName := validHostnameInput(candidateName) |
|
|
| for _, match := range c.DNSNames { |
| |
| |
| |
| |
| |
| if validCandidateName && validHostnamePattern(match) { |
| if matchHostnames(match, candidateName) { |
| return nil |
| } |
| } else { |
| if matchExactly(match, candidateName) { |
| return nil |
| } |
| } |
| } |
|
|
| return HostnameError{c, h} |
| } |
|
|
| func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool { |
| usages := make([]ExtKeyUsage, len(keyUsages)) |
| copy(usages, keyUsages) |
|
|
| if len(chain) == 0 { |
| return false |
| } |
|
|
| usagesRemaining := len(usages) |
|
|
| |
| |
| |
|
|
| NextCert: |
| for i := len(chain) - 1; i >= 0; i-- { |
| cert := chain[i] |
| if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 { |
| |
| continue |
| } |
|
|
| for _, usage := range cert.ExtKeyUsage { |
| if usage == ExtKeyUsageAny { |
| |
| continue NextCert |
| } |
| } |
|
|
| const invalidUsage = -1 |
|
|
| NextRequestedUsage: |
| for i, requestedUsage := range usages { |
| if requestedUsage == invalidUsage { |
| continue |
| } |
|
|
| for _, usage := range cert.ExtKeyUsage { |
| if requestedUsage == usage { |
| continue NextRequestedUsage |
| } |
| } |
|
|
| usages[i] = invalidUsage |
| usagesRemaining-- |
| if usagesRemaining == 0 { |
| return false |
| } |
| } |
| } |
|
|
| return true |
| } |
|
|
| func mustNewOIDFromInts(ints []uint64) OID { |
| oid, err := OIDFromInts(ints) |
| if err != nil { |
| panic(fmt.Sprintf("OIDFromInts(%v) unexpected error: %v", ints, err)) |
| } |
| return oid |
| } |
|
|
| type policyGraphNode struct { |
| validPolicy OID |
| expectedPolicySet []OID |
| |
|
|
| parents map[*policyGraphNode]bool |
| children map[*policyGraphNode]bool |
| } |
|
|
| func newPolicyGraphNode(valid OID, parents []*policyGraphNode) *policyGraphNode { |
| n := &policyGraphNode{ |
| validPolicy: valid, |
| expectedPolicySet: []OID{valid}, |
| children: map[*policyGraphNode]bool{}, |
| parents: map[*policyGraphNode]bool{}, |
| } |
| for _, p := range parents { |
| p.children[n] = true |
| n.parents[p] = true |
| } |
| return n |
| } |
|
|
| type policyGraph struct { |
| strata []map[string]*policyGraphNode |
| |
| parentIndex map[string][]*policyGraphNode |
| depth int |
| } |
|
|
| var anyPolicyOID = mustNewOIDFromInts([]uint64{2, 5, 29, 32, 0}) |
|
|
| func newPolicyGraph() *policyGraph { |
| root := policyGraphNode{ |
| validPolicy: anyPolicyOID, |
| expectedPolicySet: []OID{anyPolicyOID}, |
| children: map[*policyGraphNode]bool{}, |
| parents: map[*policyGraphNode]bool{}, |
| } |
| return &policyGraph{ |
| depth: 0, |
| strata: []map[string]*policyGraphNode{{string(anyPolicyOID.der): &root}}, |
| } |
| } |
|
|
| func (pg *policyGraph) insert(n *policyGraphNode) { |
| pg.strata[pg.depth][string(n.validPolicy.der)] = n |
| } |
|
|
| func (pg *policyGraph) parentsWithExpected(expected OID) []*policyGraphNode { |
| if pg.depth == 0 { |
| return nil |
| } |
| return pg.parentIndex[string(expected.der)] |
| } |
|
|
| func (pg *policyGraph) parentWithAnyPolicy() *policyGraphNode { |
| if pg.depth == 0 { |
| return nil |
| } |
| return pg.strata[pg.depth-1][string(anyPolicyOID.der)] |
| } |
|
|
| func (pg *policyGraph) parents() iter.Seq[*policyGraphNode] { |
| if pg.depth == 0 { |
| return nil |
| } |
| return maps.Values(pg.strata[pg.depth-1]) |
| } |
|
|
| func (pg *policyGraph) leaves() map[string]*policyGraphNode { |
| return pg.strata[pg.depth] |
| } |
|
|
| func (pg *policyGraph) leafWithPolicy(policy OID) *policyGraphNode { |
| return pg.strata[pg.depth][string(policy.der)] |
| } |
|
|
| func (pg *policyGraph) deleteLeaf(policy OID) { |
| n := pg.strata[pg.depth][string(policy.der)] |
| if n == nil { |
| return |
| } |
| for p := range n.parents { |
| delete(p.children, n) |
| } |
| for c := range n.children { |
| delete(c.parents, n) |
| } |
| delete(pg.strata[pg.depth], string(policy.der)) |
| } |
|
|
| func (pg *policyGraph) validPolicyNodes() []*policyGraphNode { |
| var validNodes []*policyGraphNode |
| for i := pg.depth; i >= 0; i-- { |
| for _, n := range pg.strata[i] { |
| if n.validPolicy.Equal(anyPolicyOID) { |
| continue |
| } |
|
|
| if len(n.parents) == 1 { |
| for p := range n.parents { |
| if p.validPolicy.Equal(anyPolicyOID) { |
| validNodes = append(validNodes, n) |
| } |
| } |
| } |
| } |
| } |
| return validNodes |
| } |
|
|
| func (pg *policyGraph) prune() { |
| for i := pg.depth - 1; i > 0; i-- { |
| for _, n := range pg.strata[i] { |
| if len(n.children) == 0 { |
| for p := range n.parents { |
| delete(p.children, n) |
| } |
| delete(pg.strata[i], string(n.validPolicy.der)) |
| } |
| } |
| } |
| } |
|
|
| func (pg *policyGraph) incrDepth() { |
| pg.parentIndex = map[string][]*policyGraphNode{} |
| for _, n := range pg.strata[pg.depth] { |
| for _, e := range n.expectedPolicySet { |
| pg.parentIndex[string(e.der)] = append(pg.parentIndex[string(e.der)], n) |
| } |
| } |
|
|
| pg.depth++ |
| pg.strata = append(pg.strata, map[string]*policyGraphNode{}) |
| } |
|
|
| func policiesValid(chain []*Certificate, opts VerifyOptions) bool { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| if len(chain) == 1 { |
| return true |
| } |
|
|
| |
| n := len(chain) - 1 |
|
|
| pg := newPolicyGraph() |
| var inhibitAnyPolicy, explicitPolicy, policyMapping int |
| if !opts.inhibitAnyPolicy { |
| inhibitAnyPolicy = n + 1 |
| } |
| if !opts.requireExplicitPolicy { |
| explicitPolicy = n + 1 |
| } |
| if !opts.inhibitPolicyMapping { |
| policyMapping = n + 1 |
| } |
|
|
| initialUserPolicySet := map[string]bool{} |
| for _, p := range opts.CertificatePolicies { |
| initialUserPolicySet[string(p.der)] = true |
| } |
| |
| |
| if len(initialUserPolicySet) == 0 { |
| initialUserPolicySet[string(anyPolicyOID.der)] = true |
| } |
|
|
| for i := n - 1; i >= 0; i-- { |
| cert := chain[i] |
|
|
| isSelfSigned := bytes.Equal(cert.RawIssuer, cert.RawSubject) |
|
|
| |
| if len(cert.Policies) == 0 { |
| pg = nil |
| } |
|
|
| |
| if explicitPolicy == 0 && pg == nil { |
| return false |
| } |
|
|
| if pg != nil { |
| pg.incrDepth() |
|
|
| policies := map[string]bool{} |
|
|
| |
| for _, policy := range cert.Policies { |
| policies[string(policy.der)] = true |
|
|
| if policy.Equal(anyPolicyOID) { |
| continue |
| } |
|
|
| |
| parents := pg.parentsWithExpected(policy) |
| if len(parents) == 0 { |
| |
| if anyParent := pg.parentWithAnyPolicy(); anyParent != nil { |
| parents = []*policyGraphNode{anyParent} |
| } |
| } |
| if len(parents) > 0 { |
| pg.insert(newPolicyGraphNode(policy, parents)) |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| if policies[string(anyPolicyOID.der)] && (inhibitAnyPolicy > 0 || (n-i < n && isSelfSigned)) { |
| missing := map[string][]*policyGraphNode{} |
| leaves := pg.leaves() |
| for p := range pg.parents() { |
| for _, expected := range p.expectedPolicySet { |
| if leaves[string(expected.der)] == nil { |
| missing[string(expected.der)] = append(missing[string(expected.der)], p) |
| } |
| } |
| } |
|
|
| for oidStr, parents := range missing { |
| pg.insert(newPolicyGraphNode(OID{der: []byte(oidStr)}, parents)) |
| } |
| } |
|
|
| |
| pg.prune() |
|
|
| if i != 0 { |
| |
| if len(cert.PolicyMappings) > 0 { |
| |
| mappings := map[string][]OID{} |
|
|
| for _, mapping := range cert.PolicyMappings { |
| if policyMapping > 0 { |
| if mapping.IssuerDomainPolicy.Equal(anyPolicyOID) || mapping.SubjectDomainPolicy.Equal(anyPolicyOID) { |
| |
| return false |
| } |
| mappings[string(mapping.IssuerDomainPolicy.der)] = append(mappings[string(mapping.IssuerDomainPolicy.der)], mapping.SubjectDomainPolicy) |
| } else { |
| |
| pg.deleteLeaf(mapping.IssuerDomainPolicy) |
| } |
| } |
|
|
| |
| pg.prune() |
|
|
| for issuerStr, subjectPolicies := range mappings { |
| |
| if matching := pg.leafWithPolicy(OID{der: []byte(issuerStr)}); matching != nil { |
| matching.expectedPolicySet = subjectPolicies |
| } else if matching := pg.leafWithPolicy(anyPolicyOID); matching != nil { |
| |
| n := newPolicyGraphNode(OID{der: []byte(issuerStr)}, []*policyGraphNode{matching}) |
| n.expectedPolicySet = subjectPolicies |
| pg.insert(n) |
| } |
| } |
| } |
| } |
| } |
|
|
| if i != 0 { |
| |
| if !isSelfSigned { |
| if explicitPolicy > 0 { |
| explicitPolicy-- |
| } |
| if policyMapping > 0 { |
| policyMapping-- |
| } |
| if inhibitAnyPolicy > 0 { |
| inhibitAnyPolicy-- |
| } |
| } |
|
|
| |
| if (cert.RequireExplicitPolicy > 0 || cert.RequireExplicitPolicyZero) && cert.RequireExplicitPolicy < explicitPolicy { |
| explicitPolicy = cert.RequireExplicitPolicy |
| } |
| if (cert.InhibitPolicyMapping > 0 || cert.InhibitPolicyMappingZero) && cert.InhibitPolicyMapping < policyMapping { |
| policyMapping = cert.InhibitPolicyMapping |
| } |
| |
| if (cert.InhibitAnyPolicy > 0 || cert.InhibitAnyPolicyZero) && cert.InhibitAnyPolicy < inhibitAnyPolicy { |
| inhibitAnyPolicy = cert.InhibitAnyPolicy |
| } |
| } |
| } |
|
|
| |
| if explicitPolicy > 0 { |
| explicitPolicy-- |
| } |
|
|
| |
| if chain[0].RequireExplicitPolicyZero { |
| explicitPolicy = 0 |
| } |
|
|
| |
| var validPolicyNodeSet []*policyGraphNode |
| |
| if pg != nil { |
| validPolicyNodeSet = pg.validPolicyNodes() |
| |
| if currentAny := pg.leafWithPolicy(anyPolicyOID); currentAny != nil { |
| validPolicyNodeSet = append(validPolicyNodeSet, currentAny) |
| } |
| } |
|
|
| |
| authorityConstrainedPolicySet := map[string]bool{} |
| for _, n := range validPolicyNodeSet { |
| authorityConstrainedPolicySet[string(n.validPolicy.der)] = true |
| } |
| |
| userConstrainedPolicySet := maps.Clone(authorityConstrainedPolicySet) |
| |
| if len(initialUserPolicySet) != 1 || !initialUserPolicySet[string(anyPolicyOID.der)] { |
| |
| for p := range userConstrainedPolicySet { |
| if !initialUserPolicySet[p] { |
| delete(userConstrainedPolicySet, p) |
| } |
| } |
| |
| if authorityConstrainedPolicySet[string(anyPolicyOID.der)] { |
| for policy := range initialUserPolicySet { |
| userConstrainedPolicySet[policy] = true |
| } |
| } |
| } |
|
|
| if explicitPolicy == 0 && len(userConstrainedPolicySet) == 0 { |
| return false |
| } |
|
|
| return true |
| } |
|
|