Debian Codegraph @

util/certificate/csr/csr.go

raw
1 /*
2 Copyright 2016 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package csr
18
19 import (
20 "context"
21 "crypto"
22 "crypto/x509"
23 "encoding/pem"
24 "fmt"
25 "reflect"
26 "time"
27
28 certificatesv1 "k8s.io/api/certificates/v1"
29 certificatesv1beta1 "k8s.io/api/certificates/v1beta1"
30 apierrors "k8s.io/apimachinery/pkg/api/errors"
31 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
32 "k8s.io/apimachinery/pkg/fields"
33 "k8s.io/apimachinery/pkg/runtime"
34 "k8s.io/apimachinery/pkg/types"
35 "k8s.io/apimachinery/pkg/util/wait"
36 "k8s.io/apimachinery/pkg/watch"
37 clientset "k8s.io/client-go/kubernetes"
38 "k8s.io/client-go/tools/cache"
39 watchtools "k8s.io/client-go/tools/watch"
40 certutil "k8s.io/client-go/util/cert"
41 "k8s.io/klog/v2"
42 "k8s.io/utils/pointer"
43 )
44
45 // RequestCertificate will either use an existing (if this process has run
46 // before but not to completion) or create a certificate signing request using the
47 // PEM encoded CSR and send it to API server. An optional requestedDuration may be passed
48 // to set the spec.expirationSeconds field on the CSR to control the lifetime of the issued
49 // certificate. This is not guaranteed as the signer may choose to ignore the request.
50 //
51 // Deprecated: use RequestCertificateWithContext instead.
52 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) {
53 return RequestCertificateWithContext(context.Background(), client, csrData, name, signerName, requestedDuration, usages, privateKey)
54 }
55
56 // RequestCertificateWithContext will either use an existing (if this process has run
57 // before but not to completion) or create a certificate signing request using the
58 // PEM encoded CSR and send it to API server. An optional requestedDuration may be passed
59 // to set the spec.expirationSeconds field on the CSR to control the lifetime of the issued
60 // certificate. This is not guaranteed as the signer may choose to ignore the request.
61 func RequestCertificateWithContext(ctx context.Context, client clientset.Interface, csrData []byte, name, signerName string, requestedDuration *time.Duration, usages []certificatesv1.KeyUsage, privateKey interface{}) (reqName string, reqUID types.UID, err error) {
62 csr := &certificatesv1.CertificateSigningRequest{
63 // Username, UID, Groups will be injected by API server.
64 TypeMeta: metav1.TypeMeta{Kind: "CertificateSigningRequest"},
65 ObjectMeta: metav1.ObjectMeta{
66 Name: name,
67 },
68 Spec: certificatesv1.CertificateSigningRequestSpec{
69 Request: csrData,
70 Usages: usages,
71 SignerName: signerName,
72 },
73 }
74 if len(csr.Name) == 0 {
75 csr.GenerateName = "csr-"
76 }
77 if requestedDuration != nil {
78 csr.Spec.ExpirationSeconds = DurationToExpirationSeconds(*requestedDuration)
79 }
80
81 reqName, reqUID, err = create(ctx, client, csr)
82 switch {
83 case err == nil:
84 return reqName, reqUID, err
85
86 case apierrors.IsAlreadyExists(err) && len(name) > 0:
87 logger := klog.FromContext(ctx)
88 logger.Info("csr for this node already exists, reusing")
89 req, err := get(ctx, client, name)
90 if err != nil {
91 return "", "", formatError("cannot retrieve certificate signing request: %v", err)
92 }
93 if err := ensureCompatible(req, csr, privateKey); err != nil {
94 return "", "", fmt.Errorf("retrieved csr is not compatible: %v", err)
95 }
96 logger.Info("csr for this node is still valid")
97 return req.Name, req.UID, nil
98
99 default:
100 return "", "", formatError("cannot create certificate signing request: %v", err)
101 }
102 }
103
104 func DurationToExpirationSeconds(duration time.Duration) *int32 {
105 return pointer.Int32(int32(duration / time.Second))
106 }
107
108 func ExpirationSecondsToDuration(expirationSeconds int32) time.Duration {
109 return time.Duration(expirationSeconds) * time.Second
110 }
111
112 func get(ctx context.Context, client clientset.Interface, name string) (*certificatesv1.CertificateSigningRequest, error) {
113 v1req, v1err := client.CertificatesV1().CertificateSigningRequests().Get(ctx, name, metav1.GetOptions{})
114 if v1err == nil || !apierrors.IsNotFound(v1err) {
115 return v1req, v1err
116 }
117
118 v1beta1req, v1beta1err := client.CertificatesV1beta1().CertificateSigningRequests().Get(ctx, name, metav1.GetOptions{})
119 if v1beta1err != nil {
120 return nil, v1beta1err
121 }
122
123 v1req = &certificatesv1.CertificateSigningRequest{
124 ObjectMeta: v1beta1req.ObjectMeta,
125 Spec: certificatesv1.CertificateSigningRequestSpec{
126 Request: v1beta1req.Spec.Request,
127 },
128 }
129 if v1beta1req.Spec.SignerName != nil {
130 v1req.Spec.SignerName = *v1beta1req.Spec.SignerName
131 }
132 for _, usage := range v1beta1req.Spec.Usages {
133 v1req.Spec.Usages = append(v1req.Spec.Usages, certificatesv1.KeyUsage(usage))
134 }
135 return v1req, nil
136 }
137
138 func create(ctx context.Context, client clientset.Interface, csr *certificatesv1.CertificateSigningRequest) (reqName string, reqUID types.UID, err error) {
139 // only attempt a create via v1 if we specified signerName and usages and are not using the legacy unknown signerName
140 if len(csr.Spec.Usages) > 0 && len(csr.Spec.SignerName) > 0 && csr.Spec.SignerName != "kubernetes.io/legacy-unknown" {
141 v1req, v1err := client.CertificatesV1().CertificateSigningRequests().Create(ctx, csr, metav1.CreateOptions{})
142 switch {
143 case v1err != nil && apierrors.IsNotFound(v1err):
144 // v1 CSR API was not found, continue to try v1beta1
145
146 case v1err != nil:
147 // other creation error
148 return "", "", v1err
149
150 default:
151 // success
152 return v1req.Name, v1req.UID, v1err
153 }
154 }
155
156 // convert relevant bits to v1beta1
157 v1beta1csr := &certificatesv1beta1.CertificateSigningRequest{
158 ObjectMeta: csr.ObjectMeta,
159 Spec: certificatesv1beta1.CertificateSigningRequestSpec{
160 SignerName: &csr.Spec.SignerName,
161 Request: csr.Spec.Request,
162 },
163 }
164 for _, usage := range csr.Spec.Usages {
165 v1beta1csr.Spec.Usages = append(v1beta1csr.Spec.Usages, certificatesv1beta1.KeyUsage(usage))
166 }
167
168 // create v1beta1
169 v1beta1req, v1beta1err := client.CertificatesV1beta1().CertificateSigningRequests().Create(ctx, v1beta1csr, metav1.CreateOptions{})
170 if v1beta1err != nil {
171 return "", "", v1beta1err
172 }
173 return v1beta1req.Name, v1beta1req.UID, nil
174 }
175
176 // WaitForCertificate waits for a certificate to be issued until timeout, or returns an error.
177 func WaitForCertificate(ctx context.Context, client clientset.Interface, reqName string, reqUID types.UID) (certData []byte, err error) {
178 fieldSelector := fields.OneTermEqualSelector("metadata.name", reqName).String()
179 logger := klog.FromContext(ctx)
180
181 var lw *cache.ListWatch
182 var obj runtime.Object
183 for {
184 // see if the v1 API is available
185 if _, err := client.CertificatesV1().CertificateSigningRequests().List(ctx, metav1.ListOptions{FieldSelector: fieldSelector}); err == nil {
186 // watch v1 objects
187 obj = &certificatesv1.CertificateSigningRequest{}
188 lw = &cache.ListWatch{
189 ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
190 options.FieldSelector = fieldSelector
191 return client.CertificatesV1().CertificateSigningRequests().List(ctx, options)
192 },
193 WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
194 options.FieldSelector = fieldSelector
195 return client.CertificatesV1().CertificateSigningRequests().Watch(ctx, options)
196 },
197 }
198 break
199 } else {
200 logger.V(2).Info("Error fetching v1 certificate signing request", "err", err)
201 }
202
203 // return if we've timed out
204 if err := ctx.Err(); err != nil {
205 return nil, wait.ErrWaitTimeout
206 }
207
208 // see if the v1beta1 API is available
209 if _, err := client.CertificatesV1beta1().CertificateSigningRequests().List(ctx, metav1.ListOptions{FieldSelector: fieldSelector}); err == nil {
210 // watch v1beta1 objects
211 obj = &certificatesv1beta1.CertificateSigningRequest{}
212 lw = &cache.ListWatch{
213 ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
214 options.FieldSelector = fieldSelector
215 return client.CertificatesV1beta1().CertificateSigningRequests().List(ctx, options)
216 },
217 WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
218 options.FieldSelector = fieldSelector
219 return client.CertificatesV1beta1().CertificateSigningRequests().Watch(ctx, options)
220 },
221 }
222 break
223 } else {
224 logger.V(2).Info("Error fetching v1beta1 certificate signing request", "err", err)
225 }
226
227 // return if we've timed out
228 if err := ctx.Err(); err != nil {
229 return nil, wait.ErrWaitTimeout
230 }
231
232 // wait and try again
233 time.Sleep(time.Second)
234 }
235
236 var issuedCertificate []byte
237 _, err = watchtools.UntilWithSync(
238 ctx,
239 lw,
240 obj,
241 nil,
242 func(event watch.Event) (bool, error) {
243 switch event.Type {
244 case watch.Modified, watch.Added:
245 case watch.Deleted:
246 return false, fmt.Errorf("csr %q was deleted", reqName)
247 default:
248 return false, nil
249 }
250
251 switch csr := event.Object.(type) {
252 case *certificatesv1.CertificateSigningRequest:
253 if csr.UID != reqUID {
254 return false, fmt.Errorf("csr %q changed UIDs", csr.Name)
255 }
256 approved := false
257 for _, c := range csr.Status.Conditions {
258 if c.Type == certificatesv1.CertificateDenied {
259 return false, fmt.Errorf("certificate signing request is denied, reason: %v, message: %v", c.Reason, c.Message)
260 }
261 if c.Type == certificatesv1.CertificateFailed {
262 return false, fmt.Errorf("certificate signing request failed, reason: %v, message: %v", c.Reason, c.Message)
263 }
264 if c.Type == certificatesv1.CertificateApproved {
265 approved = true
266 }
267 }
268 if approved {
269 if len(csr.Status.Certificate) > 0 {
270 logger.V(2).Info("Certificate signing request is issued", "csr", klog.KObj(csr))
271 issuedCertificate = csr.Status.Certificate
272 return true, nil
273 }
274 logger.V(2).Info("Certificate signing request is approved, waiting to be issued", "csr", klog.KObj(csr))
275 }
276
277 case *certificatesv1beta1.CertificateSigningRequest:
278 if csr.UID != reqUID {
279 return false, fmt.Errorf("csr %q changed UIDs", csr.Name)
280 }
281 approved := false
282 for _, c := range csr.Status.Conditions {
283 if c.Type == certificatesv1beta1.CertificateDenied {
284 return false, fmt.Errorf("certificate signing request is denied, reason: %v, message: %v", c.Reason, c.Message)
285 }
286 if c.Type == certificatesv1beta1.CertificateFailed {
287 return false, fmt.Errorf("certificate signing request failed, reason: %v, message: %v", c.Reason, c.Message)
288 }
289 if c.Type == certificatesv1beta1.CertificateApproved {
290 approved = true
291 }
292 }
293 if approved {
294 if len(csr.Status.Certificate) > 0 {
295 logger.V(2).Info("Certificate signing request is issued", "csr", klog.KObj(csr))
296 issuedCertificate = csr.Status.Certificate
297 return true, nil
298 }
299 logger.V(2).Info("Certificate signing request is approved, waiting to be issued", "csr", klog.KObj(csr))
300 }
301
302 default:
303 return false, fmt.Errorf("unexpected type received: %T", event.Object)
304 }
305
306 return false, nil
307 },
308 )
309 if err == wait.ErrWaitTimeout {
310 return nil, wait.ErrWaitTimeout
311 }
312 if err != nil {
313 return nil, formatError("cannot watch on the certificate signing request: %v", err)
314 }
315
316 return issuedCertificate, nil
317 }
318
319 // ensureCompatible ensures that a CSR object is compatible with an original CSR
320 func ensureCompatible(new, orig *certificatesv1.CertificateSigningRequest, privateKey interface{}) error {
321 newCSR, err := parseCSR(new.Spec.Request)
322 if err != nil {
323 return fmt.Errorf("unable to parse new csr: %v", err)
324 }
325 origCSR, err := parseCSR(orig.Spec.Request)
326 if err != nil {
327 return fmt.Errorf("unable to parse original csr: %v", err)
328 }
329 if !reflect.DeepEqual(newCSR.Subject, origCSR.Subject) {
330 return fmt.Errorf("csr subjects differ: new: %#v, orig: %#v", newCSR.Subject, origCSR.Subject)
331 }
332 if len(new.Spec.SignerName) > 0 && len(orig.Spec.SignerName) > 0 && new.Spec.SignerName != orig.Spec.SignerName {
333 return fmt.Errorf("csr signerNames differ: new %q, orig: %q", new.Spec.SignerName, orig.Spec.SignerName)
334 }
335 signer, ok := privateKey.(crypto.Signer)
336 if !ok {
337 return fmt.Errorf("privateKey is not a signer")
338 }
339 newCSR.PublicKey = signer.Public()
340 if err := newCSR.CheckSignature(); err != nil {
341 return fmt.Errorf("error validating signature new CSR against old key: %v", err)
342 }
343 if len(new.Status.Certificate) > 0 {
344 certs, err := certutil.ParseCertsPEM(new.Status.Certificate)
345 if err != nil {
346 return fmt.Errorf("error parsing signed certificate for CSR: %v", err)
347 }
348 now := time.Now()
349 for _, cert := range certs {
350 if now.After(cert.NotAfter) {
351 return fmt.Errorf("one of the certificates for the CSR has expired: %s", cert.NotAfter)
352 }
353 }
354 }
355 return nil
356 }
357
358 // formatError preserves the type of an API message but alters the message. Expects
359 // a single argument format string, and returns the wrapped error.
360 func formatError(format string, err error) error {
361 if s, ok := err.(apierrors.APIStatus); ok {
362 se := &apierrors.StatusError{ErrStatus: s.Status()}
363 se.ErrStatus.Message = fmt.Sprintf(format, se.ErrStatus.Message)
364 return se
365 }
366 return fmt.Errorf(format, err)
367 }
368
369 // parseCSR extracts the CSR from the API object and decodes it.
370 func parseCSR(pemData []byte) (*x509.CertificateRequest, error) {
371 // extract PEM from request object
372 block, _ := pem.Decode(pemData)
373 if block == nil || block.Type != "CERTIFICATE REQUEST" {
374 return nil, fmt.Errorf("PEM block type must be CERTIFICATE REQUEST")
375 }
376 return x509.ParseCertificateRequest(block.Bytes)
377 }