forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth_command.go
388 lines (347 loc) · 12.9 KB
/
auth_command.go
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package common
import (
"fmt"
"io/ioutil"
"os"
"strings"
"time"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/auth/native"
"github.com/gravitational/teleport/lib/client"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/service"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/sshutils"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/kingpin"
"github.com/gravitational/trace"
)
// AuthCommand implements `tctl auth` group of commands
type AuthCommand struct {
config *service.Config
authType string
genPubPath string
genPrivPath string
genUser string
genHost string
genTTL time.Duration
exportAuthorityFingerprint string
exportPrivateKeys bool
output string
outputFormat client.IdentityFileFormat
compatVersion string
compatibility string
rotateGracePeriod time.Duration
rotateType string
rotateManualMode bool
rotateTargetPhase string
authGenerate *kingpin.CmdClause
authExport *kingpin.CmdClause
authSign *kingpin.CmdClause
authRotate *kingpin.CmdClause
}
// Initialize allows TokenCommand to plug itself into the CLI parser
func (a *AuthCommand) Initialize(app *kingpin.Application, config *service.Config) {
a.config = config
// operations with authorities
auth := app.Command("auth", "Operations with user and host certificate authorities (CAs)").Hidden()
a.authExport = auth.Command("export", "Export public cluster (CA) keys to stdout")
a.authExport.Flag("keys", "if set, will print private keys").BoolVar(&a.exportPrivateKeys)
a.authExport.Flag("fingerprint", "filter authority by fingerprint").StringVar(&a.exportAuthorityFingerprint)
a.authExport.Flag("compat", "export cerfiticates compatible with specific version of Teleport").StringVar(&a.compatVersion)
a.authExport.Flag("type", "certificate type: 'user', 'host' or 'tls'").StringVar(&a.authType)
a.authGenerate = auth.Command("gen", "Generate a new SSH keypair").Hidden()
a.authGenerate.Flag("pub-key", "path to the public key").Required().StringVar(&a.genPubPath)
a.authGenerate.Flag("priv-key", "path to the private key").Required().StringVar(&a.genPrivPath)
a.authSign = auth.Command("sign", "Create an identity file(s) for a given user")
a.authSign.Flag("user", "Teleport user name").StringVar(&a.genUser)
a.authSign.Flag("host", "Teleport host name").StringVar(&a.genHost)
a.authSign.Flag("out", "identity output").Short('o').StringVar(&a.output)
a.authSign.Flag("format", fmt.Sprintf("identity format: %q (default) or %q", client.IdentityFormatFile, client.IdentityFormatOpenSSH)).Default(string(client.DefaultIdentityFormat)).StringVar((*string)(&a.outputFormat))
a.authSign.Flag("ttl", "TTL (time to live) for the generated certificate").Default(fmt.Sprintf("%v", defaults.CertDuration)).DurationVar(&a.genTTL)
a.authSign.Flag("compat", "OpenSSH compatibility flag").StringVar(&a.compatibility)
a.authRotate = auth.Command("rotate", "Rotate certificate authorities in the cluster")
a.authRotate.Flag("grace-period", "Grace period keeps previous certificate authorities signatures valid, if set to 0 will force users to relogin and nodes to re-register.").Default(fmt.Sprintf("%v", defaults.RotationGracePeriod)).DurationVar(&a.rotateGracePeriod)
a.authRotate.Flag("manual", "Activate manual rotation , set rotation phases manually").BoolVar(&a.rotateManualMode)
a.authRotate.Flag("type", "Certificate authority to rotate, rotates both host and user CA by default").StringVar(&a.rotateType)
a.authRotate.Flag("phase", fmt.Sprintf("Target rotation phase to set, used in manual rotation, one of: %v", strings.Join(services.RotatePhases, ", "))).StringVar(&a.rotateTargetPhase)
}
// TryRun takes the CLI command as an argument (like "auth gen") and executes it
// or returns match=false if 'cmd' does not belong to it
func (a *AuthCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error) {
switch cmd {
case a.authGenerate.FullCommand():
err = a.GenerateKeys()
case a.authExport.FullCommand():
err = a.ExportAuthorities(client)
case a.authSign.FullCommand():
err = a.GenerateAndSignKeys(client)
case a.authRotate.FullCommand():
err = a.RotateCertAuthority(client)
default:
return false, nil
}
return true, trace.Wrap(err)
}
// ExportAuthorities outputs the list of authorities in OpenSSH compatible formats
// If --type flag is given, only prints keys for CAs of this type, otherwise
// prints all keys
func (a *AuthCommand) ExportAuthorities(client auth.ClientI) error {
var typesToExport []services.CertAuthType
// this means to export TLS authority
if a.authType == "tls" {
clusterName, err := client.GetDomainName()
if err != nil {
return trace.Wrap(err)
}
certAuthority, err := client.GetCertAuthority(
services.CertAuthID{Type: services.HostCA, DomainName: clusterName},
a.exportPrivateKeys)
if err != nil {
return trace.Wrap(err)
}
if len(certAuthority.GetTLSKeyPairs()) != 1 {
return trace.BadParameter("expected one TLS key pair, got %v", len(certAuthority.GetTLSKeyPairs()))
}
keyPair := certAuthority.GetTLSKeyPairs()[0]
if a.exportPrivateKeys {
fmt.Println(string(keyPair.Key))
}
fmt.Println(string(keyPair.Cert))
return nil
}
// if no --type flag is given, export all types
if a.authType == "" {
typesToExport = []services.CertAuthType{services.HostCA, services.UserCA}
} else {
authType := services.CertAuthType(a.authType)
if err := authType.Check(); err != nil {
return trace.Wrap(err)
}
typesToExport = []services.CertAuthType{authType}
}
localAuthName, err := client.GetDomainName()
if err != nil {
return trace.Wrap(err)
}
// fetch authorities via auth API (and only take local CAs, ignoring
// trusted ones)
var authorities []services.CertAuthority
for _, at := range typesToExport {
cas, err := client.GetCertAuthorities(at, a.exportPrivateKeys)
if err != nil {
return trace.Wrap(err)
}
for _, ca := range cas {
if ca.GetClusterName() == localAuthName {
authorities = append(authorities, ca)
}
}
}
// print:
for _, ca := range authorities {
if a.exportPrivateKeys {
for _, key := range ca.GetSigningKeys() {
fingerprint, err := sshutils.PrivateKeyFingerprint(key)
if err != nil {
return trace.Wrap(err)
}
if a.exportAuthorityFingerprint != "" && fingerprint != a.exportAuthorityFingerprint {
continue
}
os.Stdout.Write(key)
fmt.Fprintf(os.Stdout, "\n")
}
} else {
for _, keyBytes := range ca.GetCheckingKeys() {
fingerprint, err := sshutils.AuthorizedKeyFingerprint(keyBytes)
if err != nil {
return trace.Wrap(err)
}
if a.exportAuthorityFingerprint != "" && fingerprint != a.exportAuthorityFingerprint {
continue
}
// export certificates in the old 1.0 format where host and user
// certificate authorities were exported in the known_hosts format.
if a.compatVersion == "1.0" {
castr, err := hostCAFormat(ca, keyBytes, client)
if err != nil {
return trace.Wrap(err)
}
fmt.Println(castr)
continue
}
// export certificate authority in user or host ca format
var castr string
switch ca.GetType() {
case services.UserCA:
castr, err = userCAFormat(ca, keyBytes)
case services.HostCA:
castr, err = hostCAFormat(ca, keyBytes, client)
default:
return trace.BadParameter("unknown user type: %q", ca.GetType())
}
if err != nil {
return trace.Wrap(err)
}
// print the export friendly string
fmt.Println(castr)
}
}
}
return nil
}
// GenerateKeys generates a new keypair
func (a *AuthCommand) GenerateKeys() error {
keygen, err := native.New(native.PrecomputeKeys(0))
if err != nil {
return trace.Wrap(err)
}
defer keygen.Close()
privBytes, pubBytes, err := keygen.GenerateKeyPair("")
if err != nil {
return trace.Wrap(err)
}
err = ioutil.WriteFile(a.genPubPath, pubBytes, 0600)
if err != nil {
return trace.Wrap(err)
}
err = ioutil.WriteFile(a.genPrivPath, privBytes, 0600)
if err != nil {
return trace.Wrap(err)
}
fmt.Printf("wrote public key to: %v and private key to: %v\n", a.genPubPath, a.genPrivPath)
return nil
}
// GenerateAndSignKeys generates a new keypair and signs it for role
func (a *AuthCommand) GenerateAndSignKeys(clusterApi auth.ClientI) error {
switch {
case a.genUser != "" && a.genHost == "":
return a.generateUserKeys(clusterApi)
case a.genUser == "" && a.genHost != "":
return a.generateHostKeys(clusterApi)
default:
return trace.BadParameter("--user or --host must be specified")
}
}
// RotateCertAuthority starts or restarts certificate authority rotation process
func (a *AuthCommand) RotateCertAuthority(client auth.ClientI) error {
req := auth.RotateRequest{
Type: services.CertAuthType(a.rotateType),
GracePeriod: &a.rotateGracePeriod,
TargetPhase: a.rotateTargetPhase,
}
if a.rotateManualMode {
req.Mode = services.RotationModeManual
} else {
req.Mode = services.RotationModeAuto
}
if err := client.RotateCertAuthority(req); err != nil {
return err
}
if a.rotateTargetPhase != "" {
fmt.Printf("Updated rotation phase to %q. To check status use 'tctl status'\n", a.rotateTargetPhase)
} else {
fmt.Printf("Initiated certificate authority rotation. To check status use 'tctl status'\n")
}
return nil
}
func (a *AuthCommand) generateHostKeys(clusterApi auth.ClientI) error {
// only format=openssh is supported
if a.outputFormat != client.IdentityFormatOpenSSH {
return trace.BadParameter("invalid --format flag %q, only %q is supported", a.outputFormat, client.IdentityFormatOpenSSH)
}
// split up comma separated list
principals := strings.Split(a.genHost, ",")
// generate a keypair
key, err := client.NewKey()
if err != nil {
return trace.Wrap(err)
}
cn, err := clusterApi.GetClusterName()
if err != nil {
return trace.Wrap(err)
}
clusterName := cn.GetClusterName()
key.Cert, err = clusterApi.GenerateHostCert(key.Pub,
"", "", principals,
clusterName, teleport.Roles{teleport.RoleNode}, 0)
if err != nil {
return trace.Wrap(err)
}
// if no name was given, take the first name on the list of principals
filePath := a.output
if filePath == "" {
filePath = principals[0]
}
err = client.MakeIdentityFile(filePath, key, a.outputFormat, nil)
if err != nil {
return trace.Wrap(err)
}
if a.output != "" {
fmt.Printf("\nThe certificate has been written to %s\n", a.output)
}
return nil
}
func (a *AuthCommand) generateUserKeys(clusterApi auth.ClientI) error {
// parse compatibility parameter
certificateFormat, err := utils.CheckCertificateFormatFlag(a.compatibility)
if err != nil {
return trace.Wrap(err)
}
// generate a keypair:
key, err := client.NewKey()
if err != nil {
return trace.Wrap(err)
}
// sign it and produce a cert:
key.Cert, err = clusterApi.GenerateUserCert(key.Pub, a.genUser, a.genTTL, certificateFormat)
if err != nil {
return trace.Wrap(err)
}
var certAuthorities []services.CertAuthority
if a.outputFormat == client.IdentityFormatFile {
certAuthorities, err = clusterApi.GetCertAuthorities(services.HostCA, false)
if err != nil {
return trace.Wrap(err)
}
}
// write the cert+private key to the output:
err = client.MakeIdentityFile(a.output, key, a.outputFormat, certAuthorities)
if err != nil {
return trace.Wrap(err)
}
if a.output != "" {
fmt.Printf("\nThe certificate has been written to %s\n", a.output)
}
return nil
}
// userCAFormat returns the certificate authority public key exported as a single
// line that can be placed in ~/.ssh/authorized_keys file. The format adheres to the
// man sshd (8) authorized_keys format, a space-separated list of: options, keytype,
// base64-encoded key, comment.
// For example:
//
// cert-authority AAA... type=user&clustername=cluster-a
//
// URL encoding is used to pass the CA type and cluster name into the comment field.
func userCAFormat(ca services.CertAuthority, keyBytes []byte) (string, error) {
return sshutils.MarshalAuthorizedKeysFormat(ca.GetClusterName(), keyBytes)
}
// hostCAFormat returns the certificate authority public key exported as a single line
// that can be placed in ~/.ssh/authorized_hosts. The format adheres to the man sshd (8)
// authorized_hosts format, a space-separated list of: marker, hosts, key, and comment.
// For example:
//
// @cert-authority *.cluster-a ssh-rsa AAA... type=host
//
// URL encoding is used to pass the CA type and allowed logins into the comment field.
func hostCAFormat(ca services.CertAuthority, keyBytes []byte, client auth.ClientI) (string, error) {
roles, err := services.FetchRoles(ca.GetRoles(), client, nil)
if err != nil {
return "", trace.Wrap(err)
}
allowedLogins, _ := roles.CheckLoginDuration(defaults.MinCertDuration + time.Second)
return sshutils.MarshalAuthorizedHostsFormat(ca.GetClusterName(), keyBytes, allowedLogins)
}