diff --git a/MANIFEST.sha256 b/MANIFEST.sha256 index a59dd7b..881bf15 100644 --- a/MANIFEST.sha256 +++ b/MANIFEST.sha256 @@ -25,5 +25,5 @@ e2307e22b5e248d63e84f321bfc12c32912f3e492f01763414e7e0ca47bfe072 ./ai/ROADMAP_a a5faa116761dbccbb4e1569c8a300a99a7184bd0cc587bb3f429c10d44360237 ./context/GOALS.md 44424aa2a544a07bb3a888be9045d316b23067a1848339f2e3ce4db108103af2 ./context/LIMITS.md 7f0881c683fe2c1f06864d111ee54b238c0974704b64d2d3561c5c15507c58ba ./context/SYMBOLS.ALLOWPKGS -c25f84395c9143dac68813ba1671433fe0c7636dfd5e676b40f985e6dab44965 ./context/SYMBOLS.md +680ee98454826230f8a4bda39e48c827d0dbcd2566793e11867a22b6464ad1a5 ./context/SYMBOLS.md 1479b2a3cd99cc7f9ddd1b3bb58114840859a01ad9a406c62bf0a9e4fcd87f50 ./context/TESTING.md diff --git a/cmd/relay/bootstrap.go b/cmd/relay/bootstrap.go index ae234e0..7e586e5 100644 --- a/cmd/relay/bootstrap.go +++ b/cmd/relay/bootstrap.go @@ -75,6 +75,7 @@ func registerNativeComponents(ctx context.Context, svc cabinet.Cabinet, pkiAsset Intermediates: pkiAssets.Intermediates, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning}, CRLs: pkiAssets.CRLs, + CRLFreshness: pkiAssets.CRLFreshness, } _, err := cabinet.VerifyCertificateChain(cert, opts) return err @@ -310,9 +311,10 @@ type PKIAssets struct { Roots *x509.CertPool Intermediates *x509.CertPool CRLs []*x509.RevocationList - TrustStoreLoaded bool // true when at least one root CA was loaded - CAFingerprint string // sha256 of the first loaded root CA DER bytes, "sha256:" - CertChainHash string // sha256 of all loaded CA cert DER bytes concatenated, "sha256:" + CRLFreshness *cabinet.CRLFreshness // set in prod: verification rejects a stale CRL + TrustStoreLoaded bool // true when at least one root CA was loaded + CAFingerprint string // sha256 of the first loaded root CA DER bytes, "sha256:" + CertChainHash string // sha256 of all loaded CA cert DER bytes concatenated, "sha256:" // R3b (feature-011): the cic-flow provenance/entitlement anchors, delivered by // their own detached-companion path — NOT embedded, so the relay binary's hash @@ -555,6 +557,7 @@ func loadModule(ctx context.Context, svc cabinet.Cabinet, fsys fs.FS, yamlPath s Intermediates: pkiAssets.Intermediates, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning}, CRLs: pkiAssets.CRLs, + CRLFreshness: pkiAssets.CRLFreshness, } chains, verifyErr := cabinet.VerifyCertificateChain(cert, verifyOpts) if verifyErr != nil { @@ -597,7 +600,12 @@ func loadModule(ctx context.Context, svc cabinet.Cabinet, fsys fs.FS, yamlPath s // loadPKIAssets loads X.509 certificates and CRLs from a filesystem path and populates PKIAssets // with root certificates, intermediates, and revocation lists. +// +// This is the lenient (dev) loader: every CRL still needs a valid signature from a CA +// certificate loaded here, and one that fails is never used, but an unparsable or stale CRL +// is only logged. The strict (prod) path is the CA bundle in bootstrapPKI. func loadPKIAssets(fsys fs.FS, path string, logger *logrus.Logger) (*PKIAssets, error) { + policy := crlPolicy{} assets := &PKIAssets{ Roots: x509.NewCertPool(), Intermediates: x509.NewCertPool(), @@ -605,6 +613,9 @@ func loadPKIAssets(fsys fs.FS, path string, logger *logrus.Logger) (*PKIAssets, } // chainHasher accumulates all loaded CA cert DER bytes for CertChainHash. chainHasher := sha256.New() + // CRLs are verified after the whole directory is read: a CRL may precede its issuer. + var caCerts []*x509.Certificate + var candidateCRLs []*x509.RevocationList // If path is empty, there are no PKI assets to load from a directory. // Return empty assets without trying to read a directory. @@ -651,6 +662,7 @@ func loadPKIAssets(fsys fs.FS, path string, logger *logrus.Logger) (*PKIAssets, continue } if cert.IsCA { + caCerts = append(caCerts, cert) chainHasher.Write(cert.Raw) if cert.Subject.String() == cert.Issuer.String() { // Self-signed, so it's a root assets.Roots.AddCert(cert) @@ -669,13 +681,19 @@ func loadPKIAssets(fsys fs.FS, path string, logger *logrus.Logger) (*PKIAssets, logger.WithFields(logrus.Fields{"path": file.Name(), "error": err}).Warn("Failed to parse CRL") continue } - assets.CRLs = append(assets.CRLs, crl) + candidateCRLs = append(candidateCRLs, crl) } } if !anyBlock { logger.WithField("path", file.Name()).Warn("No PEM data found in file") } } + crls, err := acceptCRLs(candidateCRLs, caCerts, policy, logger) + if err != nil { + return nil, err + } + assets.CRLs = crls + assets.CRLFreshness = policy.Freshness if assets.TrustStoreLoaded { assets.CertChainHash = "sha256:" + hex.EncodeToString(chainHasher.Sum(nil)) } diff --git a/cmd/relay/pki_bootstrap.go b/cmd/relay/pki_bootstrap.go index 0c777f3..ba831cc 100644 --- a/cmd/relay/pki_bootstrap.go +++ b/cmd/relay/pki_bootstrap.go @@ -8,6 +8,8 @@ import ( "strings" "github.com/sirupsen/logrus" + + "centralrelay/core/cabinet" ) const ( @@ -87,15 +89,50 @@ func bootstrapPKI(trustMode string, embeddedPKI fs.FS, logger *logrus.Logger) (* if !pool.AppendCertsFromPEM(pemData) { return nil, fmt.Errorf("pki bootstrap (prod): no valid certificates in %q", bundlePath) } + // CRLs travel in the same bundle (X509 CRL blocks). In prod a CRL that cannot be + // parsed, is not signed by a CA of the bundle, or is stale is a start-up error. + tolerance, err := crlToleranceFromEnv() + if err != nil { + return nil, fmt.Errorf("pki bootstrap (prod): %w", err) + } + policy := crlPolicy{Strict: true, Freshness: &cabinet.CRLFreshness{Tolerance: tolerance}} + issuers, candidateCRLs, err := parseBundleCRLs(pemData, policy, logger) + if err != nil { + return nil, fmt.Errorf("pki bootstrap (prod): %w", err) + } + crls, err := acceptCRLs(candidateCRLs, issuers, policy, logger) + if err != nil { + return nil, fmt.Errorf("pki bootstrap (prod): %w", err) + } + // The operator declares which issuers must have a CRL; a required issuer without a + // valid, fresh one is a start-up error. dev (the embedded loader) has no such policy: + // it stays lenient and ignores CIC_CRL_REQUIRED_ISSUERS. + issuerPolicy, err := crlIssuerPolicyFromEnv() + if err != nil { + return nil, fmt.Errorf("pki bootstrap (prod): %w", err) + } + if err := enforceCRLIssuerPolicy(issuerPolicy, issuers, crls); err != nil { + return nil, fmt.Errorf("pki bootstrap (prod): %w", err) + } + if issuerPolicy.none { + logger.Warn("CIC_CRL_REQUIRED_ISSUERS=none: no issuer is required to have a CRL") + } + if len(crls) == 0 { + logger.WithField("bundle_path", bundlePath).Warn("Revocation checking is inactive: the CA bundle contains no CRL") + } + // No pin source exists yet: pinning is off, and in prod that is stated, not implicit. + logger.WithField("spki_pins", 0).Warn("SPKI pinning is not configured: the pin set is empty") logger.WithFields(logrus.Fields{ "trust_mode": trustMode, "trust_store_loaded": true, "bundle_path": bundlePath, + "crls": len(crls), }).Info("PKI trust store bootstrapped (prod)") return &PKIAssets{ Roots: pool, Intermediates: x509.NewCertPool(), - CRLs: []*x509.RevocationList{}, + CRLs: crls, + CRLFreshness: policy.Freshness, TrustStoreLoaded: true, }, nil diff --git a/cmd/relay/pki_bootstrap_test.go b/cmd/relay/pki_bootstrap_test.go index 00e2ac2..86931db 100644 --- a/cmd/relay/pki_bootstrap_test.go +++ b/cmd/relay/pki_bootstrap_test.go @@ -97,6 +97,7 @@ func TestBootstrapPKI_ProdMode_WithBundle(t *testing.T) { require.NoError(t, os.WriteFile(bundlePath, pemData, 0600)) t.Setenv("CIC_PLATFORM_CA_BUNDLE", bundlePath) + t.Setenv("CIC_CRL_REQUIRED_ISSUERS", "none") assets, err := bootstrapPKI(TrustModeProd, embeddedFS, newDiscardLogger()) require.NoError(t, err) assert.True(t, assets.TrustStoreLoaded) diff --git a/cmd/relay/pki_companion.go b/cmd/relay/pki_companion.go index 5d7d939..aec9616 100644 --- a/cmd/relay/pki_companion.go +++ b/cmd/relay/pki_companion.go @@ -75,6 +75,7 @@ func verifyCICFlowProvenance(cert *x509.Certificate, pkiAssets *PKIAssets) error Intermediates: pkiAssets.Intermediates, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning}, CRLs: pkiAssets.CRLs, + CRLFreshness: pkiAssets.CRLFreshness, }) if err != nil { return fmt.Errorf("provenance verification failed: %w", err) diff --git a/cmd/relay/pki_crl.go b/cmd/relay/pki_crl.go new file mode 100644 index 0000000..b284434 --- /dev/null +++ b/cmd/relay/pki_crl.go @@ -0,0 +1,176 @@ +package main + +import ( + "bytes" + "crypto/sha256" + "crypto/x509" + "encoding/hex" + "encoding/pem" + "fmt" + "os" + "strings" + "time" + + "github.com/sirupsen/logrus" + + "centralrelay/core/cabinet" +) + +// crlPolicy decides what a bad CRL means. Strict (prod): a CRL that cannot be parsed, +// whose signature does not verify against a trusted issuer, or that is stale, is a +// start-up error. Lenient (dev): such a CRL is logged and not used. Either way a CRL +// with a bad signature is never used. +type crlPolicy struct { + Strict bool + Freshness *cabinet.CRLFreshness // enforced in strict mode and carried to verification +} + +// acceptCRLs returns the CRLs that may be used. Each one needs a valid signature from +// one of the issuers. Freshness is enforced in strict mode; lenient mode only warns. +func acceptCRLs(candidates []*x509.RevocationList, issuers []*x509.Certificate, p crlPolicy, logger *logrus.Logger) ([]*x509.RevocationList, error) { + accepted := []*x509.RevocationList{} + for _, crl := range candidates { + if err := cabinet.VerifyCRLSignature(crl, issuers); err != nil { + if p.Strict { + return nil, fmt.Errorf("pki bootstrap: %w", err) + } + logger.WithError(err).Warn("CRL rejected: its entries are not used") + continue + } + fresh := p.Freshness + if fresh == nil { + fresh = &cabinet.CRLFreshness{} + } + if err := cabinet.CheckCRLFresh(crl, fresh); err != nil { + if p.Strict { + return nil, fmt.Errorf("pki bootstrap: %w", err) + } + logger.WithError(err).Warn("CRL is stale, still used (dev mode)") + } + accepted = append(accepted, crl) + } + return accepted, nil +} + +// parseBundleCRLs reads the certificates and CRLs of a PEM bundle. In strict mode a CRL +// block that does not parse is an error; in lenient mode it is skipped with a warning. +// Certificates that do not parse are ignored (the trust pool ignores them as well). +func parseBundleCRLs(pemData []byte, p crlPolicy, logger *logrus.Logger) (issuers []*x509.Certificate, crls []*x509.RevocationList, err error) { + rest := pemData + for len(rest) > 0 { + var block *pem.Block + block, rest = pem.Decode(rest) + if block == nil { + break + } + switch block.Type { + case "CERTIFICATE": + if cert, perr := x509.ParseCertificate(block.Bytes); perr == nil && cert.IsCA { + issuers = append(issuers, cert) + } + case "X509 CRL": + crl, perr := x509.ParseRevocationList(block.Bytes) + if perr != nil { + if p.Strict { + return nil, nil, fmt.Errorf("pki bootstrap: unparsable CRL in the CA bundle: %w", perr) + } + logger.WithError(perr).Warn("Failed to parse CRL") + continue + } + crls = append(crls, crl) + } + } + return issuers, crls, nil +} + +// crlToleranceFromEnv reads CIC_CRL_MAX_STALENESS, the grace after a CRL's NextUpdate. +// Unset or empty means no grace; a value that is not a non-negative duration is an error. +func crlToleranceFromEnv() (time.Duration, error) { + v := strings.TrimSpace(os.Getenv("CIC_CRL_MAX_STALENESS")) + if v == "" { + return 0, nil + } + d, err := time.ParseDuration(v) + if err != nil || d < 0 { + return 0, fmt.Errorf("invalid CIC_CRL_MAX_STALENESS %q (want a non-negative duration such as \"30m\")", v) + } + return d, nil +} + +// crlIssuerPolicy is the operator's explicit declaration of which issuers must have a CRL. +// Trust is declared, not assumed: in prod the declaration is mandatory, and "no issuer +// requires a CRL" has to be written down as such (none). +type crlIssuerPolicy struct { + none bool // explicitly: no issuer requires a CRL + all bool // every CA certificate of the bundle requires a CRL + fingerprints map[string]bool // sha256 (lower-case hex) of the DER of each required issuer certificate +} + +// crlIssuerPolicyFromEnv reads CIC_CRL_REQUIRED_ISSUERS: "none", "all", or a comma-separated +// list of CA certificate SHA-256 fingerprints (hex, an optional "sha256:" prefix, colons +// allowed). Unset or empty is an error in prod: the policy must be declared. +func crlIssuerPolicyFromEnv() (crlIssuerPolicy, error) { + v := strings.TrimSpace(os.Getenv("CIC_CRL_REQUIRED_ISSUERS")) + switch strings.ToLower(v) { + case "": + return crlIssuerPolicy{}, fmt.Errorf("CIC_CRL_REQUIRED_ISSUERS is not set: declare which issuers require a CRL " + + `("none", "all", or a comma-separated list of CA certificate sha256 fingerprints)`) + case "none": + return crlIssuerPolicy{none: true}, nil + case "all": + return crlIssuerPolicy{all: true}, nil + } + p := crlIssuerPolicy{fingerprints: map[string]bool{}} + for _, raw := range strings.Split(v, ",") { + fp := strings.ToLower(strings.TrimSpace(raw)) + fp = strings.ReplaceAll(strings.TrimPrefix(fp, "sha256:"), ":", "") + if len(fp) != 64 || strings.Trim(fp, "0123456789abcdef") != "" { + return crlIssuerPolicy{}, fmt.Errorf("invalid CIC_CRL_REQUIRED_ISSUERS entry %q (want a 64-digit hex sha256 fingerprint, \"none\" or \"all\")", raw) + } + p.fingerprints[fp] = true + } + return p, nil +} + +func certFingerprint(c *x509.Certificate) string { + sum := sha256.Sum256(c.Raw) + return hex.EncodeToString(sum[:]) +} + +// enforceCRLIssuerPolicy checks the declared requirement against the CRLs that were accepted +// (authenticated and fresh): every required issuer needs one CRL issued by that very +// certificate. A required issuer without one (missing) is an error, and so is a declared +// fingerprint that matches no CA of the bundle (a typo must not silently drop a requirement). +// An empty but valid, fresh CRL satisfies the requirement. +func enforceCRLIssuerPolicy(p crlIssuerPolicy, caCerts []*x509.Certificate, accepted []*x509.RevocationList) error { + if p.none { + return nil + } + matched := map[string]bool{} + for _, ca := range caCerts { + fp := certFingerprint(ca) + if !p.all && !p.fingerprints[fp] { + continue + } + matched[fp] = true + covered := false + for _, crl := range accepted { + if bytes.Equal(crl.RawIssuer, ca.RawSubject) && crl.CheckSignatureFrom(ca) == nil { + covered = true + break + } + } + if !covered { + return fmt.Errorf("pki bootstrap: issuer %s (sha256:%s) requires a CRL, but the bundle has no valid, fresh CRL issued by it", ca.Subject, fp) + } + } + for fp := range p.fingerprints { + if !matched[fp] { + return fmt.Errorf("pki bootstrap: CIC_CRL_REQUIRED_ISSUERS names sha256:%s, which is no CA certificate of the bundle", fp) + } + } + if p.all && len(matched) == 0 { + return fmt.Errorf("pki bootstrap: CIC_CRL_REQUIRED_ISSUERS=all but the bundle contains no CA certificate") + } + return nil +} diff --git a/cmd/relay/pki_crl_test.go b/cmd/relay/pki_crl_test.go new file mode 100644 index 0000000..2645fe3 --- /dev/null +++ b/cmd/relay/pki_crl_test.go @@ -0,0 +1,341 @@ +package main + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "os" + "path/filepath" + "strings" + "testing" + "testing/fstest" + "time" + + "centralrelay/core/cabinet" + logrustest "github.com/sirupsen/logrus/hooks/test" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// crlTestPKI is a root CA with one code-signing leaf, enough to issue and verify CRLs. +type crlTestPKI struct { + rootCert *x509.Certificate + rootKey *ecdsa.PrivateKey + leaf *x509.Certificate +} + +func newCA(t *testing.T, cn string) (*x509.Certificate, *ecdsa.PrivateKey) { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: cn}, + NotBefore: time.Now().Add(-48 * time.Hour), + NotAfter: time.Now().Add(48 * time.Hour), + IsCA: true, + BasicConstraintsValid: true, + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + require.NoError(t, err) + cert, err := x509.ParseCertificate(der) + require.NoError(t, err) + return cert, key +} + +func newCRLTestPKI(t *testing.T) *crlTestPKI { + t.Helper() + root, rootKey := newCA(t, "CRL Test Root") + leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(4242), + Subject: pkix.Name{CommonName: "CRL Test Leaf"}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(24 * time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning}, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, root, &leafKey.PublicKey, rootKey) + require.NoError(t, err) + leaf, err := x509.ParseCertificate(der) + require.NoError(t, err) + return &crlTestPKI{rootCert: root, rootKey: rootKey, leaf: leaf} +} + +func certPEM(c *x509.Certificate) []byte { + return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Raw}) +} + +// crlPEM issues a CRL revoking the leaf, signed by signer (cert + key). +func (p *crlTestPKI) crlPEM(t *testing.T, signer *x509.Certificate, key *ecdsa.PrivateKey, nextUpdate time.Time) []byte { + t.Helper() + der, err := x509.CreateRevocationList(rand.Reader, &x509.RevocationList{ + Number: big.NewInt(1), + ThisUpdate: time.Now().Add(-3 * time.Hour), + NextUpdate: nextUpdate, + RevokedCertificateEntries: []x509.RevocationListEntry{{SerialNumber: p.leaf.SerialNumber, RevocationTime: time.Now().Add(-2 * time.Hour)}}, + }, signer, key) + require.NoError(t, err) + return pem.EncodeToMemory(&pem.Block{Type: "X509 CRL", Bytes: der}) +} + +// forgedCRLPEM is a CRL with the real root's name but signed by an attacker's key. +func (p *crlTestPKI) forgedCRLPEM(t *testing.T) []byte { + t.Helper() + attackerKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + // Same subject as the real root, different key: the issuer name matches, the signature cannot. + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(666), Subject: p.rootCert.Subject, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &attackerKey.PublicKey, attackerKey) + require.NoError(t, err) + attacker, err := x509.ParseCertificate(der) + require.NoError(t, err) + return p.crlPEM(t, attacker, attackerKey, time.Now().Add(24*time.Hour)) +} + +func writeBundle(t *testing.T, parts ...[]byte) string { + t.Helper() + var all []byte + for _, part := range parts { + all = append(all, part...) + } + path := filepath.Join(t.TempDir(), "bundle.pem") + require.NoError(t, os.WriteFile(path, all, 0600)) + t.Setenv("CIC_PLATFORM_CA_BUNDLE", path) + // The issuer policy is mandatory in prod; tests that are not about it declare "none". + t.Setenv("CIC_CRL_REQUIRED_ISSUERS", "none") + return path +} + +func verifyLeaf(p *crlTestPKI, assets *PKIAssets) error { + _, err := cabinet.VerifyCertificateChain(p.leaf, cabinet.VerifyOptions{ + Roots: assets.Roots, Intermediates: assets.Intermediates, CRLs: assets.CRLs, CRLFreshness: assets.CRLFreshness, + KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning}, + }) + return err +} + +// Acceptance 1: a CRL signed by a different key is rejected at load; its entries are not used. +func TestBootstrapPKI_Prod_CRL_ForeignKeySignature_Error(t *testing.T) { + p := newCRLTestPKI(t) + writeBundle(t, certPEM(p.rootCert), p.forgedCRLPEM(t)) + _, err := bootstrapPKI(TrustModeProd, embeddedFS, newDiscardLogger()) + require.Error(t, err) + assert.Contains(t, err.Error(), "signature does not verify") +} + +func TestLoadPKIAssets_Dev_CRL_ForeignKeySignature_NotUsed(t *testing.T) { + p := newCRLTestPKI(t) + fsys := fstest.MapFS{ + "pki/root.pem": {Data: certPEM(p.rootCert)}, + "pki/crl.pem": {Data: p.forgedCRLPEM(t)}, + } + assets, err := loadPKIAssets(fsys, "pki", newDiscardLogger()) + require.NoError(t, err, "dev stays lenient: the forged CRL is dropped, start-up continues") + assert.Empty(t, assets.CRLs, "the entries of a CRL with a bad signature must not be used") + assert.NoError(t, verifyLeaf(p, assets), "the forged CRL must not be able to revoke the leaf") +} + +// A CRL whose issuer is not in the trust store cannot be authenticated either. +func TestBootstrapPKI_Prod_CRL_UnknownIssuer_Error(t *testing.T) { + p := newCRLTestPKI(t) + otherCA, otherKey := newCA(t, "A Different Root") // not in the bundle, and a different name + writeBundle(t, certPEM(p.rootCert), p.crlPEM(t, otherCA, otherKey, time.Now().Add(24*time.Hour))) + _, err := bootstrapPKI(TrustModeProd, embeddedFS, newDiscardLogger()) + require.Error(t, err) + assert.Contains(t, err.Error(), "no issuer certificate") +} + +// Acceptance 2: an expired CRL in prod is an error; an explicit tolerance can allow it. +func TestBootstrapPKI_Prod_CRL_Stale_Error(t *testing.T) { + p := newCRLTestPKI(t) + writeBundle(t, certPEM(p.rootCert), p.crlPEM(t, p.rootCert, p.rootKey, time.Now().Add(-2*time.Hour))) + + t.Setenv("CIC_CRL_MAX_STALENESS", "") + _, err := bootstrapPKI(TrustModeProd, embeddedFS, newDiscardLogger()) + require.Error(t, err) + assert.Contains(t, err.Error(), "stale") + + t.Setenv("CIC_CRL_MAX_STALENESS", "3h") + assets, err := bootstrapPKI(TrustModeProd, embeddedFS, newDiscardLogger()) + require.NoError(t, err, "a configured tolerance covers a CRL 2h past NextUpdate") + assert.Len(t, assets.CRLs, 1) +} + +func TestBootstrapPKI_Prod_InvalidTolerance_Error(t *testing.T) { + p := newCRLTestPKI(t) + writeBundle(t, certPEM(p.rootCert)) + for _, bad := range []string{"abc", "-1h"} { + t.Setenv("CIC_CRL_MAX_STALENESS", bad) + _, err := bootstrapPKI(TrustModeProd, embeddedFS, newDiscardLogger()) + require.Error(t, err, "value %q", bad) + assert.Contains(t, err.Error(), "CIC_CRL_MAX_STALENESS") + } +} + +// Acceptance 3: an unparsable CRL in prod is a start-up error, not a WARN. +func TestBootstrapPKI_Prod_CRL_Unparsable_Error(t *testing.T) { + p := newCRLTestPKI(t) + writeBundle(t, certPEM(p.rootCert), []byte("-----BEGIN X509 CRL-----\nYWJjZGVmZw==\n-----END X509 CRL-----\n")) + _, err := bootstrapPKI(TrustModeProd, embeddedFS, newDiscardLogger()) + require.Error(t, err) + assert.Contains(t, err.Error(), "unparsable CRL") +} + +// Acceptance 4: a revoked certificate stays rejected after a restart with the same bundle. +func TestBootstrapPKI_Prod_RevokedLeafStaysRejectedAfterRestart(t *testing.T) { + p := newCRLTestPKI(t) + writeBundle(t, certPEM(p.rootCert), p.crlPEM(t, p.rootCert, p.rootKey, time.Now().Add(24*time.Hour))) + + for _, boot := range []string{"first start", "restart"} { + assets, err := bootstrapPKI(TrustModeProd, embeddedFS, newDiscardLogger()) + require.NoError(t, err, boot) + require.Len(t, assets.CRLs, 1, boot) + err = verifyLeaf(p, assets) + require.Error(t, err, "%s: the revoked leaf must be rejected", boot) + assert.Contains(t, err.Error(), "revoked", boot) + } +} + +// Without a CRL, prod still starts but says so; the empty pin set is stated too. +func TestBootstrapPKI_Prod_NoCRL_NoPins_AreVisible(t *testing.T) { + p := newCRLTestPKI(t) + writeBundle(t, certPEM(p.rootCert)) + logger, hook := logrustest.NewNullLogger() + assets, err := bootstrapPKI(TrustModeProd, embeddedFS, logger) + require.NoError(t, err) + assert.Empty(t, assets.CRLs) + + var msgs []string + for _, e := range hook.AllEntries() { + msgs = append(msgs, e.Message) + } + assert.Contains(t, msgs, "Revocation checking is inactive: the CA bundle contains no CRL") + assert.Contains(t, msgs, "SPKI pinning is not configured: the pin set is empty") +} + +func TestCrlToleranceFromEnv(t *testing.T) { + t.Setenv("CIC_CRL_MAX_STALENESS", "") + d, err := crlToleranceFromEnv() + require.NoError(t, err) + assert.Zero(t, d) + + t.Setenv("CIC_CRL_MAX_STALENESS", " 30m ") + d, err = crlToleranceFromEnv() + require.NoError(t, err) + assert.Equal(t, 30*time.Minute, d) +} + +// --- explicit issuer policy (CIC_CRL_REQUIRED_ISSUERS) --- + +// emptyCRLPEM is a valid CRL that revokes nothing. +func emptyCRLPEM(t *testing.T, signer *x509.Certificate, key *ecdsa.PrivateKey, nextUpdate time.Time) []byte { + t.Helper() + der, err := x509.CreateRevocationList(rand.Reader, &x509.RevocationList{ + Number: big.NewInt(1), ThisUpdate: time.Now().Add(-time.Hour), NextUpdate: nextUpdate, + }, signer, key) + require.NoError(t, err) + return pem.EncodeToMemory(&pem.Block{Type: "X509 CRL", Bytes: der}) +} + +// In prod the policy must be declared: unset is a start-up error, never a silent "no CRL needed". +func TestBootstrapPKI_Prod_IssuerPolicyMustBeDeclared(t *testing.T) { + p := newCRLTestPKI(t) + writeBundle(t, certPEM(p.rootCert)) + t.Setenv("CIC_CRL_REQUIRED_ISSUERS", "") + _, err := bootstrapPKI(TrustModeProd, embeddedFS, newDiscardLogger()) + require.Error(t, err) + assert.Contains(t, err.Error(), "CIC_CRL_REQUIRED_ISSUERS") +} + +func TestBootstrapPKI_Prod_IssuerPolicy_Table(t *testing.T) { + future := time.Now().Add(24 * time.Hour) + past := time.Now().Add(-2 * time.Hour) + + type tc struct { + name string + policy func(p *crlTestPKI) string + crl func(t *testing.T, p *crlTestPKI) []byte // nil: no CRL in the bundle + wantErr string // empty: ACCEPT + } + byFingerprint := func(p *crlTestPKI) string { return "sha256:" + certFingerprint(p.rootCert) } + all := func(*crlTestPKI) string { return "all" } + valid := func(t *testing.T, p *crlTestPKI) []byte { return p.crlPEM(t, p.rootCert, p.rootKey, future) } + + cases := []tc{ + {"required, valid and fresh: accept", byFingerprint, valid, ""}, + {"required (all), valid and fresh: accept", all, valid, ""}, + {"required, valid but empty: accept", byFingerprint, + func(t *testing.T, p *crlTestPKI) []byte { return emptyCRLPEM(t, p.rootCert, p.rootKey, future) }, ""}, + {"required, missing: deny", byFingerprint, nil, "requires a CRL"}, + {"required (all), missing: deny", all, nil, "requires a CRL"}, + {"required, expired: deny", byFingerprint, + func(t *testing.T, p *crlTestPKI) []byte { return p.crlPEM(t, p.rootCert, p.rootKey, past) }, "stale"}, + {"required, bad signature: deny", byFingerprint, + func(t *testing.T, p *crlTestPKI) []byte { return p.forgedCRLPEM(t) }, "signature does not verify"}, + {"required, CRL from the wrong issuer: deny", byFingerprint, + func(t *testing.T, p *crlTestPKI) []byte { + other, otherKey := newCA(t, "A Different Root") + return p.crlPEM(t, other, otherKey, future) + }, "no issuer certificate"}, + {"declared fingerprint matches no CA of the bundle: deny", + func(*crlTestPKI) string { return "sha256:" + strings.Repeat("ab", 32) }, valid, "no CA certificate of the bundle"}, + {"malformed fingerprint: deny", func(*crlTestPKI) string { return "sha256:zz" }, valid, "invalid CIC_CRL_REQUIRED_ISSUERS"}, + {"none, missing CRL: accept (explicit)", func(*crlTestPKI) string { return "none" }, nil, ""}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + p := newCRLTestPKI(t) + parts := [][]byte{certPEM(p.rootCert)} + if c.crl != nil { + parts = append(parts, c.crl(t, p)) + } + writeBundle(t, parts...) + t.Setenv("CIC_CRL_REQUIRED_ISSUERS", c.policy(p)) + _, err := bootstrapPKI(TrustModeProd, embeddedFS, newDiscardLogger()) + if c.wantErr == "" { + require.NoError(t, err) + return + } + require.Error(t, err) + assert.Contains(t, err.Error(), c.wantErr) + }) + } +} + +// dev differs on purpose, and says so: it has no issuer policy, so a missing CRL is not an +// error there, whatever CIC_CRL_REQUIRED_ISSUERS says. +func TestLoadPKIAssets_Dev_IgnoresIssuerPolicy(t *testing.T) { + p := newCRLTestPKI(t) + t.Setenv("CIC_CRL_REQUIRED_ISSUERS", "all") + fsys := fstest.MapFS{"pki/root.pem": {Data: certPEM(p.rootCert)}} + assets, err := loadPKIAssets(fsys, "pki", newDiscardLogger()) + require.NoError(t, err) + assert.Empty(t, assets.CRLs) +} + +func TestCRLIssuerPolicyFromEnv_Forms(t *testing.T) { + fp := strings.Repeat("0f", 32) + for in, check := range map[string]func(crlIssuerPolicy) bool{ + "none": func(p crlIssuerPolicy) bool { return p.none }, + " ALL ": func(p crlIssuerPolicy) bool { return p.all }, + fp: func(p crlIssuerPolicy) bool { return p.fingerprints[fp] }, + "sha256:" + strings.ToUpper(fp): func(p crlIssuerPolicy) bool { return p.fingerprints[fp] }, + fp + ", " + strings.Repeat("a1", 32): func(p crlIssuerPolicy) bool { return len(p.fingerprints) == 2 }, + } { + t.Setenv("CIC_CRL_REQUIRED_ISSUERS", in) + p, err := crlIssuerPolicyFromEnv() + require.NoError(t, err, "value %q", in) + assert.True(t, check(p), "value %q", in) + } +} diff --git a/cmd/relay/shared_trust_context_test.go b/cmd/relay/shared_trust_context_test.go index 13db0bc..1727e5e 100644 --- a/cmd/relay/shared_trust_context_test.go +++ b/cmd/relay/shared_trust_context_test.go @@ -146,6 +146,7 @@ func TestProd_ModuleSignedOutsideOperatorBundle_RejectedOnBothPaths(t *testing.T bundle := filepath.Join(t.TempDir(), "bundle.pem") require.NoError(t, os.WriteFile(bundle, operatorRoot, 0o600)) t.Setenv("CIC_PLATFORM_CA_BUNDLE", bundle) + t.Setenv("CIC_CRL_REQUIRED_ISSUERS", "none") // the CRL issuer policy is mandatory in prod; not what is tested here newProdAssets := func() *PKIAssets { a, err := bootstrapPKI(TrustModeProd, embeddedFS, newDiscardLogger()) diff --git a/context/SYMBOLS.md b/context/SYMBOLS.md index 07c9707..eaf2d7a 100644 --- a/context/SYMBOLS.md +++ b/context/SYMBOLS.md @@ -24,6 +24,7 @@ _*This file is automatically generated. Do not edit manually.*_ ### Functions - `func CanonicalizeSetPayload` +- `func CheckCRLFresh` - `func ComputeChainHashV1` - `func CoreEcho` - `func IsConflict` @@ -34,6 +35,7 @@ _*This file is automatically generated. Do not edit manually.*_ - `func NewExecutionContext` - `func SetStripWasmModuleFunc` - `func ValidateSchema` +- `func VerifyCRLSignature` - `func VerifyCertificateChain` ### Types @@ -42,6 +44,7 @@ _*This file is automatically generated. Do not edit manually.*_ - `type APIError` - `type ActuationProof` - `type BaseBlock` +- `type CRLFreshness` - `type Cabinet` - `type CabinetOption` - `type CicWasmHost` diff --git a/core/cabinet/pki_crl_test.go b/core/cabinet/pki_crl_test.go new file mode 100644 index 0000000..d2f558c --- /dev/null +++ b/core/cabinet/pki_crl_test.go @@ -0,0 +1,208 @@ +package cabinet + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "math/big" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func crlCA(t *testing.T, cn string) (*x509.Certificate, *ecdsa.PrivateKey) { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: cn}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + require.NoError(t, err) + cert, err := x509.ParseCertificate(der) + require.NoError(t, err) + return cert, key +} + +func crlOf(t *testing.T, signer *x509.Certificate, key *ecdsa.PrivateKey, next time.Time) *x509.RevocationList { + t.Helper() + der, err := x509.CreateRevocationList(rand.Reader, &x509.RevocationList{ + Number: big.NewInt(1), ThisUpdate: next.Add(-time.Hour), NextUpdate: next, + }, signer, key) + require.NoError(t, err) + crl, err := x509.ParseRevocationList(der) + require.NoError(t, err) + return crl +} + +func TestVerifyCRLSignature(t *testing.T) { + root, rootKey := crlCA(t, "Root") + crl := crlOf(t, root, rootKey, time.Now().Add(time.Hour)) + + assert.NoError(t, VerifyCRLSignature(crl, []*x509.Certificate{root})) + + // Same name, different key: the issuer matches by name, the signature must not verify. + impostor, impostorKey := crlCA(t, "Root") + forged := crlOf(t, impostor, impostorKey, time.Now().Add(time.Hour)) + err := VerifyCRLSignature(forged, []*x509.Certificate{root}) + require.Error(t, err) + assert.Contains(t, err.Error(), "signature does not verify") + + other, _ := crlCA(t, "Another CA") + err = VerifyCRLSignature(crl, []*x509.Certificate{other}) + require.Error(t, err) + assert.Contains(t, err.Error(), "no issuer certificate") + + assert.Error(t, VerifyCRLSignature(crl, nil)) +} + +func TestCheckCRLFresh(t *testing.T) { + root, rootKey := crlCA(t, "Root") + now := time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC) + clock := func() time.Time { return now } + + fresh := crlOf(t, root, rootKey, now.Add(time.Minute)) + stale := crlOf(t, root, rootKey, now.Add(-time.Minute)) + + assert.NoError(t, CheckCRLFresh(fresh, &CRLFreshness{Now: clock})) + err := CheckCRLFresh(stale, &CRLFreshness{Now: clock}) + require.Error(t, err) + assert.Contains(t, err.Error(), "stale") + + assert.NoError(t, CheckCRLFresh(stale, &CRLFreshness{Now: clock, Tolerance: 2 * time.Minute}), "tolerance covers it") + assert.NoError(t, CheckCRLFresh(stale, nil), "no rule, no check") + + noNext := &x509.RevocationList{Issuer: pkix.Name{CommonName: "Root"}, ThisUpdate: now.Add(-time.Hour)} + err = CheckCRLFresh(noNext, &CRLFreshness{Now: clock}) + require.Error(t, err, "a CRL without NextUpdate cannot prove it is current") + assert.Contains(t, err.Error(), "no NextUpdate") +} + +// A long-running relay verifies certificates long after load: a CRL that went stale since +// then must stop being trusted when a freshness rule is set. +func TestVerifyCertificateChain_StaleCRL(t *testing.T) { + root, rootKey := crlCA(t, "Root") + leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + leafTmpl := &x509.Certificate{ + SerialNumber: big.NewInt(7), Subject: pkix.Name{CommonName: "Leaf"}, + NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning}, + } + der, err := x509.CreateCertificate(rand.Reader, leafTmpl, root, &leafKey.PublicKey, rootKey) + require.NoError(t, err) + leaf, err := x509.ParseCertificate(der) + require.NoError(t, err) + pool := x509.NewCertPool() + pool.AddCert(root) + + crl := crlOf(t, root, rootKey, time.Now().Add(time.Hour)) // fresh now + opts := VerifyOptions{Roots: pool, CRLs: []*x509.RevocationList{crl}, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning}} + + opts.CRLFreshness = &CRLFreshness{} + _, err = VerifyCertificateChain(leaf, opts) + require.NoError(t, err, "a fresh CRL is accepted") + + later := time.Now().Add(2 * time.Hour) + opts.CRLFreshness = &CRLFreshness{Now: func() time.Time { return later }} + _, err = VerifyCertificateChain(leaf, opts) + require.Error(t, err, "the same CRL, two hours later, is stale") + assert.Contains(t, err.Error(), "stale") + + opts.CRLFreshness = nil + _, err = VerifyCertificateChain(leaf, opts) + assert.NoError(t, err, "no freshness rule (dev) keeps the old behaviour") +} + +// F1: a CRL must be bound to the certificate that actually issued the chain, not to a name. +// An impostor CA with the same name but another key must not be able to revoke (or, by being +// stale, break) a certificate of the real CA. +func TestCheckRevocation_BindsToTheChainIssuer(t *testing.T) { + root, rootKey := crlCA(t, "Shared Name CA") + impostor, impostorKey := crlCA(t, "Shared Name CA") // same name, different key + + leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + leafTmpl := &x509.Certificate{ + SerialNumber: big.NewInt(77), Subject: pkix.Name{CommonName: "Leaf"}, + NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning}, + } + der, err := x509.CreateCertificate(rand.Reader, leafTmpl, root, &leafKey.PublicKey, rootKey) + require.NoError(t, err) + leaf, err := x509.ParseCertificate(der) + require.NoError(t, err) + pool := x509.NewCertPool() + pool.AddCert(root) + + revoking := func(signer *x509.Certificate, key *ecdsa.PrivateKey, next time.Time) *x509.RevocationList { + d, err := x509.CreateRevocationList(rand.Reader, &x509.RevocationList{ + Number: big.NewInt(1), ThisUpdate: next.Add(-time.Hour), NextUpdate: next, + RevokedCertificateEntries: []x509.RevocationListEntry{{SerialNumber: leaf.SerialNumber, RevocationTime: time.Now()}}, + }, signer, key) + require.NoError(t, err) + crl, err := x509.ParseRevocationList(d) + require.NoError(t, err) + return crl + } + verify := func(crls ...*x509.RevocationList) error { + _, err := VerifyCertificateChain(leaf, VerifyOptions{ + Roots: pool, CRLs: crls, CRLFreshness: &CRLFreshness{}, + KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning}, + }) + return err + } + future := time.Now().Add(time.Hour) + + // The leaf is chain[0] and its issuer chain[1]: the root. The root itself is the anchor. + assert.NoError(t, verify(revoking(impostor, impostorKey, future)), + "a CRL from a same-name CA with another key must not revoke the leaf") + assert.NoError(t, verify(revoking(impostor, impostorKey, time.Now().Add(-2*time.Hour))), + "nor may its staleness break verification: it is not this issuer's CRL at all") + err = verify(revoking(root, rootKey, future)) + require.Error(t, err, "the real issuer's CRL still revokes") + assert.Contains(t, err.Error(), "revoked") +} + +// F2: temporal validity is checked in full, not only NextUpdate. +func TestCheckCRLFresh_FullInterval(t *testing.T) { + now := time.Date(2026, 11, 15, 12, 0, 0, 0, time.UTC) + f := &CRLFreshness{Now: func() time.Time { return now }} + crl := func(this, next time.Time) *x509.RevocationList { + return &x509.RevocationList{Issuer: pkix.Name{CommonName: "CA"}, ThisUpdate: this, NextUpdate: next} + } + h := time.Hour + + assert.NoError(t, CheckCRLFresh(crl(now.Add(-h), now.Add(h)), f), "a current CRL is accepted") + + err := CheckCRLFresh(crl(now.Add(h), now.Add(2*h)), f) + require.Error(t, err, "a CRL that starts in the future is not valid yet") + assert.Contains(t, err.Error(), "not yet valid") + + err = CheckCRLFresh(crl(now, now), f) + require.Error(t, err, "NextUpdate equal to ThisUpdate is not a sensible interval") + assert.Contains(t, err.Error(), "inconsistent interval") + err = CheckCRLFresh(crl(now.Add(-h), now.Add(-2*h)), f) + require.Error(t, err, "NextUpdate before ThisUpdate is not a sensible interval") + assert.Contains(t, err.Error(), "inconsistent interval") + + err = CheckCRLFresh(crl(time.Time{}, now.Add(h)), f) + require.Error(t, err, "a CRL without ThisUpdate cannot prove its validity") + assert.Contains(t, err.Error(), "no ThisUpdate") + + err = CheckCRLFresh(crl(now.Add(-3*h), now.Add(-h)), f) + require.Error(t, err, "an expired CRL is rejected") + assert.Contains(t, err.Error(), "stale") + + // The tolerance is the one explicit allowance and is symmetric. + tol := &CRLFreshness{Now: f.Now, Tolerance: 2 * h} + assert.NoError(t, CheckCRLFresh(crl(now.Add(-3*h), now.Add(-h)), tol), "grace after NextUpdate") + assert.NoError(t, CheckCRLFresh(crl(now.Add(h), now.Add(3*h)), tol), "clock skew before ThisUpdate") + assert.Error(t, CheckCRLFresh(crl(now.Add(3*h), now.Add(4*h)), tol), "skew beyond the tolerance is still rejected") +} diff --git a/core/cabinet/pki_verify.go b/core/cabinet/pki_verify.go index 2ee0b60..9f965fb 100644 --- a/core/cabinet/pki_verify.go +++ b/core/cabinet/pki_verify.go @@ -1,10 +1,12 @@ package cabinet import ( + "bytes" "crypto/sha256" "crypto/x509" "encoding/base64" "fmt" + "time" ) // VerifyOptions encapsulates the parameters for certificate chain verification. @@ -15,22 +17,97 @@ type VerifyOptions struct { KeyUsages []x509.ExtKeyUsage CRLs []*x509.RevocationList // Added for M3 revocation check PinnedSPKIs map[string]bool // Added for M3 SPKI pinning. Map of base64-encoded SHA-256 SPKI hashes. + + // CRLFreshness, when set, rejects a verification that would rely on a CRL past its + // NextUpdate (plus tolerance). Nil leaves freshness unchecked (the dev behaviour). + CRLFreshness *CRLFreshness +} + +// CRLFreshness is the freshness rule for CRLs. A CRL without a NextUpdate cannot prove +// it is current and counts as stale. +type CRLFreshness struct { + Now func() time.Time // nil means time.Now + Tolerance time.Duration // grace after NextUpdate; zero means none +} + +// CheckCRLFresh returns an error unless crl is currently valid: it must state a sensible +// interval (a ThisUpdate, and a NextUpdate after it), must not start in the future, and must +// not be past NextUpdate. Tolerance is the one explicit allowance, applied symmetrically: a +// grace after NextUpdate and the clock skew accepted before ThisUpdate. Zero means none. +func CheckCRLFresh(crl *x509.RevocationList, f *CRLFreshness) error { + if f == nil { + return nil + } + now := time.Now + if f.Now != nil { + now = f.Now + } + if crl.ThisUpdate.IsZero() { + return fmt.Errorf("CRL of %s has no ThisUpdate, so its validity cannot be established", crl.Issuer) + } + if crl.NextUpdate.IsZero() { + return fmt.Errorf("CRL of %s has no NextUpdate, so its freshness cannot be established", crl.Issuer) + } + if !crl.NextUpdate.After(crl.ThisUpdate) { + return fmt.Errorf("CRL of %s has an inconsistent interval: NextUpdate %s is not after ThisUpdate %s", + crl.Issuer, crl.NextUpdate.UTC().Format(time.RFC3339), crl.ThisUpdate.UTC().Format(time.RFC3339)) + } + if now().Add(f.Tolerance).Before(crl.ThisUpdate) { + return fmt.Errorf("CRL of %s is not yet valid: ThisUpdate %s is in the future (tolerance %s)", + crl.Issuer, crl.ThisUpdate.UTC().Format(time.RFC3339), f.Tolerance) + } + if now().After(crl.NextUpdate.Add(f.Tolerance)) { + return fmt.Errorf("CRL of %s is stale: NextUpdate %s, tolerance %s", + crl.Issuer, crl.NextUpdate.UTC().Format(time.RFC3339), f.Tolerance) + } + return nil +} + +// VerifyCRLSignature checks that crl is signed by one of the given issuer certificates +// (matched by the CRL's issuer name). A CRL whose issuer is not among them, or whose +// signature does not verify against the issuer's key, must not be used: its entries are +// unauthenticated, and a forged one could both revoke and hide revocations. +func VerifyCRLSignature(crl *x509.RevocationList, issuers []*x509.Certificate) error { + var lastErr error + for _, issuer := range issuers { + if !bytes.Equal(crl.RawIssuer, issuer.RawSubject) { + continue + } + if err := crl.CheckSignatureFrom(issuer); err != nil { + lastErr = err + continue + } + return nil + } + if lastErr != nil { + return fmt.Errorf("CRL of %s: signature does not verify against the issuer certificate: %w", crl.Issuer, lastErr) + } + return fmt.Errorf("CRL of %s: no issuer certificate for it in the trust store", crl.Issuer) } // checkRevocation checks if any certificate in the provided chains is in the revocation list. -func checkRevocation(chains [][]*x509.Certificate, crls []*x509.RevocationList) error { +// With a freshness rule, a CRL that applies to a certificate of the chain and is stale is an error. +func checkRevocation(chains [][]*x509.Certificate, crls []*x509.RevocationList, fresh *CRLFreshness) error { if len(crls) == 0 { return nil // No CRLs to check against } for _, chain := range chains { - for _, cert := range chain { + // chain is leaf-first and verified: chain[i+1] is the certificate that actually issued + // chain[i]. The last element is the trust anchor, which has no issuer to be revoked by. + for i := 0; i+1 < len(chain); i++ { + cert, issuer := chain[i], chain[i+1] for _, crl := range crls { - // Only check revocation entries from CRLs issued by this certificate's issuer. - // Comparing issuer DN prevents a CRL from one CA from revoking certs of another. - if crl.Issuer.String() != cert.Issuer.String() { + // A CRL counts for cert only if it was issued by cert's real issuer: same name + // AND a signature that verifies against that very certificate's key. Matching the + // name alone would let a CA that merely shares a name (with another key) speak + // for it, both to revoke and to vouch. + if !bytes.Equal(crl.RawIssuer, issuer.RawSubject) || crl.CheckSignatureFrom(issuer) != nil { continue } + if err := CheckCRLFresh(crl, fresh); err != nil { + return err + } for _, revokedCert := range crl.RevokedCertificateEntries { if cert.SerialNumber.Cmp(revokedCert.SerialNumber) == 0 { return fmt.Errorf("certificate with serial number %s is revoked", cert.SerialNumber) @@ -88,7 +165,7 @@ func VerifyCertificateChain(cert *x509.Certificate, opts VerifyOptions) ([][]*x5 } // 2. Check for revocation - if err := checkRevocation(chains, opts.CRLs); err != nil { + if err := checkRevocation(chains, opts.CRLs, opts.CRLFreshness); err != nil { return nil, fmt.Errorf("revocation check failed: %w", err) } diff --git a/docs/en/pipeline/relay-container.md b/docs/en/pipeline/relay-container.md index 66a6e58..2b1b15a 100644 --- a/docs/en/pipeline/relay-container.md +++ b/docs/en/pipeline/relay-container.md @@ -88,6 +88,8 @@ The `relay` service reads these from the environment (a `.env` file next to | `VAULT_CACERT` | — | e.g. `/run/secrets/relay/vault-ca.crt` | | `CIC_VAULT_MOUNT` | `transit` | Vault transit mount | | `CIC_VAULT_KEY` | — | Signing key; the token must be *authorised for this key* | +| `CIC_CRL_REQUIRED_ISSUERS` | — | **Required in `prod`**: which issuers must have a CRL. `none` (explicit: no issuer requires one, logged as a warning), `all` (every CA certificate of the bundle) or a comma-separated list of CA certificate SHA-256 fingerprints. Unset is a start-up error. A required issuer needs a CRL in `CIC_PLATFORM_CA_BUNDLE` (as `X509 CRL` blocks) that is signed by that very certificate and currently valid; a valid but empty CRL satisfies it. A missing, expired, badly signed or wrong-issuer CRL, or a fingerprint matching no CA of the bundle, is a start-up error. `dev` ignores it | +| `CIC_CRL_MAX_STALENESS` | `0` | Explicit tolerance for CRL timing in `prod`: grace after `NextUpdate` and clock skew accepted before `ThisUpdate` (a Go duration such as `30m`; invalid or negative is a start-up error) | | `CIC_TRUST_MODE` | — | PKI trust mode (`dev` or `prod`); **required**, no default, an empty value is a start-up error | | `CIC_EVIDENCE_REQUIRED` | `false` | `true` or `false` (anything else is a start-up error). `true`: when the ProofTrace of a `/set` run was not persisted (recording failed, or no recorder is configured), the call returns **503 `evidence_required`**. **The workflow has already run:** the body says `execution_completed: true`, `proof.persisted: false` and carries the `chain_hash`. **Do not retry it automatically**: a retry executes the workflow again. Default: the call stays a success and `proof.persisted` reports the recording | diff --git a/docs/hu/pipeline/relay-container.md b/docs/hu/pipeline/relay-container.md index 4feff3e..4dd0cad 100644 --- a/docs/hu/pipeline/relay-container.md +++ b/docs/hu/pipeline/relay-container.md @@ -89,6 +89,8 @@ A `relay` szolgáltatás ezeket olvassa a környezetből (a `docker-compose.yml` | `VAULT_CACERT` | — | pl. `/run/secrets/relay/vault-ca.crt` | | `CIC_VAULT_MOUNT` | `transit` | Vault transit mount | | `CIC_VAULT_KEY` | — | Aláíró kulcs; a tokennek **erre a kulcsra** kell jogosultnak lennie | +| `CIC_CRL_REQUIRED_ISSUERS` | — | **`prod`-ban kötelező**: mely kibocsátóknak kell CRL-lel rendelkezniük. `none` (explicit: egy kibocsátó sem követel, figyelmeztetés), `all` (a bundle minden CA tanúsítványa) vagy CA-tanúsítvány SHA-256 ujjlenyomatok vesszős listája. Beállítatlan = indulási hiba. A követelt kibocsátóhoz a `CIC_PLATFORM_CA_BUNDLE`-ben (`X509 CRL` blokkként) kell egy pontosan tőle aláírt, jelenleg érvényes CRL; az érvényes, de üres CRL megfelel. Hiányzó, lejárt, hibás aláírású vagy idegen kibocsátótól származó CRL, illetve a bundle egyetlen CA-jára sem illeszkedő ujjlenyomat indulási hiba. A `dev` figyelmen kívül hagyja | +| `CIC_CRL_MAX_STALENESS` | `0` | Explicit tolerancia a CRL időzítésére `prod`-ban: türelmi idő a `NextUpdate` után és óraeltérés a `ThisUpdate` előtt (Go időtartam, pl. `30m`; érvénytelen vagy negatív érték indulási hiba) | | `CIC_TRUST_MODE` | — | PKI trust mód (`dev` vagy `prod`); **kötelező**, nincs alapértelmezés, üres érték indulási hiba | | `CIC_EVIDENCE_REQUIRED` | `false` | `true` vagy `false` (bármi más indulási hiba). `true`: ha egy `/set` futás ProofTrace-e nem rögzült (a rögzítés hibázott, vagy nincs recorder), a hívás **503 `evidence_required`**-et ad. **A workflow ekkor már lefutott:** a törzs `execution_completed: true`, `proof.persisted: false` és a `chain_hash` mezőt adja. **Ne próbáld újra automatikusan**: az újrapróbálás újra végrehajtja a workflow-t. Alapértelmezés: a hívás sikeres marad, a `proof.persisted` mutatja a rögzítést |