forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
458 lines (410 loc) · 14.3 KB
/
main.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/*
Copyright 2015 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/config"
"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/teleport/lib/web"
"github.com/buger/goterm"
"github.com/gravitational/trace"
"golang.org/x/crypto/ssh"
)
type CLIConfig struct {
Debug bool
}
type UserCommand struct {
config *service.Config
login string
allowedLogins string
}
type NodeCommand struct {
config *service.Config
}
type AuthCommand struct {
config *service.Config
authType string
}
type AuthServerCommand struct {
config *service.Config
}
type ReverseTunnelCommand struct {
config *service.Config
domainNames string
dialAddrs utils.NetAddrList
ttl time.Duration
}
func main() {
utils.InitLoggerCLI()
app := utils.InitCLIParser("tctl", GlobalHelpString)
// generate default tctl configuration:
cfg := service.MakeDefaultConfig()
cmdUsers := UserCommand{config: cfg}
cmdNodes := NodeCommand{config: cfg}
cmdAuth := AuthCommand{config: cfg}
cmdAuthServers := AuthServerCommand{config: cfg}
cmdReverseTunnel := ReverseTunnelCommand{config: cfg}
// define global flags:
var ccf CLIConfig
app.Flag("debug", "Enable verbose logging to stderr").
Short('d').
BoolVar(&ccf.Debug)
// commands:
ver := app.Command("version", "Print the version.")
app.HelpFlag.Short('h')
// user add command:
users := app.Command("users", "Manage users logins")
userAdd := users.Command("add", "Generates an invitation token and prints the signup URL for setting up 2nd factor auth.")
userAdd.Arg("login", "Teleport user login").Required().StringVar(&cmdUsers.login)
userAdd.Arg("local-logins", "Local UNIX users this account can log in as [login]").
Default("").StringVar(&cmdUsers.allowedLogins)
userAdd.Alias(AddUserHelp)
// list users command
userList := users.Command("ls", "Lists all user accounts")
// delete user command
userDelete := users.Command("del", "Deletes user accounts")
userDelete.Arg("logins", "Comma-separated list of user logins to delete").
Required().StringVar(&cmdUsers.login)
// add node command
nodes := app.Command("nodes", "Issue invites for other nodes to join the cluster")
nodeAdd := nodes.Command("add", "Adds a new SSH node to join the cluster")
nodeAdd.Alias(AddNodeHelp)
nodeList := nodes.Command("ls", "Lists all active SSH nodes within the cluster")
nodeList.Alias(ListNodesHelp)
// operations with authorities
auth := app.Command("authorities", "Operations with user and host certificate authorities").Hidden()
auth.Flag("type", "authority type, 'user' or 'host'").Default(string(services.UserCA)).StringVar(&cmdAuth.authType)
authList := auth.Command("ls", "List trusted user certificate authorities").Hidden()
authExport := auth.Command("export", "Export concatenated keys to standard output").Hidden()
// operations with auth servers
authServers := app.Command("authservers", "Operations with user and host certificate authorities").Hidden()
authServerAdd := authServers.Command("add", "Add a new auth server node to the cluster").Hidden()
// operations with reverse tunnels
reverseTunnels := app.Command("rts", "Operations with reverse tunnels").Hidden()
reverseTunnelsList := reverseTunnels.Command("ls", "List reverse tunnels").Hidden()
reverseTunnelsDelete := reverseTunnels.Command("del", "Deletes reverse tunnels").Hidden()
reverseTunnelsDelete.Arg("domain", "Comma-separated list of reverse tunnels to delete").
Required().StringVar(&cmdReverseTunnel.domainNames)
reverseTunnelsUpsert := reverseTunnels.Command("upsert", "Update or add a new reverse tunnel").Hidden()
reverseTunnelsUpsert.Arg("domain", "Domain name of the reverse tunnel").
Required().StringVar(&cmdReverseTunnel.domainNames)
reverseTunnelsUpsert.Arg("addrs", "Comma-separated list of dial addresses for reverse tunnels to dial").
Required().SetValue(&cmdReverseTunnel.dialAddrs)
reverseTunnelsUpsert.Flag("ttl", "Optional TTL (time to live) for reverse tunnel").DurationVar(&cmdReverseTunnel.ttl)
// parse CLI commands+flags:
command, err := app.Parse(os.Args[1:])
if err != nil {
utils.FatalError(err)
}
// --debug flag
if ccf.Debug {
utils.InitLoggerDebug()
}
validateConfig(cfg)
// connect to the teleport auth service:
client, err := connectToAuthService(cfg)
if err != nil {
utils.FatalError(err)
}
// execute the selected command:
switch command {
case ver.FullCommand():
onVersion()
case userAdd.FullCommand():
err = cmdUsers.Add(cfg.Hostname, client)
case userList.FullCommand():
err = cmdUsers.List(client)
case userDelete.FullCommand():
err = cmdUsers.Delete(client)
case nodeAdd.FullCommand():
err = cmdNodes.Invite(client)
case nodeList.FullCommand():
err = cmdNodes.ListActive(client)
case authList.FullCommand():
err = cmdAuth.ListAuthorities(client)
case authExport.FullCommand():
err = cmdAuth.ExportAuthorities(client)
case authServerAdd.FullCommand():
err = cmdAuthServers.Invite(client)
case reverseTunnelsList.FullCommand():
err = cmdReverseTunnel.ListActive(client)
case reverseTunnelsDelete.FullCommand():
err = cmdReverseTunnel.Delete(client)
case reverseTunnelsUpsert.FullCommand():
err = cmdReverseTunnel.Upsert(client)
}
if err != nil {
utils.FatalError(err)
}
}
func onVersion() {
utils.PrintVersion()
}
func printHeader(t *goterm.Table, cols []string) {
dots := make([]string, len(cols))
for i := range dots {
dots[i] = strings.Repeat("-", len(cols[i]))
}
fmt.Fprint(t, strings.Join(cols, "\t")+"\n")
fmt.Fprint(t, strings.Join(dots, "\t")+"\n")
}
// Add creates a new sign-up token and prints a token URL to stdout.
// A user is not created until he visits the sign-up URL and completes the process
func (u *UserCommand) Add(hostname string, client *auth.TunClient) error {
// if no local logins were specified, default to 'login'
if u.allowedLogins == "" {
u.allowedLogins = u.login
}
token, err := client.CreateSignupToken(u.login, strings.Split(u.allowedLogins, ","))
if err != nil {
return err
}
if hostname == "" {
hostname, _ = os.Hostname()
}
url := web.CreateSignupLink(net.JoinHostPort(hostname, strconv.Itoa(defaults.HTTPListenPort)), token)
fmt.Printf("Signup token has been created and is valid for %v seconds. Share this URL with the user:\n%v\n\nNOTE: make sure the hostname is accessible!\n", defaults.MaxSignupTokenTTL.Seconds(), url)
return nil
}
// List prints all existing user accounts
func (u *UserCommand) List(client *auth.TunClient) error {
users, err := client.GetUsers()
if err != nil {
return trace.Wrap(err)
}
usersView := func(users []services.User) string {
t := goterm.NewTable(0, 10, 5, ' ', 0)
printHeader(t, []string{"User", "Allowed to login as"})
if len(users) == 0 {
return t.String()
}
for _, u := range users {
fmt.Fprintf(t, "%v\t%v\n", u.Name, strings.Join(u.AllowedLogins, ","))
}
return t.String()
}
fmt.Printf(usersView(users))
return nil
}
// Delete deletes teleport user(s). User IDs are passed as a comma-separated
// list in UserCommand.login
func (u *UserCommand) Delete(client *auth.TunClient) error {
for _, l := range strings.Split(u.login, ",") {
if err := client.DeleteUser(l); err != nil {
return trace.Wrap(err)
}
fmt.Printf("User '%v' has been deleted\n", l)
}
return nil
}
// Invite generates a token which can be used to add another SSH node
// to a cluster
func (u *NodeCommand) Invite(client *auth.TunClient) error {
token, err := client.GenerateToken(teleport.RoleNode, defaults.MaxProvisioningTokenTTL)
if err != nil {
return trace.Wrap(err)
}
fmt.Printf(
"The invite token: %v\nRun this on the new node to join the cluster:\n> teleport start --roles=node --token=%v --auth-server=<Address>\n\nNotes:\n",
token, token)
fmt.Printf(" 1. This invitation token will expire in %v seconds.\n", defaults.MaxProvisioningTokenTTL.Seconds())
fmt.Printf(" 2. <Address> is the IP this auth server is reachable at from the node.\n")
return nil
}
// ListActive retreives the list of nodes who recently sent heartbeats to
// to a cluster and prints it to stdout
func (u *NodeCommand) ListActive(client *auth.TunClient) error {
nodes, err := client.GetNodes()
if err != nil {
return trace.Wrap(err)
}
nodesView := func(nodes []services.Server) string {
t := goterm.NewTable(0, 10, 5, ' ', 0)
printHeader(t, []string{"Node Name", "Node ID", "Address", "Labels"})
if len(nodes) == 0 {
return t.String()
}
for _, n := range nodes {
fmt.Fprintf(t, "%v\t%v\t%v\t%v\n", n.Hostname, n.ID, n.Addr, n.LabelsString())
}
return t.String()
}
fmt.Printf(nodesView(nodes))
return nil
}
// ListAuthorities shows list of user authorities we trust
func (a *AuthCommand) ListAuthorities(client *auth.TunClient) error {
authType := services.CertAuthType(a.authType)
if err := authType.Check(); err != nil {
return trace.Wrap(err)
}
authorities, err := client.GetCertAuthorities(authType)
if err != nil {
return trace.Wrap(err)
}
view := func() string {
t := goterm.NewTable(0, 10, 5, ' ', 0)
printHeader(t, []string{"Type", "Cluster name", "Fingerprint", "Restricted to logins"})
if len(authorities) == 0 {
return t.String()
}
for _, a := range authorities {
for _, keyBytes := range a.CheckingKeys {
fingerprint := ""
key, _, _, _, err := ssh.ParseAuthorizedKey(keyBytes)
if err != nil {
fingerprint = fmt.Sprintf("<bad key: %v", err)
} else {
fingerprint = sshutils.Fingerprint(key)
}
fmt.Fprintf(t, "%v\t%v\t%v\t%v\n", a.Type, a.DomainName, fingerprint, strings.Join(a.AllowedLogins, ","))
}
}
return t.String()
}
fmt.Printf(view())
return nil
}
// ExportAuthorities outputs the list of authorities
func (a *AuthCommand) ExportAuthorities(client *auth.TunClient) error {
authType := services.CertAuthType(a.authType)
if err := authType.Check(); err != nil {
return trace.Wrap(err)
}
authorities, err := client.GetCertAuthorities(authType)
if err != nil {
return trace.Wrap(err)
}
for _, a := range authorities {
for _, key := range a.CheckingKeys {
if authType == services.UserCA {
// for user authorities, export in the sshd's TrustedUserCAKeys format
os.Stdout.Write(key)
} else {
// for host authorities export them in the authorized_keys - compatible format
fmt.Fprintf(os.Stdout, "@cert-authority *.%v %v", a.DomainName, string(key))
}
}
}
return nil
}
// Invite generates a token which can be used to add another SSH auth server
// to the cluster
func (u *AuthServerCommand) Invite(client *auth.TunClient) error {
authDomainName, err := client.GetLocalDomain()
if err != nil {
return trace.Wrap(err)
}
token, err := client.GenerateToken(teleport.RoleAuth, defaults.InviteTokenTTL)
if err != nil {
return trace.Wrap(err)
}
cfg := config.MakeAuthPeerFileConfig(authDomainName, token)
out := cfg.DebugDumpToYAML()
fmt.Printf(
"# Run this config the new auth server to join the cluster:\n# > teleport start --config config.yaml\n# Fill in auth peers in this config:\n")
fmt.Println(out)
return nil
}
// ListActive retreives the list of nodes who recently sent heartbeats to
// to a cluster and prints it to stdout
func (r *ReverseTunnelCommand) ListActive(client *auth.TunClient) error {
tunnels, err := client.GetReverseTunnels()
if err != nil {
return trace.Wrap(err)
}
tunnelsView := func() string {
t := goterm.NewTable(0, 10, 5, ' ', 0)
printHeader(t, []string{"Domain", "Dial Addresses"})
if len(tunnels) == 0 {
return t.String()
}
for _, tunnel := range tunnels {
fmt.Fprintf(t, "%v\t%v\n", tunnel.DomainName, strings.Join(tunnel.DialAddrs, ","))
}
return t.String()
}
fmt.Printf(tunnelsView())
return nil
}
// Upsert updates or inserts new reverse tunnel
func (r *ReverseTunnelCommand) Upsert(client *auth.TunClient) error {
err := client.UpsertReverseTunnel(services.ReverseTunnel{
DomainName: r.domainNames,
DialAddrs: r.dialAddrs.Addresses()},
r.ttl)
if err != nil {
return trace.Wrap(err)
}
fmt.Printf("Reverse tunnel updated\n")
return nil
}
// Delete deletes teleport user(s). User IDs are passed as a comma-separated
// list in UserCommand.login
func (r *ReverseTunnelCommand) Delete(client *auth.TunClient) error {
for _, domainName := range strings.Split(r.domainNames, ",") {
if err := client.DeleteReverseTunnel(domainName); err != nil {
return trace.Wrap(err)
}
fmt.Printf("Reverse tunnel '%v' has been deleted\n", domainName)
}
return nil
}
// connectToAuthService creates a valid client connection to the auth service
func connectToAuthService(cfg *service.Config) (client *auth.TunClient, err error) {
// connect to the local auth server by default:
cfg.Auth.Enabled = true
cfg.AuthServers = []utils.NetAddr{
*defaults.AuthConnectAddr(),
}
// read the host SSH keys and use them to open an SSH connection to the auth service
i, err := auth.ReadIdentity(cfg.DataDir, auth.IdentityID{Role: teleport.RoleAdmin, HostUUID: cfg.HostUUID})
if err != nil {
return nil, trace.Wrap(err)
}
client, err = auth.NewTunClient(
cfg.AuthServers,
cfg.HostUUID,
[]ssh.AuthMethod{ssh.PublicKeys(i.KeySigner)})
if err != nil {
return nil, trace.Wrap(err)
}
// check connectivity by calling something on a clinet:
_, err = client.GetDialer()()
if err != nil {
utils.Consolef(os.Stderr,
"Cannot connect to the auth server: %v.\nIs the auth server running on %v?", err, cfg.AuthServers[0].Addr)
os.Exit(1)
}
return client, nil
}
// validateConfig updtes&validates tctl configuration
func validateConfig(cfg *service.Config) {
var err error
// read or generate a host UUID for this node
cfg.HostUUID, err = utils.ReadOrMakeHostUUID(cfg.DataDir)
if err != nil {
utils.FatalError(err)
}
}