-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
tsh.go
4722 lines (4189 loc) · 162 KB
/
tsh.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 2016-2021 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 (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"net/url"
"os"
"os/exec"
"os/signal"
"path"
"path/filepath"
"regexp"
"runtime"
"runtime/pprof"
runtimetrace "runtime/trace"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/alecthomas/kingpin/v2"
"github.com/ghodss/yaml"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/otel/attribute"
oteltrace "go.opentelemetry.io/otel/trace"
"golang.org/x/crypto/ssh"
"golang.org/x/exp/slices"
"golang.org/x/sync/errgroup"
corev1 "k8s.io/api/core/v1"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/client/proto"
"github.com/gravitational/teleport/api/constants"
apidefaults "github.com/gravitational/teleport/api/defaults"
"github.com/gravitational/teleport/api/types"
apievents "github.com/gravitational/teleport/api/types/events"
"github.com/gravitational/teleport/api/types/wrappers"
"github.com/gravitational/teleport/api/utils/keys"
"github.com/gravitational/teleport/lib/asciitable"
"github.com/gravitational/teleport/lib/auth"
wancli "github.com/gravitational/teleport/lib/auth/webauthncli"
"github.com/gravitational/teleport/lib/benchmark"
"github.com/gravitational/teleport/lib/client"
dbprofile "github.com/gravitational/teleport/lib/client/db"
"github.com/gravitational/teleport/lib/client/identityfile"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/kube/kubeconfig"
"github.com/gravitational/teleport/lib/modules"
"github.com/gravitational/teleport/lib/observability/tracing"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/sshutils/sftp"
"github.com/gravitational/teleport/lib/sshutils/x11"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/utils/mlock"
"github.com/gravitational/teleport/lib/utils/prompt"
"github.com/gravitational/teleport/tool/common"
)
var log = logrus.WithFields(logrus.Fields{
trace.Component: teleport.ComponentTSH,
})
const (
// mfaModeAuto automatically chooses the best MFA device(s), without any
// restrictions.
// Allows both Webauthn and OTP.
mfaModeAuto = "auto"
// mfaModeCrossPlatform utilizes only cross-platform devices, such as
// pluggable hardware keys.
// Implies Webauthn.
mfaModeCrossPlatform = "cross-platform"
// mfaModePlatform utilizes only platform devices, such as Touch ID.
// Implies Webauthn.
mfaModePlatform = "platform"
// mfaModeOTP utilizes only OTP devices.
mfaModeOTP = "otp"
hostnameOrIDPredicateTemplate = `resource.spec.hostname == "%[1]s" || resource.metadata.name == "%[1]s"`
)
// CLIConf stores command line arguments and flags:
type CLIConf struct {
// UserHost contains "[login]@hostname" argument to SSH command
UserHost string
// Commands to execute on a remote host
RemoteCommand []string
// DesiredRoles indicates one or more roles which should be requested.
DesiredRoles string
// RequestReason indicates the reason for an access request.
RequestReason string
// SuggestedReviewers is a list of suggested request reviewers.
SuggestedReviewers string
// NoWait can be used with an access request to exit without waiting for a request resolution.
NoWait bool
// RequestedResourceIDs is a list of resources to request access to.
RequestedResourceIDs []string
// RequestID is an access request ID
RequestID string
// RequestIDs is a list of access request IDs
RequestIDs []string
// ReviewReason indicates the reason for an access review.
ReviewReason string
// ReviewableRequests indicates that only requests which can be reviewed should
// be listed.
ReviewableRequests bool
// SuggestedRequests indicates that only requests which suggest the current user
// as a reviewer should be listed.
SuggestedRequests bool
// MyRequests indicates that only requests created by the current user
// should be listed.
MyRequests bool
// Approve/Deny indicates the desired review kind.
Approve, Deny bool
// ResourceKind is the resource kind to search for
ResourceKind string
// Username is the Teleport user's username (to login into proxies)
Username string
// ExplicitUsername is true if Username was initially set by the end-user
// (for example, using command-line flags).
ExplicitUsername bool
// Proxy keeps the hostname:port of the Teleport proxy to use
Proxy string
// TTL defines how long a session must be active (in minutes)
MinsToLive int32
// SSH Port on a remote SSH host
NodePort int32
// Login on a remote SSH host
NodeLogin string
// InsecureSkipVerify bypasses verification of HTTPS certificate when talking to web proxy
InsecureSkipVerify bool
// SessionID identifies the session tsh is operating on.
// For `tsh join`, it is the ID of the session to join.
// For `tsh play`, it is either the ID of the session to play,
// or the path to a local session file which has already been
// downloaded.
SessionID string
// Src:dest parameter for SCP
CopySpec []string
// -r flag for scp
RecursiveCopy bool
// -L flag for ssh. Local port forwarding like 'ssh -L 80:remote.host:80 -L 443:remote.host:443'
LocalForwardPorts []string
// DynamicForwardedPorts is port forwarding using SOCKS5. It is similar to
// "ssh -D 8080 example.com".
DynamicForwardedPorts []string
// ForwardAgent agent to target node. Equivalent of -A for OpenSSH.
ForwardAgent bool
// ProxyJump is an optional -J flag pointing to the list of jumphosts,
// it is an equivalent of --proxy flag in tsh interpretation
ProxyJump string
// --local flag for ssh
LocalExec bool
// SiteName specifies remote site go login to
SiteName string
// KubernetesCluster specifies the kubernetes cluster to login to.
KubernetesCluster string
// DaemonAddr is the daemon listening address.
DaemonAddr string
// DaemonCertsDir is the directory containing certs used to create secure gRPC connection with daemon service
DaemonCertsDir string
// DaemonPrehogAddr is the URL where prehog events should be submitted.
DaemonPrehogAddr string
// DaemonPid is the PID to be stopped
DaemonPid int
// DatabaseService specifies the database proxy server to log into.
DatabaseService string
// DatabaseUser specifies database user to embed in the certificate.
DatabaseUser string
// DatabaseName specifies database name to embed in the certificate.
DatabaseName string
// AppName specifies proxied application name.
AppName string
// Interactive, when set to true, launches remote command with the terminal attached
Interactive bool
// Quiet mode, -q command (disables progress printing)
Quiet bool
// Namespace is used to select cluster namespace
Namespace string
// NoCache is used to turn off client cache for nodes discovery
NoCache bool
// BenchDuration is a duration for the benchmark
BenchDuration time.Duration
// BenchRate is a requests per second rate to maintain
BenchRate int
// BenchInteractive indicates that we should create interactive session
BenchInteractive bool
// BenchExport exports the latency profile
BenchExport bool
// BenchExportPath saves the latency profile in provided path
BenchExportPath string
// BenchTicks ticks per half distance
BenchTicks int32
// BenchValueScale value at which to scale the values recorded
BenchValueScale float64
// Context is a context to control execution
Context context.Context
// IdentityFileIn is an argument to -i flag (path to the private key+cert file)
IdentityFileIn string
// Compatibility flags, --compat, specifies OpenSSH compatibility flags.
Compatibility string
// CertificateFormat defines the format of the user SSH certificate.
CertificateFormat string
// IdentityFileOut is an argument to -out flag
IdentityFileOut string
// IdentityFormat (used for --format flag for 'tsh login') defines which
// format to use with --out to store a freshly retrieved certificate
IdentityFormat identityfile.Format
// IdentityOverwrite when true will overwrite any existing identity file at
// IdentityFileOut. When false, user will be prompted before overwriting
// any files.
IdentityOverwrite bool
// BindAddr is an address in the form of host:port to bind to
// during `tsh login` command
BindAddr string
// AuthConnector is the name of the connector to use.
AuthConnector string
// MFAMode is the preferred mode for MFA/Passwordless assertions.
MFAMode string
// SkipVersionCheck skips version checking for client and server
SkipVersionCheck bool
// Options is a list of OpenSSH options in the format used in the
// configuration file.
Options []string
// Verbose is used to print extra output.
Verbose bool
// Format is used to change the format of output
Format string
// SearchKeywords is a list of search keywords to match against resource field values.
SearchKeywords string
// PredicateExpression defines boolean conditions that will be matched against the resource.
PredicateExpression string
// NoRemoteExec will not execute a remote command after connecting to a host,
// will block instead. Useful when port forwarding. Equivalent of -N for OpenSSH.
NoRemoteExec bool
// X11ForwardingUntrusted will set up untrusted X11 forwarding for the session ('ssh -X')
X11ForwardingUntrusted bool
// X11Forwarding will set up trusted X11 forwarding for the session ('ssh -Y')
X11ForwardingTrusted bool
// X11ForwardingTimeout can optionally set to set a timeout for untrusted X11 forwarding.
X11ForwardingTimeout time.Duration
// Debug sends debug logs to stdout.
Debug bool
// Browser can be used to pass the name of a browser to override the system default
// (not currently implemented), or set to 'none' to suppress browser opening entirely.
Browser string
// UseLocalSSHAgent set to false will prevent this client from attempting to
// connect to the local ssh-agent (or similar) socket at $SSH_AUTH_SOCK.
//
// Deprecated in favor of `AddKeysToAgent`.
UseLocalSSHAgent bool
// AddKeysToAgent specifies the behavior of how certs are handled.
AddKeysToAgent string
// EnableEscapeSequences will scan stdin for SSH escape sequences during
// command/shell execution. This also requires stdin to be an interactive
// terminal.
EnableEscapeSequences bool
// PreserveAttrs preserves access/modification times from the original file.
PreserveAttrs bool
// RequestTTL is the expiration time of the Access Request (how long it
// will await approval).
RequestTTL time.Duration
// SessionTTL is the expiration time for the elevated certificate that will
// be issued if the Access Request is approved.
SessionTTL time.Duration
// executablePath is the absolute path to the current executable.
executablePath string
// unsetEnvironment unsets Teleport related environment variables.
unsetEnvironment bool
// overrideStdout allows to switch standard output source for resource command. Used in tests.
overrideStdout io.Writer
// overrideStderr allows to switch standard error source for resource command. Used in tests.
overrideStderr io.Writer
// overrideStdin allows to switch standard in source for resource command. Used in tests.
overrideStdin io.Reader
// mockSSOLogin used in tests to override sso login handler in teleport client.
mockSSOLogin client.SSOLoginFunc
// mockHeadlessLogin used in tests to override Headless login handler in teleport client.
mockHeadlessLogin client.SSHLoginFunc
// HomePath is where tsh stores profiles
HomePath string
// GlobalTshConfigPath is a path to global TSH config. Can be overridden with TELEPORT_GLOBAL_TSH_CONFIG.
GlobalTshConfigPath string
// LocalProxyPort is a port used by local proxy listener.
LocalProxyPort string
// LocalProxyCertFile is the client certificate used by local proxy.
// DEPRECATED DELETE IN 14.0
LocalProxyCertFile string
// LocalProxyKeyFile is the client key used by local proxy.
// DEPRECATED DELETE IN 14.0
LocalProxyKeyFile string
// LocalProxyTunnel specifies whether local proxy will open auth'd tunnel.
LocalProxyTunnel bool
// Exec is the command to run via tsh aws.
Exec string
// AWSRole is Amazon Role ARN or role name that will be used for AWS CLI access.
AWSRole string
// AWSCommandArgs contains arguments that will be forwarded to AWS CLI binary.
AWSCommandArgs []string
// AWSEndpointURLMode is an AWS proxy mode that serves an AWS endpoint URL
// proxy instead of an HTTPS proxy.
AWSEndpointURLMode bool
// AzureIdentity is Azure identity that will be used for Azure CLI access.
AzureIdentity string
// AzureCommandArgs contains arguments that will be forwarded to Azure CLI binary.
AzureCommandArgs []string
// GCPServiceAccount is GCP service account name that will be used for GCP CLI access.
GCPServiceAccount string
// GCPCommandArgs contains arguments that will be forwarded to GCP CLI binary.
GCPCommandArgs []string
// Reason is the reason for starting an ssh or kube session.
Reason string
// Invited is a list of invited users to an ssh or kube session.
Invited []string
// JoinMode is the participant mode someone is joining a session as.
JoinMode string
// displayParticipantRequirements is set if verbose participant requirement information should be printed for moderated sessions.
displayParticipantRequirements bool
// TshConfig is the loaded tsh configuration file ~/.tsh/config/config.yaml.
TshConfig TshConfig
// ListAll specifies if an ls command should return results from all clusters and proxies.
ListAll bool
// SampleTraces indicates whether traces should be sampled.
SampleTraces bool
// TraceExporter is a manually provided URI to send traces to instead of
// forwarding them to the Auth service.
TraceExporter string
// TracingProvider is the provider to use to create tracers, from which spans can be created.
TracingProvider oteltrace.TracerProvider
// disableAccessRequest disables automatic resource access requests.
disableAccessRequest bool
// FromUTC is the start time to use for the range of sessions listed by the session recordings listing command
FromUTC string
// ToUTC is the start time to use for the range of sessions listed by the session recordings listing command
ToUTC string
// maxRecordingsToShow is the maximum number of session recordings to show per page of results
maxRecordingsToShow int
// recordingsSince is a duration which sets the time into the past in which to list session recordings
recordingsSince string
// command is the selected command (and subcommands) parsed from command
// line args. Note that this command does not contain the binary (e.g. tsh).
command string
// cmdRunner is a custom function to execute provided exec.Cmd. Mainly used
// in testing.
cmdRunner func(*exec.Cmd) error
// kubernetesImpersonationConfig allows to configure custom kubernetes impersonation values.
kubernetesImpersonationConfig impersonationConfig
// kubeNamespace allows to configure the default Kubernetes namespace.
kubeNamespace string
// kubeAllNamespaces allows users to search for pods in every namespace.
kubeAllNamespaces bool
// kubeConfigPath is the location of the Kubeconfig for the current test.
// Setting this value allows Teleport tests to run `tsh login` commands in
// parallel.
// It shouldn't be used outside testing.
kubeConfigPath string
// Client only version display. Skips checking proxy version.
clientOnlyVersionCheck bool
// tracer is the tracer used to trace tsh commands.
tracer oteltrace.Tracer
// Headless uses headless login for the client session.
Headless bool
// MlockMode determines whether the process memory will be locked, and whether errors will be enforced.
// Allowed values include false, strict, and best_effort.
MlockMode string
// HeadlessAuthenticationID is the ID of a headless authentication.
HeadlessAuthenticationID string
// headlessSkipConfirm determines whether to provide a y/N
// confirmation prompt before prompting for MFA.
headlessSkipConfirm bool
}
// Stdout returns the stdout writer.
func (c *CLIConf) Stdout() io.Writer {
if c.overrideStdout != nil {
return c.overrideStdout
}
return os.Stdout
}
// Stderr returns the stderr writer.
func (c *CLIConf) Stderr() io.Writer {
if c.overrideStderr != nil {
return c.overrideStderr
}
return os.Stderr
}
// Stdin returns the stdin reader.
func (c *CLIConf) Stdin() io.Reader {
if c.overrideStdin != nil {
return c.overrideStdin
}
return os.Stdin
}
// CommandWithBinary returns the current/selected command with the binary.
func (c *CLIConf) CommandWithBinary() string {
return fmt.Sprintf("%s %s", teleport.ComponentTSH, c.command)
}
// RunCommand executes provided command.
func (c *CLIConf) RunCommand(cmd *exec.Cmd) error {
if c.cmdRunner != nil {
return trace.Wrap(c.cmdRunner(cmd))
}
return trace.Wrap(cmd.Run())
}
func main() {
cmdLineOrig := os.Args[1:]
var cmdLine []string
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer cancel()
// lets see: if the executable name is 'ssh' or 'scp' we convert
// that to "tsh ssh" or "tsh scp"
switch path.Base(os.Args[0]) {
case "ssh":
cmdLine = append([]string{"ssh"}, cmdLineOrig...)
case "scp":
cmdLine = append([]string{"scp"}, cmdLineOrig...)
default:
cmdLine = cmdLineOrig
}
err := Run(ctx, cmdLine)
prompt.NotifyExit() // Allow prompt to restore terminal state on exit.
if err != nil {
var exitError *common.ExitCodeError
if errors.As(err, &exitError) {
os.Exit(exitError.Code)
}
utils.FatalError(err)
}
}
const (
authEnvVar = "TELEPORT_AUTH"
clusterEnvVar = "TELEPORT_CLUSTER"
kubeClusterEnvVar = "TELEPORT_KUBE_CLUSTER"
loginEnvVar = "TELEPORT_LOGIN"
bindAddrEnvVar = "TELEPORT_LOGIN_BIND_ADDR"
proxyEnvVar = "TELEPORT_PROXY"
headlessEnvVar = "TELEPORT_HEADLESS"
headlessSkipConfirmEnvVar = "TELEPORT_HEADLESS_SKIP_CONFIRM"
// TELEPORT_SITE uses the older deprecated "site" terminology to refer to a
// cluster. All new code should use TELEPORT_CLUSTER instead.
siteEnvVar = "TELEPORT_SITE"
userEnvVar = "TELEPORT_USER"
addKeysToAgentEnvVar = "TELEPORT_ADD_KEYS_TO_AGENT"
useLocalSSHAgentEnvVar = "TELEPORT_USE_LOCAL_SSH_AGENT"
globalTshConfigEnvVar = "TELEPORT_GLOBAL_TSH_CONFIG"
mfaModeEnvVar = "TELEPORT_MFA_MODE"
mlockModeEnvVar = "TELEPORT_MLOCK_MODE"
debugEnvVar = teleport.VerboseLogsEnvVar // "TELEPORT_DEBUG"
identityFileEnvVar = "TELEPORT_IDENTITY_FILE"
gcloudSecretEnvVar = "TELEPORT_GCLOUD_SECRET"
clusterHelp = "Specify the Teleport cluster to connect"
browserHelp = "Set to 'none' to suppress browser opening on login"
searchHelp = `List of comma separated search keywords or phrases enclosed in quotations (e.g. --search=foo,bar,"some phrase")`
queryHelp = `Query by predicate language enclosed in single quotes. Supports ==, !=, &&, and || (e.g. --query='labels["key1"] == "value1" && labels["key2"] != "value2"')`
labelHelp = "List of comma separated labels to filter by labels (e.g. key1=value1,key2=value2)"
// proxyDefaultResolutionTimeout is how long to wait for an unknown proxy
// port to be resolved.
//
// Originally based on the RFC-8305 "Maximum Connection Attempt Delay"
// recommended default value of 2s. In the RFC this value is for the
// establishment of a TCP connection, rather than the full HTTP round-
// trip that we measure against, so some tweaking may be needed.
//
// Raised to 5 seconds when fallback measure was removed to account for
// users with higher latency connections.
proxyDefaultResolutionTimeout = 5 * time.Second
)
// env vars that tsh status will check to provide hints about active env vars to a user.
var tshStatusEnvVars = [...]string{proxyEnvVar, clusterEnvVar, siteEnvVar, kubeClusterEnvVar, teleport.EnvKubeConfig}
// cliOption is used in tests to inject/override configuration within Run
type cliOption func(*CLIConf) error
// initLogger initializes the logger taking into account --debug and TELEPORT_DEBUG. If TELEPORT_DEBUG is set, it will also enable CLIConf.Debug.
func initLogger(cf *CLIConf) {
isDebug, _ := strconv.ParseBool(os.Getenv(debugEnvVar))
cf.Debug = cf.Debug || isDebug
if cf.Debug {
utils.InitLogger(utils.LoggingForCLI, logrus.DebugLevel)
} else {
utils.InitLogger(utils.LoggingForCLI, logrus.WarnLevel)
}
}
// Run executes TSH client. same as main() but easier to test
func Run(ctx context.Context, args []string, opts ...cliOption) error {
cf := CLIConf{
Context: ctx,
TracingProvider: tracing.NoopProvider(),
}
// run early to enable debug logging if env var is set.
// this makes it possible to debug early startup functionality, particularly command aliases.
initLogger(&cf)
moduleCfg := modules.GetModules()
var cpuProfile, memProfile, traceProfile string
// configure CLI argument parser:
app := utils.InitCLIParser("tsh", "Teleport Command Line Client").Interspersed(true)
app.Flag("login", "Remote host login").Short('l').Envar(loginEnvVar).StringVar(&cf.NodeLogin)
app.Flag("proxy", "Teleport proxy address").Envar(proxyEnvVar).StringVar(&cf.Proxy)
app.Flag("nocache", "do not cache cluster discovery locally").Hidden().BoolVar(&cf.NoCache)
app.Flag("user", "Teleport user, defaults to current local user").Envar(userEnvVar).StringVar(&cf.Username)
app.Flag("mem-profile", "Write memory profile to file").Hidden().StringVar(&memProfile)
app.Flag("cpu-profile", "Write CPU profile to file").Hidden().StringVar(&cpuProfile)
app.Flag("trace-profile", "Write trace profile to file").Hidden().StringVar(&traceProfile)
app.Flag("option", "").Short('o').Hidden().AllowDuplicate().PreAction(func(ctx *kingpin.ParseContext) error {
return trace.BadParameter("invalid flag, perhaps you want to use this flag as tsh ssh -o?")
}).String()
app.Flag("ttl", "Minutes to live for a session").Int32Var(&cf.MinsToLive)
app.Flag("identity", "Identity file").Short('i').Envar(identityFileEnvVar).StringVar(&cf.IdentityFileIn)
app.Flag("compat", "OpenSSH compatibility flag").Hidden().StringVar(&cf.Compatibility)
app.Flag("cert-format", "SSH certificate format").StringVar(&cf.CertificateFormat)
app.Flag("trace", "Capture and export distributed traces").Hidden().BoolVar(&cf.SampleTraces)
app.Flag("trace-exporter", "An OTLP exporter URL to send spans to. Note - only tsh spans will be included.").Hidden().StringVar(&cf.TraceExporter)
if !moduleCfg.IsBoringBinary() {
// The user is *never* allowed to do this in FIPS mode.
app.Flag("insecure", "Do not verify server's certificate and host name. Use only in test environments").
Default("false").
BoolVar(&cf.InsecureSkipVerify)
}
app.Flag("auth", "Specify the name of authentication connector to use.").Envar(authEnvVar).StringVar(&cf.AuthConnector)
app.Flag("namespace", "Namespace of the cluster").Default(apidefaults.Namespace).Hidden().StringVar(&cf.Namespace)
app.Flag("skip-version-check", "Skip version checking between server and client.").BoolVar(&cf.SkipVersionCheck)
// we don't want to add `.Envar(debugEnvVar)` here:
// - we already process TELEPORT_DEBUG with initLogger(), so we don't need to do it second time
// - Kingpin is strict about syntax, so TELEPORT_DEBUG=rubbish will crash a program; we don't want such behavior for this variable.
app.Flag("debug", "Verbose logging to stdout").Short('d').BoolVar(&cf.Debug)
app.Flag("add-keys-to-agent", fmt.Sprintf("Controls how keys are handled. Valid values are %v.", client.AllAddKeysOptions)).Short('k').Envar(addKeysToAgentEnvVar).Default(client.AddKeysToAgentAuto).StringVar(&cf.AddKeysToAgent)
app.Flag("use-local-ssh-agent", "Deprecated in favor of the add-keys-to-agent flag.").
Hidden().
Envar(useLocalSSHAgentEnvVar).
Default("true").
BoolVar(&cf.UseLocalSSHAgent)
app.Flag("enable-escape-sequences", "Enable support for SSH escape sequences. Type '~?' during an SSH session to list supported sequences. Default is enabled.").
Default("true").
BoolVar(&cf.EnableEscapeSequences)
app.Flag("bind-addr", "Override host:port used when opening a browser for cluster logins").Envar(bindAddrEnvVar).StringVar(&cf.BindAddr)
modes := []string{mfaModeAuto, mfaModeCrossPlatform, mfaModePlatform, mfaModeOTP}
app.Flag("mfa-mode", fmt.Sprintf("Preferred mode for MFA and Passwordless assertions (%v)", strings.Join(modes, ", "))).
Default(mfaModeAuto).
Envar(mfaModeEnvVar).
EnumVar(&cf.MFAMode, modes...)
app.Flag("headless", "Use headless login. Shorthand for --auth=headless.").Envar(headlessEnvVar).BoolVar(&cf.Headless)
app.Flag("mlock", fmt.Sprintf("Determines whether process memory will be locked and whether failure to do so will be accepted (%v).", strings.Join(mlockModes, ", "))).
Default(mlockModeAuto).
Envar(mlockModeEnvVar).
StringVar(&cf.MlockMode)
app.HelpFlag.Short('h')
ver := app.Command("version", "Print the tsh client and Proxy server versions for the current context.")
ver.Flag("format", defaults.FormatFlagDescription(defaults.DefaultFormats...)).Short('f').Default(teleport.Text).EnumVar(&cf.Format, defaults.DefaultFormats...)
ver.Flag("client", "Show the client version only (no server required).").
BoolVar(&cf.clientOnlyVersionCheck)
// ssh
// Use Interspersed(false) to forward all flags to ssh.
ssh := app.Command("ssh", "Run shell or execute a command on a remote SSH node.").Interspersed(false)
ssh.Arg("[user@]host", "Remote hostname and the login to use").Required().StringVar(&cf.UserHost)
ssh.Arg("command", "Command to execute on a remote host").StringsVar(&cf.RemoteCommand)
app.Flag("jumphost", "SSH jumphost").Short('J').StringVar(&cf.ProxyJump)
ssh.Flag("port", "SSH port on a remote host").Short('p').Int32Var(&cf.NodePort)
ssh.Flag("forward-agent", "Forward agent to target node").Short('A').BoolVar(&cf.ForwardAgent)
ssh.Flag("forward", "Forward localhost connections to remote server").Short('L').StringsVar(&cf.LocalForwardPorts)
ssh.Flag("dynamic-forward", "Forward localhost connections to remote server using SOCKS5").Short('D').StringsVar(&cf.DynamicForwardedPorts)
ssh.Flag("local", "Execute command on localhost after connecting to SSH node").Default("false").BoolVar(&cf.LocalExec)
ssh.Flag("tty", "Allocate TTY").Short('t').BoolVar(&cf.Interactive)
ssh.Flag("cluster", clusterHelp).Short('c').StringVar(&cf.SiteName)
ssh.Flag("option", "OpenSSH options in the format used in the configuration file").Short('o').AllowDuplicate().StringsVar(&cf.Options)
ssh.Flag("no-remote-exec", "Don't execute remote command, useful for port forwarding").Short('N').BoolVar(&cf.NoRemoteExec)
ssh.Flag("x11-untrusted", "Requests untrusted (secure) X11 forwarding for this session").Short('X').BoolVar(&cf.X11ForwardingUntrusted)
ssh.Flag("x11-trusted", "Requests trusted (insecure) X11 forwarding for this session. This can make your local machine vulnerable to attacks, use with caution").Short('Y').BoolVar(&cf.X11ForwardingTrusted)
ssh.Flag("x11-untrusted-timeout", "Sets a timeout for untrusted X11 forwarding, after which the client will reject any forwarding requests from the server").Default("10m").DurationVar((&cf.X11ForwardingTimeout))
ssh.Flag("participant-req", "Displays a verbose list of required participants in a moderated session.").BoolVar(&cf.displayParticipantRequirements)
ssh.Flag("request-reason", "Reason for requesting access").StringVar(&cf.RequestReason)
ssh.Flag("disable-access-request", "Disable automatic resource access requests").BoolVar(&cf.disableAccessRequest)
// Daemon service for teleterm client
daemon := app.Command("daemon", "Daemon is the tsh daemon service.").Hidden()
daemonStart := daemon.Command("start", "Starts tsh daemon service.").Hidden()
daemonStart.Flag("addr", "Addr is the daemon listening address.").StringVar(&cf.DaemonAddr)
daemonStart.Flag("certs-dir", "Directory containing certs used to create secure gRPC connection with daemon service").StringVar(&cf.DaemonCertsDir)
daemonStart.Flag("prehog-addr", "URL where prehog events should be submitted").StringVar(&cf.DaemonPrehogAddr)
daemonStop := daemon.Command("stop", "Gracefully stops a process on Windows by sending Ctrl-Break to it.").Hidden()
daemonStop.Flag("pid", "PID to be stopped").IntVar(&cf.DaemonPid)
// AWS.
// Use Interspersed(false) to forward all flags to AWS CLI.
aws := app.Command("aws", "Access AWS API.").Interspersed(false)
aws.Arg("command", "AWS command and subcommands arguments that are going to be forwarded to AWS CLI.").StringsVar(&cf.AWSCommandArgs)
aws.Flag("app", "Optional Name of the AWS application to use if logged into multiple.").StringVar(&cf.AppName)
aws.Flag("endpoint-url", "Run local proxy to serve as an AWS endpoint URL. If not specified, local proxy serves as an HTTPS proxy.").
Short('e').Hidden().BoolVar(&cf.AWSEndpointURLMode)
aws.Flag("exec", "Execute different commands (e.g. terraform) under Teleport credentials").StringVar(&cf.Exec)
azure := app.Command("az", "Access Azure API.").Interspersed(false)
azure.Arg("command", "`az` command and subcommands arguments that are going to be forwarded to Azure CLI.").StringsVar(&cf.AzureCommandArgs)
azure.Flag("app", "Optional name of the Azure application to use if logged into multiple.").StringVar(&cf.AppName)
gcloud := app.Command("gcloud", "Access GCP API with the gcloud command.").Interspersed(false)
gcloud.Arg("command", "`gcloud` command and subcommands arguments.").StringsVar(&cf.GCPCommandArgs)
gcloud.Flag("app", "Optional name of the GCP application to use if logged into multiple.").StringVar(&cf.AppName)
gcloud.Alias("gcp")
gsutil := app.Command("gsutil", "Access Google Cloud Storage with the gsutil command.").Interspersed(false)
gsutil.Arg("command", "`gsutil` command and subcommands arguments.").StringsVar(&cf.GCPCommandArgs)
gsutil.Flag("app", "Optional name of the GCP application to use if logged into multiple.").StringVar(&cf.AppName)
// Applications.
apps := app.Command("apps", "View and control proxied applications.").Alias("app")
lsApps := apps.Command("ls", "List available applications.")
lsApps.Flag("verbose", "Show extra application fields.").Short('v').BoolVar(&cf.Verbose)
lsApps.Flag("cluster", clusterHelp).Short('c').StringVar(&cf.SiteName)
lsApps.Flag("search", searchHelp).StringVar(&cf.SearchKeywords)
lsApps.Flag("query", queryHelp).StringVar(&cf.PredicateExpression)
lsApps.Flag("format", defaults.FormatFlagDescription(defaults.DefaultFormats...)).Short('f').Default(teleport.Text).EnumVar(&cf.Format, defaults.DefaultFormats...)
lsApps.Arg("labels", labelHelp).StringVar(&cf.UserHost)
lsApps.Flag("all", "List apps from all clusters and proxies.").Short('R').BoolVar(&cf.ListAll)
appLogin := apps.Command("login", "Retrieve short-lived certificate for an app.")
appLogin.Arg("app", "App name to retrieve credentials for. Can be obtained from `tsh apps ls` output.").Required().StringVar(&cf.AppName)
appLogin.Flag("aws-role", "(For AWS CLI access only) Amazon IAM role ARN or role name.").StringVar(&cf.AWSRole)
appLogin.Flag("azure-identity", "(For Azure CLI access only) Azure managed identity name.").StringVar(&cf.AzureIdentity)
appLogin.Flag("gcp-service-account", "(For GCP CLI access only) GCP service account name.").StringVar(&cf.GCPServiceAccount)
appLogout := apps.Command("logout", "Remove app certificate.")
appLogout.Arg("app", "App to remove credentials for.").StringVar(&cf.AppName)
appConfig := apps.Command("config", "Print app connection information.")
appConfig.Arg("app", "App to print information for. Required when logged into multiple apps.").StringVar(&cf.AppName)
appConfig.Flag("format", fmt.Sprintf("Optional print format, one of: %q to print app address, %q to print CA cert path, %q to print cert path, %q print key path, %q to print example curl command, %q or %q to print everything as JSON or YAML.",
appFormatURI, appFormatCA, appFormatCert, appFormatKey, appFormatCURL, appFormatJSON, appFormatYAML),
).Short('f').StringVar(&cf.Format)
// Recordings.
recordings := app.Command("recordings", "View and control session recordings.").Alias("recording")
lsRecordings := recordings.Command("ls", "List recorded sessions.")
lsRecordings.Flag("format", defaults.FormatFlagDescription(defaults.DefaultFormats...)+". Defaults to 'text'.").Short('f').Default(teleport.Text).EnumVar(&cf.Format, defaults.DefaultFormats...)
lsRecordings.Flag("from-utc", fmt.Sprintf("Start of time range in which recordings are listed. Format %s. Defaults to 24 hours ago.", defaults.TshTctlSessionListTimeFormat)).StringVar(&cf.FromUTC)
lsRecordings.Flag("to-utc", fmt.Sprintf("End of time range in which recordings are listed. Format %s. Defaults to current time.", defaults.TshTctlSessionListTimeFormat)).StringVar(&cf.ToUTC)
lsRecordings.Flag("limit", fmt.Sprintf("Maximum number of recordings to show. Default %s.", defaults.TshTctlSessionListLimit)).Default(defaults.TshTctlSessionListLimit).IntVar(&cf.maxRecordingsToShow)
lsRecordings.Flag("last", "Duration into the past from which session recordings should be listed. Format 5h30m40s").StringVar(&cf.recordingsSince)
// Local TLS proxy.
proxy := app.Command("proxy", "Run local TLS proxy allowing connecting to Teleport in single-port mode.")
proxySSH := proxy.Command("ssh", "Start local TLS proxy for ssh connections when using Teleport in single-port mode.")
proxySSH.Arg("[user@]host", "Remote hostname and the login to use").Required().StringVar(&cf.UserHost)
proxySSH.Flag("cluster", clusterHelp).Short('c').StringVar(&cf.SiteName)
proxyDB := proxy.Command("db", "Start local TLS proxy for database connections when using Teleport in single-port mode.")
proxyDB.Arg("db", "The name of the database to start local proxy for").Required().StringVar(&cf.DatabaseService)
proxyDB.Flag("port", "Specifies the source port used by proxy db listener").Short('p').StringVar(&cf.LocalProxyPort)
proxyDB.Flag("cert-file", "Certificate file for proxy client TLS configuration").StringVar(&cf.LocalProxyCertFile)
proxyDB.Flag("key-file", "Key file for proxy client TLS configuration").StringVar(&cf.LocalProxyKeyFile)
proxyDB.Flag("tunnel", "Open authenticated tunnel using database's client certificate so clients don't need to authenticate").BoolVar(&cf.LocalProxyTunnel)
proxyDB.Flag("db-user", "Optional database user to log in as.").StringVar(&cf.DatabaseUser)
proxyDB.Flag("db-name", "Optional database name to log in to.").StringVar(&cf.DatabaseName)
proxyDB.Flag("cluster", clusterHelp).Short('c').StringVar(&cf.SiteName)
proxyApp := proxy.Command("app", "Start local TLS proxy for app connection when using Teleport in single-port mode.")
proxyApp.Arg("app", "The name of the application to start local proxy for").Required().StringVar(&cf.AppName)
proxyApp.Flag("port", "Specifies the source port used by by the proxy app listener").Short('p').StringVar(&cf.LocalProxyPort)
proxyAWS := proxy.Command("aws", "Start local proxy for AWS access.")
proxyAWS.Flag("app", "Optional Name of the AWS application to use if logged into multiple.").StringVar(&cf.AppName)
proxyAWS.Flag("port", "Specifies the source port used by the proxy listener.").Short('p').StringVar(&cf.LocalProxyPort)
proxyAWS.Flag("endpoint-url", "Run local proxy to serve as an AWS endpoint URL. If not specified, local proxy serves as an HTTPS proxy.").Short('e').BoolVar(&cf.AWSEndpointURLMode)
proxyAWS.Flag("format", awsProxyFormatFlagDescription()).Short('f').Default(envVarDefaultFormat()).EnumVar(&cf.Format, awsProxyFormats...)
proxyAzure := proxy.Command("azure", "Start local proxy for Azure access.")
proxyAzure.Flag("app", "Optional Name of the Azure application to use if logged into multiple.").StringVar(&cf.AppName)
proxyAzure.Flag("port", "Specifies the source port used by the proxy listener.").Short('p').StringVar(&cf.LocalProxyPort)
proxyAzure.Flag("format", envVarFormatFlagDescription()).Short('f').Default(envVarDefaultFormat()).EnumVar(&cf.Format, envVarFormats...)
proxyAzure.Alias("az")
proxyGcloud := proxy.Command("gcloud", "Start local proxy for GCP access.")
proxyGcloud.Flag("app", "Optional Name of the GCP application to use if logged into multiple.").StringVar(&cf.AppName)
proxyGcloud.Flag("port", "Specifies the source port used by the proxy listener.").Short('p').StringVar(&cf.LocalProxyPort)
proxyGcloud.Flag("format", envVarFormatFlagDescription()).Short('f').Default(envVarDefaultFormat()).EnumVar(&cf.Format, envVarFormats...)
proxyGcloud.Alias("gcp")
// Databases.
db := app.Command("db", "View and control proxied databases.")
db.Flag("cluster", clusterHelp).Short('c').StringVar(&cf.SiteName)
dbList := db.Command("ls", "List all available databases.")
dbList.Flag("verbose", "Show extra database fields.").Short('v').BoolVar(&cf.Verbose)
dbList.Flag("search", searchHelp).StringVar(&cf.SearchKeywords)
dbList.Flag("query", queryHelp).StringVar(&cf.PredicateExpression)
dbList.Flag("format", defaults.FormatFlagDescription(defaults.DefaultFormats...)).Short('f').Default(teleport.Text).EnumVar(&cf.Format, defaults.DefaultFormats...)
dbList.Flag("all", "List databases from all clusters and proxies.").Short('R').BoolVar(&cf.ListAll)
dbList.Arg("labels", labelHelp).StringVar(&cf.UserHost)
dbLogin := db.Command("login", "Retrieve credentials for a database.")
dbLogin.Arg("db", "Database to retrieve credentials for. Can be obtained from 'tsh db ls' output.").Required().StringVar(&cf.DatabaseService)
dbLogin.Flag("db-user", "Optional database user to configure as default.").StringVar(&cf.DatabaseUser)
dbLogin.Flag("db-name", "Optional database name to configure as default.").StringVar(&cf.DatabaseName)
dbLogout := db.Command("logout", "Remove database credentials.")
dbLogout.Arg("db", "Database to remove credentials for.").StringVar(&cf.DatabaseService)
dbEnv := db.Command("env", "Print environment variables for the configured database.")
dbEnv.Flag("format", defaults.FormatFlagDescription(defaults.DefaultFormats...)).Short('f').Default(teleport.Text).EnumVar(&cf.Format, defaults.DefaultFormats...)
dbEnv.Arg("db", "Print environment for the specified database").StringVar(&cf.DatabaseService)
// --db flag is deprecated in favor of positional argument for consistency with other commands.
dbEnv.Flag("db", "Print environment for the specified database.").Hidden().StringVar(&cf.DatabaseService)
dbConfig := db.Command("config", "Print database connection information. Useful when configuring GUI clients.")
dbConfig.Arg("db", "Print information for the specified database.").StringVar(&cf.DatabaseService)
// --db flag is deprecated in favor of positional argument for consistency with other commands.
dbConfig.Flag("db", "Print information for the specified database.").Hidden().StringVar(&cf.DatabaseService)
dbConfig.Flag("format", fmt.Sprintf("Print format: %q to print in table format (default), %q to print connect command, %q or %q to print in JSON or YAML.",
dbFormatText, dbFormatCommand, dbFormatJSON, dbFormatYAML)).Short('f').EnumVar(&cf.Format, dbFormatText, dbFormatCommand, dbFormatJSON, dbFormatYAML)
dbConnect := db.Command("connect", "Connect to a database.")
dbConnect.Arg("db", "Database service name to connect to.").StringVar(&cf.DatabaseService)
dbConnect.Flag("db-user", "Optional database user to log in as.").StringVar(&cf.DatabaseUser)
dbConnect.Flag("db-name", "Optional database name to log in to.").StringVar(&cf.DatabaseName)
// join
join := app.Command("join", "Join the active SSH or Kubernetes session.")
join.Flag("cluster", clusterHelp).Short('c').StringVar(&cf.SiteName)
join.Flag("mode", "Mode of joining the session, valid modes are observer and moderator").Short('m').Default("peer").StringVar(&cf.JoinMode)
join.Flag("reason", "The purpose of the session.").StringVar(&cf.Reason)
join.Flag("invite", "A comma separated list of people to mark as invited for the session.").StringsVar(&cf.Invited)
join.Arg("session-id", "ID of the session to join").Required().StringVar(&cf.SessionID)
// play
play := app.Command("play", "Replay the recorded session (SSH, Kubernetes, App, DB).")
play.Flag("cluster", clusterHelp).Short('c').StringVar(&cf.SiteName)
play.Flag("format", defaults.FormatFlagDescription(
teleport.PTY, teleport.JSON, teleport.YAML,
)).Short('f').Default(teleport.PTY).EnumVar(&cf.Format, teleport.PTY, teleport.JSON, teleport.YAML)
play.Arg("session-id", "ID of the session to play").Required().StringVar(&cf.SessionID)
// scp
scp := app.Command("scp", "Transfer files to a remote Node.")
scp.Flag("cluster", clusterHelp).Short('c').StringVar(&cf.SiteName)
scp.Arg("from, to", "Source and destination to copy, one must be a local path and one must be a remote path").Required().StringsVar(&cf.CopySpec)
scp.Flag("recursive", "Recursive copy of subdirectories").Short('r').BoolVar(&cf.RecursiveCopy)
scp.Flag("port", "Port to connect to on the remote host").Short('P').Int32Var(&cf.NodePort)
scp.Flag("preserve", "Preserves access and modification times from the original file").Short('p').BoolVar(&cf.PreserveAttrs)
scp.Flag("quiet", "Quiet mode").Short('q').BoolVar(&cf.Quiet)
// ls
ls := app.Command("ls", "List remote SSH nodes.")
ls.Flag("cluster", clusterHelp).Short('c').StringVar(&cf.SiteName)
ls.Flag("verbose", "One-line output (for text format), including node UUIDs").Short('v').BoolVar(&cf.Verbose)
ls.Flag("format", defaults.FormatFlagDescription(
teleport.Text, teleport.JSON, teleport.YAML, teleport.Names,
)).Short('f').Default(teleport.Text).EnumVar(&cf.Format, teleport.Text, teleport.JSON, teleport.YAML, teleport.Names)
ls.Arg("labels", labelHelp).StringVar(&cf.UserHost)
ls.Flag("search", searchHelp).StringVar(&cf.SearchKeywords)
ls.Flag("query", queryHelp).StringVar(&cf.PredicateExpression)
ls.Flag("all", "List nodes from all clusters and proxies.").Short('R').BoolVar(&cf.ListAll)
// clusters
clusters := app.Command("clusters", "List available Teleport clusters.")
clusters.Flag("format", defaults.FormatFlagDescription(defaults.DefaultFormats...)).Short('f').Default(teleport.Text).EnumVar(&cf.Format, defaults.DefaultFormats...)
clusters.Flag("quiet", "Quiet mode").Short('q').BoolVar(&cf.Quiet)
// login logs in with remote proxy and obtains a "session certificate" which gets
// stored in ~/.tsh directory
login := app.Command("login", "Log in to a cluster and retrieve the session certificate.")
login.Flag("out", "Identity output").Short('o').AllowDuplicate().StringVar(&cf.IdentityFileOut)
login.Flag("format", fmt.Sprintf("Identity format: %s, %s (for OpenSSH compatibility) or %s (for kubeconfig)",
identityfile.DefaultFormat,
identityfile.FormatOpenSSH,
identityfile.FormatKubernetes,
)).Default(string(identityfile.DefaultFormat)).Short('f').StringVar((*string)(&cf.IdentityFormat))
login.Flag("overwrite", "Whether to overwrite the existing identity file.").BoolVar(&cf.IdentityOverwrite)
login.Flag("request-roles", "Request one or more extra roles").StringVar(&cf.DesiredRoles)
login.Flag("request-reason", "Reason for requesting additional roles").StringVar(&cf.RequestReason)
login.Flag("request-reviewers", "Suggested reviewers for role request").StringVar(&cf.SuggestedReviewers)
login.Flag("request-nowait", "Finish without waiting for request resolution").BoolVar(&cf.NoWait)
login.Flag("request-id", "Login with the roles requested in the given request").StringVar(&cf.RequestID)
login.Arg("cluster", clusterHelp).StringVar(&cf.SiteName)
login.Flag("browser", browserHelp).StringVar(&cf.Browser)
login.Flag("kube-cluster", "Name of the Kubernetes cluster to login to").StringVar(&cf.KubernetesCluster)
login.Flag("verbose", "Show extra status information").Short('v').BoolVar(&cf.Verbose)
login.Alias(loginUsageFooter)
// logout deletes obtained session certificates in ~/.tsh
logout := app.Command("logout", "Delete a cluster certificate.")
// bench
bench := app.Command("bench", "Run shell or execute a command on a remote SSH node.").Hidden()
bench.Flag("cluster", clusterHelp).Short('c').StringVar(&cf.SiteName)
bench.Arg("[user@]host", "Remote hostname and the login to use").Required().StringVar(&cf.UserHost)
bench.Arg("command", "Command to execute on a remote host").Required().StringsVar(&cf.RemoteCommand)
bench.Flag("port", "SSH port on a remote host").Short('p').Int32Var(&cf.NodePort)
bench.Flag("duration", "Test duration").Default("1s").DurationVar(&cf.BenchDuration)
bench.Flag("rate", "Requests per second rate").Default("10").IntVar(&cf.BenchRate)
bench.Flag("interactive", "Create interactive SSH session").BoolVar(&cf.BenchInteractive)
bench.Flag("export", "Export the latency profile").BoolVar(&cf.BenchExport)
bench.Flag("path", "Directory to save the latency profile to, default path is the current directory").Default(".").StringVar(&cf.BenchExportPath)
bench.Flag("ticks", "Ticks per half distance").Default("100").Int32Var(&cf.BenchTicks)
bench.Flag("scale", "Value scale in which to scale the recorded values").Default("1.0").Float64Var(&cf.BenchValueScale)
// show key
show := app.Command("show", "Read an identity from file and print to stdout.").Hidden()
show.Arg("identity_file", "The file containing a public key or a certificate").Required().StringVar(&cf.IdentityFileIn)
// The status command shows which proxy the user is logged into and metadata
// about the certificate.
status := app.Command("status", "Display the list of proxy servers and retrieved certificates.")
status.Flag("format", defaults.FormatFlagDescription(defaults.DefaultFormats...)).Short('f').Default(teleport.Text).EnumVar(&cf.Format, defaults.DefaultFormats...)
status.Flag("verbose", "Show extra status information after successful login").Short('v').BoolVar(&cf.Verbose)
// The environment command prints out environment variables for the configured
// proxy and cluster. Can be used to create sessions "sticky" to a terminal
// even if the user runs "tsh login" again in another window.
environment := app.Command("env", "Print commands to set Teleport session environment variables.")
environment.Flag("format", defaults.FormatFlagDescription(defaults.DefaultFormats...)).Short('f').Default(teleport.Text).EnumVar(&cf.Format, defaults.DefaultFormats...)
environment.Flag("unset", "Print commands to clear Teleport session environment variables").BoolVar(&cf.unsetEnvironment)
req := app.Command("request", "Manage access requests.").Alias("requests")
reqList := req.Command("ls", "List access requests.").Alias("list")
reqList.Flag("format", defaults.FormatFlagDescription(defaults.DefaultFormats...)).Short('f').Default(teleport.Text).EnumVar(&cf.Format, defaults.DefaultFormats...)
reqList.Flag("reviewable", "Only show requests reviewable by current user").BoolVar(&cf.ReviewableRequests)
reqList.Flag("suggested", "Only show requests that suggest current user as reviewer").BoolVar(&cf.SuggestedRequests)
reqList.Flag("my-requests", "Only show requests created by current user").BoolVar(&cf.MyRequests)
reqShow := req.Command("show", "Show request details.").Alias("details")
reqShow.Flag("format", defaults.FormatFlagDescription(defaults.DefaultFormats...)).Short('f').Default(teleport.Text).EnumVar(&cf.Format, defaults.DefaultFormats...)
reqShow.Arg("request-id", "ID of the target request").Required().StringVar(&cf.RequestID)
// Note: The "tsh request new" subcommand should not be used anymore. It
// will be kept around for users that built automation around it, but all
// public facing documentation should now refer to "tsh request create".
reqCreate := req.Command("create", "Create a new access request.").Alias("new")
reqCreate.Flag("roles", "Roles to be requested").StringVar(&cf.DesiredRoles)
reqCreate.Flag("reason", "Reason for requesting").StringVar(&cf.RequestReason)
reqCreate.Flag("reviewers", "Suggested reviewers").StringVar(&cf.SuggestedReviewers)
reqCreate.Flag("nowait", "Finish without waiting for request resolution").BoolVar(&cf.NoWait)
reqCreate.Flag("resource", "Resource ID to be requested").StringsVar(&cf.RequestedResourceIDs)
reqCreate.Flag("request-ttl", "Expiration time for the access request").DurationVar(&cf.RequestTTL)
reqCreate.Flag("session-ttl", "Expiration time for the elevated certificate").DurationVar(&cf.SessionTTL)
reqReview := req.Command("review", "Review an access request.")
reqReview.Arg("request-id", "ID of target request").Required().StringVar(&cf.RequestID)
reqReview.Flag("approve", "Review proposes approval").BoolVar(&cf.Approve)
reqReview.Flag("deny", "Review proposes denial").BoolVar(&cf.Deny)
reqReview.Flag("reason", "Review reason message").StringVar(&cf.ReviewReason)
reqSearch := req.Command("search", "Search for resources to request access to.")
reqSearch.Flag("kind",
fmt.Sprintf("Resource kind to search for (%s)",
strings.Join(types.RequestableResourceKinds, ", ")),
).Required().EnumVar(&cf.ResourceKind, types.RequestableResourceKinds...)
reqSearch.Flag("search", searchHelp).StringVar(&cf.SearchKeywords)
reqSearch.Flag("query", queryHelp).StringVar(&cf.PredicateExpression)
reqSearch.Flag("labels", labelHelp).StringVar(&cf.UserHost)
reqSearch.Flag("kube-cluster", "Kubernetes Cluster to search for Pods").StringVar(&cf.KubernetesCluster)
reqSearch.Flag("kube-namespace", "Kubernetes Namespace to search for Pods").Default(corev1.NamespaceDefault).StringVar(&cf.kubeNamespace)
reqSearch.Flag("all-kube-namespaces", "Search Pods in every namespace").BoolVar(&cf.kubeAllNamespaces)
// Headless login approval
headless := app.Command("headless", "Headless authentication commands.").Interspersed(true)
headlessApprove := headless.Command("approve", "Approve a headless authentication request.").Interspersed(true)
headlessApprove.Arg("request id", "Headless authentication request ID").StringVar(&cf.HeadlessAuthenticationID)
headlessApprove.Flag("skip-confirm", "Skip confirmation and prompt for MFA immediately").Envar(headlessSkipConfirmEnvVar).BoolVar(&cf.headlessSkipConfirm)
reqDrop := req.Command("drop", "Drop one more access requests from current identity.")
reqDrop.Arg("request-id", "IDs of requests to drop (default drops all requests)").Default("*").StringsVar(&cf.RequestIDs)
kubectl := app.Command("kubectl", "Runs a kubectl command on a Kubernetes cluster.").Interspersed(false)
// This hack is required in order to accept any args for tsh kubectl.
kubectl.Arg("", "").StringsVar(new([]string))
// Kubernetes subcommands.
kube := newKubeCommand(app)
// MFA subcommands.
mfa := newMFACommand(app)
config := app.Command("config", "Print OpenSSH configuration details.")
// FIDO2, TouchID and WebAuthnWin commands.
f2 := newFIDO2Command(app)
tid := newTouchIDCommand(app)
webauthnwin := newWebauthnwinCommand(app)
// Device Trust commands.
deviceCmd := newDeviceCommand(app)
if runtime.GOOS == constants.WindowsOS {
bench.Hidden()
}
var err error
cf.executablePath, err = os.Executable()
if err != nil {
return trace.Wrap(err)
}
// configs
setEnvFlags(&cf, os.Getenv)
confOptions, err := loadAllConfigs(cf)
if err != nil {
return trace.Wrap(err)
}
cf.TshConfig = *confOptions
// aliases
ar := newAliasRunner(cf.TshConfig.Aliases)
aliasCommand, runtimeArgs := findAliasCommand(args)
if aliasDefinition, ok := ar.getAliasDefinition(aliasCommand); ok {
return ar.runAlias(ctx, aliasCommand, aliasDefinition, cf.executablePath, runtimeArgs)
}
// parse CLI commands+flags:
utils.UpdateAppUsageTemplate(app, args)
command, err := app.Parse(args)
if errors.Is(err, kingpin.ErrExpectedCommand) {
if _, ok := cf.TshConfig.Aliases[aliasCommand]; ok {