Skip to content

Commit 7ef33bb

Browse files
mnencialeonardocearmru
authored
fix(external): reject path traversal in external cluster secret dump (#11045)
The external cluster name and the referenced TLS secret selectors (`sslCert`, `sslKey`, `sslRootCert`) are joined into filesystem paths under the external secrets directory (`/controller/external`) when the instance manager dumps the connection material. None of these values were validated, so a name or selector containing a path separator or a `..` component could escape the intended directory and write into other volumes mounted writable in the instance container. This stays within the trust boundary of a principal who can already create or update a Cluster (and therefore already controls the resulting Pod and its volumes), so it is a hardening fix rather than a privilege escalation. It is still a free-form string flowing into `filepath.Join`, which we validate by policy regardless of who can reach it. Reject these values both in the cluster validating webhook and in the instance manager, which reads the spec directly and can bypass admission. The password secret reference is intentionally left unchecked, since it is only read from the API server and never joined into a path. The name is only ever used as a string-equality lookup key, so rejecting a path separator or a `..` component is non-breaking; no positive allowlist is imposed on the pre-existing field. Because the same validator runs at the start of the instance manager reconcile loop through the admission guard, a Cluster that already has a non-conforming external cluster name or secret selector persisted (created before this fix, or through a webhook bypass) will have its reconciliation stopped until the value is corrected. Such a configuration could not have connected correctly before, since the value would have resolved to an unintended path. Reported by @r0binak. Closes #11043 Signed-off-by: Marco Nenciarini <[email protected]> Signed-off-by: Leonardo Cecchi <[email protected]> Signed-off-by: Armando Ruocco <[email protected]> Co-authored-by: Leonardo Cecchi <[email protected]> Co-authored-by: Armando Ruocco <[email protected]>
1 parent bbc8958 commit 7ef33bb

8 files changed

Lines changed: 321 additions & 12 deletions

File tree

‎internal/cmd/plugin/logical/externalcluster.go‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,5 +57,9 @@ func GetConnectionString(
5757
return "", fmt.Errorf("external cluster not existent in the cluster definition")
5858
}
5959

60-
return external.GetServerConnectionString(&externalCluster, databaseName), nil
60+
connString, err := external.GetServerConnectionString(&externalCluster, databaseName)
61+
if err != nil {
62+
return "", fmt.Errorf("while building connection string for external cluster %q: %w", externalClusterName, err)
63+
}
64+
return connString, nil
6165
}

‎internal/management/controller/subscription_controller.go‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,5 +273,9 @@ func getSubscriptionConnectionString(
273273
return "", fmt.Errorf("externalCluster '%s' not declared in cluster %s", externalClusterName, cluster.Name)
274274
}
275275

276-
return external.GetServerConnectionString(&externalCluster, databaseName), nil
276+
connString, err := external.GetServerConnectionString(&externalCluster, databaseName)
277+
if err != nil {
278+
return "", fmt.Errorf("while building connection string for external cluster %q: %w", externalClusterName, err)
279+
}
280+
return connString, nil
277281
}

‎internal/webhook/v1/cluster_webhook.go‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1960,9 +1960,48 @@ func (v *ClusterCustomValidator) validateExternalCluster(
19601960
"one of connectionParameters, plugin and barmanObjectStore is required"))
19611961
}
19621962

1963+
// The external cluster name and the referenced secret selectors are joined
1964+
// into filesystem paths under the external secrets directory when the
1965+
// instance manager dumps the connection material, so they cannot contain a
1966+
// path separator or a parent-directory reference.
1967+
const pathComponentMsg = "cannot contain a path separator or a '..' component"
1968+
if isUnsafePathComponent(externalCluster.Name) {
1969+
result = append(result, field.Invalid(path.Child("name"), externalCluster.Name, pathComponentMsg))
1970+
}
1971+
1972+
selectors := []struct {
1973+
name string
1974+
selector *corev1.SecretKeySelector
1975+
}{
1976+
{"sslCert", externalCluster.SSLCert},
1977+
{"sslKey", externalCluster.SSLKey},
1978+
{"sslRootCert", externalCluster.SSLRootCert},
1979+
}
1980+
for _, s := range selectors {
1981+
if s.selector == nil {
1982+
continue
1983+
}
1984+
if isUnsafePathComponent(s.selector.Name) {
1985+
result = append(result,
1986+
field.Invalid(path.Child(s.name, "name"), s.selector.Name, pathComponentMsg))
1987+
}
1988+
if isUnsafePathComponent(s.selector.Key) {
1989+
result = append(result,
1990+
field.Invalid(path.Child(s.name, "key"), s.selector.Key, pathComponentMsg))
1991+
}
1992+
}
1993+
19631994
return result
19641995
}
19651996

