Debian Codegraph @

command/ssh/certificate.go

raw symbols SCIP
1 package ssh
2
3 import (
4 "bytes"
5 "crypto"
6 "crypto/rand"
7 "crypto/x509"
8 "io/ioutil"
9 "net/url"
10 "strings"
11
12 "github.com/google/uuid"
13 "github.com/pkg/errors"
14 "github.com/smallstep/certificates/api"
15 "github.com/smallstep/certificates/authority/provisioner"
16 "github.com/smallstep/certificates/ca"
17 "github.com/smallstep/certificates/ca/identity"
18 "github.com/smallstep/cli/command"
19 "github.com/smallstep/cli/crypto/keys"
20 "github.com/smallstep/cli/crypto/pemutil"
21 "github.com/smallstep/cli/crypto/sshutil"
22 "github.com/smallstep/cli/errs"
23 "github.com/smallstep/cli/flags"
24 "github.com/smallstep/cli/ui"
25 "github.com/smallstep/cli/utils"
26 "github.com/smallstep/cli/utils/cautils"
27 "github.com/urfave/cli"
28 "golang.org/x/crypto/blake2b"
29 "golang.org/x/crypto/ssh"
30 )
31
32 func certificateCommand() cli.Command {
33 return cli.Command{
34 Name: "certificate",
35 Action: command.ActionFunc(certificateAction),
36 Usage: "sign a SSH certificate using the the SSH CA",
37 UsageText: `**step ssh certificate** <key-id> <key-file>
38 [**--host**] [--**host-id**] [**--sign**] [**--principal**=<string>] [**--password-file**=<path>]
39 [**--provisioner-password-file**=<path>] [**--add-user**]
40 [**--not-before**=<time|duration>] [**--not-after**=<time|duration>]
41 [**--token**=<token>] [**--issuer**=<name>] [**--ca-url**=<uri>]
42 [**--root**=<path>] [**--no-password**] [**--insecure**] [**--force**]
43 [**--x5c-cert**=<path>] [**--x5c-key**=<path>] [**--k8ssa-token-path=<path>]`,
44 Description: `**step ssh certificate** command generates an SSH key pair and creates a
45 certificate using [step certificates](https://github.com/smallstep/certificates).
46
47 With a certificate clients or servers may trust only the CA key and verify its
48 signature on a certificate rather than trusting many user/host keys.
49
50 Note that not all the provisioner types will be able to generate user and host
51 certificates. Currently JWK provisioners can generate both, but with an OIDC
52 provisioner you will only be able to generate user certificates unless you are
53 and admin that can generate both. With a cloud identity provisioner you will
54 only be able to generate host certificates.
55
56 To configure a server to accept user certificates and provide a user certificate
57 you need to add the following lines in </etc/ssh/sshd_config>:
58 '''
59 # The path to the CA public key, it accepts multiple user CAs, one per line
60 TrustedUserCAKeys /etc/ssh/ssh_user_key.pub
61
62 # Path to the private key and certificate
63 HostKey /etc/ssh/ssh_host_ecdsa_key
64 HostCertificate /etc/ssh/ssh_host_ecdsa_key-cert.pub
65 '''
66
67 Make sure to restart the sshd daemon to refresh its configuration.
68
69 To configure clients to accept host certificates you need to add the host CA public
70 key in <~/.ssh/known_hosts> with the following format:
71 '''
72 @cert-authority *.example.com ecdsa-sha2-nistp256 AAAAE...=
73 '''
74
75 Where <*.example.com> is a pattern that matches the hosts and
76 <ecdsa-sha2-nistp256 AAAAE...=> should be the contents of the host CA public key.
77
78 ## POSITIONAL ARGUMENTS
79
80 <key-id>
81 : The certificate identity. If no principals are passed we will use
82 the key-id as a principal, if it has the format abc@def then the principal will
83 be abc.
84
85 <key-file>
86 : The private key name when generating a new key pair, or the public
87 key path when we are just signing it.
88
89 ## EXAMPLES
90
91 Generate a new SSH key pair and user certificate:
92 '''
93 $ step ssh certificate mariano@work id_ecdsa
94 '''
95
96 Generate a new SSH key pair and user certificate and set the lifetime to 2hrs:
97 '''
98 $ step ssh certificate mariano@work id_ecdsa --not-after 2h
99 '''
100
101 Generate a new SSH key pair and user certificate and set the lifetime to begin
102 2hrs from now and last for 8hrs:
103 '''
104 $ step ssh certificate mariano@work id_ecdsa --not-before 2h --not-after 10h
105 '''
106
107 Sign an SSH public key and generate a user certificate:
108 '''
109 $ step ssh certificate --sign mariano@work id_ecdsa.pub
110 '''
111
112 Generate a new SSH key pair and host certificate:
113 '''
114 $ step ssh certificate --host internal.example.com ssh_host_ecdsa_key
115 '''
116
117 Sign an SSH public key and generate a host certificate:
118 '''
119 $ step ssh certificate --host --sign \
120 internal.example.com ssh_host_ecdsa_key.pub
121 '''
122
123 Sign an SSH public key and generate a host certificate with a custom uuid:
124 '''
125 $ step ssh certificate --host --host-id 00000000-0000-0000-0000-000000000000 \
126 --sign internal.example.com ssh_host_ecdsa_key.pub
127 '''
128
129 Sign an SSH public key and generate a host certificate with a uuid derived
130 from '/etc/machine-id':
131 '''
132 $ step ssh certificate --host --host-id machine --sign \
133 internal.example.com ssh_host_ecdsa_key.pub
134 '''
135
136 Generate an ssh certificate with custom principals from an existing key pair and
137 add the certificate to the ssh agent:
138 '''
139 $ step ssh certificate --principal max --principal mariano --sign \
140 ops@work id_ecdsa.pub --private-key id_ecdsa_key
141 '''
142
143 Generate a new key pair and a certificate using a given token:
144 '''
145 $ step ssh certificate --token $TOKEN mariano@work id_ecdsa
146 '''`,
147 Flags: []cli.Flag{
148 flags.CaConfig,
149 flags.CaURL,
150 flags.Force,
151 flags.Insecure,
152 flags.Root,
153 flags.NoPassword,
154 flags.NotBefore,
155 flags.NotAfter,
156 flags.Offline,
157 flags.Provisioner,
158 flags.Token,
159 flags.TemplateSet,
160 flags.TemplateSetFile,
161 sshAddUserFlag,
162 sshHostFlag,
163 sshHostIDFlag,
164 sshPasswordFileFlag,
165 sshPrincipalFlag,
166 sshPrivateKeyFlag,
167 sshProvisionerPasswordFlag,
168 sshSignFlag,
169 flags.X5cCert,
170 flags.X5cKey,
171 flags.K8sSATokenPathFlag,
172 },
173 }
174 }
175
176 func certificateAction(ctx *cli.Context) error {
177 if err := errs.NumberOfArguments(ctx, 2); err != nil {
178 return err
179 }
180
181 args := ctx.Args()
182 subject := args.Get(0)
183 keyFile := args.Get(1)
184 baseName := keyFile
185 // SSH uses fixed suffixes for public keys and certificates
186 pubFile := baseName + ".pub"
187 crtFile := baseName + "-cert.pub"
188
189 // Flags
190 token := ctx.String("token")
191 isHost := ctx.Bool("host")
192 hostID := ctx.String("host-id")
193 isSign := ctx.Bool("sign")
194 isAddUser := ctx.Bool("add-user")
195 principals := ctx.StringSlice("principal")
196 passwordFile := ctx.String("password-file")
197 provisionerPasswordFile := ctx.String("provisioner-password-file")
198 noPassword := ctx.Bool("no-password")
199 insecure := ctx.Bool("insecure")
200 sshPrivKeyFile := ctx.String("private-key")
201 validAfter, validBefore, err := flags.ParseTimeDuration(ctx)
202 if err != nil {
203 return err
204 }
205 templateData, err := flags.ParseTemplateData(ctx)
206 if err != nil {
207 return err
208 }
209
210 // Hack to make the flag "password-file" the content of
211 // "provisioner-password-file" so the token command works as expected
212 ctx.Set("password-file", provisionerPasswordFile)
213
214 // Validation
215 switch {
216 case noPassword && !insecure:
217 return errs.RequiredInsecureFlag(ctx, "no-password")
218 case noPassword && passwordFile != "":
219 return errs.IncompatibleFlagWithFlag(ctx, "no-password", "password-file")
220 case token != "" && provisionerPasswordFile != "":
221 return errs.IncompatibleFlagWithFlag(ctx, "token", "provisioner-password-file")
222 case isHost && isAddUser:
223 return errs.IncompatibleFlagWithFlag(ctx, "host", "add-user")
224 case !isHost && hostID != "":
225 return errs.RequiredWithFlag(ctx, sshHostIDFlag.Name, sshHostFlag.Name)
226 case isAddUser && len(principals) > 1:
227 return errors.New("flag '--add-user' is incompatible with more than one principal")
228 }
229
230 // If we are signing a public key, get the proper name for the certificate
231 if isSign && strings.HasSuffix(keyFile, ".pub") {
232 baseName = keyFile[:len(keyFile)-4]
233 crtFile = baseName + "-cert.pub"
234 }
235
236 var (
237 certType string
238 tokType int
239 )
240
241 if isHost {
242 certType = provisioner.SSHHostCert
243 tokType = cautils.SSHHostSignType
244 } else {
245 certType = provisioner.SSHUserCert
246 tokType = cautils.SSHUserSignType
247 }
248
249 // By default use the first part of the subject as a principal
250 if len(principals) == 0 {
251 if isHost {
252 principals = append(principals, subject)
253 } else {
254 principals = createPrincipalsFromSubject(subject)
255 }
256 }
257
258 flow, err := cautils.NewCertificateFlow(ctx)
259 if err != nil {
260 return err
261 }
262 if len(token) == 0 {
263 if token, err = flow.GenerateSSHToken(ctx, subject, tokType, principals, validAfter, validBefore); err != nil {
264 return err
265 }
266 }
267
268 caClient, err := flow.GetClient(ctx, token)
269 if err != nil {
270 return err
271 }
272
273 version, err := caClient.Version()
274 if err != nil {
275 return err
276 }
277
278 // Generate identity certificate (x509) if necessary
279 var identityCSR api.CertificateRequest
280 var identityKey crypto.PrivateKey
281 if version.RequireClientAuthentication {
282 csr, key, err := ca.CreateIdentityRequest(subject)
283 if err != nil {
284 return err
285 }
286
287 // All host identity certs need a URI SAN to work with our ssh API.
288 if isHost {
289 var u = uuid.Nil
290 switch hostID {
291 case "":
292 // If there is an old identity cert lying around, by default use the host ID so that running
293 // this command twice doesn't clobber your old host ID.
294 u, err = readExistingUUID()
295 if err != nil {
296 u, err = uuid.NewRandom()
297 if err != nil {
298 return errs.Wrap(err, "Unable to generate a host-id.")
299 }
300 }
301 case "machine":
302 u, err = deriveMachineID()
303 if err != nil {
304 return errs.Wrap(err, "Unable to derive a host-id. Make sure /etc/machine-id exists.")
305 }
306 default:
307 u, err = uuid.Parse(hostID)
308 if err != nil {
309 return errs.InvalidFlagValue(ctx, sshHostIDFlag.Name, hostID, "[ machine | <UUID> ]")
310 }
311 }
312 uri, err := url.Parse(u.URN())
313 if err != nil {
314 return errs.Wrap(err, "failed parsing uuid urn")
315 }
316
317 template := &x509.CertificateRequest{
318 Subject: csr.Subject,
319 DNSNames: csr.DNSNames,
320 IPAddresses: csr.IPAddresses,
321 EmailAddresses: csr.EmailAddresses,
322 // Prepend the generated uri. There is code that expects the
323 // uuid URI to be the first one.
324 URIs: append([]*url.URL{uri}, csr.URIs...),
325 }
326 csrBytes, err := x509.CreateCertificateRequest(rand.Reader, template, key)
327 if err != nil {
328 return errs.Wrap(err, "failed creating certificate request")
329 }
330 newCSR, err := x509.ParseCertificateRequest(csrBytes)
331 if err != nil {
332 return errs.Wrap(err, "failed parsing certificate request bytes")
333 }
334 if err := newCSR.CheckSignature(); err != nil {
335 return errs.Wrap(err, "failed signature check on new csr")
336 }
337 csr.CertificateRequest = newCSR
338 }
339
340 identityCSR = *csr
341 identityKey = key
342 }
343
344 var sshPub ssh.PublicKey
345 var pub, priv interface{}
346
347 if isSign {
348 // Use public key supplied as input.
349 in, err := utils.ReadFile(keyFile)
350 if err != nil {
351 return err
352 }
353
354 sshPub, _, _, _, err = ssh.ParseAuthorizedKey(in)
355 if err != nil {
356 return errors.Wrap(err, "error parsing ssh public key")
357 }
358 if len(sshPrivKeyFile) > 0 {
359 if priv, err = pemutil.Read(sshPrivKeyFile); err != nil {
360 return errors.Wrap(err, "error parsing private key")
361 }
362 }
363 } else {
364 // Generate keypair
365 pub, priv, err = keys.GenerateDefaultKeyPair()
366 if err != nil {
367 return err
368 }
369
370 sshPub, err = ssh.NewPublicKey(pub)
371 if err != nil {
372 return errors.Wrap(err, "error creating public key")
373 }
374 }
375
376 var sshAuPub ssh.PublicKey
377 var sshAuPubBytes []byte
378 var auPub, auPriv interface{}
379 if isAddUser {
380 auPub, auPriv, err = keys.GenerateDefaultKeyPair()
381 if err != nil {
382 return err
383 }
384 sshAuPub, err = ssh.NewPublicKey(auPub)
385 if err != nil {
386 return errors.Wrap(err, "error creating public key")
387 }
388 sshAuPubBytes = sshAuPub.Marshal()
389 }
390
391 resp, err := caClient.SSHSign(&api.SSHSignRequest{
392 PublicKey: sshPub.Marshal(),
393 OTT: token,
394 Principals: principals,
395 CertType: certType,
396 KeyID: subject,
397 ValidAfter: validAfter,
398 ValidBefore: validBefore,
399 AddUserPublicKey: sshAuPubBytes,
400 IdentityCSR: identityCSR,
401 TemplateData: templateData,
402 })
403 if err != nil {
404 return err
405 }
406
407 // Write files
408 if !isSign {
409 // Private key (with password unless --no-password --insecure)
410 opts := []pemutil.Options{
411 pemutil.WithOpenSSH(true),
412 pemutil.ToFile(keyFile, 0600),
413 }
414 switch {
415 case noPassword && insecure:
416 case passwordFile != "":
417 opts = append(opts, pemutil.WithPasswordFile(passwordFile))
418 default:
419 opts = append(opts, pemutil.WithPasswordPrompt("Please enter the password to encrypt the private key"))
420 }
421 _, err = pemutil.Serialize(priv, opts...)
422 if err != nil {
423 return err
424 }
425
426 if err := utils.WriteFile(pubFile, marshalPublicKey(sshPub, subject), 0644); err != nil {
427 return err
428 }
429 }
430
431 // Write certificate
432 if err := utils.WriteFile(crtFile, marshalPublicKey(resp.Certificate, subject), 0644); err != nil {
433 return err
434 }
435
436 // Write Add User keys and certs
437 if isAddUser && resp.AddUserCertificate != nil {
438 id := provisioner.SanitizeSSHUserPrincipal(subject) + "-provisioner"
439 if _, err := pemutil.Serialize(auPriv, pemutil.WithOpenSSH(true), pemutil.ToFile(baseName+"-provisioner", 0600)); err != nil {
440 return err
441 }
442 if err := utils.WriteFile(baseName+"-provisioner.pub", marshalPublicKey(sshAuPub, id), 0644); err != nil {
443 return err
444 }
445 if err := utils.WriteFile(baseName+"-provisioner-cert.pub", marshalPublicKey(resp.AddUserCertificate, id), 0644); err != nil {
446 return err
447 }
448 }
449
450 // Write x509 identity certificate
451 if version.RequireClientAuthentication {
452 if err := ca.WriteDefaultIdentity(resp.IdentityCertificate, identityKey); err != nil {
453 return err
454 }
455 }
456
457 if !isSign {
458 ui.PrintSelected("Private Key", keyFile)
459 ui.PrintSelected("Public Key", pubFile)
460 }
461 ui.PrintSelected("Certificate", crtFile)
462
463 // Attempt to add key to agent if private key defined.
464 if priv != nil && certType == provisioner.SSHUserCert {
465 if agent, err := sshutil.DialAgent(); err != nil {
466 ui.Printf(`{{ "%s" | red }} {{ "SSH Agent:" | bold }} %v`+"\n", ui.IconBad, err)
467 } else {
468 defer agent.Close()
469 if err := agent.AddCertificate(subject, resp.Certificate.Certificate, priv); err != nil {
470 ui.Printf(`{{ "%s" | red }} {{ "SSH Agent:" | bold }} %v`+"\n", ui.IconBad, err)
471 } else {
472 ui.PrintSelected("SSH Agent", "yes")
473 }
474 }
475 }
476
477 if isAddUser && resp.AddUserCertificate != nil {
478 ui.PrintSelected("Add User Private Key", baseName+"-provisioner")
479 ui.PrintSelected("Add User Public Key", baseName+"-provisioner.pub")
480 ui.PrintSelected("Add User Certificate", baseName+"-provisioner-cert.pub")
481 }
482
483 return nil
484 }
485
486 func marshalPublicKey(key ssh.PublicKey, subject string) []byte {
487 b := ssh.MarshalAuthorizedKey(key)
488 if i := bytes.LastIndex(b, []byte("\n")); i >= 0 {
489 return append(b[:i], []byte(" "+subject+"\n")...)
490 }
491 return append(b, []byte(" "+subject+"\n")...)
492 }
493
494 func deriveMachineID() (uuid.UUID, error) {
495 // use /etc/machine-id
496 machineID, err := ioutil.ReadFile("/etc/machine-id")
497 if err != nil {
498 return uuid.Nil, err
499 }
500
501 // 16 bytes, not secret
502 key := []byte("man moon machine")
503 mac, err := blake2b.New(16, key)
504 if err != nil {
505 return uuid.Nil, err
506 }
507 mac.Write(machineID)
508 machineHash := mac.Sum(nil)
509 var u uuid.UUID
510 copy(u[:], machineHash)
511 // Make it a v4 uuid (taken from uuid.NewRandom):
512 u[6] = (u[6] & 0x0f) | 0x40 // Version 4
513 u[8] = (u[8] & 0x3f) | 0x80 // Variant is 10
514
515 return u, nil
516 }
517
518 func readExistingUUID() (uuid.UUID, error) {
519 id, err := identity.LoadDefaultIdentity()
520 if err != nil {
521 return uuid.Nil, errs.Wrap(err, "error loading default identity")
522 }
523 if err := id.Validate(); err != nil {
524 return uuid.Nil, errs.Wrap(err, "error validating identity file")
525 }
526 certs, err := pemutil.ReadCertificateBundle(id.Certificate)
527 if err != nil {
528 return uuid.Nil, errs.Wrap(err, "error parsing default identity")
529 }
530 leaf := certs[0]
531 if len(leaf.URIs) < 1 {
532 return uuid.Nil, errors.New("incompatible certificate: missing host uuid")
533 }
534 uri := leaf.URIs[0]
535 // TODO: add a smallstep namespace at some point
536 // so we can actually find our host id
537 u, err := uuid.Parse(uri.String())
538 if err != nil {
539 return uuid.Nil, errs.Wrap(err, "error parsing host-id")
540 }
541 return u, nil
542 }