diff --git a/pkg/controller/certs/certs.go b/pkg/controller/certs/certs.go index 3085959065..36b2eed08e 100644 --- a/pkg/controller/certs/certs.go +++ b/pkg/controller/certs/certs.go @@ -81,7 +81,7 @@ func GenerateCA(notAfter time.Time, organization string) (*KeyPair, error) { BasicConstraintsValid: true, } - privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) if err != nil { return nil, err } @@ -134,7 +134,7 @@ func CreateSignedServingPair(notAfter time.Time, organization string, ca *KeyPai DNSNames: hosts, } - privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) if err != nil { return nil, err } @@ -158,6 +158,24 @@ func CreateSignedServingPair(notAfter time.Time, organization string, ca *KeyPai return servingCert, nil } +// IsP384 reports whether the given certificate's public key is an ECDSA key on +// the P-384 curve, the curve OLM generates all of its CA and serving cert key +// material with. Certificates using any other algorithm or curve (for example, +// the P-256 material generated by older versions of OLM) should be rotated. +func IsP384(cert *x509.Certificate) bool { + if cert == nil { + return false + } + if cert.PublicKeyAlgorithm != x509.ECDSA { + return false + } + publicKey, ok := cert.PublicKey.(*ecdsa.PublicKey) + if !ok { + return false + } + return publicKey.Curve == elliptic.P384() +} + // PEMToCert converts the PEM block of the given byte array to an x509 certificate func PEMToCert(certPEM []byte) (*x509.Certificate, error) { block, _ := pem.Decode(certPEM) diff --git a/pkg/controller/certs/certs_test.go b/pkg/controller/certs/certs_test.go index 29945643bc..28d825fcba 100644 --- a/pkg/controller/certs/certs_test.go +++ b/pkg/controller/certs/certs_test.go @@ -2,6 +2,9 @@ package certs import ( "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" "crypto/x509" "encoding/pem" "errors" @@ -40,7 +43,9 @@ func TestGenerateCA(t *testing.T) { require.Equal(t, []string{testOrganization}, ca.Cert.Subject.Organization) require.Contains(t, ca.Cert.Subject.CommonName, "olm-selfsigned-") require.True(t, ca.Cert.NotAfter.Equal(notAfter), "notAfter should be the requested value") - require.Equal(t, "P-256", ca.Priv.Curve.Params().Name) + require.Equal(t, "P-384", ca.Priv.Curve.Params().Name) + require.True(t, IsP384(ca.Cert), "generated CA should use P-384") + require.Equal(t, x509.ECDSAWithSHA384, ca.Cert.SignatureAlgorithm) require.True(t, Active(ca.Cert), "freshly generated CA should be active") // The CA is self-signed: it should verify against a pool containing itself @@ -70,7 +75,9 @@ func TestCreateSignedServingPair(t *testing.T) { require.Equal(t, []string{testOrganization}, pair.Cert.Subject.Organization) require.Equal(t, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, pair.Cert.ExtKeyUsage) require.True(t, pair.Cert.NotAfter.Equal(notAfter), "notAfter should be the requested value") - require.Equal(t, "P-256", pair.Priv.Curve.Params().Name) + require.Equal(t, "P-384", pair.Priv.Curve.Params().Name) + require.True(t, IsP384(pair.Cert), "generated serving cert should use P-384") + require.Equal(t, x509.ECDSAWithSHA384, pair.Cert.SignatureAlgorithm) require.True(t, Active(pair.Cert)) // The serving cert chains to the given CA and is valid for every requested host. @@ -88,6 +95,32 @@ func TestCreateSignedServingPair(t *testing.T) { } } +func TestIsP384(t *testing.T) { + p384CA := mustGenerateCA(t) + require.True(t, IsP384(p384CA.Cert)) + + p256Key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + p256Cert := &x509.Certificate{ + PublicKeyAlgorithm: x509.ECDSA, + PublicKey: &p256Key.PublicKey, + } + require.False(t, IsP384(p256Cert), "P-256 certificates should not be reported as P-384") + + rsaKey, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + rsaCert := &x509.Certificate{ + PublicKeyAlgorithm: x509.RSA, + PublicKey: &rsaKey.PublicKey, + } + require.False(t, IsP384(rsaCert), "RSA certificates should not be reported as P-384") + + require.False(t, IsP384(nil), "nil certificates should not be reported as P-384") + + ecdsaCertWithMissingKey := &x509.Certificate{PublicKeyAlgorithm: x509.ECDSA} + require.False(t, IsP384(ecdsaCertWithMissingKey)) +} + func TestVerifyCert(t *testing.T) { ca := mustGenerateCA(t) otherCA := mustGenerateCA(t) diff --git a/pkg/controller/install/certresources.go b/pkg/controller/install/certresources.go index 825eee5e24..2042932524 100644 --- a/pkg/controller/install/certresources.go +++ b/pkg/controller/install/certresources.go @@ -258,6 +258,12 @@ func shouldRotateCerts(certSecret *corev1.Secret, hosts []string) bool { return true } + // Rotate CA and serving certs that do not use ECDSA P-384, e.g. the P-256 + // material generated by older versions of OLM. + if !certs.IsP384(ca) || !certs.IsP384(cert) { + return true + } + // check for cert freshness if !certs.Active(ca) || now.Time.After(CalculateCertRotatesAt(ca.NotAfter)) || !certs.Active(cert) || now.Time.After(CalculateCertRotatesAt(cert.NotAfter)) { diff --git a/pkg/controller/install/certresources_test.go b/pkg/controller/install/certresources_test.go index 2c7de44bd5..d9665aee8a 100644 --- a/pkg/controller/install/certresources_test.go +++ b/pkg/controller/install/certresources_test.go @@ -1,7 +1,14 @@ package install import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" "fmt" + "math" + "math/big" "reflect" "testing" "time" @@ -34,6 +41,60 @@ func keyPair(t *testing.T, expiration time.Time) *certs.KeyPair { return p } +// keyPairWithCurve generates a self-signed CA on the given curve, for building +// fixtures that mimic key material generated by older versions of OLM. +func keyPairWithCurve(t *testing.T, curve elliptic.Curve, notAfter time.Time) *certs.KeyPair { + t.Helper() + serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64)) + require.NoError(t, err) + caDetails := &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{ + CommonName: fmt.Sprintf("olm-selfsigned-%x", serial), + Organization: []string{Organization}, + }, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: notAfter, + IsCA: true, + KeyUsage: x509.KeyUsageCertSign, + BasicConstraintsValid: true, + } + priv, err := ecdsa.GenerateKey(curve, rand.Reader) + require.NoError(t, err) + certRaw, err := x509.CreateCertificate(rand.Reader, caDetails, caDetails, &priv.PublicKey, priv) + require.NoError(t, err) + cert, err := x509.ParseCertificate(certRaw) + require.NoError(t, err) + return &certs.KeyPair{Cert: cert, Priv: priv} +} + +// signedPairWithCurve generates a serving pair on the given curve, for building +// fixtures that mimic key material generated by older versions of OLM. +func signedPairWithCurve(t *testing.T, curve elliptic.Curve, ca *certs.KeyPair, notAfter time.Time, hosts []string) *certs.KeyPair { + t.Helper() + serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64)) + require.NoError(t, err) + certDetails := &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{ + CommonName: hosts[0], + Organization: []string{Organization}, + }, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: notAfter, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + BasicConstraintsValid: true, + DNSNames: hosts, + } + priv, err := ecdsa.GenerateKey(curve, rand.Reader) + require.NoError(t, err) + certRaw, err := x509.CreateCertificate(rand.Reader, certDetails, ca.Cert, &priv.PublicKey, ca.Priv) + require.NoError(t, err) + cert, err := x509.ParseCertificate(certRaw) + require.NoError(t, err) + return &certs.KeyPair{Cert: cert, Priv: priv} +} + func selector(t *testing.T, selector string) *metav1.LabelSelector { s, err := metav1.ParseToLabelSelector(selector) assert.NoError(t, err) @@ -996,3 +1057,59 @@ func TestInstallCertRequirementsForDeployment(t *testing.T) { }) } } + +func TestShouldRotateCertsKeyAlgorithm(t *testing.T) { + hosts := HostnamesForService("test-service", "test-namespace") + notAfter := time.Now().Add(730 * 24 * time.Hour) + + p384CA := keyPair(t, notAfter) + p384Pair, err := certs.CreateSignedServingPair(notAfter, Organization, p384CA, hosts) + require.NoError(t, err) + p384CAPEM, _, err := p384CA.ToPEM() + require.NoError(t, err) + p384ServingCertPEM, _, err := p384Pair.ToPEM() + require.NoError(t, err) + + p256CA := keyPairWithCurve(t, elliptic.P256(), notAfter) + p256Pair := signedPairWithCurve(t, elliptic.P256(), p256CA, notAfter, hosts) + p256CAPEM, _, err := p256CA.ToPEM() + require.NoError(t, err) + p256ServingCertPEM, _, err := p256Pair.ToPEM() + require.NoError(t, err) + + certSecret := func(caPEM, certPEM []byte) *corev1.Secret { + return &corev1.Secret{ + Data: map[string][]byte{ + OLMCAPEMKey: caPEM, + "tls.crt": certPEM, + }, + } + } + + tests := []struct { + name string + secret *corev1.Secret + rotation bool + }{ + { + name: "P-384 CA and serving cert are reused", + secret: certSecret(p384CAPEM, p384ServingCertPEM), + rotation: false, + }, + { + name: "P-256 CA is rotated", + secret: certSecret(p256CAPEM, p256ServingCertPEM), + rotation: true, + }, + { + name: "P-256 serving cert is rotated", + secret: certSecret(p384CAPEM, p256ServingCertPEM), + rotation: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.rotation, shouldRotateCerts(tt.secret, hosts)) + }) + } +} diff --git a/pkg/controller/operators/olm/operator_test.go b/pkg/controller/operators/olm/operator_test.go index 595f1cf3ca..f515d8aa50 100644 --- a/pkg/controller/operators/olm/operator_test.go +++ b/pkg/controller/operators/olm/operator_test.go @@ -606,6 +606,46 @@ func signedServingPair(notAfter time.Time, ca *certs.KeyPair, hosts []string) *c return servingPair } +// signedServingPairWithCurve generates a serving pair on the given curve, for +// building fixtures that mimic the key material generated by older versions +// of OLM (which used P-256). +func signedServingPairWithCurve(curve elliptic.Curve, notAfter time.Time, ca *certs.KeyPair, hosts []string) *certs.KeyPair { + serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64)) + if err != nil { + panic(err) + } + + certDetails := &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{ + CommonName: hosts[0], + Organization: []string{install.Organization}, + }, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: notAfter, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + BasicConstraintsValid: true, + DNSNames: hosts, + } + + privateKey, err := ecdsa.GenerateKey(curve, rand.Reader) + if err != nil { + panic(err) + } + + certRaw, err := x509.CreateCertificate(rand.Reader, certDetails, ca.Cert, &privateKey.PublicKey, ca.Priv) + if err != nil { + panic(err) + } + + cert, err := x509.ParseCertificate(certRaw) + if err != nil { + panic(err) + } + + return &certs.KeyPair{Cert: cert, Priv: privateKey} +} + func withAnnotations(obj runtime.Object, annotations map[string]string) runtime.Object { meta, ok := obj.(metav1.Object) if !ok { @@ -920,6 +960,13 @@ func crd(name, version, group string) *apiextensionsv1.CustomResourceDefinition } func generateCA(notAfter time.Time, organization string) (*certs.KeyPair, error) { + return generateCAWithCurve(elliptic.P384(), notAfter, organization) +} + +// generateCAWithCurve generates a self-signed CA on the given curve, for +// building fixtures that mimic the key material generated by older versions +// of OLM (which used P-256). +func generateCAWithCurve(curve elliptic.Curve, notAfter time.Time, organization string) (*certs.KeyPair, error) { notBefore := time.Now() serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64)) @@ -940,7 +987,7 @@ func generateCA(notAfter time.Time, organization string) (*certs.KeyPair, error) BasicConstraintsValid: true, } - privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + privateKey, err := ecdsa.GenerateKey(curve, rand.Reader) if err != nil { return nil, err } @@ -6328,6 +6375,263 @@ func GetServiceCertificaValidityPeriod(serviceSecret *corev1.Secret) (start *tim return &cert.NotBefore, &cert.NotAfter, nil } +// TestCAP384Rotation walks a CSV with an owned APIService through the +// migration from P-256 key material: after simulating the cluster state an +// older version of OLM would have left behind (a valid P-256 CA and serving +// pair in the cert Secret, a matching CABundle and olmcahash), the CSV is +// marked for a cert refresh, reinstalled with P-384 material and settles +// back in the Succeeded phase with the APIService CABundle and deployment +// olmcahash updated accordingly. +func TestCAP384Rotation(t *testing.T) { + logrus.SetLevel(logrus.DebugLevel) + namespace := "ns" + + defaultOperatorGroup := &operatorsv1.OperatorGroup{ + TypeMeta: metav1.TypeMeta{ + Kind: "OperatorGroup", + APIVersion: operatorsv1.SchemeGroupVersion.String(), + }, + ObjectMeta: metav1.ObjectMeta{ + Name: "default", + Namespace: namespace, + }, + Spec: operatorsv1.OperatorGroupSpec{}, + Status: operatorsv1.OperatorGroupStatus{ + Namespaces: []string{namespace}, + }, + } + + defaultTemplateAnnotations := map[string]string{ + operatorsv1.OperatorGroupTargetsAnnotationKey: namespace, + operatorsv1.OperatorGroupNamespaceAnnotationKey: namespace, + operatorsv1.OperatorGroupAnnotationKey: defaultOperatorGroup.GetName(), + } + + csv1 := withUID(withAPIServices(csvWithAnnotations(csv("csv1", + namespace, + "0.0.0", + "", + installStrategy("a1", nil, nil), + []*apiextensionsv1.CustomResourceDefinition{crd("c1", "v1", "g1")}, + []*apiextensionsv1.CustomResourceDefinition{}, + v1alpha1.CSVPhaseNone, + ), defaultTemplateAnnotations), apis("a1.v1.a1Kind"), nil), types.UID("csv-uid")).(*v1alpha1.ClusterServiceVersion) + + // The APIService is seeded so that its GVK is present in api discovery and + // so that its availability condition can be simulated; OLM adopts and + // updates it during install. + seededAPIService := apiService("a1", "v1", "a1-service", namespace, "a1", nil, apiregistrationv1.ConditionTrue, ownerLabelFromCSV("csv1", namespace)) + + ctx, cancel := context.WithCancel(context.TODO()) + defer cancel() + op, err := NewFakeOperator( + ctx, + withNamespaces(namespace, "kube-system"), + withClientObjs( + addAnnotation(defaultOperatorGroup, operatorsv1.OperatorGroupProvidedAPIsAnnotationKey, "c1.v1.g1,a1Kind.v1.a1"), + csv1, + ), + withK8sObjs( + // The rolebinding, service, and clusterRoleBinding have been added here as a workaround to fake client not supporting SSA + roleBinding("a1-service-auth-reader", "kube-system", "extension-apiserver-authentication-reader", "sa", namespace), + service("a1-service", namespace, "a1", 80, metav1.OwnerReference{Kind: v1alpha1.ClusterServiceVersionKind, UID: "csv-uid"}), + clusterRoleBinding("a1-service-system:auth-delegator", "system:auth-delegator", "sa", namespace), + serviceAccount("sa", namespace), + ), + withExtObjs(crd("c1", "v1", "g1")), + withRegObjs(seededAPIService), + withPartialMetadata( + &metav1.PartialObjectMetadata{ + TypeMeta: metav1.TypeMeta{ + Kind: "ClusterServiceVersion", + APIVersion: v1alpha1.SchemeGroupVersion.String(), + }, + ObjectMeta: csv1.ObjectMeta, + }, + &metav1.PartialObjectMetadata{ + TypeMeta: metav1.TypeMeta{ + Kind: "CustomResourceDefinition", + APIVersion: apiextensionsv1.SchemeGroupVersion.String(), + }, + ObjectMeta: crd("c1", "v1", "g1").ObjectMeta, + }, + ), + withOperatorNamespace(namespace), + ) + require.NoError(t, err) + + // simulateAvailability marks the CSV's deployment as rolled out and its + // owned APIService as available, as the respective controllers would in a + // real cluster. + simulateAvailability := func() { + dep, err := op.opClient.GetDeployment(namespace, "a1") + if err == nil { + dep.Status = appsv1.DeploymentStatus{ + ObservedGeneration: dep.GetGeneration(), + Replicas: 1, + UpdatedReplicas: 1, + AvailableReplicas: 1, + Conditions: []appsv1.DeploymentCondition{{ + Type: appsv1.DeploymentAvailable, + Status: corev1.ConditionTrue, + }}, + } + _, err = op.opClient.KubernetesInterface().AppsV1().Deployments(namespace).UpdateStatus(ctx, dep, metav1.UpdateOptions{}) + require.NoError(t, err) + } + + apiService, err := op.opClient.GetAPIService("v1.a1") + if err == nil && !install.IsAPIServiceAvailable(apiService) { + apiService.Status.Conditions = []apiregistrationv1.APIServiceCondition{{ + Type: apiregistrationv1.Available, + Status: apiregistrationv1.ConditionTrue, + }} + _, err = op.opClient.ApiregistrationV1Interface().ApiregistrationV1().APIServices().UpdateStatus(ctx, apiService, metav1.UpdateOptions{}) + require.NoError(t, err) + } + } + + // syncCSVUntil repeatedly syncs the CSV (simulating availability between + // syncs) until the given condition holds for the CSV as stored in the + // cluster. + syncCSVUntil := func(cond func(csv *v1alpha1.ClusterServiceVersion) bool) *v1alpha1.ClusterServiceVersion { + var last *v1alpha1.ClusterServiceVersion + var lastSyncErr error + pollErr := wait.PollUntilContextTimeout(ctx, 10*time.Millisecond, 30*time.Second, true, func(ctx context.Context) (bool, error) { + simulateAvailability() + csv, err := op.client.OperatorsV1alpha1().ClusterServiceVersions(namespace).Get(ctx, "csv1", metav1.GetOptions{}) + if err != nil { + return false, err + } + last = csv + if cond(csv) { + return true, nil + } + if err := op.syncClusterServiceVersion(csv); err != nil { + // Reconcile errors are expected while the CSV settles; keep + // trying and surface the last error on timeout. + lastSyncErr = err + } + return false, nil + }) + require.NoError(t, pollErr, "timed out waiting for CSV condition, last phase: %s, last sync error: %v", last.Status.Phase, lastSyncErr) + return last + } + + getSecret := func() *corev1.Secret { + secret, err := op.opClient.GetSecret(namespace, "a1-service-cert") + require.NoError(t, err) + return secret + } + + getAPIService := func() *apiregistrationv1.APIService { + apiService, err := op.opClient.GetAPIService("v1.a1") + require.NoError(t, err) + return apiService + } + + getDeployment := func() *appsv1.Deployment { + dep, err := op.opClient.GetDeployment(namespace, "a1") + require.NoError(t, err) + return dep + } + + // Install the CSV: OLM generates fresh P-384 key material and the CSV + // settles in the Succeeded phase. + syncCSVUntil(func(csv *v1alpha1.ClusterServiceVersion) bool { + return csv.Status.Phase == v1alpha1.CSVPhaseSucceeded + }) + + // Simulate the cluster state as an older version of OLM (which generated + // P-256 key material) would have left it: a valid P-256 CA and serving pair + // in the cert Secret, a single P-256 CA in the APIService CABundle and the + // P-256 CA hash on the deployment's pod template. The deployment's + // spec-hash label is left as-is: the cert rotation check in the Succeeded + // phase reconcile runs before any deployment spec comparison. + expiration := install.CalculateCertExpiration(time.Now()) + p256CA, err := generateCAWithCurve(elliptic.P256(), expiration, install.Organization) + require.NoError(t, err) + p256CAPEM, _, err := p256CA.ToPEM() + require.NoError(t, err) + p256CAHash := certs.PEMSHA256(p256CAPEM) + p256Pair := signedServingPairWithCurve(elliptic.P256(), expiration, p256CA, []string{"a1-service.ns", "a1-service.ns.svc"}) + p256CertPEM, p256PrivPEM, err := p256Pair.ToPEM() + require.NoError(t, err) + + secret := getSecret() + secret.Data[install.OLMCAPEMKey] = p256CAPEM + secret.Data["tls.crt"] = p256CertPEM + secret.Data["tls.key"] = p256PrivPEM + secret.SetAnnotations(map[string]string{install.OLMCAHashAnnotationKey: p256CAHash}) + _, err = op.opClient.UpdateSecret(secret) + require.NoError(t, err) + + apiService := getAPIService() + apiService.Spec.CABundle = p256CAPEM + _, err = op.opClient.UpdateAPIService(apiService) + require.NoError(t, err) + + dep := getDeployment() + dep.Spec.Template.Annotations[install.OLMCAHashAnnotationKey] = p256CAHash + _, err = op.opClient.KubernetesInterface().AppsV1().Deployments(namespace).Update(ctx, dep, metav1.UpdateOptions{}) + require.NoError(t, err) + + // Wait for the lister cache to reflect the simulated state. + require.NoError(t, wait.PollUntilContextTimeout(ctx, 10*time.Millisecond, 30*time.Second, true, func(ctx context.Context) (bool, error) { + cachedSecret, err := op.lister.CoreV1().SecretLister().Secrets(namespace).Get("a1-service-cert") + if err != nil { + return false, err + } + if hash, ok := cachedSecret.GetAnnotations()[install.OLMCAHashAnnotationKey]; !ok || hash != p256CAHash { + return false, nil + } + cachedAPIService, err := op.lister.APIRegistrationV1().APIServiceLister().Get("v1.a1") + if err != nil { + return false, err + } + if !reflect.DeepEqual(cachedAPIService.Spec.CABundle, p256CAPEM) { + return false, nil + } + cachedDep, err := op.lister.AppsV1().DeploymentLister().Deployments(namespace).Get("a1") + if err != nil { + return false, err + } + hash, ok := cachedDep.Spec.Template.GetAnnotations()[install.OLMCAHashAnnotationKey] + return ok && hash == p256CAHash, nil + })) + + // Rotate onto fresh P-384 key material: the CSV notices the P-256 certs, + // re-enters the install phases and settles back in Succeeded. + syncCSVUntil(func(csv *v1alpha1.ClusterServiceVersion) bool { + if csv.Status.Phase != v1alpha1.CSVPhaseSucceeded { + return false + } + secret := getSecret() + ca, err := certs.PEMToCert(secret.Data[install.OLMCAPEMKey]) + return err == nil && certs.IsP384(ca) + }) + + // The cert Secret now holds P-384 key material... + secret = getSecret() + rotatedCA, err := certs.PEMToCert(secret.Data[install.OLMCAPEMKey]) + require.NoError(t, err) + require.True(t, certs.IsP384(rotatedCA), "rotated CA is not ECDSA P-384") + rotatedCert, err := certs.PEMToCert(secret.Data["tls.crt"]) + require.NoError(t, err) + require.True(t, certs.IsP384(rotatedCert), "rotated serving cert is not ECDSA P-384") + rotatedCAHash := certs.PEMSHA256(secret.Data[install.OLMCAPEMKey]) + require.Equal(t, rotatedCAHash, secret.GetAnnotations()[install.OLMCAHashAnnotationKey]) + + // ...the APIService CABundle is the rotated CA alone... + apiService = getAPIService() + require.Equal(t, secret.Data[install.OLMCAPEMKey], apiService.Spec.CABundle) + + // ...and the deployment's pod template is annotated with the rotated CA + // hash so the rollout serves the rotated serving cert. + dep = getDeployment() + require.Equal(t, rotatedCAHash, dep.Spec.Template.GetAnnotations()[install.OLMCAHashAnnotationKey]) +} + func TestIsReplacing(t *testing.T) { logrus.SetLevel(logrus.DebugLevel) namespace := "ns" diff --git a/test/e2e/webhook_e2e_test.go b/test/e2e/webhook_e2e_test.go index 5cb3b01c8f..f8a034dcab 100644 --- a/test/e2e/webhook_e2e_test.go +++ b/test/e2e/webhook_e2e_test.go @@ -520,6 +520,86 @@ var _ = Describe("CSVs with a Webhook", Label("Webhooks"), func() { newWebhookCABundle := actualWebhook.Webhooks[0].ClientConfig.CABundle Expect(newWebhookCABundle).ShouldNot(Equal(oldWebhookCABundle)) }) + It("Rotates P-256 key material to P-384", func() { + sideEffect := admissionregistrationv1.SideEffectClassNone + webhook := operatorsv1alpha1.WebhookDescription{ + GenerateName: webhookName, + Type: operatorsv1alpha1.ValidatingAdmissionWebhook, + DeploymentName: genName("webhook-dep-"), + ContainerPort: 443, + AdmissionReviewVersions: []string{"v1beta1", "v1"}, + SideEffects: &sideEffect, + } + + csv := createCSVWithWebhook(generatedNamespace.GetName(), webhook) + + var err error + cleanupCSV, err = createCSV(c, crc, csv, generatedNamespace.GetName(), false, false) + Expect(err).Should(BeNil()) + + _, err = fetchCSV(crc, generatedNamespace.GetName(), csv.Name, csvSucceededChecker) + Expect(err).Should(BeNil()) + + actualWebhook, err := getWebhookWithGenerateName(c, webhook.GenerateName) + Expect(err).Should(BeNil()) + + oldWebhookCABundle := actualWebhook.Webhooks[0].ClientConfig.CABundle + + By(`Get the deployment`) + dep, err := c.KubernetesInterface().AppsV1().Deployments(generatedNamespace.GetName()).Get(context.TODO(), csv.Spec.WebhookDefinitions[0].DeploymentName, metav1.GetOptions{}) + Expect(err).Should(BeNil()) + + //Store the ca sha annotation + oldCAAnnotation, ok := dep.Spec.Template.GetAnnotations()[install.OLMCAHashAnnotationKey] + Expect(ok).Should(BeTrue()) + + caSecret, err := c.KubernetesInterface().CoreV1().Secrets(generatedNamespace.GetName()).Get(context.TODO(), install.SecretName(install.ServiceName(dep.Name)), metav1.GetOptions{}) + Expect(err).Should(BeNil()) + + By(`Patch the Secret with valid P-256 key material, as an older version of OLM would have generated`) + hosts := install.HostnamesForService(install.ServiceName(dep.Name), generatedNamespace.GetName()) + caPEM, certPEM, privPEM := generateCertsOnCurve(elliptic.P256(), hosts, time.Now().Add(-time.Hour), time.Now().Add(10*365*24*time.Hour)) + Eventually(Apply(caSecret, func(caSecret *corev1.Secret) error { + caSecret.Data[install.OLMCAPEMKey] = caPEM + caSecret.Data["tls.crt"] = certPEM + caSecret.Data["tls.key"] = privPEM + return nil + })).Should(Succeed()) + + By(`Wait for OLM to rotate onto fresh P-384 key material`) + _, err = fetchCSV(crc, generatedNamespace.GetName(), csv.Name, func(csv *operatorsv1alpha1.ClusterServiceVersion) bool { + By(`Should roll the deployment onto the rotated CA`) + rolledDep, err := c.GetDeployment(generatedNamespace.GetName(), csv.Spec.WebhookDefinitions[0].DeploymentName) + if err != nil { + return false + } + newCAAnnotation, ok := rolledDep.Spec.Template.GetAnnotations()[install.OLMCAHashAnnotationKey] + if !ok || newCAAnnotation == oldCAAnnotation { + return false + } + + By(`Check for success`) + return csvSucceededChecker(csv) + }) + Expect(err).Should(BeNil()) + + By(`The Secret should hold P-384 key material`) + rotatedSecret, err := c.KubernetesInterface().CoreV1().Secrets(generatedNamespace.GetName()).Get(context.TODO(), caSecret.GetName(), metav1.GetOptions{}) + Expect(err).Should(BeNil()) + rotatedCA, err := certs.PEMToCert(rotatedSecret.Data[install.OLMCAPEMKey]) + Expect(err).Should(BeNil()) + Expect(certs.IsP384(rotatedCA)).Should(BeTrue()) + rotatedCert, err := certs.PEMToCert(rotatedSecret.Data["tls.crt"]) + Expect(err).Should(BeNil()) + Expect(certs.IsP384(rotatedCert)).Should(BeTrue()) + + By(`The webhook CABundle should be the rotated CA`) + actualWebhook, err = getWebhookWithGenerateName(c, webhook.GenerateName) + Expect(err).Should(BeNil()) + newWebhookCABundle := actualWebhook.Webhooks[0].ClientConfig.CABundle + Expect(newWebhookCABundle).ShouldNot(Equal(oldWebhookCABundle)) + Expect(newWebhookCABundle).Should(Equal(rotatedSecret.Data[install.OLMCAPEMKey])) + }) }) When("Installed in a Global OperatorGroup", func() { var cleanupCSV cleanupFunc @@ -1259,6 +1339,16 @@ func newV1CRD(plural string) apiextensionsv1.CustomResourceDefinition { } func generateExpiredCerts(hosts []string) ([]byte, []byte, []byte) { + // The curve must be P-384: rotation triggered by the key algorithm check + // in shouldRotateCerts runs before the freshness check, so P-256 fixtures + // would no longer exercise expiry handling. + return generateCertsOnCurve(elliptic.P384(), hosts, time.Now().Add(-5*time.Minute), time.Now().Add(-5*time.Minute)) +} + +// generateCertsOnCurve generates a CA and a serving pair signed by it on the +// given curve, for mimicking the key material generated by older versions of +// OLM (which used P-256). +func generateCertsOnCurve(curve elliptic.Curve, hosts []string, notBefore, notAfter time.Time) ([]byte, []byte, []byte) { caSerial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64)) Expect(err).Should(BeNil()) @@ -1268,14 +1358,14 @@ func generateExpiredCerts(hosts []string) ([]byte, []byte, []byte) { CommonName: fmt.Sprintf("olm-selfsigned-%x", caSerial), Organization: []string{install.Organization}, }, - NotBefore: time.Now().Add(-5 * time.Minute), - NotAfter: time.Now().Add(-5 * time.Minute), + NotBefore: notBefore, + NotAfter: notAfter, IsCA: true, KeyUsage: x509.KeyUsageCertSign, BasicConstraintsValid: true, } - caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + caKey, err := ecdsa.GenerateKey(curve, rand.Reader) Expect(err).Should(BeNil()) caRaw, err := x509.CreateCertificate(rand.Reader, caDetails, caDetails, &caKey.PublicKey, caKey) @@ -1299,14 +1389,14 @@ func generateExpiredCerts(hosts []string) ([]byte, []byte, []byte) { CommonName: hosts[0], Organization: []string{install.Organization}, }, - NotBefore: time.Now(), - NotAfter: time.Now(), + NotBefore: notBefore, + NotAfter: notAfter, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, DNSNames: hosts, } - privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + privateKey, err := ecdsa.GenerateKey(curve, rand.Reader) Expect(err).Should(BeNil()) publicKey := &privateKey.PublicKey