diff --git a/cmd/command/cd/cd.go b/cmd/command/cd/cd.go index 6a58e61b..cf2014e3 100644 --- a/cmd/command/cd/cd.go +++ b/cmd/command/cd/cd.go @@ -102,6 +102,8 @@ func Commands(clients client.Plural, helmConfiguration *action.Configuration) [] cli.StringFlag{Name: "file", Usage: "The file to dump values to", Required: true}, cli.StringFlag{Name: "cluster-issuer", Usage: "The cert-manager cluster issuer to annotate ingresses with", Value: "plural"}, cli.StringFlag{Name: "ingress-class", Usage: "The ingress class to use for ingresses, defaults to the provider's ingress class"}, + cli.StringFlag{Name: "private-ca-url", Usage: "HTTPS host using your private PKI; downloads the cert chain and merges public roots into certs"}, + cli.StringFlag{Name: "private-ca-file", Usage: "PEM file with your private CA/chain; merged with public roots into certs"}, }, }, { @@ -243,7 +245,17 @@ func (p *Plural) handleInstallControlPlane(_ *cli.Context) error { func (p *Plural) handlePrintControlPlaneValues(c *cli.Context) error { p.InitPluralClient() conf := config.Read() - vals, err := cd.ControlPlaneValues(conf, c.String("file"), c.String("domain"), c.String("dsn"), c.String("name"), c.String("cluster-issuer"), c.String("ingress-class")) + vals, err := cd.ControlPlaneValues( + conf, + c.String("file"), + c.String("domain"), + c.String("dsn"), + c.String("name"), + c.String("cluster-issuer"), + c.String("ingress-class"), + c.String("private-ca-url"), + c.String("private-ca-file"), + ) if err != nil { return err } diff --git a/pkg/cd/cacert.go b/pkg/cd/cacert.go new file mode 100644 index 00000000..c4bbb109 --- /dev/null +++ b/pkg/cd/cacert.go @@ -0,0 +1,262 @@ +package cd + +import ( + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/hex" + "encoding/pem" + "fmt" + "net" + "net/url" + "os" + "strings" + "time" + + "github.com/AlecAivazis/survey/v2" +) + +var systemCABundlePaths = []string{ + "/etc/ssl/certs/ca-certificates.crt", + "/etc/pki/tls/certs/ca-bundle.crt", + "/etc/ssl/cert.pem", +} + +// FetchTLSChain dials host (OpenSSL s_client -showcerts style) and returns PEM +// for intermediates/roots presented by the peer. The leaf certificate is skipped. +// +// TLS verification is intentionally skipped so we can extract the private PKI +// chain from a host that is not yet trusted by this machine. +func FetchTLSChain(rawURL string) (string, error) { + hostPort, err := tlsDialAddress(rawURL) + if err != nil { + return "", err + } + + conn, err := tls.DialWithDialer( + &net.Dialer{Timeout: 10 * time.Second}, + "tcp", + hostPort, + // #nosec G402 -- intentional: discover private CA chain from a host not yet trusted locally + &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS12}, + ) + if err != nil { + return "", fmt.Errorf("tls dial %s: %w", hostPort, err) + } + defer conn.Close() + + state := conn.ConnectionState() + if len(state.PeerCertificates) == 0 { + return "", fmt.Errorf("no peer certificates from %s", hostPort) + } + + var b strings.Builder + certs := state.PeerCertificates + if len(certs) == 1 { + return "", fmt.Errorf("server at %s only presented a leaf certificate; provide the CA PEM with --private-ca-file or paste it when prompted", hostPort) + } + for _, cert := range certs[1:] { + if err := pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}); err != nil { + return "", err + } + } + return b.String(), nil +} + +func tlsDialAddress(raw string) (string, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return "", fmt.Errorf("empty tls address") + } + if !strings.Contains(raw, "://") { + raw = "https://" + raw + } + u, err := url.Parse(raw) + if err != nil { + return "", fmt.Errorf("parse url: %w", err) + } + host := u.Hostname() + if host == "" { + return "", fmt.Errorf("missing host in %q", raw) + } + port := u.Port() + if port == "" { + port = "443" + } + return net.JoinHostPort(host, port), nil +} + +// parseCertificates decodes and parses all CERTIFICATE PEM blocks. +func parseCertificates(pemData string) ([]*x509.Certificate, error) { + var certs []*x509.Certificate + rest := []byte(pemData) + for { + var block *pem.Block + block, rest = pem.Decode(rest) + if block == nil { + break + } + if block.Type != "CERTIFICATE" { + continue + } + cert, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return nil, fmt.Errorf("parse certificate PEM: %w", err) + } + certs = append(certs, cert) + } + if len(certs) == 0 { + return nil, fmt.Errorf("no valid CERTIFICATE PEM blocks found") + } + return certs, nil +} + +// certificateFingerprints returns SHA-256 fingerprints for display/confirmation. +func certificateFingerprints(certs []*x509.Certificate) []string { + out := make([]string, 0, len(certs)) + for _, cert := range certs { + sum := sha256.Sum256(cert.Raw) + out = append(out, strings.ToUpper(hex.EncodeToString(sum[:]))) + } + return out +} + +// MergeWithSystemRoots validates privatePEM and appends OS/browser-trusted roots. +func MergeWithSystemRoots(privatePEM string) (string, error) { + privatePEM = strings.TrimSpace(privatePEM) + if privatePEM == "" { + return "", fmt.Errorf("empty private CA PEM") + } + if _, err := parseCertificates(privatePEM); err != nil { + return "", fmt.Errorf("invalid private CA PEM: %w", err) + } + roots, err := readSystemCABundle() + if err != nil { + return "", err + } + var out strings.Builder + out.WriteString(privatePEM) + if !strings.HasSuffix(privatePEM, "\n") { + out.WriteByte('\n') + } + out.WriteString(strings.TrimSpace(string(roots))) + out.WriteByte('\n') + return out.String(), nil +} + +func readSystemCABundle() ([]byte, error) { + if path := os.Getenv("SSL_CERT_FILE"); path != "" { + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("read SSL_CERT_FILE %q: %w", path, err) + } + if len(data) == 0 { + return nil, fmt.Errorf("SSL_CERT_FILE %q is empty", path) + } + return data, nil + } + for _, path := range systemCABundlePaths { + data, err := os.ReadFile(path) + if err == nil && len(data) > 0 { + return data, nil + } + } + return nil, fmt.Errorf("could not locate a system CA bundle (tried SSL_CERT_FILE and %s)", strings.Join(systemCABundlePaths, ", ")) +} + +// ResolvePrivateCABundle builds a merged CA PEM from optional URL and/or file. +func ResolvePrivateCABundle(caURL, caFile string) (string, error) { + var private string + var err error + switch { + case caFile != "": + data, err := os.ReadFile(caFile) + if err != nil { + return "", fmt.Errorf("read private ca file: %w", err) + } + private = string(data) + case caURL != "": + private, err = FetchTLSChain(caURL) + if err != nil { + return "", err + } + default: + return "", nil + } + return MergeWithSystemRoots(private) +} + +// askPrivateCA prompts whether to configure a private CA and returns a PEM +// suitable for values templates (templates indent under data: |). +func askPrivateCA() (pemData string, err error) { + var usePrivate bool + if err = survey.AskOne(&survey.Confirm{ + Message: "Are you using a private / internal CA that console and agents must trust?", + Default: false, + }, &usePrivate); err != nil { + return "", err + } + if !usePrivate { + return "", nil + } + + var mode string + if err = survey.AskOne(&survey.Select{ + Message: "How do you want to provide the private CA?", + Options: []string{ + "Download cert chain from an HTTPS host", + "Paste / load a PEM file path", + }, + }, &mode); err != nil { + return "", err + } + + var private string + switch mode { + case "Download cert chain from an HTTPS host": + var host string + if err = survey.AskOne(&survey.Input{ + Message: "Example HTTPS URL or host using that PKI (eg https://git.corp.example):", + }, &host, survey.WithValidator(survey.Required)); err != nil { + return "", err + } + private, err = FetchTLSChain(host) + if err != nil { + return "", err + } + certs, err := parseCertificates(private) + if err != nil { + return "", err + } + fps := certificateFingerprints(certs) + fmt.Println("Downloaded CA certificate fingerprints (SHA-256):") + for i, fp := range fps { + subject := certs[i].Subject.String() + fmt.Printf(" %d. %s\n %s\n", i+1, subject, fp) + } + var confirm bool + if err = survey.AskOne(&survey.Confirm{ + Message: "Trust these CA certificates end-to-end for console and agents?", + Default: false, + }, &confirm); err != nil { + return "", err + } + if !confirm { + return "", fmt.Errorf("private CA download was not confirmed") + } + default: + var path string + if err = survey.AskOne(&survey.Input{ + Message: "Path to a PEM file containing your private CA / chain:", + }, &path, survey.WithValidator(survey.Required)); err != nil { + return "", err + } + data, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("read ca file: %w", err) + } + private = string(data) + } + + return MergeWithSystemRoots(private) +} diff --git a/pkg/cd/cacert_test.go b/pkg/cd/cacert_test.go new file mode 100644 index 00000000..22319d4a --- /dev/null +++ b/pkg/cd/cacert_test.go @@ -0,0 +1,132 @@ +package cd + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "net" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestParseCertificatesRejectsInvalid(t *testing.T) { + _, err := parseCertificates("not a cert") + require.Error(t, err) + + _, err = parseCertificates("-----BEGIN CERTIFICATE-----\nbm90LWEtY2VydA==\n-----END CERTIFICATE-----\n") + require.Error(t, err) +} + +func TestMergeWithSystemRoots(t *testing.T) { + dir := t.TempDir() + bundle := filepath.Join(dir, "ca-certificates.crt") + + old := systemCABundlePaths + systemCABundlePaths = []string{bundle} + t.Cleanup(func() { systemCABundlePaths = old }) + + caCert, _ := mustCreateCA(t) + var private strings.Builder + require.NoError(t, pem.Encode(&private, &pem.Block{Type: "CERTIFICATE", Bytes: caCert.Raw})) + + _, err := MergeWithSystemRoots("not-a-pem") + require.Error(t, err) + + require.NoError(t, os.WriteFile(bundle, []byte(private.String()), 0o644)) + merged, err := MergeWithSystemRoots(private.String()) + require.NoError(t, err) + require.Contains(t, merged, "BEGIN CERTIFICATE") +} + +func TestFetchTLSChain(t *testing.T) { + caCert, caKey := mustCreateCA(t) + leafCert, leafKey := mustCreateLeaf(t, caCert, caKey) + + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + tlsLn := tls.NewListener(ln, &tls.Config{ + Certificates: []tls.Certificate{{ + Certificate: [][]byte{leafCert.Raw, caCert.Raw}, + PrivateKey: leafKey, + }}, + }) + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })} + go func() { + _ = srv.Serve(tlsLn) + }() + defer srv.Close() + + pemChain, err := FetchTLSChain("https://" + ln.Addr().String()) + require.NoError(t, err) + require.Contains(t, pemChain, "BEGIN CERTIFICATE") + block, _ := pem.Decode([]byte(pemChain)) + require.NotNil(t, block) + parsed, err := x509.ParseCertificate(block.Bytes) + require.NoError(t, err) + require.True(t, parsed.Equal(caCert)) +} + +func TestReadSystemCABundleSSLCertFile(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "custom.crt") + require.NoError(t, os.WriteFile(path, []byte("custom-roots\n"), 0o644)) + t.Setenv("SSL_CERT_FILE", path) + + data, err := readSystemCABundle() + require.NoError(t, err) + require.Equal(t, "custom-roots\n", string(data)) +} + +func mustCreateCA(t *testing.T) (*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: "test-ca"}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + IsCA: true, + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, + BasicConstraintsValid: true, + } + 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 mustCreateLeaf(t *testing.T, ca *x509.Certificate, caKey *ecdsa.PrivateKey) (*x509.Certificate, *ecdsa.PrivateKey) { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(2), + Subject: pkix.Name{CommonName: "localhost"}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + DNSNames: []string{"localhost"}, + IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, ca, &key.PublicKey, caKey) + require.NoError(t, err) + cert, err := x509.ParseCertificate(der) + require.NoError(t, err) + return cert, key +} diff --git a/pkg/cd/control_plane_install.go b/pkg/cd/control_plane_install.go index 84a58983..978f68e7 100644 --- a/pkg/cd/control_plane_install.go +++ b/pkg/cd/control_plane_install.go @@ -57,7 +57,7 @@ type consoleValues struct { Secrets secrets `yaml:"secrets"` } -func ControlPlaneValues(conf config.Config, file, domain, dsn, name, clusterIssuer, ingressClass string) (string, error) { +func ControlPlaneValues(conf config.Config, file, domain, dsn, name, clusterIssuer, ingressClass, privateCAURL, privateCAFile string) (string, error) { consoleDns := fmt.Sprintf("console.%s", domain) kasDns := fmt.Sprintf("kas.%s", domain) existing := consoleValues{} @@ -122,6 +122,16 @@ func ControlPlaneValues(conf config.Config, file, domain, dsn, name, clusterIssu "clusterIssuer": clusterIssuer, } + if privateCAURL != "" || privateCAFile != "" { + merged, err := ResolvePrivateCABundle(privateCAURL, privateCAFile) + if err != nil { + return "", err + } + if merged != "" { + configuration["privateCaPem"] = merged + } + } + for _, val := range []string{clusterIssuer, ingressClass} { if err := validateResourceName(val); err != nil { return "", err @@ -229,6 +239,11 @@ func CreateControlPlane(conf config.Config) (string, error) { return "", err } + privateCaPem, err := askPrivateCA() + if err != nil { + return "", err + } + randoms := map[string]string{} randoms["erlang"] = crypto.RandString(64) for _, key := range []string{"jwt", "adminPassword", "kasApi", "kasPrivateApi", "kasRedis"} { @@ -254,6 +269,9 @@ func CreateControlPlane(conf config.Config) (string, error) { if clusterIssuer != "" { configuration["clusterIssuer"] = clusterIssuer } + if privateCaPem != "" { + configuration["privateCaPem"] = privateCaPem + } for k, v := range randoms { configuration[k] = v }