1997+
// isUnsafePathComponent reports whether a spec-provided value would escape the
1998+
// directory it is meant to be joined into, either through a path separator or a
1999+
// parent-directory reference. The instance manager enforces the same rule at the
2000+
// write site, since it reads the spec directly and can bypass admission.
2001+
func isUnsafePathComponent(value string) bool {
2002+
return value == "." || value == ".." || strings.ContainsAny(value, `/\`)
2003+
}
2004+
19662005
func (v *ClusterCustomValidator) validateReplicaClusterChange(r, old *apiv1.Cluster) field.ErrorList {
19672006
// If the replication role didn't change then everything
19682007
// is fine

‎internal/webhook/v1/cluster_webhook_test.go‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2476,6 +2476,80 @@ var _ = Describe("validation of an external cluster", func() {
24762476
cluster.Spec.ExternalClusters[0].BarmanObjectStore = &apiv1.BarmanObjectStoreConfiguration{}
24772477
Expect(v.validateExternalClusters(cluster)).To(BeEmpty())
24782478
})
2479+
2480+
DescribeTable("rejects names and secret selectors that would escape the secrets directory",
2481+
func(mutate func(*apiv1.ExternalCluster)) {
2482+
ec := apiv1.ExternalCluster{
2483+
Name: "one",
2484+
ConnectionParameters: map[string]string{"dbname": "postgres"},
2485+
}
2486+
mutate(&ec)
2487+
cluster := &apiv1.Cluster{
2488+
Spec: apiv1.ClusterSpec{ExternalClusters: []apiv1.ExternalCluster{ec}},
2489+
}
2490+
Expect(v.validateExternalClusters(cluster)).ToNot(BeEmpty())
2491+
},
2492+
Entry("traversal in the name", func(ec *apiv1.ExternalCluster) {
2493+
ec.Name = "../pwned"
2494+
}),
2495+
Entry("separator in the name", func(ec *apiv1.ExternalCluster) {
2496+
ec.Name = "nested/pwned"
2497+
}),
2498+
Entry("traversal in the sslCert secret name", func(ec *apiv1.ExternalCluster) {
2499+
ec.SSLCert = &corev1.SecretKeySelector{
2500+
LocalObjectReference: corev1.LocalObjectReference{Name: "../pwned"},
2501+
Key: "tls.crt",
2502+
}
2503+
}),
2504+
Entry("traversal in the sslCert secret key", func(ec *apiv1.ExternalCluster) {
2505+
ec.SSLCert = &corev1.SecretKeySelector{
2506+
LocalObjectReference: corev1.LocalObjectReference{Name: "cert"},
2507+
Key: "../pwned",
2508+
}
2509+
}),
2510+
)
2511+
2512+
It("does not reject a password selector whose value would be unsafe as a path", func() {
2513+
// The password selector name and key are never joined into a
2514+
// filesystem path, so the webhook must leave them untouched.
2515+
cluster := &apiv1.Cluster{
2516+
Spec: apiv1.ClusterSpec{
2517+
ExternalClusters: []apiv1.ExternalCluster{
2518+
{
2519+
Name: "one",
2520+
ConnectionParameters: map[string]string{"dbname": "postgres"},
2521+
Password: &corev1.SecretKeySelector{
2522+
LocalObjectReference: corev1.LocalObjectReference{Name: "../pwned"},
2523+
Key: "../pwned",
2524+
},
2525+
},
2526+
},
2527+
},
2528+
}
2529+
Expect(v.validateExternalClusters(cluster)).To(BeEmpty())
2530+
})
2531+
2532+
It("accepts a well-formed name and secret selectors", func() {
2533+
cluster := &apiv1.Cluster{
2534+
Spec: apiv1.ClusterSpec{
2535+
ExternalClusters: []apiv1.ExternalCluster{
2536+
{
2537+
Name: "one",
2538+
ConnectionParameters: map[string]string{"dbname": "postgres"},
2539+
SSLCert: &corev1.SecretKeySelector{
2540+
LocalObjectReference: corev1.LocalObjectReference{Name: "cert"},
2541+
Key: "tls.crt",
2542+
},
2543+
Password: &corev1.SecretKeySelector{
2544+
LocalObjectReference: corev1.LocalObjectReference{Name: "creds"},
2545+
Key: "password",
2546+
},
2547+
},
2548+
},
2549+
},
2550+
}
2551+
Expect(v.validateExternalClusters(cluster)).To(BeEmpty())
2552+
})
24792553
})
24802554

24812555
var _ = Describe("bootstrap base backup validation", func() {

‎pkg/management/external/external.go‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,11 @@ import (
3535
func GetServerConnectionString(
3636
server *apiv1.ExternalCluster,
3737
databaseName string,
38-
) string {
38+
) (string, error) {
39+
if err := validateExternalClusterPaths(server); err != nil {
40+
return "", err
41+
}
42+
3943
connectionParameters := maps.Clone(server.ConnectionParameters)
4044

4145
if server.SSLCert != nil {
@@ -62,7 +66,7 @@ func GetServerConnectionString(
6266
connectionParameters["dbname"] = databaseName
6367
}
6468

65-
return configfile.CreateConnectionString(connectionParameters)
69+
return configfile.CreateConnectionString(connectionParameters), nil
6670
}
6771

6872
// ConfigureConnectionToServer creates a connection string to the external
@@ -75,6 +79,10 @@ func ConfigureConnectionToServer(
7579
namespace string,
7680
server *apiv1.ExternalCluster,
7781
) (string, error) {
82+
if err := validateExternalClusterPaths(server); err != nil {
83+
return "", err
84+
}
85+
7886
connectionParameters := maps.Clone(server.ConnectionParameters)
7987

8088
if server.SSLCert != nil {
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/*
2+
Copyright © contributors to CloudNativePG, established as
3+
CloudNativePG a Series of LF Projects, LLC.
4+
5+
Licensed under the Apache License, Version 2.0 (the "License");
6+
you may not use this file except in compliance with the License.
7+
You may obtain a copy of the License at
8+
9+
http://www.apache.org/licenses/LICENSE-2.0
10+
11+
Unless required by applicable law or agreed to in writing, software
12+
distributed under the License is distributed on an "AS IS" BASIS,
13+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
See the License for the specific language governing permissions and
15+
limitations under the License.
16+
17+
SPDX-License-Identifier: Apache-2.0
18+
*/
19+
20+
package external
21+
22+
import (
23+
"context"
24+
"os"
25+
"path/filepath"
26+
27+
corev1 "k8s.io/api/core/v1"
28+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
29+
"sigs.k8s.io/controller-runtime/pkg/client/fake"
30+
31+
apiv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1"
32+
schemeBuilder "github.com/cloudnative-pg/cloudnative-pg/internal/scheme"
33+
34+
. "github.com/onsi/ginkgo/v2"
35+
. "github.com/onsi/gomega"
36+
)
37+
38+
var _ = Describe("ConfigureConnectionToServer", func() {
39+
const namespace = "test-namespace"
40+
41+
var base string
42+
43+
BeforeEach(func() {
44+
base = GinkgoT().TempDir()
45+
customExternalSecretsPath = base
46+
DeferCleanup(func() { customExternalSecretsPath = "" })
47+
})
48+
49+
// The exhaustive set of rejected values is covered by the
50+
// validateExternalClusterPaths unit tests; this spec only verifies that the
51+
// write entry point actually enforces the guard before touching the disk, so
52+
// the security boundary cannot be silently lost by dropping the call.
53+
It("rejects a path-traversal server name before writing anything to disk", func() {
54+
fakeClient := fake.NewClientBuilder().
55+
WithScheme(schemeBuilder.BuildWithAllKnownScheme()).
56+
WithObjects(&corev1.Secret{
57+
ObjectMeta: metav1.ObjectMeta{Name: "cert-secret", Namespace: namespace},
58+
Data: map[string][]byte{"tls.crt": []byte("payload")},
59+
}).
60+
Build()
61+
62+
server := &apiv1.ExternalCluster{
63+
Name: "../pwned",
64+
SSLCert: &corev1.SecretKeySelector{
65+
LocalObjectReference: corev1.LocalObjectReference{Name: "cert-secret"},
66+
Key: "tls.crt",
67+
},
68+
}
69+
70+
_, err := ConfigureConnectionToServer(context.Background(), fakeClient, namespace, server)
71+
Expect(err).To(MatchError(ErrInvalidPathComponent))
72+
73+
// The guard must fire before any directory or file is created, both
74+
// inside the secrets directory and as a sibling reachable via traversal.
75+
entries, readErr := os.ReadDir(base)
76+
Expect(readErr).ToNot(HaveOccurred())
77+
Expect(entries).To(BeEmpty(), "the external secrets directory must stay empty")
78+
Expect(filepath.Join(filepath.Dir(base), "pwned")).ToNot(BeAnExistingFile())
79+
})
80+
})

‎pkg/management/external/utils.go‎

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,17 @@ package external
2121

2222
import (
2323
"context"
24+
"errors"
2425
"fmt"
2526
"os"
2627
"path/filepath"
28+
"strings"
2729

2830
"github.com/cloudnative-pg/machinery/pkg/fileutils"
2931
corev1 "k8s.io/api/core/v1"
3032
ctrl "sigs.k8s.io/controller-runtime/pkg/client"
3133

34+
apiv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1"
3235
"github.com/cloudnative-pg/cloudnative-pg/pkg/management/external/internal/pgpass"
3336
)
3437

@@ -51,6 +54,41 @@ func getExternalSecretsPath() string {
5154
return defaultExternalSecretsPath
5255
}
5356

57+
// ErrInvalidPathComponent is returned when a value that is used as a filesystem
58+
// path component contains a path separator or a parent-directory reference, both
59+
// of which could be used to escape the external secrets directory.
60+
var ErrInvalidPathComponent = errors.New("value cannot be used as a filesystem path component")
61+
62+
// validatePathComponent ensures that a spec-provided value can be safely joined
63+
// into the external secrets path without escaping it. The admission webhook
64+
// rejects these values too, but the instance manager reads the spec directly, so
65+
// the check is repeated here as a defense-in-depth guard.
66+
func validatePathComponent(value string) error {
67+
if value == "." || value == ".." || strings.ContainsAny(value, `/\`) {
68+
return fmt.Errorf("%w: %q", ErrInvalidPathComponent, value)
69+
}
70+
return nil
71+
}
72+
73+
// validateExternalClusterPaths ensures that all ExternalCluster fields used as
74+
// filesystem path components are safe to join into the external secrets directory.
75+
func validateExternalClusterPaths(server *apiv1.ExternalCluster) error {
76+
if err := validatePathComponent(server.Name); err != nil {
77+
return err
78+
}
79+
for _, selector := range []*corev1.SecretKeySelector{server.SSLCert, server.SSLKey, server.SSLRootCert} {
80+
if selector == nil {
81+
continue
82+
}
83+
for _, component := range []string{selector.Name, selector.Key} {
84+
if err := validatePathComponent(component); err != nil {
85+
return err
86+
}
87+
}
88+
}
89+
return nil
90+
}
91+
5492
// readSecretKeyRef reads the passed secret selector into a string.
5593
// This function is mainly useful to get a PostgreSQL's role password
5694
// from a Kubernetes secret
@@ -73,7 +111,7 @@ func readSecretKeyRef(
73111
}
74112

75113
// getSecretKeyRefFileName get the name of the file where the content of the
76-
// connection secret will be dumped
114+
// connection secret will be dumped.
77115
func getSecretKeyRefFileName(
78116
serverName string,
79117
selector *corev1.SecretKeySelector,
@@ -105,12 +143,11 @@ func dumpSecretKeyRefToFile(
105143
return "", fmt.Errorf("missing key %v in secret %v", selector.Key, selector.Name)
106144
}
107145

108-
directory := filepath.Join(getExternalSecretsPath(), serverName)
109-
if err := os.MkdirAll(directory, 0o700); err != nil {
146+
filePath := getSecretKeyRefFileName(serverName, selector)
147+
if err := os.MkdirAll(filepath.Dir(filePath), 0o700); err != nil {
110148
return "", err
111149
}
112150

113-
filePath := filepath.Join(directory, fmt.Sprintf("%v_%v", selector.Name, selector.Key))
114151
// Write atomically: this file is reused across reconciliations and read
115152
// concurrently by libpq, so an in-place rewrite could expose a partial file
116153
// or leave stale bytes behind when the secret rotates to shorter content.
@@ -121,7 +158,7 @@ func dumpSecretKeyRefToFile(
121158
return filePath, nil
122159
}
123160

124-
// getPgPassFilePath gets the path where the pgpass file will be stored
161+
// getPgPassFilePath gets the path where the pgpass file will be stored.
125162
func getPgPassFilePath(serverName string) string {
126163
directory := filepath.Join(getExternalSecretsPath(), serverName)
127164
filePath := filepath.Join(directory, "pgpass")
@@ -136,11 +173,10 @@ func createPgPassFile(
136173
) (string, error) {
137174
pgpassLine := pgpass.NewConnectionInfo(connectionParameters, password)
138175

139-
directory := filepath.Join(getExternalSecretsPath(), serverName)
140-
if err := os.MkdirAll(directory, 0o700); err != nil {
176+
filePath := getPgPassFilePath(serverName)
177+
if err := os.MkdirAll(filepath.Dir(filePath), 0o700); err != nil {
141178
return "", err
142179
}
143-
filePath := filepath.Join(directory, "pgpass")
144180

145181
return filePath, pgpass.From(pgpassLine).Write(filePath)
146182
}

0 commit comments

Comments
 (0)