Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion MANIFEST.sha256
Original file line number Diff line number Diff line change
Expand Up @@ -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
26 changes: 22 additions & 4 deletions cmd/relay/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:<hex>"
CertChainHash string // sha256 of all loaded CA cert DER bytes concatenated, "sha256:<hex>"
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:<hex>"
CertChainHash string // sha256 of all loaded CA cert DER bytes concatenated, "sha256:<hex>"

// R3b (feature-011): the cic-flow provenance/entitlement anchors, delivered by
// their own detached-companion path — NOT embedded, so the relay binary's hash
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -597,14 +600,22 @@ 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(),
CRLs: []*x509.RevocationList{},
}
// 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.
Expand Down Expand Up @@ -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)
Expand All @@ -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))
}
Expand Down
39 changes: 38 additions & 1 deletion cmd/relay/pki_bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"strings"

"github.com/sirupsen/logrus"

"centralrelay/core/cabinet"
)

const (
Expand Down Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions cmd/relay/pki_bootstrap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions cmd/relay/pki_companion.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
176 changes: 176 additions & 0 deletions cmd/relay/pki_crl.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading