csr: add expirationSeconds field to control cert lifetime

This change updates the CSR API to add a new, optional field called
expirationSeconds.  This field is a request to the signer for the
maximum duration the client wishes the cert to have.  The signer is
free to ignore this request based on its own internal policy.  The
signers built-in to KCM will honor this field if it is not set to a
value greater than --cluster-signing-duration.  The minimum allowed
value for this field is 600 seconds (ten minutes).

This change will help enforce safer durations for certificates in
the Kube ecosystem and will help related projects such as
cert-manager with their migration to the Kube CSR API.

Future enhancements may update the Kubelet to take advantage of this
field when it is configured in a way that can tolerate shorter
certificate lifespans with regular rotation.

Signed-off-by: Monis Khan <mok@vmware.com>
This commit is contained in:
Monis Khan
2021-06-25 22:08:10 -04:00
parent 0dad7d1c47
commit cd91e59f7c
24 changed files with 1413 additions and 71 deletions

View File

@@ -44,7 +44,7 @@ type CertificateSigningRequest struct {
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// spec contains the certificate request, and is immutable after creation.
// Only the request, signerName, and usages fields can be set on creation.
// Only the request, signerName, expirationSeconds, and usages fields can be set on creation.
// Other fields are derived by Kubernetes and cannot be modified by users.
Spec CertificateSigningRequestSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"`
@@ -84,6 +84,30 @@ type CertificateSigningRequestSpec struct {
// 6. Whether or not requests for CA certificates are allowed.
SignerName string `json:"signerName" protobuf:"bytes,7,opt,name=signerName"`
// expirationSeconds is the requested duration of validity of the issued
// certificate. The certificate signer may issue a certificate with a different
// validity duration so a client must check the delta between the notBefore and
// and notAfter fields in the issued certificate to determine the actual duration.
//
// The v1.22+ in-tree implementations of the well-known Kubernetes signers will
// honor this field as long as the requested duration is not greater than the
// maximum duration they will honor per the --cluster-signing-duration CLI
// flag to the Kubernetes controller manager.
//
// Certificate signers may not honor this field for various reasons:
//
// 1. Old signer that is unaware of the field (such as the in-tree
// implementations prior to v1.22)
// 2. Signer whose configured maximum is shorter than the requested duration
// 3. Signer whose configured minimum is longer than the requested duration
//
// The minimum valid value for expirationSeconds is 600, i.e. 10 minutes.
//
// As of v1.22, this field is beta and is controlled via the CSRDuration feature gate.
//
// +optional
ExpirationSeconds *int32 `json:"expirationSeconds,omitempty" protobuf:"varint,8,opt,name=expirationSeconds"`
// usages specifies a set of key usages requested in the issued certificate.
//
// Requests for TLS client certificates typically request: "digital signature", "key encipherment", "client auth".

View File

@@ -36,18 +36,17 @@ type CertificateSigningRequest struct {
// +optional
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// The certificate request itself and any additional information.
// +optional
Spec CertificateSigningRequestSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
// spec contains the certificate request, and is immutable after creation.
// Only the request, signerName, expirationSeconds, and usages fields can be set on creation.
// Other fields are derived by Kubernetes and cannot be modified by users.
Spec CertificateSigningRequestSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"`
// Derived information about the request.
// +optional
Status CertificateSigningRequestStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}
// This information is immutable after the request is created. Only the Request
// and Usages fields can be set on creation, other fields are derived by
// Kubernetes and cannot be modified by users.
// CertificateSigningRequestSpec contains the certificate request.
type CertificateSigningRequestSpec struct {
// Base64-encoded PKCS#10 CSR data
// +listType=atomic
@@ -66,6 +65,30 @@ type CertificateSigningRequestSpec struct {
// +optional
SignerName *string `json:"signerName,omitempty" protobuf:"bytes,7,opt,name=signerName"`
// expirationSeconds is the requested duration of validity of the issued
// certificate. The certificate signer may issue a certificate with a different
// validity duration so a client must check the delta between the notBefore and
// and notAfter fields in the issued certificate to determine the actual duration.
//
// The v1.22+ in-tree implementations of the well-known Kubernetes signers will
// honor this field as long as the requested duration is not greater than the
// maximum duration they will honor per the --cluster-signing-duration CLI
// flag to the Kubernetes controller manager.
//
// Certificate signers may not honor this field for various reasons:
//
// 1. Old signer that is unaware of the field (such as the in-tree
// implementations prior to v1.22)
// 2. Signer whose configured maximum is shorter than the requested duration
// 3. Signer whose configured minimum is longer than the requested duration
//
// The minimum valid value for expirationSeconds is 600, i.e. 10 minutes.
//
// As of v1.22, this field is beta and is controlled via the CSRDuration feature gate.
//
// +optional
ExpirationSeconds *int32 `json:"expirationSeconds,omitempty" protobuf:"varint,8,opt,name=expirationSeconds"`
// allowedUsages specifies a set of usage contexts the key will be
// valid for.
// See: https://tools.ietf.org/html/rfc5280#section-4.2.1.3

View File

@@ -88,6 +88,11 @@ type Config struct {
// SignerName is the name of the certificate signer that should sign certificates
// generated by the manager.
SignerName string
// RequestedCertificateLifetime is the requested lifetime length for certificates generated by the manager.
// Optional.
// This will set the spec.expirationSeconds field on the CSR. Controlling the lifetime of
// the issued certificate is not guaranteed as the signer may choose to ignore the request.
RequestedCertificateLifetime *time.Duration
// Usages is the types of usages that certificates generated by the manager
// can be used for.
Usages []certificates.KeyUsage
@@ -184,10 +189,11 @@ type manager struct {
lastRequestCancel context.CancelFunc
lastRequest *x509.CertificateRequest
dynamicTemplate bool
signerName string
usages []certificates.KeyUsage
forceRotation bool
dynamicTemplate bool
signerName string
requestedCertificateLifetime *time.Duration
usages []certificates.KeyUsage
forceRotation bool
certStore Store
@@ -230,18 +236,19 @@ func NewManager(config *Config) (Manager, error) {
}
m := manager{
stopCh: make(chan struct{}),
clientsetFn: config.ClientsetFn,
getTemplate: getTemplate,
dynamicTemplate: config.GetTemplate != nil,
signerName: config.SignerName,
usages: config.Usages,
certStore: config.CertificateStore,
cert: cert,
forceRotation: forceRotation,
certificateRotation: config.CertificateRotation,
certificateRenewFailure: config.CertificateRenewFailure,
now: time.Now,
stopCh: make(chan struct{}),
clientsetFn: config.ClientsetFn,
getTemplate: getTemplate,
dynamicTemplate: config.GetTemplate != nil,
signerName: config.SignerName,
requestedCertificateLifetime: config.RequestedCertificateLifetime,
usages: config.Usages,
certStore: config.CertificateStore,
cert: cert,
forceRotation: forceRotation,
certificateRotation: config.CertificateRotation,
certificateRenewFailure: config.CertificateRenewFailure,
now: time.Now,
}
name := config.Name
@@ -459,7 +466,7 @@ func (m *manager) rotateCerts() (bool, error) {
// Call the Certificate Signing Request API to get a certificate for the
// new private key.
reqName, reqUID, err := csr.RequestCertificate(clientSet, csrPEM, "", m.signerName, m.usages, privateKey)
reqName, reqUID, err := csr.RequestCertificate(clientSet, csrPEM, "", m.signerName, m.requestedCertificateLifetime, m.usages, privateKey)
if err != nil {
utilruntime.HandleError(fmt.Errorf("%s: Failed while requesting a signed certificate from the control plane: %v", m.name, err))
if m.certificateRenewFailure != nil {

View File

@@ -25,8 +25,6 @@ import (
"reflect"
"time"
"k8s.io/klog/v2"
certificatesv1 "k8s.io/api/certificates/v1"
certificatesv1beta1 "k8s.io/api/certificates/v1beta1"
"k8s.io/apimachinery/pkg/api/errors"
@@ -41,12 +39,16 @@ import (
"k8s.io/client-go/tools/cache"
watchtools "k8s.io/client-go/tools/watch"
certutil "k8s.io/client-go/util/cert"
"k8s.io/klog/v2"
"k8s.io/utils/pointer"
)
// RequestCertificate will either use an existing (if this process has run
// before but not to completion) or create a certificate signing request using the
// PEM encoded CSR and send it to API server.
func RequestCertificate(client clientset.Interface, csrData []byte, name string, signerName string, usages []certificatesv1.KeyUsage, privateKey interface{}) (reqName string, reqUID types.UID, err error) {
// PEM encoded CSR and send it to API server. An optional requestedDuration may be passed
// to set the spec.expirationSeconds field on the CSR to control the lifetime of the issued
// certificate. This is not guaranteed as the signer may choose to ignore the request.
func RequestCertificate(client clientset.Interface, csrData []byte, name, signerName string, requestedDuration *time.Duration, usages []certificatesv1.KeyUsage, privateKey interface{}) (reqName string, reqUID types.UID, err error) {
csr := &certificatesv1.CertificateSigningRequest{
// Username, UID, Groups will be injected by API server.
TypeMeta: metav1.TypeMeta{Kind: "CertificateSigningRequest"},
@@ -62,6 +64,9 @@ func RequestCertificate(client clientset.Interface, csrData []byte, name string,
if len(csr.Name) == 0 {
csr.GenerateName = "csr-"
}
if requestedDuration != nil {
csr.Spec.ExpirationSeconds = DurationToExpirationSeconds(*requestedDuration)
}
reqName, reqUID, err = create(client, csr)
switch {
@@ -85,6 +90,14 @@ func RequestCertificate(client clientset.Interface, csrData []byte, name string,
}
}
func DurationToExpirationSeconds(duration time.Duration) *int32 {
return pointer.Int32(int32(duration / time.Second))
}
func ExpirationSecondsToDuration(expirationSeconds int32) time.Duration {
return time.Duration(expirationSeconds) * time.Second
}
func get(client clientset.Interface, name string) (*certificatesv1.CertificateSigningRequest, error) {
v1req, v1err := client.CertificatesV1().CertificateSigningRequests().Get(context.TODO(), name, metav1.GetOptions{})
if v1err == nil || !apierrors.IsNotFound(v1err) {

View File

@@ -193,8 +193,8 @@ type CSRSigningControllerConfiguration struct {
// legacyUnknownSignerConfiguration holds the certificate and key used to issue certificates for the kubernetes.io/legacy-unknown
LegacyUnknownSignerConfiguration CSRSigningConfiguration
// clusterSigningDuration is the length of duration signed certificates
// will be given.
// clusterSigningDuration is the max length of duration signed certificates will be given.
// Individual CSRs may request shorter certs by setting spec.expirationSeconds.
ClusterSigningDuration metav1.Duration
}

View File

@@ -33,7 +33,6 @@ import (
"unicode"
"github.com/fatih/camelcase"
"k8s.io/apimachinery/pkg/runtime"
appsv1 "k8s.io/api/apps/v1"
autoscalingv1 "k8s.io/api/autoscaling/v1"
@@ -60,6 +59,7 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/duration"
@@ -72,6 +72,7 @@ import (
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/reference"
utilcsr "k8s.io/client-go/util/certificate/csr"
"k8s.io/klog/v2"
"k8s.io/kubectl/pkg/scheme"
"k8s.io/kubectl/pkg/util/certificate"
@@ -3690,12 +3691,13 @@ type CertificateSigningRequestDescriber struct {
func (p *CertificateSigningRequestDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {
var (
crBytes []byte
metadata metav1.ObjectMeta
status string
signerName string
username string
events *corev1.EventList
crBytes []byte
metadata metav1.ObjectMeta
status string
signerName string
expirationSeconds *int32
username string
events *corev1.EventList
)
if csr, err := p.client.CertificatesV1().CertificateSigningRequests().Get(context.TODO(), name, metav1.GetOptions{}); err == nil {
@@ -3707,6 +3709,7 @@ func (p *CertificateSigningRequestDescriber) Describe(namespace, name string, de
}
status = extractCSRStatus(conditionTypes, csr.Status.Certificate)
signerName = csr.Spec.SignerName
expirationSeconds = csr.Spec.ExpirationSeconds
username = csr.Spec.Username
if describerSettings.ShowEvents {
events, _ = searchEvents(p.client.CoreV1(), csr, describerSettings.ChunkSize)
@@ -3722,6 +3725,7 @@ func (p *CertificateSigningRequestDescriber) Describe(namespace, name string, de
if csr.Spec.SignerName != nil {
signerName = *csr.Spec.SignerName
}
expirationSeconds = csr.Spec.ExpirationSeconds
username = csr.Spec.Username
if describerSettings.ShowEvents {
events, _ = searchEvents(p.client.CoreV1(), csr, describerSettings.ChunkSize)
@@ -3735,10 +3739,10 @@ func (p *CertificateSigningRequestDescriber) Describe(namespace, name string, de
return "", fmt.Errorf("Error parsing CSR: %v", err)
}
return describeCertificateSigningRequest(metadata, signerName, username, cr, status, events)
return describeCertificateSigningRequest(metadata, signerName, expirationSeconds, username, cr, status, events)
}
func describeCertificateSigningRequest(csr metav1.ObjectMeta, signerName string, username string, cr *x509.CertificateRequest, status string, events *corev1.EventList) (string, error) {
func describeCertificateSigningRequest(csr metav1.ObjectMeta, signerName string, expirationSeconds *int32, username string, cr *x509.CertificateRequest, status string, events *corev1.EventList) (string, error) {
printListHelper := func(w PrefixWriter, prefix, name string, values []string) {
if len(values) == 0 {
return
@@ -3758,6 +3762,9 @@ func describeCertificateSigningRequest(csr metav1.ObjectMeta, signerName string,
if len(signerName) > 0 {
w.Write(LEVEL_0, "Signer:\t%s\n", signerName)
}
if expirationSeconds != nil {
w.Write(LEVEL_0, "Requested Duration:\t%s\n", duration.HumanDuration(utilcsr.ExpirationSecondsToDuration(*expirationSeconds)))
}
w.Write(LEVEL_0, "Status:\t%s\n", status)
w.Write(LEVEL_0, "Subject:\n")