Skip to content

Commit 15b7442

Browse files
committed
fix(cozystack-controller): rebuild CA projection from validated blocks
The write-path guard validated the CA value as a certificate chain but then published a clone of the original input. pem.Decode silently skips bytes before the first PEM block and between blocks, and the private-key header guard only matches a "-----BEGIN ... PRIVATE KEY-----" line, so a raw DER or JWK private key placed ahead of or between real certificates passes both checks and is copied verbatim into the tenant-readable projection. Assemble the projection from the re-encoded certificate DER instead of cloning the input, so preamble and interstitial key material are structurally unreachable. The empty-value, wrong-type, non-parseable and trailing-byte rejections are unchanged. Signed-off-by: Aleksei Sviridkin <[email protected]>
1 parent 48ee0f2 commit 15b7442

2 files changed

Lines changed: 162 additions & 35 deletions

File tree

‎internal/controller/cacert/reconciler.go‎

Lines changed: 48 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -115,9 +115,11 @@ limitations under the License.
115115
// chart-side guard in cozy-lib.tls.caCertSecret
116116
// (packages/library/cozy-lib/templates/_tls.tpl), so both ends of the
117117
// contract reject the same inputs.
118-
// 2. Sanitize at write time. Exactly one whitelisted key is copied, under
119-
// the canonical name. The source Data map is never copied wholesale —
120-
// that is the precise bug this controller exists to prevent.
118+
// 2. Sanitize at write time. Exactly one whitelisted key is emitted, under
119+
// the canonical name, and its value is rebuilt from the certificate blocks
120+
// the guard parsed rather than copied from the source. The source Data map
121+
// is never copied wholesale — that is the precise bug this controller
122+
// exists to prevent.
121123
// 3. Tolerate asynchronous sources. An operator creates its CA Secret long
122124
// after the chart renders, and may populate it later still. "Not there
123125
// yet" is the normal startup state: a quiet, retried wait, never an error
@@ -1320,27 +1322,41 @@ func selectorsDigest(def *cozyv1alpha1.ApplicationDefinition) (string, error) {
13201322
}
13211323

