-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
683 lines (612 loc) · 19 KB
/
client.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
/*
Copyright 2015 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package client
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"io"
"io/ioutil"
"net"
"strconv"
"strings"
"time"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/sshutils"
"github.com/gravitational/teleport/lib/sshutils/scp"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"
)
// ProxyClient implements ssh client to a teleport proxy
// It can provide list of nodes or connect to nodes
type ProxyClient struct {
teleportClient *TeleportClient
Client *ssh.Client
hostLogin string
proxyAddress string
proxyPrincipal string
hostKeyCallback ssh.HostKeyCallback
authMethod ssh.AuthMethod
siteName string
clientAddr string
}
// NodeClient implements ssh client to a ssh node (teleport or any regular ssh node)
// NodeClient can run shell and commands or upload and download files.
type NodeClient struct {
Namespace string
Client *ssh.Client
Proxy *ProxyClient
TC *TeleportClient
}
// GetSites returns list of the "sites" (AKA teleport clusters) connected to the proxy
// Each site is returned as an instance of its auth server
//
func (proxy *ProxyClient) GetSites() ([]services.Site, error) {
proxySession, err := proxy.Client.NewSession()
if err != nil {
return nil, trace.Wrap(err)
}
stdout := &bytes.Buffer{}
reader, err := proxySession.StdoutPipe()
if err != nil {
return nil, trace.Wrap(err)
}
done := make(chan struct{})
go func() {
io.Copy(stdout, reader)
close(done)
}()
if err := proxySession.RequestSubsystem("proxysites"); err != nil {
return nil, trace.Wrap(err)
}
select {
case <-done:
case <-time.After(defaults.DefaultDialTimeout):
return nil, trace.ConnectionProblem(nil, "timeout")
}
log.Debugf("[CLIENT] found clusters: %v", stdout.String())
var sites []services.Site
if err := json.Unmarshal(stdout.Bytes(), &sites); err != nil {
return nil, trace.Wrap(err)
}
return sites, nil
}
// FindServersByLabels returns list of the nodes which have labels exactly matching
// the given label set.
//
// A server is matched when ALL labels match.
// If no labels are passed, ALL nodes are returned.
func (proxy *ProxyClient) FindServersByLabels(ctx context.Context, namespace string, labels map[string]string) ([]services.Server, error) {
if namespace == "" {
return nil, trace.BadParameter(auth.MissingNamespaceError)
}
nodes := make([]services.Server, 0)
site, err := proxy.ClusterAccessPoint(ctx, false)
if err != nil {
return nil, trace.Wrap(err)
}
siteNodes, err := site.GetNodes(namespace)
if err != nil {
return nil, trace.Wrap(err)
}
// look at every node on this site and see which ones match:
for _, node := range siteNodes {
if node.MatchAgainst(labels) {
nodes = append(nodes, node)
}
}
return nodes, nil
}
// ClusterAccessPoint returns cluster access point used for discovery
// and could be cached based on the access policy
func (proxy *ProxyClient) ClusterAccessPoint(ctx context.Context, quiet bool) (auth.AccessPoint, error) {
// get the current cluster:
cluster, err := proxy.currentCluster()
if err != nil {
return nil, trace.Wrap(err)
}
clt, err := proxy.ConnectToSite(ctx, quiet)
if err != nil {
return nil, trace.Wrap(err)
}
return proxy.teleportClient.accessPoint(clt, proxy.proxyAddress, cluster.Name)
}
// ConnectToSite connects to the auth server of the given site via proxy.
// It returns connected and authenticated auth server client
//
// if 'quiet' is set to true, no errors will be printed to stdout, otherwise
// any connection errors are visible to a user.
func (proxy *ProxyClient) ConnectToSite(ctx context.Context, quiet bool) (auth.ClientI, error) {
// get the current cluster:
site, err := proxy.currentCluster()
if err != nil {
return nil, trace.Wrap(err)
}
dialer := func(ctx context.Context, network, _ string) (net.Conn, error) {
return proxy.dialAuthServer(ctx, site.Name)
}
if proxy.teleportClient.SkipLocalAuth {
return auth.NewTLSClientWithDialer(dialer, proxy.teleportClient.TLS)
}
tlsConfig := utils.TLSConfig()
localAgent := proxy.teleportClient.LocalAgent()
pool, err := localAgent.GetCerts()
if err != nil {
return nil, trace.Wrap(err)
}
tlsConfig.RootCAs = pool
key, err := localAgent.GetKey()
if err != nil {
return nil, trace.Wrap(err, "failed to fetch TLS key for %v", proxy.teleportClient.Username)
}
if len(key.TLSCert) != 0 {
tlsCert, err := tls.X509KeyPair(key.TLSCert, key.Priv)
if err != nil {
return nil, trace.Wrap(err, "failed to parse TLS cert and key")
}
tlsConfig.Certificates = append(tlsConfig.Certificates, tlsCert)
}
if len(tlsConfig.Certificates) == 0 {
return nil, trace.BadParameter("no TLS keys found for user %v, please relogin to get new credentials", proxy.teleportClient.Username)
}
clt, err := auth.NewTLSClientWithDialer(dialer, tlsConfig)
if err != nil {
return nil, trace.Wrap(err)
}
return clt, nil
}
// closerConn wraps connection and attaches additional closers to it
type closerConn struct {
net.Conn
closers []io.Closer
}
// addCloser adds any closer in ctx that will be called
// whenever server closes session channel
func (c *closerConn) addCloser(closer io.Closer) {
c.closers = append(c.closers, closer)
}
func (c *closerConn) Close() error {
var errors []error
for _, closer := range c.closers {
errors = append(errors, closer.Close())
}
errors = append(errors, c.Conn.Close())
return trace.NewAggregate(errors...)
}
// nodeName removes the port number from the hostname, if present
func nodeName(node string) string {
n, _, err := net.SplitHostPort(node)
if err != nil {
return node
}
return n
}
type proxyResponse struct {
isRecord bool
err error
}
// isRecordingProxy returns true if the proxy is in recording mode. Note, this
// function can only be called after authentication has occured and should be
// called before the first session is created.
func (proxy *ProxyClient) isRecordingProxy() (bool, error) {
responseCh := make(chan proxyResponse)
// we have to run this in a goroutine because older version of Teleport handled
// global out-of-band requests incorrectly: Teleport would ignore requests it
// does not know about and never reply to them. So if we wait a second and
// don't hear anything back, most likley we are trying to connect to an older
// version of Teleport and we should not try and forward our agent.
go func() {
ok, responseBytes, err := proxy.Client.SendRequest(teleport.RecordingProxyReqType, true, nil)
if err != nil {
responseCh <- proxyResponse{isRecord: false, err: trace.Wrap(err)}
return
}
if !ok {
responseCh <- proxyResponse{isRecord: false, err: trace.AccessDenied("unable to determine proxy type")}
return
}
recordingProxy, err := strconv.ParseBool(string(responseBytes))
if err != nil {
responseCh <- proxyResponse{isRecord: false, err: trace.Wrap(err)}
return
}
responseCh <- proxyResponse{isRecord: recordingProxy, err: nil}
}()
select {
case resp := <-responseCh:
if resp.err != nil {
return false, trace.Wrap(resp.err)
}
return resp.isRecord, nil
case <-time.After(1 * time.Second):
// probably the older version of the proxy or at least someone that is
// responding incorrectly, don't forward agent to it
return false, nil
}
}
// dialAuthServer returns auth server connection forwarded via proxy
func (proxy *ProxyClient) dialAuthServer(ctx context.Context, clusterName string) (net.Conn, error) {
log.Debugf("Client %v is connecting to auth server on cluster %q.", proxy.clientAddr, clusterName)
address := "@" + clusterName
// parse destination first:
localAddr, err := utils.ParseAddr("tcp://" + proxy.proxyAddress)
if err != nil {
return nil, trace.Wrap(err)
}
fakeAddr, err := utils.ParseAddr("tcp://" + address)
if err != nil {
return nil, trace.Wrap(err)
}
proxySession, err := proxy.Client.NewSession()
if err != nil {
return nil, trace.Wrap(err)
}
proxyWriter, err := proxySession.StdinPipe()
if err != nil {
return nil, trace.Wrap(err)
}
proxyReader, err := proxySession.StdoutPipe()
if err != nil {
return nil, trace.Wrap(err)
}
proxyErr, err := proxySession.StderrPipe()
if err != nil {
return nil, trace.Wrap(err)
}
err = proxySession.RequestSubsystem("proxy:" + address)
if err != nil {
// read the stderr output from the failed SSH session and append
// it to the end of our own message:
serverErrorMsg, _ := ioutil.ReadAll(proxyErr)
return nil, trace.ConnectionProblem(err, "failed connecting to node %v. %s",
nodeName(strings.Split(address, "@")[0]), serverErrorMsg)
}
return utils.NewPipeNetConn(
proxyReader,
proxyWriter,
proxySession,
localAddr,
fakeAddr,
), nil
}
// ConnectToNode connects to the ssh server via Proxy.
// It returns connected and authenticated NodeClient
func (proxy *ProxyClient) ConnectToNode(ctx context.Context, nodeAddress string, user string, quiet bool) (*NodeClient, error) {
log.Infof("[CLIENT] client=%v connecting to node=%s", proxy.clientAddr, nodeAddress)
// parse destination first:
localAddr, err := utils.ParseAddr("tcp://" + proxy.proxyAddress)
if err != nil {
return nil, trace.Wrap(err)
}
fakeAddr, err := utils.ParseAddr("tcp://" + nodeAddress)
if err != nil {
return nil, trace.Wrap(err)
}
// after auth but before we create the first session, find out if the proxy
// is in recording mode or not
recordingProxy, err := proxy.isRecordingProxy()
if err != nil {
return nil, trace.Wrap(err)
}
proxySession, err := proxy.Client.NewSession()
if err != nil {
return nil, trace.Wrap(err)
}
proxyWriter, err := proxySession.StdinPipe()
if err != nil {
return nil, trace.Wrap(err)
}
proxyReader, err := proxySession.StdoutPipe()
if err != nil {
return nil, trace.Wrap(err)
}
proxyErr, err := proxySession.StderrPipe()
if err != nil {
return nil, trace.Wrap(err)
}
// pass the true client IP (if specified) to the proxy so it could pass it into the
// SSH session for proper audit
if len(proxy.clientAddr) > 0 {
if err = proxySession.Setenv(sshutils.TrueClientAddrVar, proxy.clientAddr); err != nil {
log.Error(err)
}
}
// the client only tries to forward an agent when the proxy is in recording
// mode. we always try and forward an agent here because each new session
// creates a new context which holds the agent. if ForwardToAgent returns an error
// "already have handler for" we ignore it.
if recordingProxy {
err = agent.ForwardToAgent(proxy.Client, proxy.teleportClient.localAgent.Agent)
if err != nil && !strings.Contains(err.Error(), "agent: already have handler for") {
return nil, trace.Wrap(err)
}
err = agent.RequestAgentForwarding(proxySession)
if err != nil {
return nil, trace.Wrap(err)
}
}
err = proxySession.RequestSubsystem("proxy:" + nodeAddress)
if err != nil {
// read the stderr output from the failed SSH session and append
// it to the end of our own message:
serverErrorMsg, _ := ioutil.ReadAll(proxyErr)
return nil, trace.ConnectionProblem(err, "failed connecting to node %v. %s",
nodeName(strings.Split(nodeAddress, "@")[0]), serverErrorMsg)
}
pipeNetConn := utils.NewPipeNetConn(
proxyReader,
proxyWriter,
proxySession,
localAddr,
fakeAddr,
)
sshConfig := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{proxy.authMethod},
HostKeyCallback: proxy.hostKeyCallback,
}
conn, chans, reqs, err := newClientConn(ctx, pipeNetConn, nodeAddress, sshConfig)
if err != nil {
if utils.IsHandshakeFailedError(err) {
proxySession.Close()
parts := strings.Split(nodeAddress, "@")
hostname := parts[0]
if len(hostname) == 0 && len(parts) > 1 {
hostname = "cluster " + parts[1]
}
return nil, trace.Errorf(`access denied to %v connecting to %v`, user, nodeName(hostname))
}
return nil, trace.Wrap(err)
}
// We pass an empty channel which we close right away to ssh.NewClient
// because the client need to handle requests itself.
emptyCh := make(chan *ssh.Request)
close(emptyCh)
client := ssh.NewClient(conn, chans, emptyCh)
nc := &NodeClient{
Client: client,
Proxy: proxy,
Namespace: defaults.Namespace,
TC: proxy.teleportClient,
}
// Start a goroutine that will run for the duration of the client to process
// global requests from the client. Teleport clients will use this to update
// terminal sizes when the remote PTY size has changed.
go nc.handleGlobalRequests(ctx, reqs)
return nc, nil
}
func (c *NodeClient) handleGlobalRequests(ctx context.Context, requestCh <-chan *ssh.Request) {
for {
select {
case r := <-requestCh:
// When the channel is closing, nil is returned.
if r == nil {
return
}
switch r.Type {
case teleport.SessionEvent:
// Parse event and create events.EventFields that can be consumed directly
// by caller.
var e events.EventFields
err := json.Unmarshal(r.Payload, &e)
if err != nil {
log.Warnf("Unable to parse event: %v: %v.", string(r.Payload), err)
continue
}
// Send event to event channel.
err = c.TC.SendEvent(ctx, e)
if err != nil {
log.Warnf("Unable to send event %v: %v.", string(r.Payload), err)
continue
}
default:
// This handles keepalive messages and matches the behaviour of OpenSSH.
r.Reply(false, nil)
}
case <-ctx.Done():
return
}
}
}
// newClientConn is a wrapper around ssh.NewClientConn
func newClientConn(ctx context.Context,
conn net.Conn,
nodeAddress string,
config *ssh.ClientConfig) (ssh.Conn, <-chan ssh.NewChannel, <-chan *ssh.Request, error) {
type response struct {
conn ssh.Conn
chanCh <-chan ssh.NewChannel
reqCh <-chan *ssh.Request
err error
}
respCh := make(chan response, 1)
go func() {
conn, chans, reqs, err := ssh.NewClientConn(conn, nodeAddress, config)
respCh <- response{conn, chans, reqs, err}
}()
select {
case resp := <-respCh:
if resp.err != nil {
return nil, nil, nil, trace.Wrap(resp.err, "failed to connect to %q", nodeAddress)
}
return resp.conn, resp.chanCh, resp.reqCh, nil
case <-ctx.Done():
errClose := conn.Close()
if errClose != nil {
log.Error(errClose)
}
// drain the channel
resp := <-respCh
return nil, nil, nil, trace.ConnectionProblem(resp.err, "failed to connect to %q", nodeAddress)
}
}
func (proxy *ProxyClient) Close() error {
return proxy.Client.Close()
}
// Upload uploads local file(s) or to the remote server's destination path
func (client *NodeClient) Upload(srcPath, rDestPath string, recursive bool, stderr, progressWriter io.Writer) error {
scpConf := scp.Command{
Source: true,
Recursive: recursive,
Target: []string{srcPath},
Terminal: progressWriter,
}
// "impersonate" scp to a server
shellCmd := "/usr/bin/scp -t"
if recursive {
shellCmd += " -r"
}
shellCmd += (" " + rDestPath)
return client.scp(scpConf, shellCmd, stderr)
}
// Download downloads file or dir from the remote server
func (client *NodeClient) Download(remoteSourcePath, localDestinationPath string, recursive bool, stderr, progressWriter io.Writer) error {
scpConf := scp.Command{
Sink: true,
Recursive: recursive,
Target: []string{localDestinationPath},
Terminal: progressWriter,
}
// "impersonate" scp to a server
shellCmd := "/usr/bin/scp -f"
if recursive {
shellCmd += " -r"
}
shellCmd += (" " + remoteSourcePath)
return client.scp(scpConf, shellCmd, stderr)
}
// scp runs remote scp command(shellCmd) on the remote server and
// runs local scp handler using scpConf
func (client *NodeClient) scp(scpCommand scp.Command, shellCmd string, errWriter io.Writer) error {
s, err := client.Client.NewSession()
if err != nil {
return trace.Wrap(err)
}
defer s.Close()
stdin, err := s.StdinPipe()
if err != nil {
return trace.Wrap(err)
}
stdout, err := s.StdoutPipe()
if err != nil {
return trace.Wrap(err)
}
ch := utils.NewPipeNetConn(
stdout,
stdin,
utils.MultiCloser(),
&net.IPAddr{},
&net.IPAddr{},
)
closeC := make(chan interface{}, 1)
go func() {
if err = scpCommand.Execute(ch); err != nil {
log.Error(err)
}
stdin.Close()
close(closeC)
}()
runErr := s.Run(shellCmd)
if runErr != nil && err == nil {
err = runErr
}
<-closeC
if trace.IsEOF(err) {
err = nil
}
return trace.Wrap(err)
}
// listenAndForward listens on a given socket and forwards all incoming connections
// to the given remote address via
func (client *NodeClient) listenAndForward(socket net.Listener, remoteAddr string) {
defer socket.Close()
defer client.Close()
proxyConnection := func(incoming net.Conn) {
defer incoming.Close()
var (
conn net.Conn
err error
)
log.Debugf("nodeClient.listenAndForward(%v -> %v) started", incoming.RemoteAddr(), remoteAddr)
for attempt := 1; attempt <= 5; attempt++ {
conn, err = client.Client.Dial("tcp", remoteAddr)
if err != nil {
log.Errorf("Connection attempt %v: %v", attempt, err)
// failed to establish an outbound connection? try again:
time.Sleep(time.Millisecond * time.Duration(100*attempt))
continue
}
// connection established: continue:
break
}
// permanent failure establishing connection
if err != nil {
log.Errorf("Failed to connect to node %v", remoteAddr)
return
}
defer conn.Close()
// start proxying:
doneC := make(chan interface{}, 2)
go func() {
io.Copy(incoming, conn)
doneC <- true
}()
go func() {
io.Copy(conn, incoming)
doneC <- true
}()
<-doneC
<-doneC
log.Debugf("nodeClient.listenAndForward(%v -> %v) exited", incoming.RemoteAddr(), remoteAddr)
}
// request processing loop: accept incoming requests to be connected to nodes
// and proxy them to 'remoteAddr'
for {
incoming, err := socket.Accept()
if err != nil {
log.Error(err)
break
}
go proxyConnection(incoming)
}
}
func (client *NodeClient) Close() error {
return client.Client.Close()
}
// currentCluster returns the connection to the API of the current cluster
func (proxy *ProxyClient) currentCluster() (*services.Site, error) {
sites, err := proxy.GetSites()
if err != nil {
return nil, trace.Wrap(err)
}
if len(sites) == 0 {
return nil, trace.NotFound("no clusters registered")
}
if proxy.siteName == "" {
return &sites[0], nil
}
for _, site := range sites {
if site.Name == proxy.siteName {
return &site, nil
}
}
return nil, trace.NotFound("cluster %v not found", proxy.siteName)
}