Debian Codegraph @

command/ca/renew.go

raw symbols SCIP
1 package ca
2
3 import (
4 "crypto"
5 "crypto/tls"
6 "crypto/x509"
7 "encoding/pem"
8 "io/ioutil"
9 "log"
10 "math/rand"
11 "net/http"
12 "os"
13 "os/exec"
14 "os/signal"
15 "strconv"
16 "strings"
17 "syscall"
18 "time"
19
20 "github.com/pkg/errors"
21 "github.com/smallstep/certificates/api"
22 "github.com/smallstep/certificates/ca"
23 "github.com/smallstep/certificates/pki"
24 "github.com/smallstep/cli/command"
25 "github.com/smallstep/cli/crypto/pemutil"
26 "github.com/smallstep/cli/crypto/x509util"
27 "github.com/smallstep/cli/errs"
28 "github.com/smallstep/cli/flags"
29 "github.com/smallstep/cli/ui"
30 "github.com/smallstep/cli/utils"
31 "github.com/smallstep/cli/utils/cautils"
32 "github.com/smallstep/cli/utils/sysutils"
33 "github.com/urfave/cli"
34 )
35
36 func renewCertificateCommand() cli.Command {
37 return cli.Command{
38 Name: "renew",
39 Action: command.ActionFunc(renewCertificateAction),
40 Usage: "renew a valid certificate",
41 UsageText: `**step ca renew** <crt-file> <key-file>
42 [**--ca-url**=<uri>] [**--root**=<path>] [**--password-file**=<path>]
43 [**--out**=<path>] [**--expires-in**=<duration>] [**--force**]
44 [**--expires-in**=<duration>] [**--pid**=<int>] [**--pid-file**=<path>]
45 [**--signal**=<int>] [**--exec**=<string>] [**--daemon**]
46 [**--renew-period**=<duration>]`,
47 Description: `
48 **step ca renew** command renews the given certificate (with a request to the
49 certificate authority) and writes the new certificate to disk - either overwriting
50 <crt-file> or using a new file when the **--out**=<file> flag is used.
51
52 With the **--daemon** flag the command will periodically update the given
53 certificate. By default, it will renew the certificate before 2/3 of the validity
54 period of the certificate has elapsed. A random jitter is used to avoid multiple
55 instances running at the same time. The amount of time between renewal and
56 certificate expiration can be configured using the **--expires-in** flag, or a
57 fixed period can be set with the **--renew-period** flag.
58
59 The **--daemon** flag can be combined with **--pid**, **--signal**, or **--exec**
60 to provide certificate reloads on your services.
61
62 ## POSITIONAL ARGUMENTS
63
64 <crt-file>
65 : The certificate in PEM format that we want to renew.
66
67 <key-file>
68 : They key file of the certificate.
69
70 ## EXAMPLES
71
72 Renew a certificate with the configured CA:
73 '''
74 $ step ca renew internal.crt internal.key
75 Would you like to overwrite internal.crt [Y/n]: y
76 '''
77
78 Renew a certificate without overwriting the previous certificate:
79 '''
80 $ step ca renew --out renewed.crt internal.crt internal.key
81 '''
82
83 Renew a certificate forcing the overwrite of the previous certificate:
84 '''
85 $ step ca renew --force internal.crt internal.key
86 '''
87
88 Renew a certificate providing the <--ca-url> and <--root> flags:
89 '''
90 $ step ca renew --ca-url https://ca.smallstep.com:9000 \
91 --root /path/to/root_ca.crt internal.crt internal.key
92 Would you like to overwrite internal.crt [Y/n]: y
93 '''
94
95 Renew skipped because it was too early:
96 '''
97 $ step ca renew --expires-in 8h internal.crt internal.key
98 certificate not renewed: expires in 10h52m5s
99 '''
100
101 Renew the certificate before 2/3 of the validity has passed:
102 '''
103 $ step ca renew --daemon internal.crt internal.key
104 '''
105
106 Renew the certificate before 8 hours and 30m of the expiration time:
107 '''
108 $ step ca renew --daemon --expires-in 8h30m internal.crt internal.key
109 '''
110
111 Renew the certificate every 16h:
112 '''
113 $ step ca renew --daemon --renew-period 16h internal.crt internal.key
114 '''
115
116 Renew the certificate and reload nginx:
117 '''
118 $ step ca renew --daemon --exec "nginx -s reload" internal.crt internal.key
119 '''
120
121 Renew the certificate and convert it to DER:
122 '''
123 $ step ca renew --daemon --renew-period 16h \
124 --exec "step certificate format --force --out internal.der internal.crt" \
125 internal.crt internal.key
126 '''
127
128 Renew a certificate using the offline mode, requires the configuration
129 files, certificates, and keys created with **step ca init**:
130 '''
131 $ step ca renew --offline internal.crt internal.key
132 '''`,
133 Flags: []cli.Flag{
134 flags.CaConfig,
135 flags.CaURL,
136 flags.Force,
137 flags.Offline,
138 flags.PasswordFile,
139 flags.Root,
140 cli.StringFlag{
141 Name: "out,output-file",
142 Usage: "The new certificate <file> path. Defaults to overwriting the <crt-file> positional argument",
143 },
144 cli.StringFlag{
145 Name: "expires-in",
146 Usage: `The amount of time remaining before certificate expiration,
147 at which point a renewal should be attempted. The certificate renewal will not
148 be performed if the time to expiration is greater than the **--expires-in** value.
149 A random jitter (duration/20) will be added to avoid multiple services hitting the
150 renew endpoint at the same time. The <duration> is a sequence of decimal numbers,
151 each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".
152 Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".`,
153 },
154 cli.IntFlag{
155 Name: "pid",
156 Usage: `The process id to signal after the certificate has been renewed. By default the
157 the SIGHUP (1) signal will be used, but this can be configured with the **--signal**
158 flag.`,
159 },
160 cli.StringFlag{
161 Name: "pid-file",
162 Usage: `The <path> from which to read the process id that will be signaled after the certificate
163 has been renewed. By default the the SIGHUP (1) signal will be used, but this can be configured with the **--signal**
164 flag.`,
165 },
166 cli.IntFlag{
167 Name: "signal",
168 Usage: `The signal <number> to send to the selected PID, so it can reload the
169 configuration and load the new certificate. Default value is SIGHUP (1)`,
170 Value: int(syscall.SIGHUP),
171 },
172 cli.StringFlag{
173 Name: "exec",
174 Usage: "The <command> to run after the certificate has been renewed.",
175 },
176 cli.BoolFlag{
177 Name: "daemon",
178 Usage: `Run the renew command as a daemon, renewing and overwriting the certificate
179 periodically. By default the daemon will renew a certificate before 2/3 of the
180 time to expiration has elapsed. The period can be configured using the
181 **--renew-period** or **--expires-in** flags.`,
182 },
183 cli.StringFlag{
184 Name: "renew-period",
185 Usage: `The period with which to schedule renewals of the certificate in daemon mode.
186 Requires the **--daemon** flag. The <duration> is a sequence of decimal numbers,
187 each with optional fraction and a unit suffix, such as "300ms", "1.5h", or "2h45m".
188 Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".`,
189 },
190 },
191 }
192 }
193
194 func renewCertificateAction(ctx *cli.Context) error {
195 err := errs.NumberOfArguments(ctx, 2)
196 if err != nil {
197 return err
198 }
199
200 args := ctx.Args()
201 certFile := args.Get(0)
202 keyFile := args.Get(1)
203 passFile := ctx.String("password-file")
204 isDaemon := ctx.Bool("daemon")
205 execCmd := ctx.String("exec")
206
207 outFile := ctx.String("out")
208 if len(outFile) == 0 {
209 outFile = certFile
210 }
211
212 rootFile := ctx.String("root")
213 if len(rootFile) == 0 {
214 rootFile = pki.GetRootCAPath()
215 }
216
217 caURL, err := flags.ParseCaURL(ctx)
218 if err != nil {
219 return err
220 }
221
222 var expiresIn, renewPeriod time.Duration
223 if s := ctx.String("expires-in"); len(s) > 0 {
224 if expiresIn, err = time.ParseDuration(s); err != nil {
225 return errs.InvalidFlagValue(ctx, "expires-in", s, "")
226 }
227 }
228 if s := ctx.String("renew-period"); len(s) > 0 {
229 if renewPeriod, err = time.ParseDuration(s); err != nil {
230 return errs.InvalidFlagValue(ctx, "renew-period", s, "")
231 }
232 }
233 if expiresIn > 0 && renewPeriod > 0 {
234 return errs.IncompatibleFlagWithFlag(ctx, "expires-in", "renew-period")
235 }
236 if renewPeriod > 0 && !isDaemon {
237 return errs.RequiredWithFlag(ctx, "renew-period", "daemon")
238 }
239
240 if ctx.IsSet("pid") && ctx.IsSet("pid-file") {
241 return errs.MutuallyExclusiveFlags(ctx, "pid", "pid-file")
242 }
243 pid := ctx.Int("pid")
244 if ctx.IsSet("pid") && pid <= 0 {
245 return errs.InvalidFlagValue(ctx, "pid", strconv.Itoa(pid), "")
246 }
247
248 pidFile := ctx.String("pid-file")
249 if len(pidFile) > 0 {
250 pidB, err := ioutil.ReadFile(pidFile)
251 if err != nil {
252 return errs.FileError(err, pidFile)
253 }
254 pid, err = strconv.Atoi(strings.TrimSpace(string(pidB)))
255 if err != nil {
256 return errs.Wrap(err, "error converting %s to integer process id", pidB)
257 }
258 if pid <= 0 {
259 return errs.InvalidFlagValue(ctx, "pid-file", strconv.Itoa(pid), "")
260 }
261 }
262
263 signum := ctx.Int("signal")
264 if ctx.IsSet("signal") && signum <= 0 {
265 return errs.InvalidFlagValue(ctx, "signal", strconv.Itoa(signum), "")
266 }
267
268 cert, err := tlsLoadX509KeyPair(certFile, keyFile, passFile)
269 if err != nil {
270 return err
271 }
272 leaf := cert.Leaf
273
274 if leaf.NotAfter.Before(time.Now()) {
275 return errors.New("cannot renew an expired certificate")
276 }
277 cvp := leaf.NotAfter.Sub(leaf.NotBefore)
278 if renewPeriod > 0 && renewPeriod >= cvp {
279 return errors.Errorf("flag '--renew-period' must be within (lower than) the certificate "+
280 "validity period; renew-period=%v, cert-validity-period=%v", renewPeriod, cvp)
281 }
282
283 renewer, err := newRenewer(ctx, caURL, cert, rootFile)
284 if err != nil {
285 return err
286 }
287
288 afterRenew := getAfterRenewFunc(pid, signum, execCmd)
289 if isDaemon {
290 // Force is always enabled when daemon mode is used
291 ctx.Set("force", "true")
292 next := nextRenewDuration(leaf, expiresIn, renewPeriod)
293 return renewer.Daemon(outFile, next, expiresIn, renewPeriod, afterRenew)
294 }
295
296 // Do not renew if (cert.notAfter - now) > (expiresIn + jitter)
297 if expiresIn > 0 {
298 jitter := rand.Int63n(int64(expiresIn / 20))
299 if d := time.Until(leaf.NotAfter); d > expiresIn+time.Duration(jitter) {
300 ui.Printf("certificate not renewed: expires in %s\n", d.Round(time.Second))
301 return nil
302 }
303 }
304
305 if _, err := renewer.Renew(outFile); err != nil {
306 return err
307 }
308
309 ui.Printf("Your certificate has been saved in %s.\n", outFile)
310 return afterRenew()
311 }
312
313 func nextRenewDuration(leaf *x509.Certificate, expiresIn, renewPeriod time.Duration) time.Duration {
314 if renewPeriod > 0 {
315 // Renew now if it will be expired in renewPeriod
316 if (time.Until(leaf.NotAfter) - renewPeriod) <= 0 {
317 return 0
318 }
319 return renewPeriod
320 }
321
322 period := leaf.NotAfter.Sub(leaf.NotBefore)
323 if expiresIn == 0 {
324 expiresIn = period / 3
325 }
326
327 d := time.Until(leaf.NotAfter) - expiresIn
328 n := rand.Int63n(int64(period / 20))
329 d -= time.Duration(n)
330 if d < 0 {
331 d = 0
332 }
333 return d
334 }
335
336 func getAfterRenewFunc(pid, signum int, execCmd string) func() error {
337 return func() error {
338 if err := runKillPid(pid, signum); err != nil {
339 return err
340 }
341 return runExecCmd(execCmd)
342 }
343 }
344
345 func runKillPid(pid, signum int) error {
346 if pid == 0 {
347 return nil
348 }
349 if err := sysutils.Kill(pid, syscall.Signal(signum)); err != nil {
350 return errors.Wrapf(err, "kill %d with signal %d failed", pid, signum)
351 }
352 return nil
353 }
354
355 func runExecCmd(execCmd string) error {
356 execCmd = strings.TrimSpace(execCmd)
357 if execCmd == "" {
358 return nil
359 }
360 parts := strings.Split(execCmd, " ")
361 cmd := exec.Command(parts[0], parts[1:]...)
362 cmd.Stdin = os.Stdin
363 cmd.Stdout = os.Stdout
364 cmd.Stderr = os.Stderr
365 return cmd.Run()
366 }
367
368 type renewer struct {
369 client cautils.CaClient
370 transport *http.Transport
371 key crypto.PrivateKey
372 offline bool
373 }
374
375 func newRenewer(ctx *cli.Context, caURL string, cert tls.Certificate, rootFile string) (*renewer, error) {
376 if len(cert.Certificate) == 0 {
377 return nil, errors.New("error loading certificate: certificate chain is empty")
378 }
379
380 rootCAs, err := x509util.ReadCertPool(rootFile)
381 if err != nil {
382 return nil, err
383 }
384
385 tr := &http.Transport{
386 Proxy: http.ProxyFromEnvironment,
387 TLSClientConfig: &tls.Config{
388 Certificates: []tls.Certificate{cert},
389 RootCAs: rootCAs,
390 PreferServerCipherSuites: true,
391 },
392 }
393
394 var client cautils.CaClient
395 offline := ctx.Bool("offline")
396 if offline {
397 caConfig := ctx.String("ca-config")
398 if caConfig == "" {
399 return nil, errs.InvalidFlagValue(ctx, "ca-config", "", "")
400 }
401 client, err = cautils.NewOfflineCA(caConfig)
402 if err != nil {
403 return nil, err
404 }
405 } else {
406 client, err = ca.NewClient(caURL, ca.WithTransport(tr))
407 if err != nil {
408 return nil, err
409 }
410 }
411
412 return &renewer{
413 client: client,
414 transport: tr,
415 key: cert.PrivateKey,
416 offline: offline,
417 }, nil
418 }
419
420 func (r *renewer) Renew(outFile string) (*api.SignResponse, error) {
421 resp, err := r.client.Renew(r.transport)
422 if err != nil {
423 return nil, errors.Wrap(err, "error renewing certificate")
424 }
425
426 if resp.CertChainPEM == nil || len(resp.CertChainPEM) == 0 {
427 resp.CertChainPEM = []api.Certificate{resp.ServerPEM, resp.CaPEM}
428 }
429 var data []byte
430 for _, certPEM := range resp.CertChainPEM {
431 pemblk, err := pemutil.Serialize(certPEM.Certificate)
432 if err != nil {
433 return nil, errors.Wrap(err, "error serializing certificate PEM")
434 }
435 data = append(data, pem.EncodeToMemory(pemblk)...)
436 }
437 if err := utils.WriteFile(outFile, data, 0600); err != nil {
438 return nil, errs.FileError(err, outFile)
439 }
440
441 return resp, nil
442 }
443
444 // RenewAndPrepareNext renews the cert and prepares the cert for it's next renewal.
445 // NOTE: this function logs each time the certificate is successfully renewed.
446 func (r *renewer) RenewAndPrepareNext(outFile string, expiresIn, renewPeriod time.Duration) (time.Duration, error) {
447 const durationOnErrors = 1 * time.Minute
448 Info := log.New(os.Stdout, "INFO: ", log.LstdFlags)
449
450 resp, err := r.Renew(outFile)
451 if err != nil {
452 return durationOnErrors, err
453 }
454
455 x509Chain, err := pemutil.ReadCertificateBundle(outFile)
456 if err != nil {
457 return durationOnErrors, errs.Wrap(err, "error reading certificate chain")
458 }
459 x509ChainBytes := make([][]byte, len(x509Chain))
460 for i, c := range x509Chain {
461 x509ChainBytes[i] = c.Raw
462 }
463
464 cert := tls.Certificate{
465 Certificate: x509ChainBytes,
466 PrivateKey: r.key,
467 Leaf: x509Chain[0],
468 }
469 if len(cert.Certificate) == 0 {
470 return durationOnErrors, errors.New("error loading certificate: certificate chain is empty")
471 }
472
473 // Prepare next transport
474 r.transport.TLSClientConfig.Certificates = []tls.Certificate{cert}
475
476 // Get next renew duration
477 next := nextRenewDuration(resp.ServerPEM.Certificate, expiresIn, renewPeriod)
478 Info.Printf("%s certificate renewed, next in %s", resp.ServerPEM.Certificate.Subject.CommonName, next.Round(time.Second))
479 return next, nil
480 }
481
482 func (r *renewer) Daemon(outFile string, next, expiresIn, renewPeriod time.Duration, afterRenew func() error) error {
483 // Loggers
484 Info := log.New(os.Stdout, "INFO: ", log.LstdFlags)
485 Error := log.New(os.Stderr, "ERROR: ", log.LstdFlags)
486
487 // Daemon loop
488 signals := make(chan os.Signal, 1)
489 signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
490 defer signal.Stop(signals)
491
492 Info.Printf("first renewal in %s", next.Round(time.Second))
493 for {
494 select {
495 case sig := <-signals:
496 switch sig {
497 case syscall.SIGHUP:
498 if _, err := r.RenewAndPrepareNext(outFile, expiresIn, renewPeriod); err != nil {
499 Error.Println(err)
500 } else if err := afterRenew(); err != nil {
501 Error.Println(err)
502 }
503 case syscall.SIGINT, syscall.SIGTERM:
504 return nil
505 }
506 case <-time.After(next):
507 if _, err := r.RenewAndPrepareNext(outFile, expiresIn, renewPeriod); err != nil {
508 Error.Println(err)
509 } else if err := afterRenew(); err != nil {
510 Error.Println(err)
511 }
512 }
513 }
514 }
515
516 func tlsLoadX509KeyPair(certFile, keyFile, passFile string) (tls.Certificate, error) {
517 x509Chain, err := pemutil.ReadCertificateBundle(certFile)
518 if err != nil {
519 return tls.Certificate{}, errs.Wrap(err, "error reading certificate chain")
520 }
521 x509ChainBytes := make([][]byte, len(x509Chain))
522 for i, c := range x509Chain {
523 x509ChainBytes[i] = c.Raw
524 }
525
526 opts := []pemutil.Options{pemutil.WithFilename(keyFile)}
527 if passFile != "" {
528 opts = append(opts, pemutil.WithPasswordFile(passFile))
529 }
530 pk, err := pemutil.Read(keyFile, opts...)
531 if err != nil {
532 return tls.Certificate{}, errs.Wrap(err, "error parsing private key")
533 }
534
535 return tls.Certificate{
536 Certificate: x509ChainBytes,
537 PrivateKey: pk,
538 Leaf: x509Chain[0],
539 }, nil
540 }