13221324
// projectionData builds the projection payload and is the single write-path
1323-
// guard. It emits exactly one key — the canonical ca.crt — and refuses to
1324-
// emit anything that carries a PEM private-key header or is not a PEM
1325-
// certificate. Every byte written to a projection passes through here, on
1325+
// guard. It emits exactly one key — the canonical ca.crt — whose value is
1326+
// REBUILT from the certificate blocks it validated, never copied from the
1327+
// input. It refuses anything that carries a PEM private-key header or is not a
1328+
// PEM certificate. Every byte written to a projection passes through here, on
13261329
// both legs, on create and on update.
13271330
//
13281331
// The two checks run in this order deliberately. The key guard is the one whose
13291332
// failure is a security incident and it must own that verdict: a private key
13301333
// wrapped in certificate armour has to be refused AS key material, with the
13311334
// event that says so, not as a parse failure.
1335+
//
1336+
// Rebuilding the value from the parsed blocks — instead of cloning the input
1337+
// once it validates — is what makes the guard airtight, and it closes a real
1338+
// hole. The key guard above matches a PEM "-----BEGIN ... PRIVATE KEY-----"
1339+
// header; a RAW DER or JWK private key wears no such header, so it walks past.
1340+
// pem.Decode then SKIPS bytes before the first block and between blocks, so
1341+
// that key never reaches the certificate loop either. A projection cloned from
1342+
// the input would therefore hand the tenant a trust anchor with a private key
1343+
// tucked in front of, or between, the certificates. A projection assembled only
1344+
// from the re-encoded certificate DER cannot carry a byte the guard did not
1345+
// parse as a certificate.
13321346
func projectionData(value []byte) (map[string][]byte, error) {
13331347
if containsPrivateKey(string(value)) {
13341348
return nil, errPrivateKey
13351349
}
1336-
if err := assertCertificateChain(value); err != nil {
1350+
chain, err := certificateChainPEM(value)
1351+
if err != nil {
13371352
return nil, err
13381353
}
1339-
return map[string][]byte{caCertKey: bytes.Clone(value)}, nil
1354+
return map[string][]byte{caCertKey: chain}, nil
13401355
}
13411356

1342-
// assertCertificateChain reports whether value is a PEM sequence of nothing but
1343-
// certificates that x509 accepts.
1357+
// certificateChainPEM validates that value is a PEM sequence of nothing but
1358+
// certificates that x509 accepts, and returns those certificates re-encoded as
1359+
// a clean PEM chain — the exact bytes the projection publishes.
13441360
//
13451361
// A header match is not this check, and the difference is the guard's whole
13461362
// worth. "-----BEGIN CERTIFICATE-----" around a truncated DER prefix, around
@@ -1357,37 +1373,46 @@ func projectionData(value []byte) (map[string][]byte, error) {
13571373
// - nothing but PEM blocks left at the end, so a value cannot carry a
13581374
// certificate and then trail arbitrary bytes past the first match.
13591375
//
1360-
// One residue is worth naming rather than hiding: pem.Decode SKIPS text that
1361-
// precedes a block, so human-readable preamble between certificates (what
1362-
// `openssl x509 -text` emits) is tolerated here, exactly as it is by
1363-
// crypto/x509's own CertPool.AppendCertsFromPEM. That text cannot smuggle key
1364-
// material — projectionData refuses the whole value on a private-key header
1365-
// before this runs — and it cannot smuggle a certificate, because anything the
1366-
// tenant's verifier would load out of it is a block, and every block is checked.
1367-
func assertCertificateChain(value []byte) error {
1376+
// The returned chain is assembled from the PARSED certificate DER, not from the
1377+
// input. pem.Decode silently skips text before a block and between blocks — the
1378+
// human-readable preamble `openssl x509 -text` emits, but also a raw DER or JWK
1379+
// key that carries no PEM private-key header — so copying the input verbatim
1380+
// would republish those bytes to the tenant. Re-encoding only the certificates
1381+
// makes preamble and interstitial key material structurally unreachable; the
1382+
// trailing-byte rejection still keeps a value from parsing as a certificate and
1383+
// then trailing arbitrary bytes past the last block.
1384+
func certificateChainPEM(value []byte) ([]byte, error) {
13681385
// "At least one block" is enforced HERE and only here: an empty value is
13691386
// rejected up front, which is what guarantees the loop below runs at least
13701387
// once, and every iteration either returns an error or parses a certificate.
13711388
// A counter checked afterwards would be unreachable.
13721389
rest := bytes.TrimSpace(value)
13731390
if len(rest) == 0 {
1374-
return fmt.Errorf("%w: value is empty", errNotCertificate)
1391+
return nil, fmt.Errorf("%w: value is empty", errNotCertificate)
13751392
}
1393+
var chain []byte
13761394
for len(rest) > 0 {
13771395
var block *pem.Block
13781396
block, rest = pem.Decode(rest)
13791397
if block == nil {
1380-
return fmt.Errorf("%w: value carries %d bytes that are not a PEM block", errNotCertificate, len(rest))
1398+
return nil, fmt.Errorf("%w: value carries %d bytes that are not a PEM block", errNotCertificate, len(rest))
13811399
}
13821400
if block.Type != certificatePEMType {
1383-
return fmt.Errorf("%w: PEM block is of type %q, want %q", errNotCertificate, block.Type, certificatePEMType)
1401+
return nil, fmt.Errorf("%w: PEM block is of type %q, want %q", errNotCertificate, block.Type, certificatePEMType)
13841402
}
13851403
if _, err := x509.ParseCertificate(block.Bytes); err != nil {
1386-
return fmt.Errorf("%w: %v", errNotCertificate, err)
1404+
return nil, fmt.Errorf("%w: %v", errNotCertificate, err)
13871405
}
1406+
// Re-encode ONLY the parsed certificate DER: no PEM headers, no
1407+
// surrounding bytes, nothing the loop did not just verify is a
1408+
// certificate. This is the byte-for-byte content of the projection.
1409+
chain = append(chain, pem.EncodeToMemory(&pem.Block{
1410+
Type: certificatePEMType,
1411+
Bytes: block.Bytes,
1412+
})...)
13881413
rest = bytes.TrimSpace(rest)
13891414
}
1390-
return nil
1415+
return chain, nil
13911416
}
13921417

13931418
// refusalRetry returns how long to wait before re-examining a source whose value

‎internal/controller/cacert/reconciler_test.go‎

Lines changed: 114 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ limitations under the License.
1717
package cacert
1818

1919
import (
20+
"bytes"
2021
"context"
2122
"crypto/ecdsa"
2223
"crypto/elliptic"
@@ -87,7 +88,7 @@ const (
8788
//
8889
// They used to be certificate armour wrapped around a truncated DER prefix,
8990
// which the write-path guard accepted because it only matched the BEGIN line.
90-
// Now that the guard parses what it publishes (see assertCertificateChain), a
91+
// Now that the guard parses what it publishes (see certificateChainPEM), a
9192
// fixture has to be the thing it claims to be — and the fact that these two
9293
// constants had to change at all is the clearest statement of what the old
9394
// guard was worth.
@@ -133,6 +134,23 @@ func mustCertPEM(commonName string) string {
133134
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
134135
}
135136

137+
// mustPrivateKeyDER returns a RAW DER-encoded PKCS#8 private key, with no PEM
138+
// armour at all. It is the fixture for the smuggling cases: key material that
139+
// wears no "-----BEGIN ... PRIVATE KEY-----" header slips past the header guard,
140+
// and pem.Decode skips it as inter-block noise, so only a projection rebuilt
141+
// from the parsed certificates can keep it away from the tenant.
142+
func mustPrivateKeyDER() []byte {
143+
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
144+
if err != nil {
145+
panic("generate test private key: " + err.Error())
146+
}
147+
der, err := x509.MarshalPKCS8PrivateKey(key)
148+
if err != nil {
149+
panic("marshal test private key: " + err.Error())
150+
}
151+
return der
152+
}
153+
136154
// mustPublicKeyDER returns a DER-encoded public key, for the fixture that
137155
// checks a well-formed PEM block of the WRONG type is still refused.
138156
func mustPublicKeyDER() []byte {
@@ -2046,22 +2064,30 @@ func TestProjectionData_RefusesCertificateArmouredNonCertificate(t *testing.T) {
20462064
// TestProjectionData_AcceptsRealCertificates keeps the guard from failing closed
20472065
// on the values it exists to publish: a single CA, and the multi-certificate
20482066
// bundle an intermediate chain arrives as.
2067+
//
2068+
// The projection is the certificate blocks re-encoded, not the input echoed
2069+
// back. For a value that is already canonical PEM the two are byte-identical
2070+
// (want == in); a value with surrounding whitespace comes back as the bare
2071+
// blocks, because everything the guard did not parse as a certificate is
2072+
// dropped.
20492073
func TestProjectionData_AcceptsRealCertificates(t *testing.T) {
20502074
bundle := testCA + testCARot
2051-
for name, value := range map[string]string{
2052-
"one certificate": testCA,
2053-
"a chain of two": bundle,
2054-
"trailing whitespace": testCA + "\n\n \n",
2075+
for _, tc := range []struct {
2076+
name string
2077+
in string
2078+
want string
2079+
}{
2080+
{"one certificate", testCA, testCA},
2081+
{"a chain of two", bundle, bundle},
2082+
{"trailing whitespace", testCA + "\n\n \n", testCA},
20552083
} {
2056-
t.Run(name, func(t *testing.T) {
2057-
got, err := projectionData([]byte(value))
2084+
t.Run(tc.name, func(t *testing.T) {
2085+
got, err := projectionData([]byte(tc.in))
20582086
if err != nil {
2059-
t.Fatalf("projectionData(%s) = %v, want accepted", name, err)
2087+
t.Fatalf("projectionData(%s) = %v, want accepted", tc.name, err)
20602088
}
2061-
// The value is published verbatim: the guard validates, it never
2062-
// rewrites what the engine minted.
2063-
if string(got[caCertKey]) != value {
2064-
t.Errorf("projectionData must publish the value verbatim, got %q want %q", got[caCertKey], value)
2089+
if string(got[caCertKey]) != tc.want {
2090+
t.Errorf("projectionData(%s) published %q, want the validated blocks %q", tc.name, got[caCertKey], tc.want)
20652091
}
20662092
})
20672093
}
@@ -2089,6 +2115,82 @@ func TestProjectionData_KeyGuardWinsOverTheParse(t *testing.T) {
20892115
}
20902116
}
20912117

2118+
// TestProjectionData_StripsKeyMaterialSmuggledAroundBlocks is the write path's
2119+
// deepest guarantee: the projection is REBUILT from the certificate blocks it
2120+
// validated, never copied from the input.
2121+
//
2122+
// The header guard (containsPrivateKey) only sees "-----BEGIN ... PRIVATE
2123+
// KEY-----". A raw PKCS#8 DER key, or a JSON Web Key, carries no such header, so
2124+
// it walks past that guard. pem.Decode then skips it — text before the first
2125+
// block and between blocks is silently dropped by the decoder — so the
2126+
// certificate loop never inspects it either. A projection that cloned the input
2127+
// once it validated would therefore hand the tenant a trust anchor with a
2128+
// private key tucked in front of, or between, the certificates. Rebuilding from
2129+
// the parsed DER makes that byte structurally unreachable.
2130+
func TestProjectionData_StripsKeyMaterialSmuggledAroundBlocks(t *testing.T) {
2131+
derKey := mustPrivateKeyDER()
2132+
// A private JWK: text, no PEM header, sits before the certificate.
2133+
jwkKey := `{"kty":"EC","crv":"P-256","d":"c2VjcmV0LXByaXZhdGUta2V5LW1hdGVyaWFs"}`
2134+
2135+
concat := func(parts ...[]byte) []byte { return bytes.Join(parts, nil) }
2136+
for _, tc := range []struct {
2137+
name string
2138+
in []byte
2139+
want string
2140+
}{
2141+
{
2142+
// Raw DER key, newline, then a real certificate.
2143+
name: "leading DER key",
2144+
in: concat(derKey, []byte("\n"), []byte(testCA)),
2145+
want: testCA,
2146+
},
2147+
{
2148+
// A private JWK ahead of the certificate.
2149+
name: "leading JWK key",
2150+
in: []byte(jwkKey + "\n" + testCA),
2151+
want: testCA,
2152+
},
2153+
{
2154+
// Key bytes wedged BETWEEN two certificate blocks.
2155+
name: "interstitial DER key",
2156+
in: concat([]byte(testCA), derKey, []byte("\n"), []byte(testCARot)),
2157+
want: testCA + testCARot,
2158+
},
2159+
} {
2160+
t.Run(tc.name, func(t *testing.T) {
2161+
got, err := projectionData(tc.in)
2162+
if err != nil {
2163+
t.Fatalf("projectionData(%s) = %v, want the value accepted and sanitized", tc.name, err)
2164+
}
2165+
if string(got[caCertKey]) != tc.want {
2166+
t.Errorf("projectionData(%s) published %q, want only the validated blocks %q", tc.name, got[caCertKey], tc.want)
2167+
}
2168+
if bytes.Contains(got[caCertKey], derKey) {
2169+
t.Errorf("projectionData(%s) leaked raw DER private-key material into the tenant projection", tc.name)
2170+
}
2171+
})
2172+
}
2173+
}
2174+
2175+
// TestProjectionData_DropsHumanReadablePreamble pins that the text dump
2176+
// `openssl x509 -text` prints before each certificate — which pem.Decode
2177+
// tolerates — is not republished to the tenant. The projection carries the
2178+
// certificate blocks and nothing else.
2179+
func TestProjectionData_DropsHumanReadablePreamble(t *testing.T) {
2180+
preamble := "Certificate:\n Data:\n Version: 3 (0x2)\n"
2181+
in := preamble + testCA + preamble + testCARot
2182+
got, err := projectionData([]byte(in))
2183+
if err != nil {
2184+
t.Fatalf("projectionData(preamble+chain) = %v, want accepted", err)
2185+
}
2186+
if string(got[caCertKey]) != testCA+testCARot {
2187+
t.Errorf("projectionData must publish only the certificate blocks, got %q", got[caCertKey])
2188+
}
2189+
if bytes.Contains(got[caCertKey], []byte("Certificate:")) {
2190+
t.Errorf("projectionData leaked human-readable preamble into the tenant projection")
2191+
}
2192+
}
2193+
20922194
func TestIsSource(t *testing.T) {
20932195
for _, tc := range []struct {
20942196
name string

0 commit comments

Comments
 (0)