-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
1754 lines (1564 loc) · 49.9 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
/*
Copyright 2016 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 client
import (
"bufio"
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"net"
"net/url"
"os"
"os/exec"
"os/signal"
"os/user"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/backend"
"github.com/gravitational/teleport/lib/backend/dir"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/shell"
"github.com/gravitational/teleport/lib/state"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/trace"
"github.com/moby/moby/pkg/term"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/crypto/ssh/terminal"
)
const (
// Directory location where tsh profiles (and session keys) are stored
ProfileDir = ".tsh"
)
// 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
}
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)
}
// 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
// Remote host to connect
Host string
// Labels represent host Labels
Labels map[string]string
// Namespace is nodes namespace
Namespace 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
// ProxyHostPort is a host or IP of the proxy (with optional ":ssh_port,https_port").
// The value is taken from the --proxy flag and can look like --proxy=host:5025,5080
ProxyHostPort 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
// SkipLocalAuth tells the client to use AuthMethods parameter for authentication and NOT
// use its own SSH agent or ask user for passwords. This is used by external programs linking
// against Teleport client and obtaining credentials from elsewhere.
SkipLocalAuth bool
// Agent is used when SkipLocalAuth is true
Agent agent.Agent
// ForwardAgent is used by the client to request agent forwarding from the server.
ForwardAgent bool
// AuthMethods are used to login into the cluster. If specified, the client will
// use them in addition to certs stored in its local agent (from disk)
AuthMethods []ssh.AuthMethod
// TLSConfig is TLS configuration, if specified, the client
// will use this TLS configuration to access API endpoints
TLS *tls.Config
// DefaultPrincipal determines the default SSH username (principal) the client should be using
// when connecting to auth/proxy servers. Usually it's returned with a certificate,
// but this variables provides a default (used by the web-based terminal client)
DefaultPrincipal 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
// Locally forwarded ports (parameters to -L ssh flag)
LocalForwardPorts 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
// Env is a map of environmnent variables to send when opening session
Env map[string]string
// Interactive, when set to true, tells tsh to launch a remote command
// in interactive mode, i.e. attaching the temrinal to it
Interactive 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
// CheckVersions will check that client version is compatible
// with auth server version when connecting.
CheckVersions bool
}
// 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
}
func MakeDefaultConfig() *Config {
return &Config{
Stdout: os.Stdout,
Stderr: os.Stderr,
Stdin: os.Stdin,
}
}
// ProfileStatus combines metadata from the logged in profile and associated
// SSH certificate.
type ProfileStatus struct {
// ProxyURL is the URL the web client is accessible at.
ProxyURL url.URL
// Username is the Teleport username.
Username string
// Roles is a list of Teleport Roles this user has been assigned.
Roles []string
// Logins are the Linux accounts, also known as principals in OpenSSH terminology.
Logins []string
// ValidUntil is the time at which this SSH certificate will expire.
ValidUntil time.Time
// Extensions is a list of enabled SSH features for the certificate.
Extensions []string
}
// readProfile reads in the profile as well as the associated certificate
// and returns a *ProfileStatus which can be used to print the status of the
// profile.
func readProfile(profileDir string, profileName string) (*ProfileStatus, error) {
var err error
// Read in the profile for this proxy.
profile, err := ProfileFromFile(filepath.Join(profileDir, profileName))
if err != nil {
return nil, trace.Wrap(err)
}
// Read in the SSH certificate for the user logged into this proxy.
store, err := NewFSLocalKeyStore(profileDir)
if err != nil {
return nil, trace.Wrap(err)
}
keys, err := store.GetKey(profile.ProxyHost, profile.Username)
if err != nil {
return nil, trace.Wrap(err)
}
publicKey, _, _, _, err := ssh.ParseAuthorizedKey(keys.Cert)
if err != nil {
return nil, trace.Wrap(err)
}
cert, ok := publicKey.(*ssh.Certificate)
if !ok {
return nil, trace.BadParameter("no certificate found")
}
// Extract from the certificate how much longer it will be valid for.
validUntil := time.Unix(int64(cert.ValidBefore), 0)
// Extract roles from certificate. Note, if the certificate is in old format,
// this will be empty.
var roles []string
rawRoles, ok := cert.Extensions[teleport.CertExtensionTeleportRoles]
if ok {
roles, err = services.UnmarshalCertRoles(rawRoles)
if err != nil {
return nil, trace.Wrap(err)
}
}
sort.Strings(roles)
// Extract extensions from certificate. This lists the abilities of the
// certificate (like can the user request a PTY, port forwarding, etc.)
var extensions []string
for ext, _ := range cert.Extensions {
if ext == teleport.CertExtensionTeleportRoles {
continue
}
extensions = append(extensions, ext)
}
sort.Strings(extensions)
return &ProfileStatus{
ProxyURL: url.URL{
Scheme: "https",
Host: net.JoinHostPort(profile.ProxyHost, strconv.Itoa(profile.ProxyWebPort)),
},
Username: profile.Username,
Logins: cert.ValidPrincipals,
ValidUntil: validUntil,
Extensions: extensions,
Roles: roles,
}, nil
}
// fullProfileName takes a profile directory and the host the user is trying
// to connect to and returns the name of the profile file.
func fullProfileName(profileDir string, proxyHost string) (string, error) {
var err error
var profileName string
// If no profile name was passed in, try and extract the active profile from
// the ~/.tsh/profile symlink. If one was passed in, append .yaml to name.
if proxyHost == "" {
profileName, err = os.Readlink(filepath.Join(profileDir, "profile"))
if err != nil {
return "", trace.ConvertSystemError(err)
}
} else {
profileName = proxyHost + ".yaml"
}
// Make sure the profile requested actually exists.
_, err = os.Stat(filepath.Join(profileDir, profileName))
if err != nil {
return "", trace.ConvertSystemError(err)
}
return profileName, nil
}
// Status returns the active profile as well as a list of available profiles.
func Status(profileDir string, proxyHost string) (*ProfileStatus, []*ProfileStatus, error) {
var err error
var profile *ProfileStatus
var others []*ProfileStatus
// Construct the full path to the profile requested and make sure it exists.
profileDir = FullProfilePath(profileDir)
stat, err := os.Stat(profileDir)
if err != nil {
return nil, nil, trace.Wrap(err)
}
if !stat.IsDir() {
return nil, nil, trace.BadParameter("profile path not a directory")
}
// Construct the name of the profile requested. If an empty string was
// passed in, the name of the active profile will be extracted from the
// ~/.tsh/profile symlink.
profileName, err := fullProfileName(profileDir, proxyHost)
if err != nil {
if trace.IsNotFound(err) {
return nil, nil, trace.NotFound("not logged in")
}
return nil, nil, trace.Wrap(err)
}
// Read in the active profile first.
profile, err = readProfile(profileDir, profileName)
if err != nil {
return nil, nil, trace.Wrap(err)
}
// Next, get list of all other available profiles. Filter out logged in
// profile if it exists and return a slice of *ProfileStatus.
files, err := ioutil.ReadDir(profileDir)
if err != nil {
return nil, nil, trace.Wrap(err)
}
for _, file := range files {
if file.IsDir() {
continue
}
if !strings.HasSuffix(file.Name(), ".yaml") {
continue
}
if file.Name() == profileName {
continue
}
ps, err := readProfile(profileDir, file.Name())
if err != nil {
return nil, nil, trace.Wrap(err)
}
others = append(others, ps)
}
return profile, others, 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(profileDir string, proxyName string) error {
profileDir = FullProfilePath(profileDir)
// read the profile:
cp, err := ProfileFromDir(profileDir, ProxyHost(proxyName))
if err != nil {
if trace.IsNotFound(err) {
return nil
}
return trace.Wrap(err)
}
// apply the profile to the current configuration:
c.SetProxy(cp.ProxyHost, cp.ProxyWebPort, cp.ProxySSHPort)
c.Username = cp.Username
c.SiteName = cp.SiteName
c.LocalForwardPorts, err = ParsePortForwardSpec(cp.ForwardedPorts)
if err != nil {
log.Warnf("Error parsing user profile: %v", err)
}
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(profileDir string, profileOptions ...ProfileOptions) error {
if c.ProxyHostPort == "" {
return nil
}
profileDir = FullProfilePath(profileDir)
profilePath := path.Join(profileDir, c.ProxyHost()) + ".yaml"
var cp ClientProfile
cp.ProxyHost = c.ProxyHost()
cp.Username = c.Username
cp.ProxySSHPort = c.ProxySSHPort()
cp.ProxyWebPort = c.ProxyWebPort()
cp.ForwardedPorts = c.LocalForwardPorts.ToStringSpec()
cp.SiteName = c.SiteName
// create a profile file and set it current base on the option
var opts ProfileOptions
if len(profileOptions) == 0 {
// default behavior is to override the profile
opts = ProfileMakeCurrent
} else {
for _, flag := range profileOptions {
opts |= flag
}
}
if err := cp.SaveTo(profilePath, opts); err != nil {
return trace.Wrap(err)
}
return nil
}
func (c *Config) SetProxy(host string, webPort, sshPort int) {
c.ProxyHostPort = fmt.Sprintf("%s:%d,%d", host, webPort, sshPort)
}
// ProxyHost returns the hostname of the proxy server (without any port numbers)
func (c *Config) ProxyHost() string {
return ProxyHost(c.ProxyHostPort)
}
// ProxyHost returns the hostname of the proxy server (without any port numbers)
func ProxyHost(proxyHost string) string {
host, _, err := net.SplitHostPort(proxyHost)
if err != nil {
return proxyHost
}
return host
}
func (c *Config) ProxySSHHostPort() string {
return net.JoinHostPort(c.ProxyHost(), strconv.Itoa(c.ProxySSHPort()))
}
func (c *Config) ProxyWebHostPort() string {
return net.JoinHostPort(c.ProxyHost(), strconv.Itoa(c.ProxyWebPort()))
}
// ProxyWebPort returns the port number of teleport HTTP proxy stored in the config
// usually 3080 by default.
func (c *Config) ProxyWebPort() (retval int) {
retval = defaults.HTTPListenPort
_, port, err := net.SplitHostPort(c.ProxyHostPort)
if err == nil && len(port) > 0 && port[0] != ',' {
ports := strings.Split(port, ",")
if len(ports) > 0 {
retval, err = strconv.Atoi(ports[0])
if err != nil {
log.Warnf("invalid proxy web port: '%v': %v", ports, err)
}
}
}
return retval
}
// ProxySSHPort returns the port number of teleport SSH proxy stored in the config
// usually 3023 by default.
func (c *Config) ProxySSHPort() (retval int) {
retval = defaults.SSHProxyListenPort
_, port, err := net.SplitHostPort(c.ProxyHostPort)
if err == nil && len(port) > 0 {
ports := strings.Split(port, ",")
if len(ports) > 1 {
retval, err = strconv.Atoi(ports[1])
if err != nil {
log.Warnf("invalid proxy SSH port: '%v': %v", ports, err)
}
}
}
return retval
}
// ProxySpecified returns true if proxy has been specified
func (c *Config) ProxySpecified() bool {
return len(c.ProxyHostPort) > 0
}
// TeleportClient is a wrapper around SSH client with teleport specific
// workflow built in
type TeleportClient struct {
Config
localAgent *LocalKeyAgent
// OnShellCreated gets called when the shell is created. It's
// safe to keep it nil.
OnShellCreated ShellCreatedCallback
// eventsCh is a channel used to inform clients about events have that
// occured during the session.
eventsCh chan events.EventFields
}
// ShellCreatedCallback can be supplied for every teleport client. It will
// be called right after the remote shell is created, but the session
// hasn't begun yet.
//
// It allows clients to cancel SSH action
type ShellCreatedCallback func(s *ssh.Session, c *ssh.Client, terminal io.ReadWriteCloser) (exit bool, err error)
// NewClient creates a TeleportClient object and fully configures it
func NewClient(c *Config) (tc *TeleportClient, err error) {
// validate configuration
if c.Username == "" {
c.Username, err = Username()
if err != nil {
return nil, trace.Wrap(err)
}
log.Infof("No teleport login given. defaulting to %s", c.Username)
}
if c.ProxyHostPort == "" {
return nil, trace.BadParameter("No proxy address specified, missed --proxy flag?")
}
if c.HostLogin == "" {
c.HostLogin, err = Username()
if err != nil {
return nil, trace.Wrap(err)
}
log.Infof("no host login given. defaulting to %s", c.HostLogin)
}
if c.KeyTTL == 0 {
c.KeyTTL = defaults.CertDuration
} else if c.KeyTTL > defaults.MaxCertDuration || c.KeyTTL < defaults.MinCertDuration {
return nil, trace.BadParameter("invalid requested cert TTL")
}
c.Namespace = services.ProcessNamespace(c.Namespace)
tc = &TeleportClient{Config: *c}
if tc.Stdout == nil {
tc.Stdout = os.Stdout
}
if tc.Stderr == nil {
tc.Stderr = os.Stderr
}
if tc.Stdin == nil {
tc.Stdin = os.Stdin
}
// Create a buffered channel to hold events that occured during this session.
// This channel must be buffered because the SSH connection directly feeds
// into it. Delays in pulling messages off the global SSH request channel
// could lead to the connection hanging.
tc.eventsCh = make(chan events.EventFields, 1024)
// sometimes we need to use external auth without using local auth
// methods, e.g. in automation daemons
if c.SkipLocalAuth {
if len(c.AuthMethods) == 0 {
return nil, trace.BadParameter("SkipLocalAuth is true but no AuthMethods provided")
}
if c.TLS == nil {
return nil, trace.BadParameter("SkipLocalAuth is true but no TLS config is provided")
}
// if the client was passed an agent in the configuration and skip local auth, use
// the passed in agent.
if c.Agent != nil {
tc.localAgent = &LocalKeyAgent{Agent: c.Agent}
}
} else {
// initialize the local agent (auth agent which uses local SSH keys signed by the CA):
tc.localAgent, err = NewLocalAgent(c.KeysDir, tc.ProxyHost(), c.Username)
if err != nil {
return nil, trace.Wrap(err)
}
if tc.HostKeyCallback == nil {
tc.HostKeyCallback = tc.localAgent.CheckHostSignature
}
}
return tc, nil
}
// accessPoint returns access point based on the cache policy
func (tc *TeleportClient) accessPoint(clt auth.AccessPoint, proxyHostPort string, clusterName string) (auth.AccessPoint, error) {
if tc.CachePolicy == nil {
log.Debugf("not using caching access point")
return clt, nil
}
dirPath, err := initKeysDir(tc.KeysDir)
if err != nil {
return nil, trace.Wrap(err)
}
path := filepath.Join(dirPath, "cache", proxyHostPort, clusterName)
log.Debugf("using caching access point %v", path)
cacheBackend, err := dir.New(backend.Params{"path": path})
if err != nil {
return nil, trace.Wrap(err)
}
// make a caching auth client for the auth server:
return state.NewCachingAuthClient(state.Config{
SkipPreload: true,
AccessPoint: clt,
Backend: cacheBackend,
CacheMaxTTL: tc.CachePolicy.CacheTTL,
NeverExpires: tc.CachePolicy.NeverExpires,
})
}
func (tc *TeleportClient) LocalAgent() *LocalKeyAgent {
return tc.localAgent
}
// getTargetNodes returns a list of node addresses this SSH command needs to
// operate on.
func (tc *TeleportClient) getTargetNodes(ctx context.Context, proxy *ProxyClient) ([]string, error) {
var (
err error
nodes []services.Server
retval = make([]string, 0)
)
if tc.Labels != nil && len(tc.Labels) > 0 {
nodes, err = proxy.FindServersByLabels(ctx, tc.Namespace, tc.Labels)
if err != nil {
return nil, trace.Wrap(err)
}
for i := 0; i < len(nodes); i++ {
retval = append(retval, nodes[i].GetAddr())
}
}
if len(nodes) == 0 {
retval = append(retval, net.JoinHostPort(tc.Host, strconv.Itoa(tc.HostPort)))
}
return retval, nil
}
// SSH connects to a node and, if 'command' is specified, executes the command on it,
// otherwise runs interactive shell
//
// Returns nil if successful, or (possibly) *exec.ExitError
func (tc *TeleportClient) SSH(ctx context.Context, command []string, runLocally bool) error {
// connect to proxy first:
if !tc.Config.ProxySpecified() {
return trace.BadParameter("proxy server is not specified")
}
proxyClient, err := tc.ConnectToProxy(ctx)
if err != nil {
return trace.Wrap(err)
}
defer proxyClient.Close()
siteInfo, err := proxyClient.currentCluster()
if err != nil {
return trace.Wrap(err)
}
// which nodes are we executing this commands on?
nodeAddrs, err := tc.getTargetNodes(ctx, proxyClient)
if err != nil {
return trace.Wrap(err)
}
if len(nodeAddrs) == 0 {
return trace.BadParameter("no target host specified")
}
nodeClient, err := proxyClient.ConnectToNode(
ctx,
nodeAddrs[0]+"@"+tc.Namespace+"@"+siteInfo.Name,
tc.Config.HostLogin,
false)
if err != nil {
tc.ExitStatus = 1
return trace.Wrap(err)
}
// proxy local ports (forward incoming connections to remote host ports)
tc.startPortForwarding(nodeClient)
// local execution?
if runLocally {
if len(tc.Config.LocalForwardPorts) == 0 {
fmt.Println("Executing command locally without connecting to any servers. This makes no sense.")
}
return runLocalCommand(command)
}
// Issue "exec" request(s) to run on remote node(s).
if len(command) > 0 {
if len(nodeAddrs) > 1 {
fmt.Printf("\x1b[1mWARNING\x1b[0m: Multiple nodes matched label selector, running command on all.")
}
return tc.runCommand(ctx, siteInfo.Name, nodeAddrs, proxyClient, command)
}
// Issue "shell" request to run single node.
if len(nodeAddrs) > 1 {
fmt.Printf("\x1b[1mWARNING\x1b[0m: Multiple nodes match the label selector, picking first: %v\n", nodeAddrs[0])
}
return tc.runShell(nodeClient, nil)
}
func (tc *TeleportClient) startPortForwarding(nodeClient *NodeClient) error {
if len(tc.Config.LocalForwardPorts) > 0 {
for _, fp := range tc.Config.LocalForwardPorts {
socket, err := net.Listen("tcp", net.JoinHostPort(fp.SrcIP, strconv.Itoa(fp.SrcPort)))
if err != nil {
return trace.Wrap(err)
}
go nodeClient.listenAndForward(socket, net.JoinHostPort(fp.DestHost, strconv.Itoa(fp.DestPort)))
}
}
return nil
}
// Join connects to the existing/active SSH session
func (tc *TeleportClient) Join(ctx context.Context, namespace string, sessionID session.ID, input io.Reader) (err error) {
if namespace == "" {
return trace.BadParameter(auth.MissingNamespaceError)
}
tc.Stdin = input
if sessionID.Check() != nil {
return trace.Errorf("Invalid session ID format: %s", string(sessionID))
}
var notFoundErrorMessage = fmt.Sprintf("session '%s' not found or it has ended", sessionID)
// connect to proxy:
if !tc.Config.ProxySpecified() {
return trace.BadParameter("proxy server is not specified")
}
proxyClient, err := tc.ConnectToProxy(ctx)
if err != nil {
return trace.Wrap(err)
}
defer proxyClient.Close()
site, err := proxyClient.ConnectToSite(ctx, false)
if err != nil {
return trace.Wrap(err)
}
// find the session ID on the site:
sessions, err := site.GetSessions(namespace)
if err != nil {
return trace.Wrap(err)
}
var session *session.Session
for _, s := range sessions {
if s.ID == sessionID {
session = &s
break
}
}
if session == nil {
return trace.NotFound(notFoundErrorMessage)
}
// pick the 1st party of the session and use his server ID to connect to
if len(session.Parties) == 0 {
return trace.NotFound(notFoundErrorMessage)
}
serverID := session.Parties[0].ServerID
// find a server address by its ID
nodes, err := site.GetNodes(namespace)
if err != nil {
return trace.Wrap(err)
}
var node services.Server
for _, n := range nodes {
if n.GetName() == serverID {
node = n
break
}
}
if node == nil {
return trace.NotFound(notFoundErrorMessage)
}
// connect to server:
fullNodeAddr := node.GetAddr()
if tc.SiteName != "" {
fullNodeAddr = fmt.Sprintf("%s@%s@%s", node.GetAddr(), tc.Namespace, tc.SiteName)
}
nc, err := proxyClient.ConnectToNode(ctx, fullNodeAddr, tc.Config.HostLogin, false)
if err != nil {
return trace.Wrap(err)
}
defer nc.Close()
// start forwarding ports, if configured:
tc.startPortForwarding(nc)
// running shell with a given session means "join" it:
return tc.runShell(nc, session)
}
// Play replays the recorded session
func (tc *TeleportClient) Play(ctx context.Context, namespace, sessionId string) (err error) {
if namespace == "" {
return trace.BadParameter(auth.MissingNamespaceError)
}
sid, err := session.ParseID(sessionId)
if err != nil {
return fmt.Errorf("'%v' is not a valid session ID (must be GUID)", sid)
}
// connect to the auth server (site) who made the recording
proxyClient, err := tc.ConnectToProxy(ctx)
if err != nil {
return trace.Wrap(err)
}
site, err := proxyClient.ConnectToSite(ctx, false)
if err != nil {
return trace.Wrap(err)
}
// request events for that session (to get timing data)
sessionEvents, err := site.GetSessionEvents(namespace, *sid, 0, true)
if err != nil {
return trace.Wrap(err)
}
// read the stream into a buffer:
var stream []byte
for err == nil {
tmp, err := site.GetSessionChunk(namespace, *sid, len(stream), events.MaxChunkBytes)
if err != nil {
return trace.Wrap(err)
}
if len(tmp) == 0 {
err = io.EOF
break
}
stream = append(stream, tmp...)
}
// configure terminal for direct unbuffered echo-less input:
if term.IsTerminal(0) {
state, err := term.SetRawTerminal(0)
if err != nil {
return nil
}
defer term.RestoreTerminal(0, state)
}
player := newSessionPlayer(sessionEvents, stream)
// keys:
const (
keyCtrlC = 3
keyCtrlD = 4
keySpace = 32
keyLeft = 68
keyRight = 67
keyUp = 65
keyDown = 66
)
// playback control goroutine
go func() {
defer player.Stop()
key := make([]byte, 1)
for {
_, err = os.Stdin.Read(key)
if err != nil {
return
}
switch key[0] {
// Ctrl+C or Ctrl+D
case keyCtrlC, keyCtrlD:
return
// Space key
case keySpace:
player.TogglePause()
// <- arrow
case keyLeft, keyDown:
player.Rewind()
// -> arrow
case keyRight, keyUp:
player.Forward()
}
}
}()
// player starts playing in its own goroutine
player.Play()
// wait for keypresses loop to end
<-player.stopC
fmt.Println("\n\nend of session playback")
return trace.Wrap(err)
}
// SCP securely copies file(s) from one SSH server to another
func (tc *TeleportClient) SCP(ctx context.Context, args []string, port int, recursive bool, quiet bool) (err error) {
if len(args) < 2 {
return trace.Errorf("Need at least two arguments for scp")
}
first := args[0]
last := args[len(args)-1]
// local copy?
if !isRemoteDest(first) && !isRemoteDest(last) {
return trace.BadParameter("making local copies is not supported")
}
if !tc.Config.ProxySpecified() {
return trace.BadParameter("proxy server is not specified")
}
log.Infof("Connecting to proxy to copy (recursively=%v)...", recursive)
proxyClient, err := tc.ConnectToProxy(ctx)
if err != nil {
return trace.Wrap(err)
}
defer proxyClient.Close()
// helper function connects to the src/target node:
connectToNode := func(addr string) (*NodeClient, error) {
// determine which cluster we're connecting to:
siteInfo, err := proxyClient.currentCluster()
if err != nil {
return nil, trace.Wrap(err)
}
return proxyClient.ConnectToNode(ctx, addr+"@"+tc.Namespace+"@"+siteInfo.Name, tc.HostLogin, false)
}
var progressWriter io.Writer
if !quiet {
progressWriter = tc.Stdout
}
// gets called to convert SSH error code to tc.ExitStatus
onError := func(err error) error {
exitError, _ := trace.Unwrap(err).(*ssh.ExitError)
if exitError != nil {
tc.ExitStatus = exitError.ExitStatus()
}
return err
}
// upload:
if isRemoteDest(last) {
login, host, dest := parseSCPDestination(last)
if login != "" {
tc.HostLogin = login
}
addr := net.JoinHostPort(host, strconv.Itoa(port))
client, err := connectToNode(addr)
if err != nil {
return trace.Wrap(err)
}
// copy everything except the last arg (that's destination)
for _, src := range args[:len(args)-1] {
err = client.Upload(src, dest, recursive, tc.Stderr, progressWriter)
if err != nil {
return onError(err)
}
}
// download:
} else {
login, host, src := parseSCPDestination(first)
addr := net.JoinHostPort(host, strconv.Itoa(port))
if login != "" {
tc.HostLogin = login
}
client, err := connectToNode(addr)
if err != nil {
return trace.Wrap(err)
}
// copy everything except the last arg (that's destination)
for _, dest := range args[1:] {
err = client.Download(src, dest, recursive, tc.Stderr, progressWriter)
if err != nil {
return onError(err)
}
}
}
return nil
}
// parseSCPDestination takes a string representing a remote resource for SCP
// to download/upload, like "user@host:/path/to/resource.txt" and returns
// 3 components of it
func parseSCPDestination(s string) (login, host, dest string) {