File: rekey.go

package info (click to toggle)
golang-github-smallstep-cli 0.15.16%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,404 kB
  • sloc: sh: 512; makefile: 99
file content (192 lines) | stat: -rw-r--r-- 5,036 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package ssh

import (
	"io/ioutil"
	"strconv"

	"github.com/pkg/errors"
	"github.com/smallstep/certificates/api"
	"github.com/smallstep/certificates/authority/provisioner"
	"github.com/smallstep/certificates/ca/identity"
	"github.com/smallstep/cli/command"
	"github.com/smallstep/cli/crypto/keys"
	"github.com/smallstep/cli/crypto/pemutil"
	"github.com/smallstep/cli/errs"
	"github.com/smallstep/cli/flags"
	"github.com/smallstep/cli/ui"
	"github.com/smallstep/cli/utils"
	"github.com/smallstep/cli/utils/cautils"
	"github.com/urfave/cli"
	"golang.org/x/crypto/ssh"
)

func rekeyCommand() cli.Command {
	return cli.Command{
		Name:   "rekey",
		Action: command.ActionFunc(rekeyAction),
		Usage:  "rekey a SSH certificate using the SSH CA",
		UsageText: `**step ssh rekey** <ssh-cert> <ssh-key>
[**--out**=<file>] [**--issuer**=<name>] [**--password-file**=<path>]
[**--force**] [**--ca-url**=<uri>] [**--root**=<path>]
[**--offline**] [**--ca-config**=<path>]`,
		Description: `**step ssh rekey** command generates a new SSH Certificate and key using
an existing SSH Cerfificate and key pair to authenticate and templatize the
request. It writes the new certificate to disk - either overwriting
<ssh-cert> or using new files when the **--out**=<file> flag is used.

## POSITIONAL ARGUMENTS

<ssh-cert>
:  The ssh certificate to renew.

<ssh-key>
:  The ssh certificate private key.

## EXAMPLES

Rekey an ssh certificate:
'''
$ step ssh rekey id_ecdsa-cert.pub id_ecdsa
'''

Rekey an ssh certificate creating id2_ecdsa, id2_ecdsa.pub, and id2_ecdsa-cert.pub:
'''
$ step ssh rekey --out id2_ecdsa id_ecdsa-cert.pub id_ecdsa
'''`,
		Flags: []cli.Flag{
			cli.StringFlag{
				Name:  "out",
				Usage: `The new key <file> path. Defaults to overwriting the <ssh-cert> positional argument.`,
			},
			flags.Provisioner,
			sshProvisionerPasswordFlag,
			flags.NoPassword,
			flags.Insecure,
			flags.Force,
			flags.CaURL,
			flags.Root,
			flags.Offline,
			flags.CaConfig,
			flags.SSHPOPCert,
			flags.SSHPOPKey,
		},
	}
}

func rekeyAction(ctx *cli.Context) error {
	if err := errs.NumberOfArguments(ctx, 2); err != nil {
		return err
	}

	args := ctx.Args()
	certFile := args.Get(0)
	keyFile := args.Get(1)

	// SSH uses fixed suffixes for public keys and certificates
	var newPubFile, newCertFile, newKeyFile string
	if out := ctx.String("out"); out != "" {
		newPubFile = out + ".pub"
		newCertFile = out + "-cert.pub"
		newKeyFile = out
	} else {
		newPubFile = keyFile + ".pub"
		newCertFile = certFile
		newKeyFile = keyFile
	}

	// Extra flags
	passwordFile := ctx.String("password-file")
	noPassword := ctx.Bool("no-password")
	insecure := ctx.Bool("insecure")

	flow, err := cautils.NewCertificateFlow(ctx)
	if err != nil {
		return err
	}

	// Load the cert, because we need the serial number.
	certBytes, err := ioutil.ReadFile(certFile)
	if err != nil {
		return errors.Wrapf(err, "error reading ssh certificate from %s", certFile)
	}
	sshpub, _, _, _, err := ssh.ParseAuthorizedKey(certBytes)
	if err != nil {
		return errors.Wrapf(err, "error parsing ssh public key from %s", certFile)
	}
	cert, ok := sshpub.(*ssh.Certificate)
	if !ok {
		return errors.New("error casting ssh public key to ssh certificate")
	}
	serial := strconv.FormatUint(cert.Serial, 10)

	ctx.Set("sshpop-cert", certFile)
	ctx.Set("sshpop-key", keyFile)
	token, err := flow.GenerateSSHToken(ctx, serial, cautils.SSHRekeyType, nil, provisioner.TimeDuration{}, provisioner.TimeDuration{})
	if err != nil {
		return err
	}

	caClient, err := flow.GetClient(ctx, token)
	if err != nil {
		return err
	}

	// Generate keypair
	pub, priv, err := keys.GenerateDefaultKeyPair()
	if err != nil {
		return err
	}

	sshPub, err := ssh.NewPublicKey(pub)
	if err != nil {
		return errors.Wrap(err, "error creating public key")
	}

	resp, err := caClient.SSHRekey(&api.SSHRekeyRequest{
		OTT:       token,
		PublicKey: sshPub.Marshal(),
	})
	if err != nil {
		return err
	}

	// Private key (with password unless --no-password --insecure)
	opts := []pemutil.Options{
		pemutil.WithOpenSSH(true),
		pemutil.ToFile(newKeyFile, 0600),
	}
	switch {
	case noPassword && insecure:
	case passwordFile != "":
		opts = append(opts, pemutil.WithPasswordFile(passwordFile))
	default:
		opts = append(opts, pemutil.WithPasswordPrompt("Please enter the password to encrypt the private key"))
	}
	_, err = pemutil.Serialize(priv, opts...)
	if err != nil {
		return err
	}

	// Write public key
	if err := utils.WriteFile(newPubFile, marshalPublicKey(sshPub, cert.KeyId), 0644); err != nil {
		return err
	}

	// Write certificate
	if err := utils.WriteFile(newCertFile, marshalPublicKey(resp.Certificate, cert.KeyId), 0644); err != nil {
		return err
	}

	// Write renewed identity
	if len(resp.IdentityCertificate) > 0 {
		if err := identity.WriteIdentityCertificate(resp.IdentityCertificate); err != nil {
			return err
		}
	}

	ui.PrintSelected("Private Key", newKeyFile)
	ui.PrintSelected("Public Key", newPubFile)
	ui.PrintSelected("Certificate", newCertFile)

	return nil
}