Debian Codegraph @

command/certificate/create.go

raw symbols SCIP
1 package certificate
2
3 import (
4 "crypto"
5 "crypto/x509"
6 "encoding/pem"
7 "time"
8
9 "github.com/pkg/errors"
10 "github.com/smallstep/cli/command"
11 "github.com/smallstep/cli/crypto/keys"
12 "github.com/smallstep/cli/crypto/pemutil"
13 "github.com/smallstep/cli/errs"
14 "github.com/smallstep/cli/flags"
15 "github.com/smallstep/cli/ui"
16 "github.com/smallstep/cli/utils"
17 "github.com/urfave/cli"
18 "go.step.sm/crypto/x509util"
19 )
20
21 const (
22 // Supported profiles
23 profileLeaf = "leaf"
24 profileSelfSigned = "self-signed"
25 profileIntermediateCA = "intermediate-ca"
26 profileRootCA = "root-ca"
27 profileCSR = "csr" // Used only on sign
28
29 // Default durations
30 defaultLeafValidity = 24 * time.Hour
31 defaultSelfSignedValidity = 24 * time.Hour
32 defaultIntermediateValidity = time.Hour * 24 * 365 * 10
33 defaultRootValidity = time.Hour * 24 * 365 * 10
34 defaultTemplatevalidity = 24 * time.Hour
35 )
36
37 func createCommand() cli.Command {
38 return cli.Command{
39 Name: "create",
40 Action: command.ActionFunc(createAction),
41 Usage: "create a certificate or certificate signing request",
42 UsageText: `**step certificate create** <subject> <crt-file> <key-file>
43 [**--csr**] [**--profile**=<profile>] [**--template**=<path>]
44 [**--not-before**=<duration>] [**--not-after**=<duration>]
45 [**--password-file**=<path>] [**--ca**=<issuer-cert>]
46 [**--ca-key**=<issuer-key>] [**--ca-password-file**=<path>]
47 [**--san**=<SAN>] [**--bundle**] [**--key**=<path>]
48 [**--kty**=<type>] [**--curve**=<curve>] [**--size**=<size>] [**--no-password**]`,
49 Description: `**step certificate create** generates a certificate or a
50 certificate signing request (CSR) that can be signed later using 'step
51 certificate sign' (or some other tool) to produce a certificate.
52
53 By default this command creates x.509 certificates or CSRs for use with TLS. If
54 you need something else, you can customize the output using templates. See **TEMPLATES** below.
55
56 ## POSITIONAL ARGUMENTS
57
58 <subject>
59 : The subject of the certificate. Typically this is a hostname for services or an email address for people.
60
61 <crt_file>
62 : File to write CRT or CSR to (PEM format)
63
64 <key_file>
65 : File to write private key to (PEM format). This argument is optional if **--key** is passed.
66
67 ## EXIT CODES
68
69 This command returns 0 on success and \>0 if any error occurs.
70
71 ## TEMPLATES
72
73 With templates, you can customize the generated certificate or CSR.
74 Templates are JSON files representing a [certificate](https://pkg.go.dev/go.step.sm/crypto/x509util?tab=doc#Certificate) [1]
75 or a [certificate request](https://pkg.go.dev/go.step.sm/crypto/x509util?tab=doc#CertificateRequest) [2].
76 They use Golang's [<text/template>](https://golang.org/pkg/text/template/) package [3] and
77 [<Sprig>](https://masterminds.github.io/sprig/) functions [4].
78
79 Here's the default template used for generating a leaf certificate:
80 '''
81 {
82 "subject": {{ toJson .Subject }},
83 "sans": {{ toJson .SANs }},
84 {{- if typeIs "*rsa.PublicKey" .Insecure.CR.PublicKey }}
85 "keyUsage": ["keyEncipherment", "digitalSignature"],
86 {{- else }}
87 "keyUsage": ["digitalSignature"],
88 {{- end }}
89 "extKeyUsage": ["serverAuth", "clientAuth"]
90 }
91 '''
92
93 And this is the default template for a CSR:
94 '''
95 {
96 "subject": {{ toJson .Subject }},
97 "sans": {{ toJson .SANs }}
98 }
99 '''
100
101 In a custom template, you can change the **subject**, **dnsNames**,
102 **emailAddresses**, **ipAddresses**, and **uris**, and you can add custom
103 x.509 **extensions** or set the **signatureAlgorithm**.
104
105 For certificate templates, the common extensions **keyUsage**, **extKeyUsage**, and
106 **basicConstraints** are also represented as JSON fields.
107
108 Two variables are available in templates: **.Subject** contains the <subject> argument,
109 and **.SANs** contains the SANs provided with the **--san** flag.
110
111 Both .Subject and .SANs are objects, and they must be converted to JSON to be used in
112 the template, you can do this using Sprig's **toJson** function. On the .Subject
113 object you can access the common name string using the template variable
114 **.Subject.CommonName**. In **EXAMPLES** below, you can see how these
115 variables are used in a certificate request.
116
117 For more information on the template properties and functions see:
118 '''raw
119 [1] https://pkg.go.dev/go.step.sm/crypto/x509util?tab=doc#Certificate
120 [2] https://pkg.go.dev/go.step.sm/crypto/x509util?tab=doc#CertificateRequest
121 [3] https://golang.org/pkg/text/template/
122 [4] https://masterminds.github.io/sprig/
123 '''
124
125 ## EXAMPLES
126
127 Create a CSR and key:
128
129 '''
130 $ step certificate create foo foo.csr foo.key --csr
131 '''
132
133 Create a CSR using an existing private key:
134
135 '''
136 $ step certificate create --csr --key key.priv foo foo.csr
137 '''
138
139 Create a CSR using an existing encrypted private key:
140
141 '''
142 $ step certificate create --csr --key key.priv --password-file key.pass foo foo.csr
143 '''
144
145 Create a CSR and key with custom Subject Alternative Names:
146
147 '''
148 $ step certificate create foo foo.csr foo.key --csr \
149 --san inter.smallstep.com --san 1.1.1.1 --san ca.smallstep.com
150 '''
151
152 Create a CSR and key - do not encrypt the key when writing to disk:
153
154 '''
155 $ step certificate create foo foo.csr foo.key --csr --no-password --insecure
156 '''
157
158 Create a root certificate and key:
159
160 '''
161 $ step certificate create root-ca root-ca.crt root-ca.key --profile root-ca
162 '''
163
164 Create an intermediate certificate and key:
165
166 '''
167 $ step certificate create intermediate-ca intermediate-ca.crt intermediate-ca.key \
168 --profile intermediate-ca --ca ./root-ca.crt --ca-key ./root-ca.key
169 '''
170
171 Create a leaf certificate and key:
172
173 '''
174 $ step certificate create foo foo.crt foo.key --profile leaf \
175 --ca ./intermediate-ca.crt --ca-key ./intermediate-ca.key
176 '''
177
178 Create a leaf certificate and encrypt the private key:
179
180 '''
181 $ step certificate create foo foo.crt foo.key --profile leaf \
182 --password-file ./leaf.pass \
183 --ca ./intermediate-ca.crt --ca-key ./intermediate-ca.key
184 '''
185
186 Create a leaf certificate and decrypt the CA private key:
187
188 '''
189 $ step certificate create foo foo.crt foo.key --profile leaf \
190 --ca ./intermediate-ca.crt --ca-key ./intermediate-ca.key --ca-password-file ./intermediate.pass
191 '''
192
193 Create a leaf certificate and key with custom Subject Alternative Names:
194
195 '''
196 $ step certificate create foo foo.crt foo.key --profile leaf \
197 --ca ./intermediate-ca.crt --ca-key ./intermediate-ca.key \
198 --san inter.smallstep.com --san 1.1.1.1 --san ca.smallstep.com
199 '''
200
201 Create a leaf certificate and key with custom validity:
202
203 '''
204 $ step certificate create foo foo.crt foo.key --profile leaf \
205 --ca ./intermediate-ca.crt --ca-key ./intermediate-ca.key \
206 --not-before 24h --not-after 2160h
207 '''
208
209 Create a self-signed leaf certificate and key:
210
211 '''
212 $ step certificate create self-signed-leaf.local leaf.crt leaf.key --profile self-signed --subtle
213 '''
214
215 Create a root certificate and key with underlying OKP Ed25519:
216
217 '''
218 $ step certificate create root-ca root-ca.crt root-ca.key --profile root-ca \
219 --kty OKP --curve Ed25519
220 '''
221
222 Create an intermediate certificate and key with underlying EC P-256 key pair:
223
224 '''
225 $ step certificate create intermediate-ca intermediate-ca.crt intermediate-ca.key \
226 --profile intermediate-ca --ca ./root-ca.crt --ca-key ./root-ca.key --kty EC --curve P-256
227 '''
228
229 Create a leaf certificate and key with underlying RSA 2048 key pair:
230
231 '''
232 $ step certificate create foo foo.crt foo.key --profile leaf \
233 --ca ./intermediate-ca.crt --ca-key ./intermediate-ca.key --kty RSA --size 2048
234 '''
235
236 Create a CSR and key with underlying OKP Ed25519:
237
238 '''
239 $ step certificate create foo foo.csr foo.key --csr --kty OKP --curve Ed25519
240 '''
241
242 Create a root certificate using a custom template. The root certificate will
243 have a path length constraint that allows at least 2 intermediates:
244 '''
245 $ cat root.tpl
246 {
247 "subject": {
248 "commonName": "Acme Corporation Root CA"
249 },
250 "issuer": {
251 "commonName": "Acme Corporation Root CA"
252 },
253 "keyUsage": ["certSign", "crlSign"],
254 "basicConstraints": {
255 "isCA": true,
256 "maxPathLen": 2
257 }
258 }
259 $ step certificate create --template root.tpl \
260 "Acme Corporation Root CA" root_ca.crt root_ca_key
261 '''
262
263 Create an intermediate certificate using the previous root. This intermediate
264 will be able to sign also new intermediate certificates:
265 '''
266 $ cat intermediate.tpl
267 {
268 "subject": {
269 "commonName": "Acme Corporation Intermediate CA"
270 },
271 "keyUsage": ["certSign", "crlSign"],
272 "basicConstraints": {
273 "isCA": true,
274 "maxPathLen": 1
275 }
276 }
277 $ step certificate create --template intermediate.tpl \
278 --ca root_ca.crt --ca-key root_ca_key \
279 "Acme Corporation Intermediate CA" intermediate_ca.crt intermediate_ca_key
280 '''
281
282 Sign a new intermediate using the previous intermediate, now with path
283 length 0 using the **--profile** flag:
284 '''
285 $ step certificate create --profile intermediate-ca \
286 --ca intermediate_ca.crt --ca-key intermediate_ca_key \
287 "Coyote Corporation" coyote_ca.crt coyote_ca_key
288 '''
289
290 Create a leaf certificate, that is the default profile and bundle it with
291 the two intermediate certificates and validate it:
292 '''
293 $ step certificate create --ca coyote_ca.crt --ca-key coyote_ca_key \
294 "[email protected]" leaf.crt coyote.key
295 $ cat leaf.crt coyote_ca.crt intermediate_ca.crt > coyote.crt
296 $ step certificate verify --roots root_ca.crt coyote.crt
297 '''
298
299 Create a certificate request using a template:
300 '''
301 $ cat csr.tpl
302 {
303 "subject": {
304 "country": "US",
305 "organization": "Coyote Corporation",
306 "commonName": "{{ .Subject.CommonName }}"
307 },
308 "sans": {{ toJson .SANs }}
309 }
310 $ step certificate create --csr --template csr.tpl --san [email protected] \
311 "Wile E. Coyote" coyote.csr coyote.key
312 '''`,
313 Flags: []cli.Flag{
314 cli.BoolFlag{
315 Name: "csr",
316 Usage: `Generate a certificate signing request (CSR) instead of a certificate.`,
317 },
318 cli.StringFlag{
319 Name: "profile",
320 Value: profileLeaf,
321 Usage: `The certificate profile sets various certificate details such as
322 certificate use and expiration. The default profile is 'leaf' which is suitable
323 for a client or server using TLS.
324
325 : <profile> is a case-sensitive string and must be one of:
326
327 **leaf**
328 : Generate a leaf x.509 certificate suitable for use with TLS.
329
330 **intermediate-ca**
331 : Generate a certificate that can be used to sign additional leaf certificates.
332
333 **root-ca**
334 : Generate a new self-signed root certificate suitable for use as a root CA.
335
336 **self-signed**
337 : Generate a new self-signed leaf certificate suitable for use with TLS.
338 This profile requires the **--subtle** flag because the use of self-signed leaf
339 certificates is discouraged unless absolutely necessary.`,
340 },
341 cli.StringFlag{
342 Name: "template",
343 Usage: `The certificate template <path>, a JSON representation of the certificate to create.`,
344 },
345 cli.StringFlag{
346 Name: "password-file",
347 Usage: `The <path> to the file containing the password to
348 encrypt the new private key or decrypt the user submitted private key.`,
349 },
350 cli.StringFlag{
351 Name: "ca",
352 Usage: `The certificate authority used to issue the new certificate (PEM file).`,
353 },
354 cli.StringFlag{
355 Name: "ca-key",
356 Usage: `The certificate authority private key used to sign the new certificate (PEM file).`,
357 },
358 cli.StringFlag{
359 Name: "ca-password-file",
360 Usage: `The <path> to the file containing the password to
361 decrypt the CA private key.`,
362 },
363 cli.StringFlag{
364 Name: "key",
365 Usage: "The <path> of the private key to use instead of creating a new one (PEM file).",
366 },
367 cli.BoolFlag{
368 Name: "no-password",
369 Usage: `Do not ask for a password to encrypt the private key.
370 Sensitive key material will be written to disk unencrypted. This is not
371 recommended. Requires **--insecure** flag.`,
372 },
373 cli.StringFlag{
374 Name: "not-before",
375 Usage: `The <time|duration> set in the NotBefore property of the certificate. If a
376 <time> is used it is expected to be in RFC 3339 format. If a <duration> is
377 used, it is a sequence of decimal numbers, each with optional fraction and a
378 unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns",
379 "us" (or "µs"), "ms", "s", "m", "h".`,
380 },
381 cli.StringFlag{
382 Name: "not-after",
383 Usage: `The <time|duration> set in the NotAfter property of the certificate. If a
384 <time> is used it is expected to be in RFC 3339 format. If a <duration> is
385 used, it is a sequence of decimal numbers, each with optional fraction and a
386 unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns",
387 "us" (or "µs"), "ms", "s", "m", "h".`,
388 },
389 cli.StringSliceFlag{
390 Name: "san",
391 Usage: `Add DNS or IP Address Subjective Alternative Names (SANs). Use the '--san'
392 flag multiple times to configure multiple SANs.`,
393 },
394 cli.BoolFlag{
395 Name: "bundle",
396 Usage: `Bundle the new leaf certificate with the signing certificate. This flag requires
397 the **--ca** flag.`,
398 },
399 flags.KTY,
400 flags.Size,
401 flags.Curve,
402 flags.Force,
403 flags.Subtle,
404 cli.BoolFlag{
405 Name: "insecure",
406 Hidden: true,
407 },
408 },
409 }
410 }
411
412 func createAction(ctx *cli.Context) error {
413 minArg := 2
414 if key := ctx.String("key"); key == "" {
415 minArg = 3
416 }
417 if err := errs.MinMaxNumberOfArguments(ctx, minArg, 3); err != nil {
418 return err
419 }
420
421 insecure := ctx.Bool("insecure")
422 noPass := ctx.Bool("no-password")
423 if noPass && !insecure {
424 return errs.RequiredWithFlag(ctx, "insecure", "no-password")
425 }
426
427 subject := ctx.Args().Get(0)
428 crtFile := ctx.Args().Get(1)
429 keyFile := ctx.Args().Get(2)
430 if crtFile == keyFile {
431 return errs.EqualArguments(ctx, "<crt-file>", "<key-file>")
432 }
433
434 notBefore, ok := flags.ParseTimeOrDuration(ctx.String("not-before"))
435 if !ok {
436 return errs.InvalidFlagValue(ctx, "not-before", ctx.String("not-before"), "")
437 }
438 notAfter, ok := flags.ParseTimeOrDuration(ctx.String("not-after"))
439 if !ok {
440 return errs.InvalidFlagValue(ctx, "not-after", ctx.String("not-after"), "")
441 }
442 if !notAfter.IsZero() && !notBefore.IsZero() && notBefore.After(notAfter) {
443 return errs.IncompatibleFlagValues(ctx, "not-before", ctx.String("not-before"), "not-after", ctx.String("not-after"))
444 }
445
446 var (
447 sans = ctx.StringSlice("san")
448 profile = ctx.String("profile")
449 templateFile = ctx.String("template")
450 bundle = ctx.Bool("bundle")
451 subtle = ctx.Bool("subtle")
452 )
453
454 if ctx.IsSet("profile") && templateFile != "" {
455 return errs.IncompatibleFlagWithFlag(ctx, "profile", "template")
456 }
457
458 // Read template if passed
459 var template string
460 if templateFile != "" {
461 b, err := utils.ReadFile(templateFile)
462 if err != nil {
463 return err
464 }
465 template = string(b)
466 }
467
468 // Read or generate key pair
469 pub, priv, err := parseOrCreateKey(ctx)
470 if err != nil {
471 return err
472 }
473
474 // Create certificate request
475 if ctx.Bool("csr") {
476 if bundle {
477 return errs.IncompatibleFlagWithFlag(ctx, "bundle", "csr")
478 }
479 if profile != "" && profile != profileLeaf {
480 return errs.IncompatibleFlagWithFlag(ctx, "profile", "csr")
481 }
482 if ctx.IsSet("ca") {
483 return errs.IncompatibleFlagWithFlag(ctx, "ca", "csr")
484 }
485 if ctx.IsSet("ca-key") {
486 return errs.IncompatibleFlagWithFlag(ctx, "ca-key", "csr")
487 }
488 if ctx.IsSet("ca-password-file") {
489 return errs.IncompatibleFlagWithFlag(ctx, "ca-password-file", "csr")
490 }
491 if ctx.IsSet("not-before") {
492 return errs.IncompatibleFlagWithFlag(ctx, "not-before", "csr")
493 }
494 if ctx.IsSet("not-after") {
495 return errs.IncompatibleFlagWithFlag(ctx, "not-after", "csr")
496 }
497
498 // Use subject as default san
499 if len(sans) == 0 {
500 sans = append(sans, subject)
501 }
502
503 // Use default template if empty
504 if template == "" {
505 template = x509util.DefaultCertificateRequestTemplate
506 }
507
508 // Create certificate request
509 data := x509util.CreateTemplateData(subject, sans)
510 csr, err := x509util.NewCertificateRequest(priv, x509util.WithTemplate(template, data))
511 if err != nil {
512 return err
513 }
514 cr, err := csr.GetCertificateRequest()
515 if err != nil {
516 return err
517 }
518
519 block, err := pemutil.Serialize(cr)
520 if err != nil {
521 return err
522 }
523
524 // Save key and certificate request
525 if keyFile != "" {
526 if err := savePrivateKey(ctx, keyFile, priv, noPass); err != nil {
527 return err
528 }
529 }
530
531 if err = utils.WriteFile(crtFile, pem.EncodeToMemory(block), 0600); err != nil {
532 return errs.FileError(err, crtFile)
533 }
534
535 ui.Printf("Your certificate signing request has been saved in %s.\n", crtFile)
536 if keyFile != "" {
537 ui.Printf("Your private key has been saved in %s.\n", keyFile)
538 }
539
540 return nil
541 }
542
543 // Bundle is only valid for leaf certificates
544 if bundle && profile != profileLeaf {
545 return errs.IncompatibleFlagValue(ctx, "bundle", "profile", profile)
546 }
547
548 // Subtle is required on self-signed certificates
549 if !subtle && profile == profileSelfSigned {
550 return errs.RequiredWithFlagValue(ctx, "profile", "self-signed", "subtle")
551 }
552
553 // Parse --ca and --ca-key flags and check when those flags are required.
554 parent, signer, err := parseSigner(ctx, priv)
555 if err != nil {
556 return err
557 }
558
559 // Use subject as default SAN when using a template or for leaf and self-signed certificates.
560 if len(sans) == 0 && (template != "" || profile == profileLeaf || profile == profileSelfSigned) {
561 sans = append(sans, subject)
562 }
563
564 var defaultValidity time.Duration
565 if template == "" {
566 switch profile {
567 case profileLeaf:
568 template = x509util.DefaultLeafTemplate
569 defaultValidity = defaultLeafValidity
570 case profileIntermediateCA:
571 template = x509util.DefaultIntermediateTemplate
572 defaultValidity = defaultIntermediateValidity
573 case profileRootCA:
574 template = x509util.DefaultRootTemplate
575 defaultValidity = defaultRootValidity
576 case profileSelfSigned:
577 template = x509util.DefaultLeafTemplate
578 defaultValidity = defaultSelfSignedValidity
579 default:
580 return errs.InvalidFlagValue(ctx, "profile", profile, "leaf, intermediate-ca, root-ca, self-signed")
581 }
582 } else {
583 defaultValidity = defaultTemplatevalidity
584 }
585
586 // Create X.509 certificate used as base for the certificate
587 cr, err := x509util.CreateCertificateRequest(subject, sans, signer)
588 if err != nil {
589 return err
590 }
591
592 // Create X.509 certificate
593 templateData := x509util.CreateTemplateData(subject, sans)
594 certificate, err := x509util.NewCertificate(cr, x509util.WithTemplate(template, templateData))
595 if err != nil {
596 return err
597 }
598 certTemplate := certificate.GetCertificate()
599 if parent == nil {
600 parent = certTemplate
601 }
602
603 // Set certificate validity
604 certTemplate.NotBefore = notBefore
605 certTemplate.NotAfter = notAfter
606
607 if certTemplate.NotBefore.IsZero() {
608 certTemplate.NotBefore = time.Now()
609 }
610 if certTemplate.NotAfter.IsZero() {
611 certTemplate.NotAfter = certTemplate.NotBefore.Add(defaultValidity)
612 }
613 // Check that the certificate is not already expired
614 if certTemplate.NotBefore.After(certTemplate.NotAfter) {
615 return errors.Errorf("invalid value '%s' for flag '--not-after': certificate is already expired", ctx.String("not-after"))
616 }
617
618 cert, err := x509util.CreateCertificate(certTemplate, parent, pub, signer)
619 if err != nil {
620 return err
621 }
622
623 // Serialize certificate
624 block, err := pemutil.Serialize(cert)
625 if err != nil {
626 return err
627 }
628
629 pubBytes := pem.EncodeToMemory(block)
630 if bundle {
631 if block, err = pemutil.Serialize(parent); err != nil {
632 return err
633 }
634 pubBytes = append(pubBytes, pem.EncodeToMemory(block)...)
635 }
636
637 // Save key and certificate request
638 if keyFile != "" {
639 if err := savePrivateKey(ctx, keyFile, priv, noPass); err != nil {
640 return err
641 }
642 }
643
644 if err = utils.WriteFile(crtFile, pubBytes, 0600); err != nil {
645 return errs.FileError(err, crtFile)
646 }
647
648 ui.Printf("Your certificate has been saved in %s.\n", crtFile)
649 if keyFile != "" {
650 ui.Printf("Your private key has been saved in %s.\n", keyFile)
651 }
652
653 return nil
654 }
655
656 func parseOrCreateKey(ctx *cli.Context) (crypto.PublicKey, crypto.Signer, error) {
657 keyFile := ctx.String("key")
658
659 // Validate key parameters and generate key pair
660 if keyFile == "" {
661 kty, crv, size, err := utils.GetKeyDetailsFromCLI(ctx, ctx.Bool("insecure"), "kty", "curve", "size")
662 if err != nil {
663 return nil, nil, err
664 }
665 pub, priv, err := keys.GenerateKeyPair(kty, crv, size)
666 if err != nil {
667 return nil, nil, err
668 }
669 signer, ok := priv.(crypto.Signer)
670 if !ok {
671 return nil, nil, errors.Errorf("private key of type %T is not a crypto.Signer", priv)
672 }
673 return pub, signer, nil
674 }
675
676 // Validate incompatible flags and read a key file
677 switch {
678 case ctx.IsSet("kty"):
679 return nil, nil, errs.IncompatibleFlag(ctx, "key", "kty")
680 case ctx.IsSet("crv"):
681 return nil, nil, errs.IncompatibleFlag(ctx, "key", "crv")
682 case ctx.IsSet("size"):
683 return nil, nil, errs.IncompatibleFlag(ctx, "key", "size")
684 }
685
686 ops := []pemutil.Options{}
687 passFile := ctx.String("password-file")
688 if len(passFile) != 0 {
689 ops = append(ops, pemutil.WithPasswordFile(passFile))
690 }
691 v, err := pemutil.Read(keyFile, ops...)
692 if err != nil {
693 return nil, nil, err
694 }
695 signer, ok := v.(crypto.Signer)
696 if !ok {
697 return nil, nil, errors.Errorf("file %s does not contain a valid private key", keyFile)
698 }
699 return signer.Public(), signer, nil
700 }
701
702 // parseSigner returns the parent certificate and key for leaf and intermediate
703 // certificates. When a template is used, it will return the key only if the
704 // flags --ca and --ca-key are passed.
705 func parseSigner(ctx *cli.Context, defaultSigner crypto.Signer) (*x509.Certificate, crypto.Signer, error) {
706 var (
707 caCert = ctx.String("ca")
708 caKey = ctx.String("ca-key")
709 profile = ctx.String("profile")
710 template = ctx.String("template")
711 )
712
713 // Check required flags when profile is used.
714 if template == "" {
715 switch profile {
716 case profileLeaf, profileIntermediateCA:
717 if caCert == "" {
718 return nil, nil, errs.RequiredWithFlagValue(ctx, "profile", profile, "ca")
719 }
720 if caKey == "" {
721 return nil, nil, errs.RequiredWithFlagValue(ctx, "profile", profile, "ca-key")
722 }
723 case profileRootCA, profileSelfSigned:
724 if caCert != "" {
725 return nil, nil, errs.IncompatibleFlagValue(ctx, "ca", "profile", profile)
726 }
727 if caKey != "" {
728 return nil, nil, errs.IncompatibleFlagValue(ctx, "ca-key", "profile", profile)
729 }
730 default:
731 return nil, nil, errs.InvalidFlagValue(ctx, "profile", profile, "leaf, intermediate-ca, root-ca, self-signed")
732 }
733 }
734
735 // Root, self-signed, or template with no parent.
736 if caCert == "" && caKey == "" {
737 return nil, defaultSigner, nil
738 }
739
740 // Leaf, intermediate or template with
741 switch {
742 case caCert != "" && caKey == "":
743 return nil, nil, errs.RequiredWithFlag(ctx, "ca", "ca-key")
744 case caCert == "" && caKey != "":
745 return nil, nil, errs.RequiredWithFlag(ctx, "ca-key", "ca")
746 }
747
748 // Parse --ca as a certificate.
749 cert, err := pemutil.ReadCertificate(caCert)
750 if err != nil {
751 return nil, nil, err
752 }
753
754 // Parse --ca-key as a crypto.Signer.
755 passFile := ctx.String("ca-password-file")
756 ops := []pemutil.Options{}
757 if len(passFile) != 0 {
758 ops = append(ops, pemutil.WithPasswordFile(passFile))
759 }
760 key, err := pemutil.Read(caKey, ops...)
761 if err != nil {
762 return nil, nil, err
763 }
764 signer, ok := key.(crypto.Signer)
765 if !ok {
766 return nil, nil, errors.Errorf("invalid value '%s' for flag '--ca-key': file is not a valid private key", caKey)
767 }
768
769 return cert, signer, nil
770 }
771
772 // savePrivateKey saves the given key, asking the password if necessary.
773 func savePrivateKey(ctx *cli.Context, filename string, priv interface{}, insecure bool) error {
774 var err error
775 if insecure {
776 _, err = pemutil.Serialize(priv, pemutil.ToFile(filename, 0600))
777 return err
778 }
779
780 var pass []byte
781 if passFile := ctx.String("password-file"); passFile != "" {
782 pass, err = utils.ReadPasswordFromFile(passFile)
783 if err != nil {
784 return errors.Wrap(err, "error reading encrypting password from file")
785 }
786 } else {
787 pass, err = ui.PromptPassword("Please enter the password to encrypt the private key",
788 ui.WithValidateNotEmpty())
789 if err != nil {
790 return errors.Wrap(err, "error reading password")
791 }
792 }
793 _, err = pemutil.Serialize(priv, pemutil.WithPassword(pass), pemutil.ToFile(filename, 0600))
794 return err
795 }