| 1 | package ssh |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | |
| 6 | "github.com/pkg/errors" |
| 7 | "github.com/smallstep/cli/command" |
| 8 | "github.com/smallstep/cli/crypto/sshutil" |
| 9 | "github.com/smallstep/cli/errs" |
| 10 | "github.com/urfave/cli" |
| 11 | ) |
| 12 | |
| 13 | func listCommand() cli.Command { |
| 14 | return cli.Command{ |
| 15 | Name: "list", |
| 16 | Action: command.ActionFunc(listAction), |
| 17 | Usage: "list public keys known to the ssh agent", |
| 18 | UsageText: `**step ssh list** [<subject>] [**--raw**]`, |
| 19 | Description: `**step ssh list** list public key identities known to the ssh agent. |
| 20 | |
| 21 | By default it prints key fingerprints, to list the raw key use the flag **--raw**. |
| 22 | |
| 23 | ## POSITIONAL ARGUMENTS |
| 24 | |
| 25 | <subject> |
| 26 | : Optional subject or comment to filter keys by. |
| 27 | |
| 28 | ## EXAMPLES |
| 29 | |
| 30 | List all key fingerprints known to the agent: |
| 31 | ''' |
| 32 | $ step ssh list |
| 33 | ''' |
| 34 | |
| 35 | List all the key fingerprints with the comment joe@work: |
| 36 | ''' |
| 37 | $ step ssh list joe@work |
| 38 | ''' |
| 39 | |
| 40 | List all keys known to the agent: |
| 41 | ''' |
| 42 | $ step ssh list --raw |
| 43 | ''' |
| 44 | |
| 45 | List all the keys with the comment joe@work: |
| 46 | ''' |
| 47 | $ step ssh list --raw joe@work |
| 48 | '''`, |
| 49 | Flags: []cli.Flag{ |
| 50 | cli.BoolFlag{ |
| 51 | Name: "raw", |
| 52 | Usage: "List public keys instead of fingerprints.", |
| 53 | }, |
| 54 | }, |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | func listAction(ctx *cli.Context) error { |
| 59 | if err := errs.MinMaxNumberOfArguments(ctx, 0, 1); err != nil { |
| 60 | return err |
| 61 | } |
| 62 | |
| 63 | var subject string |
| 64 | if ctx.NArg() > 0 { |
| 65 | subject = ctx.Args().First() |
| 66 | } |
| 67 | |
| 68 | agent, err := sshutil.DialAgent() |
| 69 | if err != nil { |
| 70 | return err |
| 71 | } |
| 72 | |
| 73 | keys, err := agent.List() |
| 74 | if err != nil { |
| 75 | return errors.Wrap(err, "error listing identities") |
| 76 | } |
| 77 | |
| 78 | if len(keys) == 0 { |
| 79 | fmt.Println("The agent has no identities.") |
| 80 | return nil |
| 81 | } |
| 82 | |
| 83 | if ctx.Bool("raw") { |
| 84 | for _, k := range keys { |
| 85 | if ctx.NArg() == 0 || k.Comment == subject { |
| 86 | fmt.Println(k.String()) |
| 87 | } |
| 88 | } |
| 89 | } else { |
| 90 | for _, k := range keys { |
| 91 | if ctx.NArg() == 0 || k.Comment == subject { |
| 92 | s, err := sshutil.Fingerprint([]byte(k.String())) |
| 93 | if err != nil { |
| 94 | return err |
| 95 | } |
| 96 | fmt.Println(s) |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | return nil |
| 102 | } |