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: 2 additions & 0 deletions api/v1alpha1/storagecluster_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,11 +180,13 @@ type BackupCredentialsSecretRef struct {
// HashicorpVaultSettings configures the HashiCorp Vault endpoint the cluster uses to store keys.
type HashicorpVaultSettings struct {
// +operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Vault Base URL"
// +kubebuilder:validation:Pattern=`^https://[a-zA-Z0-9.-]+(:[0-9]{1,5})?(/.*)?$`
// BaseURL is the HashiCorp Vault endpoint (e.g. https://vault.example.com:8200).
BaseURL string `json:"baseURL,omitempty"`
}

type BackupSpec struct {
// +kubebuilder:validation:Pattern=`^https://[a-zA-Z0-9.-]+(:[0-9]{1,5})?(/.*)?$`
LocalEndpoint string `json:"localEndpoint,omitempty"`
// +optional
SnapshotBackups *bool `json:"snapshotBackups,omitempty"`
Expand Down
2 changes: 2 additions & 0 deletions config/crd/bases/storage.simplyblock.io_storageclusters.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ spec:
- name
type: object
localEndpoint:
pattern: ^https://[a-zA-Z0-9.-]+(:[0-9]{1,5})?(/.*)?$
type: string
localTesting:
type: boolean
Expand Down Expand Up @@ -145,6 +146,7 @@ spec:
properties:
baseURL:
description: BaseURL is the HashiCorp Vault endpoint (e.g. https://vault.example.com:8200).
pattern: ^https://[a-zA-Z0-9.-]+(:[0-9]{1,5})?(/.*)?$
type: string
type: object
inflightIOThreshold:
Expand Down
2 changes: 2 additions & 0 deletions dist/install.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1294,6 +1294,7 @@ spec:
- name
type: object
localEndpoint:
pattern: ^https://[a-zA-Z0-9.-]+(:[0-9]{1,5})?(/.*)?$
type: string
localTesting:
type: boolean
Expand Down Expand Up @@ -1359,6 +1360,7 @@ spec:
properties:
baseURL:
description: BaseURL is the HashiCorp Vault endpoint (e.g. https://vault.example.com:8200).
pattern: ^https://[a-zA-Z0-9.-]+(:[0-9]{1,5})?(/.*)?$
type: string
type: object
inflightIOThreshold:
Expand Down
4 changes: 2 additions & 2 deletions internal/controller/simplyblockstoragecluster_backup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func TestBuildBackupConfig(t *testing.T) {
},
Spec: simplyblockv1alpha1.StorageClusterSpec{
Backup: &simplyblockv1alpha1.BackupSpec{
LocalEndpoint: "http://10.10.11.10:9000",
LocalEndpoint: "https://203.0.113.10:9000",
SnapshotBackups: &snapshotBackups,
WithCompression: &withCompression,
SecondaryTarget: &secondaryTarget,
Expand Down Expand Up @@ -75,7 +75,7 @@ func TestBuildBackupConfig(t *testing.T) {
if backupConfig.SecretAccessKey != "password" {
t.Fatalf("unexpected secret_access_key: %#v", backupConfig.SecretAccessKey)
}
if backupConfig.LocalEndpoint != "http://10.10.11.10:9000" {
if backupConfig.LocalEndpoint != "https://203.0.113.10:9000" {
t.Fatalf("unexpected local_endpoint: %#v", backupConfig.LocalEndpoint)
}
if backupConfig.SnapshotBackups == nil || *backupConfig.SnapshotBackups != true {
Expand Down
28 changes: 24 additions & 4 deletions internal/controller/simplyblockstoragecluster_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ const (
// (missing, unreadable, or lacking required keys).
eventReasonBackupCredentialsError = "BackupCredentialsError"

// eventReasonInvalidConfig is emitted when a user-supplied field in the CR
// fails validation (e.g. a non-HTTPS or private-IP URL).
eventReasonInvalidConfig = "InvalidConfig"

// eventReasonClusterCreationFailed is emitted when the cluster creation API
// call returns a non-2xx status. The event message includes the HTTP status
// code and the full response body so the root cause is visible without
Expand Down Expand Up @@ -204,6 +208,13 @@ func (r *StorageClusterReconciler) reconcileCreate(
return ctrl.Result{RequeueAfter: 20 * time.Second}, nil
}

vaultConfig, err := buildHashicorpVaultConfig(clusterCR.Spec.HashicorpVaultSettings)
if err != nil {
log.Error(err, "Invalid HashiCorp Vault configuration")
r.Recorder.Eventf(clusterCR, corev1.EventTypeWarning, eventReasonInvalidConfig, "Invalid HashiCorp Vault configuration: %v", err)
return ctrl.Result{}, err
}

params := utils.ClusterAddParams{
Name: clusterCR.Name,
BlkSize: utils.IntPtrOrDefault(clusterCR.Spec.BlockSize, 512),
Expand Down Expand Up @@ -236,7 +247,7 @@ func (r *StorageClusterReconciler) reconcileCreate(
RpcBasePort: utils.IntPtrOrDefault(clusterCR.Spec.RpcBasePort, 8080),
SnodeApiPort: utils.IntPtrOrDefault(clusterCR.Spec.SnodeApiPort, 50001),
BackupConfig: backupConfig,
HashicorpVaultSettings: buildHashicorpVaultConfig(clusterCR.Spec.HashicorpVaultSettings),
HashicorpVaultSettings: vaultConfig,
EnableFailureDomain: utils.BoolPtrOrFalse(clusterCR.Spec.EnableFailureDomains),
}

Expand Down Expand Up @@ -384,6 +395,12 @@ func (r *StorageClusterReconciler) buildBackupConfig(
return nil, fmt.Errorf("secret %q missing key %q", secretName, "secret_access_key")
}

if ep := clusterCR.Spec.Backup.LocalEndpoint; ep != "" {
if err := utils.ValidateExternalURL(ep); err != nil {
return nil, fmt.Errorf("backup.localEndpoint: %w", err)
}
}

return &utils.BackupConfig{
AccessKeyID: string(accessKeyID),
SecretAccessKey: string(secretAccessKey),
Expand All @@ -395,11 +412,14 @@ func (r *StorageClusterReconciler) buildBackupConfig(
}, nil
}

func buildHashicorpVaultConfig(s *simplyblockv1alpha1.HashicorpVaultSettings) *utils.HashicorpVaultConfig {
func buildHashicorpVaultConfig(s *simplyblockv1alpha1.HashicorpVaultSettings) (*utils.HashicorpVaultConfig, error) {
if s == nil || s.BaseURL == "" {
return nil
return nil, nil
}
if err := utils.ValidateExternalURL(s.BaseURL); err != nil {
return nil, fmt.Errorf("hashicorpVault.baseURL: %w", err)
}
return &utils.HashicorpVaultConfig{BaseURL: s.BaseURL}
return &utils.HashicorpVaultConfig{BaseURL: s.BaseURL}, nil
}

// SetupWithManager sets up the controller with the Manager.
Expand Down
70 changes: 70 additions & 0 deletions internal/utils/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,81 @@ import (
"errors"
"fmt"
"math"
"net"
"net/url"
"regexp"
"strconv"
"strings"
)

// blockedIPNets contains IP ranges that must never be targeted by user-supplied URLs
// (SSRF protection: RFC-1918, loopback, link-local, cloud IMDS, IPv6 equivalents).
var blockedIPNets = func() []*net.IPNet {
cidrs := []string{
"10.0.0.0/8",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still believe that the internal networks need to be removed from the list in this specific case since it's totally valid on self-hosted (and even hosted) clusters:

  • 10.0.0.0/8 (actually Kubernetes default)
  • 172.16.0.0/12
  • 192.168.0.0/16
  • fc00::/7

"172.16.0.0/12",
"192.168.0.0/16",
Comment thread
noctarius marked this conversation as resolved.
"127.0.0.0/8",
"169.254.0.0/16",
"0.0.0.0/8",
"::1/128",
"fe80::/10",
"fc00::/7",
}
nets := make([]*net.IPNet, 0, len(cidrs))
for _, cidr := range cidrs {
_, n, _ := net.ParseCIDR(cidr)
nets = append(nets, n)
}
return nets
}()

func isBlockedIP(ip net.IP) bool {
for _, n := range blockedIPNets {
if n.Contains(ip) {
return true
}
}
return false
}

// ValidateExternalURL rejects URLs that are unsafe to forward to the backend:
// - scheme must be https
// - host must not be a blocked IP literal (RFC-1918, loopback, link-local)
// - hostname must resolve and all resolved IPs must not be blocked
func ValidateExternalURL(rawURL string) error {
if rawURL == "" {
return nil
}
u, err := url.Parse(rawURL)
if err != nil {
return fmt.Errorf("malformed URL: %w", err)
}
if u.Scheme != "https" {
return fmt.Errorf("URL scheme must be https, got %q", u.Scheme)
}
host := u.Hostname()
if host == "" {
return fmt.Errorf("URL must contain a hostname")
}
if ip := net.ParseIP(host); ip != nil {
if isBlockedIP(ip) {
return fmt.Errorf("URL targets a restricted IP address (%s)", host)
}
return nil
}
addrs, err := net.LookupHost(host)
if err != nil {
return fmt.Errorf("cannot resolve host %q: %w", host, err)
}
for _, addr := range addrs {
if ip := net.ParseIP(addr); ip != nil && isBlockedIP(ip) {
return fmt.Errorf("URL resolves to a restricted IP address (%s)", addr)
}
}
return nil
}

var exponentMultipliers = []string{"", "K", "M", "G", "T", "P", "E", "Z"}
var uuidRegex = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$`)

Expand Down
44 changes: 43 additions & 1 deletion internal/utils/helpers_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,48 @@
package utils

import "testing"
import (
"strings"
"testing"
)

func TestValidateExternalURL(t *testing.T) {
tests := []struct {
name string
url string
wantErr string // substring; empty means no error expected
}{
{name: "empty is ok", url: ""},
{name: "valid https public IP", url: "https://8.8.8.8:8200"},
{name: "valid https public IP with path", url: "https://1.1.1.1/bucket"},
{name: "http rejected", url: "http://vault.example.com", wantErr: "scheme must be https"},
{name: "no scheme rejected", url: "vault.example.com", wantErr: "scheme must be https"},
{name: "RFC-1918 10.x", url: "https://10.0.0.1", wantErr: "restricted IP"},
{name: "RFC-1918 172.16.x", url: "https://172.16.5.1", wantErr: "restricted IP"},
{name: "RFC-1918 192.168.x", url: "https://192.168.1.1", wantErr: "restricted IP"},
{name: "loopback", url: "https://127.0.0.1", wantErr: "restricted IP"},
{name: "link-local IMDS", url: "https://169.254.169.254", wantErr: "restricted IP"},
{name: "IPv6 loopback", url: "https://[::1]", wantErr: "restricted IP"},
{name: "IPv6 link-local", url: "https://[fe80::1]", wantErr: "restricted IP"},
{name: "IPv6 ULA", url: "https://[fd00::1]", wantErr: "restricted IP"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
err := ValidateExternalURL(tc.url)
if tc.wantErr == "" {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
return
}
if err == nil {
t.Fatalf("expected error containing %q, got nil", tc.wantErr)
}
if !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("expected error %q to contain %q", err.Error(), tc.wantErr)
}
})
}
}

func TestIntAndBoolHelpers(t *testing.T) {
var i int32 = 7
Expand Down
Loading