Debian Codegraph @

command/certificate/sign.go

raw symbols SCIP
1 package certificate
2
3 import (
4 "bytes"
5 "crypto"
6 "crypto/ecdsa"
7 "crypto/ed25519"
8 "crypto/rsa"
9 "crypto/x509"
10 "encoding/pem"
11 "fmt"
12 "strconv"
13 "time"
14
15 "github.com/pkg/errors"
16 "github.com/smallstep/cli/errs"
17 "github.com/smallstep/cli/flags"
18 "github.com/smallstep/cli/ui"
19 "github.com/smallstep/cli/utils"
20 "github.com/urfave/cli"
21 "go.step.sm/crypto/pemutil"
22 "go.step.sm/crypto/x509util"
23 )
24
25 const customIntermediateTemplate = `{
26 "subject": {{ toJson .Subject }},
27 "keyUsage": ["certSign", "crlSign"],
28 "basicConstraints": {
29 "isCA": true,
30 "maxPathLen": {{ .MaxPathLen }}
31 }
32 }`
33
34 func signCommand() cli.Command {
35 return cli.Command{
36 Name: "sign",
37 Action: cli.ActionFunc(signAction),
38 Usage: "sign a certificate signing request (CSR)",
39 UsageText: `**step certificate sign** <csr_file> <crt_file> <key_file>
40 [**--profile**=<profile>] [**--template**=<path>]
41 [**--password-file**=<path>] [**--path-len**=<maximum>]
42 [**--not-before**=<time|duration>] [**--not-after**=<time|duration>]
43 [**--bundle**]`,
44 Description: `**step certificate sign** generates a signed
45 certificate from a certificate signing request (CSR).
46
47 ## POSITIONAL ARGUMENTS
48
49 <csr_file>
50 : The path to a certificate signing request (CSR) to be signed.
51
52 <crt_file>
53 : The path to an issuing certificate.
54
55 <key_file>
56 : The path to a private key for signing the CSR.
57
58 ## EXIT CODES
59
60 This command returns 0 on success and \>0 if any error occurs.
61
62 ## EXAMPLES
63
64 Sign a certificate signing request using the leaf profile:
65 '''
66 $ step certificate sign leaf.csr issuer.crt issuer.key
67 # or
68 $ step certificate sign --profile leaf leaf.csr issuer.crt issuer.key
69 '''
70
71 Sign a CSR and bundle the new certificate with the issuer:
72 '''
73 $ step certificate sign --bundle leaf.csr issuer.crt issuer.key
74 '''
75
76 Sign a CSR with custom validity and bundle the new certificate with the issuer:
77 '''
78 $ step certificate sign --bundle --not-before -1m --not-after 16h leaf.csr issuer.crt issuer.key
79 '''
80
81 Sign an intermediate ca:
82 '''
83 $ step certificate sign --profile intermediate-ca intermediate.csr issuer.crt issuer.key
84 '''
85
86 Sign an intermediate ca that can sign other intermediates; in this example, the
87 issuer must set the pathLenConstraint at least to 2 or without a limit:
88 '''
89 $ step certificate sign --profile intermediate-ca --path-len 1 intermediate.csr issuer.crt issuer.key
90 '''
91
92 Sign a CSR but only use information present in it, it doesn't add any key or
93 extended key usages if they are not in the CSR.
94 '''
95 $ step certificate sign --profile csr test.csr issuer.crt issuer.key
96 '''
97
98 Sign a CSR with only clientAuth as key usage using a template:
99 '''
100 $ cat coyote.tpl
101 {
102 "subject": {
103 "country": "US",
104 "organization": "Coyote Corporation",
105 "commonName": "{{ .Subject.CommonName }}"
106 },
107 "emailAddresses": {{ toJson .Insecure.CR.EmailAddresses }},
108 "keyUsage": ["digitalSignature"],
109 "extKeyUsage": ["clientAuth"]
110 }
111 $ step certificate create --csr [email protected] coyote.csr coyote.key
112 $ step certificate sign --template coyote.tpl coyote.csr issuer.crt issuer.key
113 '''`,
114 Flags: []cli.Flag{
115 cli.StringFlag{
116 Name: "profile",
117 Value: profileLeaf,
118 Usage: `The certificate profile sets various certificate details such as
119 certificate use and expiration. The default profile is 'leaf' which is suitable
120 for a client or server using TLS.
121
122 : <profile> is a case-sensitive string and must be one of:
123
124 **leaf**
125 : Signs a leaf x.509 certificate suitable for use with TLS.
126
127 **intermediate-ca**
128 : Signs a certificate that can be used to sign additional leaf certificates.
129
130 **csr**
131 : Signs a x.509 certificate without modifying the CSR.`,
132 },
133 cli.StringFlag{
134 Name: "template",
135 Usage: `The certificate template <path>, a JSON representation of the certificate to create.`,
136 },
137 flags.PasswordFile,
138 cli.StringFlag{
139 Name: "not-before",
140 Usage: `The <time|duration> set in the NotBefore property of the certificate. If a
141 <time> is used it is expected to be in RFC 3339 format. If a <duration> is
142 used, it is a sequence of decimal numbers, each with optional fraction and a
143 unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns",
144 "us" (or "µs"), "ms", "s", "m", "h".`,
145 },
146 cli.StringFlag{
147 Name: "not-after",
148 Usage: `The <time|duration> set in the NotAfter property of the certificate. If a
149 <time> is used it is expected to be in RFC 3339 format. If a <duration> is
150 used, it is a sequence of decimal numbers, each with optional fraction and a
151 unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns",
152 "us" (or "µs"), "ms", "s", "m", "h".`,
153 },
154 cli.IntFlag{
155 Name: "path-len",
156 Usage: `The <maximum> path length to set in the pathLenConstraint of an intermediate-ca.
157 Defaults to 0. If it's set to -1 no path length limit is imposed.`,
158 Value: 0,
159 },
160 cli.BoolFlag{
161 Name: "bundle",
162 Usage: `Bundle the new leaf certificate with the signing certificate.`,
163 },
164 },
165 }
166 }
167
168 func signAction(ctx *cli.Context) error {
169 if err := errs.NumberOfArguments(ctx, 3); err != nil {
170 return err
171 }
172
173 csrFile := ctx.Args().Get(0)
174 crtFile := ctx.Args().Get(1)
175 keyFile := ctx.Args().Get(2)
176
177 // Parse certificate request
178 csr, err := pemutil.ReadCertificateRequest(csrFile)
179 if err != nil {
180 return err
181 }
182 if err = csr.CheckSignature(); err != nil {
183 return errors.Wrapf(err, "certificate request has invalid signature")
184 }
185
186 // Parse issuer and issuer key (at least one should be present)
187 issuers, err := pemutil.ReadCertificateBundle(crtFile)
188 if err != nil {
189 return err
190 }
191 ops := []pemutil.Options{}
192 passFile := ctx.String("password-file")
193 if len(passFile) == 0 {
194 ops = append(ops, pemutil.WithPasswordPrompt(
195 fmt.Sprintf("Please enter the password to decrypt %s", keyFile),
196 func(s string) ([]byte, error) {
197 return ui.PromptPassword(s)
198 }))
199 } else {
200 ops = append(ops, pemutil.WithPasswordFile(passFile))
201 }
202 key, err := pemutil.Read(keyFile, ops...)
203 if err != nil {
204 return err
205 }
206 signer, ok := key.(crypto.Signer)
207 if !ok {
208 return errors.Errorf("key in %s does not satisfy the crypto.Signer interface", keyFile)
209 }
210 if err := validateIssuerKey(issuers[0], signer); err != nil {
211 return err
212 }
213
214 // Profile flag
215 profile := ctx.String("profile")
216 if profile != profileLeaf && profile != profileIntermediateCA && profile != profileCSR {
217 return errs.InvalidFlagValue(ctx, "profile", profile, "leaf, intermediate-ca, csr")
218 }
219
220 // Template flag
221 templateFile := ctx.String("template")
222 if ctx.IsSet("profile") && templateFile != "" {
223 return errs.IncompatibleFlagWithFlag(ctx, "profile", "template")
224 }
225
226 // Read template if passed. If not use a template depending on the profile.
227 var template string
228 if templateFile != "" {
229 b, err := utils.ReadFile(templateFile)
230 if err != nil {
231 return err
232 }
233 template = string(b)
234 } else {
235 switch profile {
236 case profileLeaf:
237 template = x509util.DefaultLeafTemplate
238 case profileIntermediateCA:
239 template = customIntermediateTemplate
240 case profileCSR:
241 template = x509util.CertificateRequestTemplate
242 default:
243 return errors.Errorf("unknown profile %s: this is not expected", profile)
244 }
245 }
246
247 // pathLenConstraint
248 maxPathLen := ctx.Int("path-len")
249 if -1 > maxPathLen {
250 return errs.InvalidFlagValueMsg(ctx, "path-len", strconv.Itoa(maxPathLen), "path-len must be -1 or greater")
251 }
252
253 // Make sure the issuer can sign the profile
254 if err := validateIssuer(issuers[0], profile, maxPathLen); err != nil {
255 return err
256 }
257
258 // NotBefore and NotAfter flags.
259 notBefore, ok := flags.ParseTimeOrDuration(ctx.String("not-before"))
260 if !ok {
261 return errs.InvalidFlagValue(ctx, "not-before", ctx.String("not-before"), "")
262 }
263 if notBefore.IsZero() {
264 notBefore = time.Now()
265 }
266
267 notAfter, ok := flags.ParseTimeOrDuration(ctx.String("not-after"))
268 if !ok {
269 return errs.InvalidFlagValue(ctx, "not-after", ctx.String("not-after"), "")
270 }
271 if !notAfter.IsZero() && !notBefore.IsZero() && notBefore.After(notAfter) {
272 return errs.IncompatibleFlagValues(ctx, "not-before", ctx.String("not-before"), "not-after", ctx.String("not-after"))
273 }
274 if notAfter.IsZero() {
275 if profile == profileIntermediateCA {
276 notAfter = notBefore.Add(defaultIntermediateValidity)
277 } else {
278 notAfter = notBefore.Add(defaultLeafValidity)
279 }
280 }
281
282 // Create certificate template from csr.
283 data := createTemplateData(csr, maxPathLen)
284 tpl, err := x509util.NewCertificate(csr, x509util.WithTemplate(template, data))
285 if err != nil {
286 return err
287 }
288 certTpl := tpl.GetCertificate()
289 certTpl.NotBefore = notBefore
290 certTpl.NotAfter = notAfter
291
292 // Sign certificate
293 cert, err := x509util.CreateCertificate(certTpl, issuers[0], certTpl.PublicKey, signer)
294 if err != nil {
295 return err
296 }
297
298 // Write certificate
299 pubPEMs := []*pem.Block{{
300 Type: "CERTIFICATE",
301 Bytes: cert.Raw,
302 }}
303 if ctx.Bool("bundle") {
304 for _, iss := range issuers {
305 pubPEMs = append(pubPEMs, &pem.Block{
306 Type: "CERTIFICATE",
307 Bytes: iss.Raw,
308 })
309 }
310 }
311
312 pubBytes := []byte{}
313 for _, pp := range pubPEMs {
314 pubBytes = append(pubBytes, pem.EncodeToMemory(pp)...)
315 }
316 fmt.Print(string(pubBytes))
317
318 return nil
319 }
320
321 // validateIssuerKey makes sure the issuer and key matches.
322 func validateIssuerKey(crt *x509.Certificate, signer crypto.Signer) error {
323 switch pub := crt.PublicKey.(type) {
324 case *rsa.PublicKey:
325 priv, ok := signer.(*rsa.PrivateKey)
326 if !ok {
327 return errors.New("private key type does not match issuer public key type")
328 }
329 if pub.N.Cmp(priv.N) != 0 {
330 return errors.New("private key does not match issuer public key")
331 }
332 case *ecdsa.PublicKey:
333 priv, ok := signer.(*ecdsa.PrivateKey)
334 if !ok {
335 return errors.New("private key type does not match issuer public key type")
336 }
337 if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
338 return errors.New("private key does not match issuer public key")
339 }
340 case ed25519.PublicKey:
341 priv, ok := signer.(ed25519.PrivateKey)
342 if !ok {
343 return errors.New("private key type does not match issuer public key type")
344 }
345 if !bytes.Equal(priv.Public().(ed25519.PublicKey), pub) {
346 return errors.New("private key does not match issuer public key")
347 }
348 default:
349 return errors.New("unknown public key algorithm")
350 }
351
352 return nil
353 }
354
355 // validateIssuer makes sure the issuer can sign the certificate request.
356 func validateIssuer(crt *x509.Certificate, profile string, maxPathLen int) error {
357 if !crt.BasicConstraintsValid || !crt.IsCA {
358 return errors.New("issuer certificate is not a certificate authority")
359 }
360 if crt.KeyUsage&x509.KeyUsageCertSign == 0 {
361 return errors.New("issuer certificate does not have the keyCertSign usage")
362 }
363
364 if profile == profileIntermediateCA {
365 if crt.MaxPathLenZero {
366 return errors.New("issuer certificate cannot sign an intermediate-ca: pathLenConstraint is 0")
367 }
368 if crt.MaxPathLen != -1 && (maxPathLen == -1 || maxPathLen >= crt.MaxPathLen) {
369 return errors.Errorf("issuer certificate cannot sign an intermediate-ca: pathLenConstraint is %d, want at most %d", crt.MaxPathLen, crt.MaxPathLen-1)
370 }
371 }
372
373 return nil
374 }
375
376 // createTemplateData create a new template data with subject and sans based on
377 // the information in the certificate request, and the maxPathLen for
378 // intermediate certificates.
379 func createTemplateData(cr *x509.CertificateRequest, maxPathLen int) x509util.TemplateData {
380 var sans []string
381 sans = append(sans, cr.DNSNames...)
382 sans = append(sans, cr.EmailAddresses...)
383 for _, v := range cr.IPAddresses {
384 sans = append(sans, v.String())
385 }
386 for _, v := range cr.URIs {
387 sans = append(sans, v.String())
388 }
389
390 data := x509util.NewTemplateData()
391 data.SetCertificateRequest(cr)
392 data.Set("MaxPathLen", maxPathLen)
393 data.SetSubject(x509util.Subject{
394 Country: cr.Subject.Country,
395 Organization: cr.Subject.Organization,
396 OrganizationalUnit: cr.Subject.OrganizationalUnit,
397 Locality: cr.Subject.Locality,
398 Province: cr.Subject.Province,
399 StreetAddress: cr.Subject.StreetAddress,
400 PostalCode: cr.Subject.PostalCode,
401 SerialNumber: cr.Subject.SerialNumber,
402 CommonName: cr.Subject.CommonName,
403 })
404 data.SetSANs(sans)
405 return data
406 }