-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1100 lines (1017 loc) · 33.8 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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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 (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/auth/native"
"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/Sirupsen/logrus"
"github.com/buger/goterm"
"github.com/gravitational/kingpin"
"github.com/gravitational/trace"
"golang.org/x/crypto/ssh"
kyaml "k8s.io/client-go/1.4/pkg/util/yaml"
)
type CLIConfig struct {
Debug bool
ConfigFile string
ConfigString string
}
type UserCommand struct {
config *service.Config
login string
allowedLogins string
roles string
identities []string
}
type NodeCommand struct {
config *service.Config
// count is optional hidden field that will cause
// tctl issue count tokens and output them in JSON format
count int
// format is the output format, e.g. text or json
format string
// list of roles for the new node to assume
roles string
// TTL: duration of time during which a generated node token will
// be valid.
ttl time.Duration
// namespace is node namespace
namespace string
}
type AuthCommand struct {
config *service.Config
authType string
genPubPath string
genPrivPath string
genUser string
genTTL time.Duration
exportAuthorityFingerprint string
exportPrivateKeys bool
outDir string
}
type AuthServerCommand struct {
config *service.Config
}
type ReverseTunnelCommand struct {
config *service.Config
domainNames string
dialAddrs utils.NetAddrList
ttl time.Duration
}
type TokenCommand struct {
config *service.Config
// token argument to 'tokens del' command
token string
}
type GetCommand struct {
config *service.Config
ref services.Ref
format string
namespace string
withSecrets bool
}
type CreateCommand struct {
config *service.Config
filename string
}
type DeleteCommand struct {
config *service.Config
ref services.Ref
}
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}
cmdReverseTunnel := ReverseTunnelCommand{config: cfg}
cmdTokens := TokenCommand{config: cfg}
cmdGet := GetCommand{config: cfg}
cmdCreate := CreateCommand{config: cfg}
cmdDelete := DeleteCommand{config: cfg}
// define global flags:
var ccf CLIConfig
app.Flag("debug", "Enable verbose logging to stderr").
Short('d').
BoolVar(&ccf.Debug)
app.Flag("config", fmt.Sprintf("Path to a configuration file [%v]", defaults.ConfigFilePath)).
Short('c').
ExistingFileVar(&ccf.ConfigFile)
app.Flag("config-string",
"Base64 encoded configuration string").Hidden().Envar(defaults.ConfigEnvar).StringVar(&ccf.ConfigString)
// 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", "Generate an invitation token and print the signup URL")
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.Flag("identity", "[EXPERIMENTAL] Add OpenID Connect identity, e.g. --identity=google:bob@gmail.com").Hidden().StringsVar(&cmdUsers.identities)
userAdd.Alias(AddUserHelp)
userUpdate := users.Command("update", "Update properties for existing user").Hidden()
userUpdate.Arg("login", "Teleport user login").Required().StringVar(&cmdUsers.login)
userUpdate.Flag("set-roles", "Roles to assign to this user").
Default("").StringVar(&cmdUsers.roles)
delete := app.Command("del", "Delete resources").Hidden()
delete.Arg("resource", "Resource to delete").SetValue(&cmdDelete.ref)
// get one or many resources in the system
get := app.Command("get", "Get one or many objects in the system").Hidden()
get.Arg("resource", "Resource type and name").SetValue(&cmdGet.ref)
get.Flag("format", "Format output type, one of 'yaml', 'json' or 'text'").Default(formatText).StringVar(&cmdGet.format)
get.Flag("namespace", "Namespace of the resources").Default(defaults.Namespace).StringVar(&cmdGet.namespace)
get.Flag("with-secrets", "Include secrets in resources like certificate authorities or OIDC connectors").Default("false").BoolVar(&cmdGet.withSecrets)
// upsert one or many resources
create := app.Command("create", "Create or update a resource").Hidden()
create.Flag("filename", "resource definition file").Short('f').StringVar(&cmdCreate.filename)
// list users command
userList := users.Command("ls", "List 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", "Generate an invitation token. Use it to add a new node to the Teleport cluster")
nodeAdd.Flag("roles", "Comma-separated list of roles for the new node to assume [node]").Default("node").StringVar(&cmdNodes.roles)
nodeAdd.Flag("ttl", "Time to live for a generated token").Default(defaults.ProvisioningTokenTTL.String()).DurationVar(&cmdNodes.ttl)
nodeAdd.Flag("count", "add count tokens and output JSON with the list").Hidden().Default("1").IntVar(&cmdNodes.count)
nodeAdd.Flag("format", "output format, 'text' or 'json'").Hidden().Default("text").StringVar(&cmdNodes.format)
nodeAdd.Alias(AddNodeHelp)
nodeList := nodes.Command("ls", "List all active SSH nodes within the cluster")
nodeList.Flag("namespace", "Namespace of the nodes").Default(defaults.Namespace).StringVar(&cmdNodes.namespace)
nodeList.Alias(ListNodesHelp)
// operations on invitation tokens
tokens := app.Command("tokens", "List or revoke invitation tokens")
tokenList := tokens.Command("ls", "List node and user invitation tokens")
tokenDel := tokens.Command("del", "Delete/revoke an invitation token")
tokenDel.Arg("token", "Token to delete").StringVar(&cmdTokens.token)
// operations with authorities
auth := app.Command("auth", "Operations with user and host certificate authorities").Hidden()
auth.Flag("type", "authority type, 'user' or 'host'").StringVar(&cmdAuth.authType)
authList := auth.Command("ls", "List trusted certificate authorities (CAs)")
authExport := auth.Command("export", "Export CA keys to standard output")
authExport.Flag("keys", "if set, will print private keys").BoolVar(&cmdAuth.exportPrivateKeys)
authExport.Flag("fingerprint", "filter authority by fingerprint").StringVar(&cmdAuth.exportAuthorityFingerprint)
authGenerate := auth.Command("gen", "Generate a new SSH keypair")
authGenerate.Flag("pub-key", "path to the public key").Required().StringVar(&cmdAuth.genPubPath)
authGenerate.Flag("priv-key", "path to the private key").Required().StringVar(&cmdAuth.genPrivPath)
authSign := auth.Command("sign", "Create a signed user session cerfiticate")
authSign.Flag("user", "Teleport user name").Required().StringVar(&cmdAuth.genUser)
authSign.Flag("out", "Output directory [defaults to current]").Short('o').StringVar(&cmdAuth.outDir)
authSign.Flag("ttl", "TTL (time to live) for the generated certificate").Default(fmt.Sprintf("%v", defaults.CertDuration)).DurationVar(&cmdAuth.genTTL)
// operations with reverse tunnels
reverseTunnels := app.Command("tunnels", "Operations on reverse tunnels clusters").Hidden()
reverseTunnelsList := reverseTunnels.Command("ls", "List tunnels").Hidden()
reverseTunnelsDelete := reverseTunnels.Command("del", "Delete a tunnel").Hidden()
reverseTunnelsDelete.Arg("name", "Tunnels to delete").
Required().StringVar(&cmdReverseTunnel.domainNames)
reverseTunnelsUpsert := reverseTunnels.Command("add", "Create a new reverse tunnel").Hidden()
reverseTunnelsUpsert.Arg("name", "Name of the tunnel").
Required().StringVar(&cmdReverseTunnel.domainNames)
reverseTunnelsUpsert.Arg("addrs", "Comma-separated list of tunnels").
Required().SetValue(&cmdReverseTunnel.dialAddrs)
reverseTunnelsUpsert.Flag("ttl", "Optional TTL (time to live) for the tunnel").DurationVar(&cmdReverseTunnel.ttl)
// parse CLI commands+flags:
command, err := app.Parse(os.Args[1:])
if err != nil {
utils.FatalError(err)
}
// "version" command?
if command == ver.FullCommand() {
onVersion()
return
}
applyConfig(&ccf, cfg)
validateConfig(cfg)
// some commands do not need a connection to client
switch command {
case authGenerate.FullCommand():
err = cmdAuth.GenerateKeys()
if err != nil {
utils.FatalError(err)
}
return
}
// connect to the teleport auth service:
client, err := connectToAuthService(cfg)
if err != nil {
utils.FatalError(err)
}
// execute the selected command:
switch command {
case get.FullCommand():
err = cmdGet.Get(client)
case create.FullCommand():
err = cmdCreate.Create(client)
case delete.FullCommand():
err = cmdDelete.Delete(client)
case userAdd.FullCommand():
err = cmdUsers.Add(client)
case userList.FullCommand():
err = cmdUsers.List(client)
case userUpdate.FullCommand():
err = cmdUsers.Update(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 reverseTunnelsList.FullCommand():
err = cmdReverseTunnel.ListActive(client)
case reverseTunnelsDelete.FullCommand():
err = cmdReverseTunnel.Delete(client)
case reverseTunnelsUpsert.FullCommand():
err = cmdReverseTunnel.Upsert(client)
case tokenList.FullCommand():
err = cmdTokens.List(client)
case tokenDel.FullCommand():
err = cmdTokens.Del(client)
case authSign.FullCommand():
err = cmdAuth.GenerateAndSignKeys(client)
if err != nil {
utils.FatalError(err)
}
return
}
if err != nil {
logrus.Error(trace.DebugReport(err))
utils.FatalError(err)
}
}
func Ref(s kingpin.Settings) *services.Ref {
r := new(services.Ref)
s.SetValue(r)
return r
}
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(client *auth.TunClient) error {
// if no local logins were specified, default to 'login'
if u.allowedLogins == "" {
u.allowedLogins = u.login
}
user := services.UserV1{
Name: u.login,
AllowedLogins: strings.Split(u.allowedLogins, ","),
}
if len(u.identities) != 0 {
for _, identityVar := range u.identities {
vals := strings.SplitN(identityVar, ":", 2)
if len(vals) != 2 {
return trace.Errorf("bad flag --identity=%v, expected <connector-id>:<email> format", identityVar)
}
user.OIDCIdentities = append(user.OIDCIdentities, services.OIDCIdentity{ConnectorID: vals[0], Email: vals[1]})
}
}
token, err := client.CreateSignupToken(user)
if err != nil {
return err
}
proxies, err := client.GetProxies()
if err != nil {
return trace.Wrap(err)
}
hostname := "teleport-proxy"
if len(proxies) == 0 {
fmt.Printf("\x1b[1mWARNING\x1b[0m: this Teleport cluster does not have any proxy servers online.\nYou need to start some to be able to login.\n\n")
} else {
hostname = proxies[0].GetHostname()
}
// try to auto-suggest the activation link
_, proxyPort, err := net.SplitHostPort(u.config.Proxy.WebAddr.Addr)
if err != nil {
proxyPort = strconv.Itoa(defaults.HTTPListenPort)
}
url := web.CreateSignupLink(net.JoinHostPort(hostname, proxyPort), 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 '%s' is accessible!\n", defaults.MaxSignupTokenTTL.Seconds(), url, hostname)
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)
}
coll := &userCollection{users: users}
coll.writeText(os.Stdout)
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
}
// Update updates existing user
func (u *UserCommand) Update(client *auth.TunClient) error {
user, err := client.GetUser(u.login)
if err != nil {
return trace.Wrap(err)
}
roles := strings.Split(u.roles, ",")
for _, role := range roles {
if _, err := client.GetRole(role); err != nil {
return trace.Wrap(err)
}
}
user.SetRoles(roles)
if err := client.UpsertUser(user); err != nil {
return trace.Wrap(err)
}
fmt.Printf("%v has been updated with roles %v\n", user.GetName(), strings.Join(user.GetRoles(), ","))
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 {
if u.count < 1 {
return trace.BadParameter("count should be > 0, got %v", u.count)
}
// parse --roles flag
roles, err := teleport.ParseRoles(u.roles)
if err != nil {
return trace.Wrap(err)
}
var tokens []string
for i := 0; i < u.count; i++ {
token, err := client.GenerateToken(roles, u.ttl)
if err != nil {
return trace.Wrap(err)
}
tokens = append(tokens, token)
}
authServers, err := client.GetAuthServers()
if err != nil {
return trace.Wrap(err)
}
if len(authServers) == 0 {
return trace.Errorf("This cluster does not have any auth servers running")
}
// output format swtich:
if u.format == "text" {
for _, token := range tokens {
fmt.Printf(
"The invite token: %v\nRun this on the new node to join the cluster:\n> teleport start --roles=%s --token=%v --auth-server=%v\n\nPlease note:\n",
token, strings.ToLower(roles.String()), token, authServers[0].GetAddr())
}
fmt.Printf(" - This invitation token will expire in %d minutes\n", int(u.ttl.Minutes()))
fmt.Printf(" - %v must be reachable from the new node, see --advertise-ip server flag\n", authServers[0].GetAddr())
} else {
out, err := json.Marshal(tokens)
if err != nil {
return trace.Wrap(err, "failed to marshal tokens")
}
fmt.Printf(string(out))
}
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(u.namespace)
if err != nil {
return trace.Wrap(err)
}
coll := &serverCollection{servers: nodes}
coll.writeText(os.Stdout)
return nil
}
// ListAuthorities shows list of user authorities we trust
func (a *AuthCommand) ListAuthorities(client *auth.TunClient) error {
// by default show authorities of both types:
authTypes := []services.CertAuthType{
services.UserCA,
services.HostCA,
}
// but if there was a --type switch, only select those:
if a.authType != "" {
authTypes = []services.CertAuthType{services.CertAuthType(a.authType)}
if err := authTypes[0].Check(); err != nil {
return trace.Wrap(err)
}
}
localAuthName, err := client.GetDomainName()
if err != nil {
return trace.Wrap(err)
}
var (
localCAs []services.CertAuthority
trustedCAs []services.CertAuthority
)
for _, t := range authTypes {
cas, err := client.GetCertAuthorities(t, false)
if err != nil {
return trace.Wrap(err)
}
for i := range cas {
if cas[i].GetClusterName() == localAuthName {
localCAs = append(localCAs, cas[i])
} else {
trustedCAs = append(trustedCAs, cas[i])
}
}
}
localCAsView := func() string {
t := goterm.NewTable(0, 10, 5, ' ', 0)
printHeader(t, []string{"CA Type", "Fingerprint"})
for _, a := range localCAs {
for _, keyBytes := range a.GetCheckingKeys() {
fingerprint, err := sshutils.AuthorizedKeyFingerprint(keyBytes)
if err != nil {
fingerprint = fmt.Sprintf("<bad key: %v", err)
}
fmt.Fprintf(t, "%v\t%v\n", a.GetType(), fingerprint)
}
}
return fmt.Sprintf("CA keys for the local cluster %v:\n\n", localAuthName) +
t.String()
}
trustedCAsView := func() string {
t := goterm.NewTable(0, 10, 5, ' ', 0)
printHeader(t, []string{"Cluster Name", "CA Type", "Fingerprint", "Roles"})
for _, a := range trustedCAs {
for _, keyBytes := range a.GetCheckingKeys() {
fingerprint, err := sshutils.AuthorizedKeyFingerprint(keyBytes)
if err != nil {
fingerprint = fmt.Sprintf("<bad key: %v", err)
}
var logins string
if a.GetType() == services.HostCA {
logins = "N/A"
} else {
logins = strings.Join(a.GetRoles(), ",")
}
fmt.Fprintf(t, "%v\t%v\t%v\t%v\n", a.GetClusterName(), a.GetType(), fingerprint, logins)
}
}
return "\nCA Keys for Trusted Clusters:\n\n" + t.String()
}
fmt.Printf(localCAsView())
if len(trustedCAs) > 0 {
fmt.Printf(trustedCAsView())
}
return nil
}
// 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.TunClient) error {
var typesToExport []services.CertAuthType
// 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
}
options := url.Values{
"type": []string{string(ca.GetType())},
}
roles, err := services.FetchRoles(ca.GetRoles(), client)
if err != nil {
return trace.Wrap(err)
}
allowedLogins, _ := roles.CheckLogins(defaults.MinCertDuration + time.Second)
if len(allowedLogins) > 0 {
options["logins"] = allowedLogins
}
// Every auth public key is exported as a single line adhering to man sshd (8)
// authorized_hosts format, a space-separated list of: makrer, hosts, key, and comment
// example:
// @cert-authority *.cluster-a ssh-rsa AAA... type=user
// We use URL encoding to pass the CA type and allowed logins into the comment field
fmt.Fprintf(os.Stdout, "@cert-authority *.%s %s %s\n",
ca.GetClusterName(), strings.TrimSpace(string(keyBytes)), options.Encode())
}
}
}
return nil
}
// GenerateKeys generates a new keypair
func (a *AuthCommand) GenerateKeys() error {
keygen := native.New()
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(client *auth.TunClient) error {
ca := native.New()
defer ca.Close()
privateKey, publicKey, err := ca.GenerateKeyPair("")
if err != nil {
return trace.Wrap(err)
}
cert, err := client.GenerateUserCert(publicKey, a.genUser, a.genTTL)
if err != nil {
return trace.Wrap(err)
}
certPath := a.genUser + ".cert"
keyPath := a.genUser + ".key"
pubPath := a.genUser + ".pub"
// --out flag
if a.outDir != "" {
if !utils.IsDir(a.outDir) {
if err = os.MkdirAll(a.outDir, 0770); err != nil {
return trace.Wrap(err)
}
}
certPath = filepath.Join(a.outDir, certPath)
keyPath = filepath.Join(a.outDir, keyPath)
pubPath = filepath.Join(a.outDir, pubPath)
}
err = ioutil.WriteFile(certPath, cert, 0600)
if err != nil {
return trace.Wrap(err)
}
err = ioutil.WriteFile(keyPath, privateKey, 0600)
if err != nil {
return trace.Wrap(err)
}
err = ioutil.WriteFile(pubPath, publicKey, 0600)
if err != nil {
return trace.Wrap(err)
}
fmt.Printf("Public key : %v\nPrivate key: %v\nCertificate: %v\n",
pubPath, keyPath, certPath)
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)
}
coll := &reverseTunnelCollection{tunnels: tunnels}
coll.writeText(os.Stdout)
return nil
}
// Upsert updates or inserts new reverse tunnel
func (r *ReverseTunnelCommand) Upsert(client *auth.TunClient) error {
err := client.UpsertReverseTunnel(services.NewReverseTunnel(r.domainNames, 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 {
if trace.IsNotFound(err) {
return trace.Errorf("'%v' is not found", domainName)
}
return trace.Wrap(err)
}
fmt.Printf("Cluster '%v' has been disconnected\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
if len(cfg.AuthServers) == 0 {
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(
"tctl",
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 validates and updates tctl configuration
func validateConfig(cfg *service.Config) {
var err error
// read a host UUID for this node
cfg.HostUUID, err = utils.ReadHostUUID(cfg.DataDir)
if err != nil {
utils.FatalError(err)
}
}
// applyConfig takes configuration values from the config file and applies
// them to 'service.Config' object
func applyConfig(ccf *CLIConfig, cfg *service.Config) error {
// load /etc/teleport.yaml and apply it's values:
fileConf, err := config.ReadConfigFile(ccf.ConfigFile)
if err != nil {
return trace.Wrap(err)
}
// if configuration is passed as an environment variable,
// try to decode it and override the config file
if ccf.ConfigString != "" {
fileConf, err = config.ReadFromString(ccf.ConfigString)
if err != nil {
return trace.Wrap(err)
}
}
if err = config.ApplyFileConfig(fileConf, cfg); err != nil {
return trace.Wrap(err)
}
// --debug flag
if ccf.Debug {
utils.InitLoggerDebug()
logrus.Debugf("DEBUG loggign enabled")
}
return nil
}
// onTokenList is called to execute "tokens ls" command
func (c *TokenCommand) List(client *auth.TunClient) error {
tokens, err := client.GetTokens()
if err != nil {
return trace.Wrap(err)
}
if len(tokens) == 0 {
fmt.Println("No active tokens found.")
return nil
}
tokensView := func() string {
table := goterm.NewTable(0, 10, 5, ' ', 0)
printHeader(table, []string{"Token", "Role", "Expiry Time (UTC)"})
for _, t := range tokens {
expiry := "never"
if t.Expires.Unix() > 0 {
expiry = t.Expires.Format(time.RFC822)
}
fmt.Fprintf(table, "%v\t%v\t%s\n", t.Token, t.Roles.String(), expiry)
}
return table.String()
}
fmt.Printf(tokensView())
return nil
}
// onTokenList is called to execute "tokens del" command
func (c *TokenCommand) Del(client *auth.TunClient) error {
if c.token == "" {
return trace.Errorf("Need an argument: token")
}
if err := client.DeleteToken(c.token); err != nil {
return trace.Wrap(err)
}
fmt.Printf("Token %s has been deleted\n", c.token)
return nil
}
// Get prints one or many resources of a certain type
func (g *GetCommand) Get(client *auth.TunClient) error {
collection, err := g.getCollection(client)
if err != nil {
return trace.Wrap(err)
}
switch g.format {
case formatText:
return collection.writeText(os.Stdout)
case formatJSON:
return collection.writeJSON(os.Stdout)
case formatYAML:
return collection.writeYAML(os.Stdout)
}
return trace.BadParameter("unsupported format")
}
// Create updates or insterts one or many resources
func (u *CreateCommand) Create(client *auth.TunClient) error {
var reader io.ReadCloser
var err error
if u.filename != "" {
reader, err = utils.OpenFile(u.filename)
if err != nil {
return trace.Wrap(err)
}
} else {
reader = ioutil.NopCloser(os.Stdin)
}
decoder := kyaml.NewYAMLOrJSONDecoder(reader, 32*1024)
count := 0
for {
var raw services.UnknownResource
err := decoder.Decode(&raw)
if err != nil {
if err == io.EOF {
if count == 0 {
return trace.BadParameter("no resources found, emtpy input?")
}
return nil
}
return trace.Wrap(err)
}
count += 1
switch raw.Kind {
case services.KindOIDCConnector:
conn, err := services.GetOIDCConnectorMarshaler().UnmarshalOIDCConnector(raw.Raw)
if err != nil {
return trace.Wrap(err)
}
if err := client.UpsertOIDCConnector(conn, 0); err != nil {
return trace.Wrap(err)
}
fmt.Printf("OIDC connector %v upserted\n", conn.GetName())
case services.KindReverseTunnel:
tun, err := services.GetReverseTunnelMarshaler().UnmarshalReverseTunnel(raw.Raw)
if err != nil {
return trace.Wrap(err)
}
if err := client.UpsertReverseTunnel(tun, 0); err != nil {
return trace.Wrap(err)
}
fmt.Printf("reverse tunnel %v upserted\n", tun.GetName())
case services.KindCertAuthority:
ca, err := services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(raw.Raw)
if err != nil {
return trace.Wrap(err)
}
if err := client.UpsertCertAuthority(ca, 0); err != nil {
return trace.Wrap(err)
}
fmt.Printf("cert authority %v upserted\n", ca.GetName())
case services.KindUser:
user, err := services.GetUserMarshaler().UnmarshalUser(raw.Raw)
if err != nil {
return trace.Wrap(err)
}
if err := client.UpsertUser(user); err != nil {
return trace.Wrap(err)
}
fmt.Printf("user %v upserted\n", user.GetName())
case services.KindRole:
role, err := services.GetRoleMarshaler().UnmarshalRole(raw.Raw)
if err != nil {
return trace.Wrap(err)
}
if err := client.UpsertRole(role); err != nil {
return trace.Wrap(err)
}
fmt.Printf("role %v upserted\n", role.GetName())
case services.KindNamespace:
ns, err := services.UnmarshalNamespace(raw.Raw)
if err != nil {
return trace.Wrap(err)
}
if err := client.UpsertNamespace(*ns); err != nil {
return trace.Wrap(err)
}
fmt.Printf("namespace %v upserted\n", ns.Metadata.Name)
case "":
return trace.BadParameter("missing resource kind")
default:
return trace.BadParameter("%v is not supported", raw.Kind)
}
}
}
// Delete deletes resource by name
func (d *DeleteCommand) Delete(client *auth.TunClient) error {
if d.ref.Kind == "" {
return trace.BadParameter("provide full resource name to delete e.g. roles/example")
}
if d.ref.Name == "" {
return trace.BadParameter("provide full resource name to delete e.g. roles/example")
}
for {
switch d.ref.Kind {
case services.KindUser:
if err := client.DeleteUser(d.ref.Name); err != nil {
return trace.Wrap(err)
}
fmt.Printf("user %v has been deleted\n", d.ref.Name)
case services.KindOIDCConnector:
if err := client.DeleteOIDCConnector(d.ref.Name); err != nil {
return trace.Wrap(err)
}
fmt.Printf("OIDC Connector %v has been deleted\n", d.ref.Name)
case services.KindReverseTunnel:
if err := client.DeleteReverseTunnel(d.ref.Name); err != nil {
return trace.Wrap(err)
}
fmt.Printf("reverse tunnel %v has been deleted\n", d.ref.Name)
case services.KindRole:
if err := client.DeleteRole(d.ref.Name); err != nil {
return trace.Wrap(err)
}
fmt.Printf("role %v has been deleted\n", d.ref.Name)