-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathapi.go
5377 lines (4694 loc) · 173 KB
/
api.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
/*
* Teleport
* Copyright (C) 2023 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package client
import (
"cmp"
"context"
"crypto"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io"
"net"
"net/url"
"os"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/gravitational/trace"
"go.opentelemetry.io/otel/attribute"
oteltrace "go.opentelemetry.io/otel/trace"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/net/http2"
"golang.org/x/sync/errgroup"
"golang.org/x/term"
"google.golang.org/grpc"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/client"
"github.com/gravitational/teleport/api/client/proto"
proxyclient "github.com/gravitational/teleport/api/client/proxy"
"github.com/gravitational/teleport/api/client/webclient"
"github.com/gravitational/teleport/api/constants"
apidefaults "github.com/gravitational/teleport/api/defaults"
devicepb "github.com/gravitational/teleport/api/gen/proto/go/teleport/devicetrust/v1"
kubeproto "github.com/gravitational/teleport/api/gen/proto/go/teleport/kube/v1"
mfav1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/mfa/v1"
"github.com/gravitational/teleport/api/mfa"
apitracing "github.com/gravitational/teleport/api/observability/tracing"
tracessh "github.com/gravitational/teleport/api/observability/tracing/ssh"
"github.com/gravitational/teleport/api/profile"
"github.com/gravitational/teleport/api/types"
apievents "github.com/gravitational/teleport/api/types/events"
apiutils "github.com/gravitational/teleport/api/utils"
"github.com/gravitational/teleport/api/utils/grpc/interceptors"
"github.com/gravitational/teleport/api/utils/keys"
"github.com/gravitational/teleport/api/utils/prompt"
"github.com/gravitational/teleport/lib/auth/authclient"
"github.com/gravitational/teleport/lib/auth/touchid"
wancli "github.com/gravitational/teleport/lib/auth/webauthncli"
"github.com/gravitational/teleport/lib/authz"
"github.com/gravitational/teleport/lib/autoupdate/tools"
libmfa "github.com/gravitational/teleport/lib/client/mfa"
"github.com/gravitational/teleport/lib/client/sso"
"github.com/gravitational/teleport/lib/client/terminal"
"github.com/gravitational/teleport/lib/cryptosuites"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/devicetrust"
dtauthntypes "github.com/gravitational/teleport/lib/devicetrust/authn/types"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/modules"
"github.com/gravitational/teleport/lib/multiplexer"
"github.com/gravitational/teleport/lib/observability/tracing"
libplayer "github.com/gravitational/teleport/lib/player"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/session"
alpncommon "github.com/gravitational/teleport/lib/srv/alpnproxy/common"
"github.com/gravitational/teleport/lib/sshutils"
"github.com/gravitational/teleport/lib/sshutils/sftp"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/utils/agentconn"
logutils "github.com/gravitational/teleport/lib/utils/log"
)
const (
AddKeysToAgentAuto = "auto"
AddKeysToAgentNo = "no"
AddKeysToAgentYes = "yes"
AddKeysToAgentOnly = "only"
)
var AllAddKeysOptions = []string{AddKeysToAgentAuto, AddKeysToAgentNo, AddKeysToAgentYes, AddKeysToAgentOnly}
// ValidateAgentKeyOption validates that a string is a valid option for the AddKeysToAgent parameter.
func ValidateAgentKeyOption(supplied string) error {
for _, option := range AllAddKeysOptions {
if supplied == option {
return nil
}
}
return trace.BadParameter("invalid value %q, must be one of %v", supplied, AllAddKeysOptions)
}
// AgentForwardingMode describes how the user key agent will be forwarded
// to a remote machine, if at all.
type AgentForwardingMode int
const (
ForwardAgentNo AgentForwardingMode = iota
ForwardAgentYes
ForwardAgentLocal
)
const remoteForwardUnsupportedMessage = "ssh: tcpip-forward request denied by peer"
var log = logutils.NewPackageLogger(teleport.ComponentKey, teleport.ComponentClient)
// ForwardedPort specifies local tunnel to remote
// destination managed by the client, is equivalent
// of ssh -L src:host:dst command
type ForwardedPort struct {
SrcIP string
SrcPort int
DestPort int
DestHost string
}
// ForwardedPorts contains an array of forwarded port structs
type ForwardedPorts []ForwardedPort
// ToString returns a string representation of a forwarded port spec, compatible
// with OpenSSH's -L flag, i.e. "src_host:src_port:dest_host:dest_port".
func (p *ForwardedPort) ToString() string {
sport := strconv.Itoa(p.SrcPort)
dport := strconv.Itoa(p.DestPort)
if utils.IsLocalhost(p.SrcIP) {
return sport + ":" + net.JoinHostPort(p.DestHost, dport)
}
return net.JoinHostPort(p.SrcIP, sport) + ":" + net.JoinHostPort(p.DestHost, dport)
}
// DynamicForwardedPort local port for dynamic application-level port
// forwarding. Whenever a connection is made to this port, SOCKS5 protocol
// is used to determine the address of the remote host. More or less
// equivalent to OpenSSH's -D flag.
type DynamicForwardedPort struct {
// SrcIP is the IP address to listen on locally.
SrcIP string
// SrcPort is the port to listen on locally.
SrcPort int
}
// DynamicForwardedPorts is a slice of locally forwarded dynamic ports (SOCKS5).
type DynamicForwardedPorts []DynamicForwardedPort
// ToString returns a string representation of a dynamic port spec, compatible
// with OpenSSH's -D flag, i.e. "src_host:src_port".
func (p *DynamicForwardedPort) ToString() string {
sport := strconv.Itoa(p.SrcPort)
if utils.IsLocalhost(p.SrcIP) {
return sport
}
return net.JoinHostPort(p.SrcIP, sport)
}
// HostKeyCallback is called by SSH client when it needs to check
// remote host key or certificate validity
type HostKeyCallback func(host string, ip net.Addr, key ssh.PublicKey) error
// Config is a client config
type Config struct {
// Username is the Teleport account username (for logging into Teleport proxies)
Username string
// ExplicitUsername is true if Username was initially set by the end-user
// (for example, using command-line flags).
ExplicitUsername bool
// Remote host to connect
Host string
// SearchKeywords host to connect
SearchKeywords []string
// PredicateExpression host to connect
PredicateExpression string
// UseSearchAsRoles modifies the behavior of resource loading to
// use search as roles feature.
UseSearchAsRoles bool
// Labels represent host Labels
Labels map[string]string
// HostLogin is a user login on a remote host
HostLogin string
// HostPort is a remote host port to connect to. This is used for **explicit**
// port setting via -p flag, otherwise '0' is passed which means "use server default"
HostPort int
// JumpHosts if specified are interpreted in a similar way
// as -J flag in ssh - used to dial through
JumpHosts []utils.JumpHost
// WebProxyAddr is the host:port the web proxy can be accessed at.
WebProxyAddr string
// SSHProxyAddr is the host:port the SSH proxy can be accessed at.
SSHProxyAddr string
// KubeProxyAddr is the host:port the Kubernetes proxy can be accessed at.
KubeProxyAddr string
// PostgresProxyAddr is the host:port the Postgres proxy can be accessed at.
PostgresProxyAddr string
// MongoProxyAddr is the host:port the Mongo proxy can be accessed at.
MongoProxyAddr string
// MySQLProxyAddr is the host:port the MySQL proxy can be accessed at.
MySQLProxyAddr string
// KeyTTL is a time to live for the temporary SSH keypair to remain valid:
KeyTTL time.Duration
// InsecureSkipVerify is an option to skip HTTPS cert check
InsecureSkipVerify bool
// NonInteractive tells the client not to trigger interactive features for non-interactive commands,
// such as prompting user to re-login on credential errors. This is used by external programs linking
// against Teleport client and obtaining credentials from elsewhere. e.g. from an identity file.
NonInteractive bool
// Agent is an SSH agent to use for local Agent procedures. Defaults to in-memory agent keyring.
Agent agent.ExtendedAgent
ClientStore *Store
// ForwardAgent is used by the client to request agent forwarding from the server.
ForwardAgent AgentForwardingMode
// EnableX11Forwarding specifies whether X11 forwarding should be enabled.
EnableX11Forwarding bool
// X11ForwardingTimeout can be set to set a X11 forwarding timeout in seconds,
// after which any X11 forwarding requests in that session will be rejected.
X11ForwardingTimeout time.Duration
// X11ForwardingTrusted specifies the X11 forwarding security mode.
X11ForwardingTrusted bool
// AuthMethods are used to login into the cluster. If specified, the client will
// use them in addition to certs stored in the client store.
AuthMethods []ssh.AuthMethod
// TLSConfig is TLS configuration, if specified, the client
// will use this TLS configuration to access API endpoints
TLS *tls.Config
// ProxySSHPrincipal determines the SSH username (principal) the client should be using
// when connecting to auth/proxy servers. By default, the SSH username is pulled from
// the user's certificate, but the web-based terminal provides this username explicitly.
ProxySSHPrincipal string
Stdout io.Writer
Stderr io.Writer
Stdin io.Reader
// ExitStatus carries the returned value (exit status) of the remote
// process execution (via SSH exec)
ExitStatus int
// SiteName specifies site to execute operation,
// if omitted, first available site will be selected
SiteName string
// KubernetesCluster specifies the kubernetes cluster for any relevant
// operations. If empty, the auth server will choose one using stable (same
// cluster every time) but unspecified logic.
KubernetesCluster string
// DatabaseService specifies name of the database proxy server to issue
// certificate for.
DatabaseService string
// LocalForwardPorts are the local ports tsh listens on for port forwarding
// (parameters to -L ssh flag).
LocalForwardPorts ForwardedPorts
// DynamicForwardedPorts are the list of ports tsh listens on for dynamic
// port forwarding (parameters to -D ssh flag).
DynamicForwardedPorts DynamicForwardedPorts
// RemoteForwardPorts are the list of ports the remote connection listens on
// for remote port forwarding (parameters to -R ssh flag).
RemoteForwardPorts ForwardedPorts
// HostKeyCallback will be called to check host keys of the remote
// node, if not specified will be using CheckHostSignature function
// that uses local cache to validate hosts
HostKeyCallback ssh.HostKeyCallback
// KeyDir defines where temporary session keys will be stored.
// if empty, they'll go to ~/.tsh
KeysDir string
// SessionID is a session ID to use when opening a new session.
SessionID string
// extraEnvs contains additional environment variables that will be added
// to SSH session.
extraEnvs map[string]string
// InteractiveCommand tells tsh to launch a remote exec command in interactive mode,
// i.e. attaching the terminal to it.
InteractiveCommand bool
// ClientAddr (if set) specifies the true client IP. Usually it's not needed (since the server
// can look at the connecting address to determine client's IP) but for cases when the
// client is web-based, this must be set to HTTP's remote addr
ClientAddr string
// CachePolicy defines local caching policy in case if discovery goes down
// by default does not use caching
CachePolicy *CachePolicy
// CertificateFormat is the format of the SSH certificate.
CertificateFormat string
// AuthConnector is the name of the authentication connector to use.
AuthConnector string
// AuthenticatorAttachment is the desired authenticator attachment.
AuthenticatorAttachment wancli.AuthenticatorAttachment
// PreferOTP prefers OTP in favor of other MFA methods.
// Useful in constrained environments without access to USB or platform
// authenticators, such as remote hosts or virtual machines.
PreferOTP bool
// PreferSSO prefers SSO in favor of other MFA methods.
PreferSSO bool
// CheckVersions will check that client version is compatible
// with auth server version when connecting.
CheckVersions bool
// BindAddr is an optional host:port to bind to for SSO redirect flows.
BindAddr string
// CallbackAddr is the optional base URL to give to the user when performing
// SSO redirect flows.
CallbackAddr 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
// 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
// AddKeysToAgent specifies how the client handles keys.
// auto - will attempt to add keys to agent if the agent supports it
// only - attempt to load keys into agent but don't write them to disk
// on - attempt to load keys into agent
// off - do not attempt to load keys into agent
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
// MockSSOLogin is used in tests for mocking the SSO login response.
MockSSOLogin SSOLoginFunc
// MockHeadlessLogin is used in tests for mocking the Headless login response.
MockHeadlessLogin SSHLoginFunc
// OverrideMySQLOptionFilePath overrides the MySQL option file path to use.
// Useful in parallel tests so they don't all use the default path in the
// user home dir.
OverrideMySQLOptionFilePath string
// OverridePostgresServiceFilePath overrides the Postgres service file path.
// Useful in parallel tests so they don't all use the default path in the
// user home dir.
OverridePostgresServiceFilePath string
// HomePath is where tsh stores profiles
HomePath string
// TLSRoutingEnabled indicates that proxy supports ALPN SNI server where
// all proxy services are exposed on a single TLS listener (Proxy Web Listener).
TLSRoutingEnabled bool
// TLSRoutingConnUpgradeRequired indicates that ALPN connection upgrades
// are required for making TLS routing requests.
//
// Note that this is applicable to the Proxy's Web port regardless of
// whether the Proxy is in single-port or multi-port configuration.
TLSRoutingConnUpgradeRequired bool
// Reason is a reason attached to started sessions meant to describe their intent.
Reason string
// Invited is a list of people invited to a session.
Invited []string
// DisplayParticipantRequirements is set if debug information about participants requirements
// should be printed in moderated sessions.
DisplayParticipantRequirements bool
// ExtraProxyHeaders is a collection of http headers to be included in requests to the WebProxy.
ExtraProxyHeaders map[string]string
// AllowStdinHijack allows stdin hijack during MFA prompts.
// Stdin hijack provides a better login UX, but it can be difficult to reason
// about and is often a source of bugs.
// Do not set this options unless you deeply understand what you are doing.
AllowStdinHijack bool
// Tracer is the tracer to create spans with
Tracer oteltrace.Tracer
// PrivateKeyPolicy is a key policy that this client will try to follow during login.
PrivateKeyPolicy keys.PrivateKeyPolicy
// PIVSlot specifies a specific PIV slot to use with hardware key support.
PIVSlot keys.PIVSlot
// LoadAllCAs indicates that tsh should load the CAs of all clusters
// instead of just the current cluster.
LoadAllCAs bool
// AllowHeadless determines whether headless login can be used. Currently, only
// the ssh, scp, and ls commands can use headless login. Other commands will ignore
// headless auth connector and default to local instead.
AllowHeadless bool
// DialOpts used by the api.client.proxy.Client when establishing a connection to
// the proxy server. Used by tests.
DialOpts []grpc.DialOption
// PROXYSigner is used to sign PROXY headers for securely propagating client IP address
PROXYSigner multiplexer.PROXYHeaderSigner
// DTAuthnRunCeremony is the device authentication function to execute
// during device login ceremonies. If not provided and device trust is
// required, then the device login will fail.
DTAuthnRunCeremony DTAuthnRunCeremonyFunc
// dtAttemptLoginIgnorePing and dtAutoEnrollIgnorePing allow Device Trust
// tests to ignore Ping responses.
// Useful to force flows that only typically happen on Teleport Enterprise.
dtAttemptLoginIgnorePing, dtAutoEnrollIgnorePing bool
// DTAutoEnroll is the device auto-enroll function to execute during
// device enrollment. If not provided and device trust auto-enrollment
// is enabled, then the enrollment process will fail.
DTAutoEnroll DTAutoEnrollFunc
// WebauthnLogin allows tests to override the Webauthn Login func.
// Defaults to [wancli.Login].
WebauthnLogin WebauthnLoginFunc
// SSHLogDir is the directory to log the output of multiple SSH commands to.
// If not set, no logs will be created.
SSHLogDir string
// MFAPromptConstructor is a custom MFA prompt constructor to use when prompting for MFA.
MFAPromptConstructor func(cfg *libmfa.PromptConfig) mfa.Prompt
// SSOMFACeremonyConstructor is a custom SSO MFA ceremony constructor.
SSOMFACeremonyConstructor func(rd *sso.Redirector) mfa.SSOMFACeremony
// CustomHardwareKeyPrompt is a custom hardware key prompt to use when asking
// for a hardware key PIN, touch, etc.
// If empty, a default CLI prompt is used.
CustomHardwareKeyPrompt keys.HardwareKeyPrompt
// DisableSSHResumption disables transparent SSH connection resumption.
DisableSSHResumption bool
// SAMLSingleLogoutEnabled is whether SAML SLO (single logout) is enabled, this can only be true if this is a SAML SSO session
// using an auth connector with a SAML SLO URL configured.
SAMLSingleLogoutEnabled bool
// SSHDialTimeout is the timeout value that should be used for SSH connections.
SSHDialTimeout time.Duration
// GenerateUnifiedKey indicates that the client should generate a single key
// for SSH and TLS instead of split keys.
GenerateUnifiedKey bool
// StdinFunc allows tests to override prompt.Stdin().
// If nil prompt.Stdin() is used.
StdinFunc func() prompt.StdinReader
// HasTouchIDCredentialsFunc allows tests to override touchid.HasCredentials.
// If nil touchid.HasCredentials is used.
HasTouchIDCredentialsFunc func(rpID, user string) bool
// SSOHost is the host of the SSO provider used to log in.
SSOHost string
}
// CachePolicy defines cache policy for local clients
type CachePolicy struct {
// CacheTTL defines cache TTL
CacheTTL time.Duration
// NeverExpire never expires local cache information
NeverExpires bool
}
// MakeDefaultConfig returns default client config
func MakeDefaultConfig() *Config {
return &Config{
Stdout: os.Stdout,
Stderr: os.Stderr,
Stdin: os.Stdin,
AddKeysToAgent: AddKeysToAgentAuto,
EnableEscapeSequences: true,
Tracer: tracing.NoopProvider().Tracer("TeleportClient"),
}
}
// VirtualPathKind is the suffix component for env vars denoting the type of
// file that will be loaded.
type VirtualPathKind string
const (
// VirtualPathEnvPrefix is the env var name prefix shared by all virtual
// path vars.
VirtualPathEnvPrefix = "TSH_VIRTUAL_PATH"
VirtualPathKey VirtualPathKind = "KEY"
VirtualPathCA VirtualPathKind = "CA"
VirtualPathDatabase VirtualPathKind = "DB"
VirtualPathAppCert VirtualPathKind = "APP"
VirtualPathKubernetes VirtualPathKind = "KUBE"
)
// VirtualPathParams are an ordered list of additional optional parameters
// for a virtual path. They can be used to specify a more exact resource name
// if multiple might be available. Simpler integrations can instead only
// specify the kind and it will apply wherever a more specific env var isn't
// found.
type VirtualPathParams []string
// VirtualPathCAParams returns parameters for selecting CA certificates.
func VirtualPathCAParams(caType types.CertAuthType) VirtualPathParams {
return VirtualPathParams{
strings.ToUpper(string(caType)),
}
}
// VirtualPathDatabaseCertParams returns parameters for selecting a specific database
// certificate by name.
func VirtualPathDatabaseCertParams(databaseName string) VirtualPathParams {
return VirtualPathParams{databaseName}
}
// VirtualPathDatabaseKeyParams returns parameters for selecting a specific database
// key by name.
func VirtualPathDatabaseKeyParams(databaseName string) VirtualPathParams {
return VirtualPathParams{"DB", databaseName}
}
// VirtualPathAppCertParams returns parameters for selecting specific app cert by name.
func VirtualPathAppCertParams(appName string) VirtualPathParams {
return VirtualPathParams{appName}
}
// VirtualPathAppKeyParams returns parameters for selecting specific app key by name.
func VirtualPathAppKeyParams(appName string) VirtualPathParams {
return VirtualPathParams{"APP", appName}
}
// VirtualPathKubernetesParams returns parameters for selecting k8s clusters by
// name.
func VirtualPathKubernetesParams(k8sCluster string) VirtualPathParams {
return VirtualPathParams{k8sCluster}
}
// VirtualPathEnvName formats a single virtual path environment variable name.
func VirtualPathEnvName(kind VirtualPathKind, params VirtualPathParams) string {
components := append([]string{
VirtualPathEnvPrefix,
string(kind),
}, params...)
return strings.ToUpper(strings.Join(components, "_"))
}
// VirtualPathEnvNames determines an ordered list of environment variables that
// should be checked to resolve an env var override. Params may be nil to
// indicate no additional arguments are to be specified or accepted.
func VirtualPathEnvNames(kind VirtualPathKind, params VirtualPathParams) []string {
// Bail out early if there are no parameters.
if len(params) == 0 {
return []string{VirtualPathEnvName(kind, VirtualPathParams{})}
}
var vars []string
for i := len(params); i >= 0; i-- {
vars = append(vars, VirtualPathEnvName(kind, params[0:i]))
}
return vars
}
// RetryWithRelogin is a helper error handling method, attempts to relogin and
// retry the function once.
func RetryWithRelogin(ctx context.Context, tc *TeleportClient, fn func() error, opts ...RetryWithReloginOption) error {
fnErr := fn()
switch {
case fnErr == nil:
return nil
case utils.IsPredicateError(fnErr):
return trace.Wrap(utils.PredicateError{Err: fnErr})
case tc.NonInteractive:
return trace.Wrap(fnErr, "cannot relogin in non-interactive session")
case !IsErrorResolvableWithRelogin(fnErr):
// If the connection to Auth was unexpectedly cut, see if the client is too
// old to interact with the cluster.
if errors.Is(fnErr, io.EOF) || (trace.IsConnectionProblem(fnErr) && strings.Contains(fnErr.Error(), "error reading from server: EOF")) {
// The results are intentionally ignored - Ping prints warnings
// related to versions, and that's all that is needed here.
_, _ = tc.Ping(ctx)
}
return trace.Wrap(fnErr)
}
opt := defaultRetryWithReloginOptions()
for _, o := range opts {
o(opt)
}
log.DebugContext(ctx, "Activating relogin on error", "error", fnErr, "error_type", logutils.TypeAttr(trace.Unwrap(fnErr)))
if keys.IsPrivateKeyPolicyError(fnErr) {
privateKeyPolicy, err := keys.ParsePrivateKeyPolicyError(fnErr)
if err != nil {
return trace.Wrap(err)
}
if err := tc.updatePrivateKeyPolicy(privateKeyPolicy); err != nil {
return trace.Wrap(err)
}
}
if opt.beforeLoginHook != nil {
if err := opt.beforeLoginHook(); err != nil {
return trace.Wrap(err)
}
}
key, err := tc.Login(ctx)
if err != nil {
if errors.Is(err, prompt.ErrNotTerminal) {
log.DebugContext(ctx, "Relogin is not available in this environment", "error", err)
return trace.Wrap(fnErr)
}
if trace.IsTrustError(err) {
return trace.Wrap(err, "refusing to connect to untrusted proxy %v without --insecure flag\n", tc.SSHProxyAddr)
}
return trace.Wrap(err)
}
proxyClient, rootAuthClient, err := tc.ConnectToRootCluster(ctx, key)
if err != nil {
return trace.Wrap(err)
}
defer func() {
rootAuthClient.Close()
proxyClient.Close()
}()
// Attempt device login. This activates a fresh key if successful.
if err := tc.AttemptDeviceLogin(ctx, key, rootAuthClient); err != nil {
return trace.Wrap(err)
}
// Save profile to record proxy credentials
if err := tc.SaveProfile(opt.makeCurrentProfile); err != nil {
log.WarnContext(ctx, "Failed to save profile", "error", err)
return trace.Wrap(err)
}
if err := tools.CheckAndUpdateRemote(ctx, tc.WebProxyAddr, tc.InsecureSkipVerify, os.Args[1:]); err != nil {
return trace.Wrap(err)
}
if opt.afterLoginHook != nil {
if err := opt.afterLoginHook(); err != nil {
return trace.Wrap(err)
}
}
return fn()
}
// RetryWithReloginOption is a functional option for configuring the
// RetryWithRelogin helper.
type RetryWithReloginOption func(*retryWithReloginOptions)
// retryWithReloginOptions is a struct for configuring the RetryWithRelogin
type retryWithReloginOptions struct {
// beforeLoginHook is a function that will be called before the login attempt.
beforeLoginHook func() error
// afterLoginHook is a function that will be called after a successful login.
afterLoginHook func() error
// makeCurrentProfile determines whether to update the current profile after login.
makeCurrentProfile bool
}
func defaultRetryWithReloginOptions() *retryWithReloginOptions {
return &retryWithReloginOptions{
makeCurrentProfile: true,
}
}
// WithBeforeLoginHook is a functional option for configuring a function that will
// be called before the login attempt.
func WithBeforeLoginHook(fn func() error) RetryWithReloginOption {
return func(o *retryWithReloginOptions) {
o.beforeLoginHook = fn
}
}
// WithAfterLoginHook is a functional option for configuring a function that will
// be called after a successful login.
func WithAfterLoginHook(fn func() error) RetryWithReloginOption {
return func(o *retryWithReloginOptions) {
o.afterLoginHook = fn
}
}
// WithMakeCurrentProfile is a functional option for configuring whether to update the current profile after a
// successful login.
func WithMakeCurrentProfile(makeCurrentProfile bool) RetryWithReloginOption {
return func(o *retryWithReloginOptions) {
o.makeCurrentProfile = makeCurrentProfile
}
}
// NonRetryableError wraps an error to indicate that the error should fail
// IsErrorResolvableWithRelogin. This wrapper is used to workaround the false
// positives like trace.IsBadParameter check in IsErrorResolvableWithRelogin.
type NonRetryableError struct {
// Err is the original error.
Err error
}
// Error returns the error text.
func (e *NonRetryableError) Error() string {
if e == nil || e.Err == nil {
return ""
}
return e.Err.Error()
}
// Unwrap returns the original error.
func (e *NonRetryableError) Unwrap() error {
if e == nil {
return nil
}
return e.Err
}
// IsNonRetryableError checks if the provided error is a NonRetryableError.
// Equivalent to `errors.As(err, new(*NonRetryableError))`.
func IsNonRetryableError(err error) bool {
return errors.As(err, new(*NonRetryableError))
}
// IsErrorResolvableWithRelogin returns true if relogin is attempted on `err`.
func IsErrorResolvableWithRelogin(err error) bool {
if IsNonRetryableError(err) {
return false
}
// Private key policy errors indicate that the user must login with an
// unexpected private key policy requirement satisfied. This can occur
// in the following cases:
// - User is logging in for the first time, and their strictest private
// key policy requirement is specified in a role.
// - User is assuming a role with a stricter private key policy requirement
// than the user's given roles.
// - The private key policy in the user's roles or the cluster auth
// preference have been upgraded since the user last logged in, making
// their current login session invalid.
if keys.IsPrivateKeyPolicyError(err) {
return true
}
// Ignore any failures resulting from RPCs.
// These were all materialized as status.Error here before
// https://github.com/gravitational/teleport/pull/30578.
var remoteErr *interceptors.RemoteError
if errors.As(err, &remoteErr) {
// Exception for the two "retryable" errors that come from RPCs.
//
// Since Connect no longer checks the user cert before making an RPC,
// it has to be able to properly recognize "expired certs" errors
// that come from the server (to show a re-login dialog).
//
// TODO(gzdunek): These manual checks should be replaced with retryable
// errors returned explicitly, as described below by codingllama.
isClientCredentialsHaveExpired := errors.Is(err, client.ErrClientCredentialsHaveExpired)
isTLSExpiredCertificate := strings.Contains(err.Error(), "tls: expired certificate")
return isClientCredentialsHaveExpired || isTLSExpiredCertificate
}
// TODO(codingllama): Retrying BadParameter is a terrible idea.
// We should fix this and remove the RemoteError condition above as well.
// Any retriable error should be explicitly marked as such.
// Once trace.IsBadParameter check is removed, the nonRetryableError
// workaround can also be removed.
return trace.IsBadParameter(err) ||
trace.IsTrustError(err) ||
utils.IsCertExpiredError(err) ||
// Assume that failed handshake is a result of expired credentials.
utils.IsHandshakeFailedError(err) ||
IsNoCredentialsError(err)
}
// GetProfile gets the profile for the specified proxy address, or
// the current profile if no proxy is specified.
func (c *Config) GetProfile(ps ProfileStore, proxyAddr string) (*profile.Profile, error) {
var proxyHost string
var err error
if proxyAddr == "" {
proxyHost, err = ps.CurrentProfile()
if err != nil {
return nil, trace.Wrap(err)
}
} else {
proxyHost, err = utils.Host(proxyAddr)
if err != nil {
return nil, trace.Wrap(err)
}
}
profile, err := ps.GetProfile(proxyHost)
if err != nil {
return nil, trace.Wrap(err)
}
return profile, nil
}
// LoadProfile populates Config with the values stored in the given
// profiles directory. If profileDir is an empty string, the default profile
// directory ~/.tsh is used.
func (c *Config) LoadProfile(ps ProfileStore, proxyAddr string) error {
profile, err := c.GetProfile(ps, proxyAddr)
if err != nil {
return trace.Wrap(err)
}
c.Username = profile.Username
c.SiteName = profile.SiteName
c.KubeProxyAddr = profile.KubeProxyAddr
c.WebProxyAddr = profile.WebProxyAddr
c.SSHProxyAddr = profile.SSHProxyAddr
c.PostgresProxyAddr = profile.PostgresProxyAddr
c.MySQLProxyAddr = profile.MySQLProxyAddr
c.MongoProxyAddr = profile.MongoProxyAddr
c.TLSRoutingEnabled = profile.TLSRoutingEnabled
c.TLSRoutingConnUpgradeRequired = profile.TLSRoutingConnUpgradeRequired
c.KeysDir = profile.Dir
c.AuthConnector = profile.AuthConnector
c.LoadAllCAs = profile.LoadAllCAs
c.PrivateKeyPolicy = profile.PrivateKeyPolicy
c.PIVSlot = profile.PIVSlot
c.SAMLSingleLogoutEnabled = profile.SAMLSingleLogoutEnabled
c.SSHDialTimeout = profile.SSHDialTimeout
c.SSOHost = profile.SSOHost
c.AuthenticatorAttachment, err = parseMFAMode(profile.MFAMode)
if err != nil {
return trace.BadParameter("unable to parse mfa mode in user profile: %v.", err)
}
c.DynamicForwardedPorts, err = ParseDynamicPortForwardSpec(profile.DynamicForwardedPorts)
if err != nil {
log.WarnContext(context.Background(), "Unable to parse dynamic port forwarding in user profile", "error", err)
}
if required, ok := client.OverwriteALPNConnUpgradeRequirementByEnv(c.WebProxyAddr); ok {
c.TLSRoutingConnUpgradeRequired = required
}
log.InfoContext(context.Background(), "ALPN connection upgrade required",
"web_proxy_addr", c.WebProxyAddr,
"upgrade_required", c.TLSRoutingConnUpgradeRequired,
)
return nil
}
// SaveProfile updates the given profiles directory with the current configuration
// If profileDir is an empty string, the default ~/.tsh is used
func (c *Config) SaveProfile(makeCurrent bool) error {
if c.WebProxyAddr == "" {
return nil
}
if err := c.ClientStore.SaveProfile(c.Profile(), makeCurrent); err != nil {
return trace.Wrap(err)
}
return nil
}
// Profile converts Config to *profile.Profile.
func (c *Config) Profile() *profile.Profile {
return &profile.Profile{
Username: c.Username,
WebProxyAddr: c.WebProxyAddr,
SSHProxyAddr: c.SSHProxyAddr,
KubeProxyAddr: c.KubeProxyAddr,
PostgresProxyAddr: c.PostgresProxyAddr,
MySQLProxyAddr: c.MySQLProxyAddr,
MongoProxyAddr: c.MongoProxyAddr,
SiteName: c.SiteName,
TLSRoutingEnabled: c.TLSRoutingEnabled,
TLSRoutingConnUpgradeRequired: c.TLSRoutingConnUpgradeRequired,
AuthConnector: c.AuthConnector,
MFAMode: c.AuthenticatorAttachment.String(),
LoadAllCAs: c.LoadAllCAs,
PrivateKeyPolicy: c.PrivateKeyPolicy,
PIVSlot: c.PIVSlot,
SAMLSingleLogoutEnabled: c.SAMLSingleLogoutEnabled,
SSHDialTimeout: c.SSHDialTimeout,
SSOHost: c.SSOHost,
}
}
// ParsedProxyHost holds the hostname and Web & SSH proxy addresses
// parsed out of a WebProxyAddress string.
type ParsedProxyHost struct {
Host string
// UsingDefaultWebProxyPort means that the port in WebProxyAddr was
// supplied by ParseProxyHost function rather than ProxyHost string
// itself.
UsingDefaultWebProxyPort bool
WebProxyAddr string
SSHProxyAddr string
}
// ParseProxyHost parses a ProxyHost string of the format <hostname>:<proxy_web_port>,<proxy_ssh_port>
// and returns the parsed components.
//
// There are several "default" ports that the Web Proxy service may use, and if the port is not
// specified in the supplied proxyHost string
//
// If a definitive answer is not possible (e.g. no proxy port is specified in
// the supplied string), ParseProxyHost() will supply default versions and flag
// that a default value is being used in the returned `ParsedProxyHost`
func ParseProxyHost(proxyHost string) (*ParsedProxyHost, error) {
host, port, err := net.SplitHostPort(proxyHost)
if err != nil {
host = proxyHost
port = ""
}
// set the default values of the port strings. One, both, or neither may
// be overridden by the port string parsing below.
usingDefaultWebProxyPort := true
webPort := strconv.Itoa(defaults.HTTPListenPort)
sshPort := strconv.Itoa(defaults.SSHProxyListenPort)
// Split the port string out into at most two parts, the proxy port and
// ssh port. Any more that 2 parts will be considered an error.
parts := strings.Split(port, ",")
switch {
// Default ports for both the SSH and Web proxy.
case len(parts) == 0:
break
// User defined HTTP proxy port, default SSH proxy port.
case len(parts) == 1: