forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sshserver.go
1174 lines (1031 loc) · 34 KB
/
sshserver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2015 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package regular implements SSH server that supports multiplexing
// tunneling, SSH connections proxying and only supports Key based auth
package regular
import (
"context"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"os/user"
"path/filepath"
"strconv"
"strings"
"sync"
"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/limiter"
"github.com/gravitational/teleport/lib/pam"
"github.com/gravitational/teleport/lib/reversetunnel"
"github.com/gravitational/teleport/lib/services"
rsession "github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/srv"
"github.com/gravitational/teleport/lib/sshutils"
"github.com/gravitational/teleport/lib/teleagent"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/sirupsen/logrus"
)
var log = logrus.WithFields(logrus.Fields{
trace.Component: teleport.ComponentNode,
})
// Server implements SSH server that uses configuration backend and
// certificate-based authentication
type Server struct {
sync.Mutex
namespace string
addr utils.NetAddr
hostname string
srv *sshutils.Server
hostSigner ssh.Signer
shell string
getRotation RotationGetter
authService auth.AccessPoint
reg *srv.SessionRegistry
sessionServer rsession.Service
limiter *limiter.Limiter
labels map[string]string //static server labels
cmdLabels map[string]services.CommandLabel //dymanic server labels
labelsMutex *sync.Mutex
proxyMode bool
proxyTun reversetunnel.Server
advertiseIP string
proxyPublicAddr utils.NetAddr
// server UUID gets generated once on the first start and never changes
// usually stored in a file inside the data dir
uuid string
// this gets set to true for unit testing
isTestStub bool
// sets to true when the server needs to be stopped
closer *utils.CloseBroadcaster
// alog points to the AuditLog this server uses to report
// auditable events
alog events.IAuditLog
// clock is a system clock
clock clockwork.Clock
// permitUserEnvironment controls if this server will read ~/.tsh/environment
// before creating a new session.
permitUserEnvironment bool
// ciphers is a list of ciphers that the server supports. If omitted,
// the defaults will be used.
ciphers []string
// kexAlgorithms is a list of key exchange (KEX) algorithms that the
// server supports. If omitted, the defaults will be used.
kexAlgorithms []string
// macAlgorithms is a list of message authentication codes (MAC) that
// the server supports. If omitted the defaults will be used.
macAlgorithms []string
// authHandlers are common authorization and authentication related handlers.
authHandlers *srv.AuthHandlers
// termHandlers are common terminal related handlers.
termHandlers *srv.TermHandlers
// pamConfig holds configuration for PAM.
pamConfig *pam.Config
// dataDir is a server local data directory
dataDir string
}
// GetClock returns server clock implementation
func (s *Server) GetClock() clockwork.Clock {
return s.clock
}
// GetDataDir returns server data dir
func (s *Server) GetDataDir() string {
return s.dataDir
}
func (s *Server) GetNamespace() string {
return s.namespace
}
func (s *Server) GetAuditLog() events.IAuditLog {
if s.isAuditedAtProxy() {
return events.NewDiscardAuditLog()
}
return s.alog
}
func (s *Server) GetAccessPoint() auth.AccessPoint {
return s.authService
}
func (s *Server) GetSessionServer() rsession.Service {
if s.isAuditedAtProxy() {
return rsession.NewDiscardSessionServer()
}
return s.sessionServer
}
// GetPAM returns the PAM configuration for this server.
func (s *Server) GetPAM() (*pam.Config, error) {
return s.pamConfig, nil
}
// isAuditedAtProxy returns true if sessions are being recorded at the proxy
// and this is a Teleport node.
func (s *Server) isAuditedAtProxy() bool {
// always be safe, better to double record than not record at all
clusterConfig, err := s.GetAccessPoint().GetClusterConfig()
if err != nil {
return false
}
isRecordAtProxy := clusterConfig.GetSessionRecording() == services.RecordAtProxy
isTeleportNode := s.Component() == teleport.ComponentNode
if isRecordAtProxy && isTeleportNode {
return true
}
return false
}
// ServerOption is a functional option passed to the server
type ServerOption func(s *Server) error
// Close closes listening socket and stops accepting connections
func (s *Server) Close() error {
s.closer.Close()
s.reg.Close()
return s.srv.Close()
}
// Shutdown performs graceful shutdown
func (s *Server) Shutdown(ctx context.Context) error {
// wait until connections drain off
err := s.srv.Shutdown(ctx)
s.closer.Close()
s.reg.Close()
return err
}
// Start starts server
func (s *Server) Start() error {
if len(s.getCommandLabels()) > 0 {
s.updateLabels()
}
go s.heartbeatPresence()
return s.srv.Start()
}
// Serve servers service on started listener
func (s *Server) Serve(l net.Listener) error {
if len(s.getCommandLabels()) > 0 {
s.updateLabels()
}
go s.heartbeatPresence()
return s.srv.Serve(l)
}
// Wait waits until server stops
func (s *Server) Wait() {
s.srv.Wait(context.TODO())
}
// RotationGetter returns rotation state
type RotationGetter func(role teleport.Role) (*services.Rotation, error)
// SetRotationGetter sets rotation state getter
func SetRotationGetter(getter RotationGetter) ServerOption {
return func(s *Server) error {
s.getRotation = getter
return nil
}
}
// SetShell sets default shell that will be executed for interactive
// sessions
func SetShell(shell string) ServerOption {
return func(s *Server) error {
s.shell = shell
return nil
}
}
// SetSessionServer represents realtime session registry server
func SetSessionServer(sessionServer rsession.Service) ServerOption {
return func(s *Server) error {
s.sessionServer = sessionServer
return nil
}
}
// SetProxyMode starts this server in SSH proxying mode
func SetProxyMode(tsrv reversetunnel.Server) ServerOption {
return func(s *Server) error {
// always set proxy mode to true,
// because in some tests reverse tunnel is disabled,
// but proxy is still used without it.
s.proxyMode = true
s.proxyTun = tsrv
return nil
}
}
// SetLabels sets dynamic and static labels that server will report to the
// auth servers
func SetLabels(labels map[string]string,
cmdLabels services.CommandLabels) ServerOption {
return func(s *Server) error {
for name, label := range cmdLabels {
if label.GetPeriod() < time.Second {
label.SetPeriod(time.Second)
cmdLabels[name] = label
log.Warningf("label period can't be less that 1 second. Period for label '%v' was set to 1 second", name)
}
}
s.labels = labels
s.cmdLabels = cmdLabels
return nil
}
}
// SetLimiter sets rate and connection limiter for this server
func SetLimiter(limiter *limiter.Limiter) ServerOption {
return func(s *Server) error {
s.limiter = limiter
return nil
}
}
// SetAuditLog assigns an audit log interfaces to this server
func SetAuditLog(alog events.IAuditLog) ServerOption {
return func(s *Server) error {
s.alog = alog
return nil
}
}
func SetNamespace(namespace string) ServerOption {
return func(s *Server) error {
s.namespace = namespace
return nil
}
}
// SetPermitUserEnvironment allows you to set the value of permitUserEnvironment.
func SetPermitUserEnvironment(permitUserEnvironment bool) ServerOption {
return func(s *Server) error {
s.permitUserEnvironment = permitUserEnvironment
return nil
}
}
func SetCiphers(ciphers []string) ServerOption {
return func(s *Server) error {
s.ciphers = ciphers
return nil
}
}
func SetKEXAlgorithms(kexAlgorithms []string) ServerOption {
return func(s *Server) error {
s.kexAlgorithms = kexAlgorithms
return nil
}
}
func SetMACAlgorithms(macAlgorithms []string) ServerOption {
return func(s *Server) error {
s.macAlgorithms = macAlgorithms
return nil
}
}
func SetPAMConfig(pamConfig *pam.Config) ServerOption {
return func(s *Server) error {
s.pamConfig = pamConfig
return nil
}
}
// New returns an unstarted server
func New(addr utils.NetAddr,
hostname string,
signers []ssh.Signer,
authService auth.AccessPoint,
dataDir string,
advertiseIP string,
proxyPublicAddr utils.NetAddr,
options ...ServerOption) (*Server, error) {
// read the host UUID:
uuid, err := utils.ReadOrMakeHostUUID(dataDir)
if err != nil {
return nil, trace.Wrap(err)
}
s := &Server{
addr: addr,
authService: authService,
hostname: hostname,
labelsMutex: &sync.Mutex{},
advertiseIP: advertiseIP,
proxyPublicAddr: proxyPublicAddr,
uuid: uuid,
closer: utils.NewCloseBroadcaster(),
clock: clockwork.NewRealClock(),
dataDir: dataDir,
}
s.limiter, err = limiter.NewLimiter(limiter.LimiterConfig{})
if err != nil {
return nil, trace.Wrap(err)
}
for _, o := range options {
if err := o(s); err != nil {
return nil, trace.Wrap(err)
}
}
// TODO(klizhentas): replace function arguments with struct
if s.alog == nil {
return nil, trace.BadParameter("setup valid AuditLog parameter using SetAuditLog")
}
if s.namespace == "" {
return nil, trace.BadParameter("setup valid namespace parameter using SetNamespace")
}
var component string
if s.proxyMode {
component = teleport.ComponentProxy
} else {
component = teleport.ComponentNode
}
s.reg, err = srv.NewSessionRegistry(s)
if err != nil {
return nil, trace.Wrap(err)
}
// add in common auth handlers
s.authHandlers = &srv.AuthHandlers{
Entry: logrus.WithFields(logrus.Fields{
trace.Component: component,
trace.ComponentFields: logrus.Fields{},
}),
Server: s,
Component: component,
AuditLog: s.alog,
AccessPoint: s.authService,
}
// common term handlers
s.termHandlers = &srv.TermHandlers{
SessionRegistry: s.reg,
}
server, err := sshutils.NewServer(
component,
addr, s, signers,
sshutils.AuthMethods{PublicKey: s.authHandlers.UserKeyAuth},
sshutils.SetLimiter(s.limiter),
sshutils.SetRequestHandler(s),
sshutils.SetCiphers(s.ciphers),
sshutils.SetKEXAlgorithms(s.kexAlgorithms),
sshutils.SetMACAlgorithms(s.macAlgorithms))
if err != nil {
return nil, trace.Wrap(err)
}
s.srv = server
return s, nil
}
func (s *Server) getNamespace() string {
return services.ProcessNamespace(s.namespace)
}
func (s *Server) Component() string {
if s.proxyMode {
return teleport.ComponentProxy
}
return teleport.ComponentNode
}
// Addr returns server address
func (s *Server) Addr() string {
return s.srv.Addr()
}
// ID returns server ID
func (s *Server) ID() string {
return s.uuid
}
// PermitUserEnvironment returns if ~/.tsh/environment will be read before a
// session is created by this server.
func (s *Server) PermitUserEnvironment() bool {
return s.permitUserEnvironment
}
func (s *Server) setAdvertiseIP(ip string) {
s.Lock()
defer s.Unlock()
s.advertiseIP = ip
}
func (s *Server) getAdvertiseIP() string {
s.Lock()
defer s.Unlock()
return s.advertiseIP
}
// AdvertiseAddr returns an address this server should be publicly accessible
// as, in "ip:host" form
func (s *Server) AdvertiseAddr() string {
// set if we have explicit --advertise-ip option
advertiseIP := s.getAdvertiseIP()
if advertiseIP == "" {
return s.addr.Addr
}
_, port, _ := net.SplitHostPort(s.addr.Addr)
ahost, aport, err := utils.ParseAdvertiseAddr(advertiseIP)
if err != nil {
log.Warningf("Failed to parse advertise address %q, %v, using default value %q.", advertiseIP, err, s.addr.Addr)
return s.addr.Addr
}
if aport == "" {
aport = port
}
return fmt.Sprintf("%v:%v", ahost, aport)
}
func (s *Server) getRole() teleport.Role {
if s.proxyMode {
return teleport.RoleProxy
}
return teleport.RoleNode
}
// GetInfo returns a services.Server that represents this server.
func (s *Server) GetInfo() services.Server {
return &services.ServerV2{
Kind: services.KindNode,
Version: services.V2,
Metadata: services.Metadata{
Name: s.ID(),
Namespace: s.getNamespace(),
Labels: s.labels,
},
Spec: services.ServerSpecV2{
CmdLabels: services.LabelsToV2(s.getCommandLabels()),
Addr: s.AdvertiseAddr(),
Hostname: s.hostname,
},
}
}
// registerServer attempts to register server in the cluster
func (s *Server) registerServer() error {
server := s.GetInfo()
if s.getRotation != nil {
rotation, err := s.getRotation(s.getRole())
if err != nil {
if !trace.IsNotFound(err) {
log.Warningf("Failed to get rotation state: %v", err)
}
} else {
server.SetRotation(*rotation)
}
}
server.SetTTL(s.clock, defaults.ServerHeartbeatTTL)
if !s.proxyMode {
return trace.Wrap(s.authService.UpsertNode(server))
}
server.SetPublicAddr(s.proxyPublicAddr.String())
return trace.Wrap(s.authService.UpsertProxy(server))
}
// heartbeatPresence periodically calls into the auth server to let everyone
// know we're up & alive
func (s *Server) heartbeatPresence() {
sleepTime := defaults.ServerHeartbeatTTL/2 + utils.RandomDuration(defaults.ServerHeartbeatTTL/10)
ticker := time.NewTicker(sleepTime)
defer ticker.Stop()
for {
if err := s.registerServer(); err != nil {
log.Warningf("failed to announce %v presence: %v", s.ID(), err)
}
select {
case <-ticker.C:
continue
case <-s.closer.C:
{
log.Debugf("server.heartbeatPresence() exited")
return
}
}
}
}
func (s *Server) updateLabels() {
for name, label := range s.getCommandLabels() {
go s.periodicUpdateLabel(name, label.Clone())
}
}
func (s *Server) syncUpdateLabels() {
for name, label := range s.getCommandLabels() {
s.updateLabel(name, label)
}
}
func (s *Server) updateLabel(name string, label services.CommandLabel) {
out, err := exec.Command(label.GetCommand()[0], label.GetCommand()[1:]...).Output()
if err != nil {
log.Errorf(err.Error())
label.SetResult(err.Error() + " output: " + string(out))
} else {
label.SetResult(strings.TrimSpace(string(out)))
}
s.setCommandLabel(name, label)
}
func (s *Server) periodicUpdateLabel(name string, label services.CommandLabel) {
for {
s.updateLabel(name, label)
time.Sleep(label.GetPeriod())
}
}
func (s *Server) setCommandLabel(name string, value services.CommandLabel) {
s.labelsMutex.Lock()
defer s.labelsMutex.Unlock()
s.cmdLabels[name] = value
}
func (s *Server) getCommandLabels() map[string]services.CommandLabel {
s.labelsMutex.Lock()
defer s.labelsMutex.Unlock()
out := make(map[string]services.CommandLabel, len(s.cmdLabels))
for key, val := range s.cmdLabels {
out[key] = val.Clone()
}
return out
}
// serveAgent will build the a sock path for this user and serve an SSH agent on unix socket.
func (s *Server) serveAgent(ctx *srv.ServerContext) error {
// gather information about user and process. this will be used to set the
// socket path and permissions
systemUser, err := user.Lookup(ctx.Identity.Login)
if err != nil {
return trace.ConvertSystemError(err)
}
uid, err := strconv.Atoi(systemUser.Uid)
if err != nil {
return trace.Wrap(err)
}
gid, err := strconv.Atoi(systemUser.Gid)
if err != nil {
return trace.Wrap(err)
}
pid := os.Getpid()
// build the socket path and set permissions
socketDir, err := ioutil.TempDir(os.TempDir(), "teleport-")
if err != nil {
return trace.Wrap(err)
}
dirCloser := &utils.RemoveDirCloser{Path: socketDir}
socketPath := filepath.Join(socketDir, fmt.Sprintf("teleport-%v.socket", pid))
if err := os.Chown(socketDir, uid, gid); err != nil {
if err := dirCloser.Close(); err != nil {
log.Warnf("failed to remove directory: %v", err)
}
return trace.ConvertSystemError(err)
}
// start an agent on a unix socket
agentServer := &teleagent.AgentServer{Agent: ctx.GetAgent()}
err = agentServer.ListenUnixSocket(socketPath, uid, gid, 0600)
if err != nil {
return trace.Wrap(err)
}
ctx.SetEnv(teleport.SSHAuthSock, socketPath)
ctx.SetEnv(teleport.SSHAgentPID, fmt.Sprintf("%v", pid))
ctx.AddCloser(agentServer)
ctx.AddCloser(dirCloser)
ctx.Debugf("Opened agent channel for Teleport user %v and socket %v.", ctx.Identity.TeleportUser, socketPath)
go agentServer.Serve()
return nil
}
// EmitAuditEvent logs a given event to the audit log attached to the
// server who owns these sessions
func (s *Server) EmitAuditEvent(eventType string, fields events.EventFields) {
log.Debugf("server.EmitAuditEvent(%v)", eventType)
alog := s.alog
if alog != nil {
// record the event time with ms precision
fields[events.EventTime] = s.clock.Now().In(time.UTC).Round(time.Millisecond)
if err := alog.EmitAuditEvent(eventType, fields); err != nil {
log.Error(trace.DebugReport(err))
}
} else {
log.Warn("SSH server has no audit log")
}
}
// HandleRequest processes global out-of-band requests. Global out-of-band
// requests are processed in order (this way the originator knows which
// request we are responding to). If Teleport does not support the request
// type or an error occurs while processing that request Teleport will reply
// req.Reply(false, nil).
//
// For more details: https://tools.ietf.org/html/rfc4254.html#page-4
func (s *Server) HandleRequest(r *ssh.Request) {
switch r.Type {
case teleport.KeepAliveReqType:
s.handleKeepAlive(r)
case teleport.RecordingProxyReqType:
s.handleRecordingProxy(r)
default:
if r.WantReply {
r.Reply(false, nil)
}
log.Debugf("Discarding %q global request: %+v", r.Type, r)
}
}
// HandleNewChan is called when new channel is opened
func (s *Server) HandleNewChan(nc net.Conn, sconn *ssh.ServerConn, nch ssh.NewChannel) {
identityContext, err := s.authHandlers.CreateIdentityContext(sconn)
if err != nil {
nch.Reject(ssh.Prohibited, fmt.Sprintf("Unable to create identity from connection: %v", err))
return
}
channelType := nch.ChannelType()
if s.proxyMode {
// Channels of type "session" handle requests that are involved in running
// commands on a server. In the case of proxy mode subsystem and agent
// forwarding requests occur over the "session" channel.
if channelType == "session" {
ch, requests, err := nch.Accept()
if err != nil {
log.Warnf("Unable to accept channel: %v.", err)
nch.Reject(ssh.ConnectionFailed, fmt.Sprintf("unable to accept channel: %v", err))
return
}
go s.handleSessionRequests(sconn, identityContext, ch, requests)
} else {
nch.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %v", channelType))
}
return
}
switch channelType {
// Channels of type "session" handle requests that are involved in running
// commands on a server, subsystem requests, and agent forwarding.
case "session":
ch, requests, err := nch.Accept()
if err != nil {
log.Warnf("Unable to accept channel: %v.", err)
nch.Reject(ssh.ConnectionFailed, fmt.Sprintf("unable to accept channel: %v", err))
return
}
go s.handleSessionRequests(sconn, identityContext, ch, requests)
// Channels of type "direct-tcpip" handles request for port forwarding.
case "direct-tcpip":
req, err := sshutils.ParseDirectTCPIPReq(nch.ExtraData())
if err != nil {
log.Errorf("Failed to parse request data: %v, err: %v.", string(nch.ExtraData()), err)
nch.Reject(ssh.UnknownChannelType, "failed to parse direct-tcpip request")
return
}
ch, _, err := nch.Accept()
if err != nil {
log.Warnf("Unable to accept channel: %v.", err)
nch.Reject(ssh.ConnectionFailed, fmt.Sprintf("unable to accept channel: %v", err))
return
}
go s.handleDirectTCPIPRequest(sconn, identityContext, ch, req)
default:
nch.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %v", channelType))
}
}
// handleDirectTCPIPRequest handles port forwarding requests.
func (s *Server) handleDirectTCPIPRequest(sconn *ssh.ServerConn, identityContext srv.IdentityContext, ch ssh.Channel, req *sshutils.DirectTCPIPReq) {
// Create context for this channel. This context will be closed when
// forwarding is complete.
ctx, err := srv.NewServerContext(s, sconn, identityContext)
if err != nil {
ctx.Errorf("Unable to create connection context: %v.", err)
ch.Stderr().Write([]byte("Unable to create connection context."))
return
}
ctx.IsTestStub = s.isTestStub
ctx.AddCloser(ch)
defer ctx.Debugf("direct-tcp closed")
defer ctx.Close()
srcAddr := net.JoinHostPort(req.Orig, strconv.Itoa(int(req.OrigPort)))
dstAddr := net.JoinHostPort(req.Host, strconv.Itoa(int(req.Port)))
// check if the role allows port forwarding for this user
err = s.authHandlers.CheckPortForward(dstAddr, ctx)
if err != nil {
ch.Stderr().Write([]byte(err.Error()))
return
}
ctx.Debugf("Opening direct-tcpip channel from %v to %v", srcAddr, dstAddr)
// If PAM is enabled check the account and open a session.
var pamContext *pam.PAM
if s.pamConfig.Enabled {
// Note, stdout/stderr is discarded here, otherwise MOTD would be printed to
// the users screen during port forwarding.
pamContext, err = pam.Open(&pam.Config{
ServiceName: s.pamConfig.ServiceName,
Username: ctx.Identity.Login,
Stdin: ch,
Stderr: ioutil.Discard,
Stdout: ioutil.Discard,
})
if err != nil {
ctx.Errorf("Unable to open PAM context for direct-tcpip request: %v.", err)
ch.Stderr().Write([]byte(err.Error()))
return
}
ctx.Debugf("Opening PAM context for direct-tcpip request.")
}
conn, err := net.Dial("tcp", dstAddr)
if err != nil {
ctx.Infof("Failed to connect to: %v: %v", dstAddr, err)
return
}
defer conn.Close()
// audit event:
s.EmitAuditEvent(events.PortForwardEvent, events.EventFields{
events.PortForwardAddr: dstAddr,
events.PortForwardSuccess: true,
events.EventLogin: ctx.Identity.Login,
events.EventUser: ctx.Identity.TeleportUser,
events.LocalAddr: sconn.LocalAddr().String(),
events.RemoteAddr: sconn.RemoteAddr().String(),
})
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
io.Copy(ch, conn)
ch.Close()
}()
wg.Add(1)
go func() {
defer wg.Done()
io.Copy(conn, srv.NewTrackingReader(ctx, ch))
conn.Close()
}()
wg.Wait()
// If PAM is enabled, close the PAM context after port forwarding is complete.
if s.pamConfig.Enabled {
err = pamContext.Close()
if err != nil {
ctx.Errorf("Unable to close PAM context for direct-tcpip request: %v.", err)
return
}
ctx.Debugf("Closing PAM context for direct-tcpip request.")
}
}
// handleSessionRequests handles out of band session requests once the session
// channel has been created this function's loop handles all the "exec",
// "subsystem" and "shell" requests.
func (s *Server) handleSessionRequests(sconn *ssh.ServerConn, identityContext srv.IdentityContext, ch ssh.Channel, in <-chan *ssh.Request) {
// Create context for this channel. This context will be closed when the
// session request is complete.
ctx, err := srv.NewServerContext(s, sconn, identityContext)
if err != nil {
ctx.Errorf("Unable to create connection context: %v.", err)
ch.Stderr().Write([]byte("Unable to create connection context."))
return
}
ctx.IsTestStub = s.isTestStub
ctx.AddCloser(ch)
defer ctx.Close()
// Create a close context used to signal between the server and the
// keep-alive loop when to close th connection (from either side).
closeContext, closeCancel := context.WithCancel(context.Background())
defer closeCancel()
clusterConfig, err := s.GetAccessPoint().GetClusterConfig()
if err != nil {
log.Errorf("Unable to fetch cluster config: %v.", err)
ch.Stderr().Write([]byte("Unable to fetch cluster configuration."))
return
}
// The keep-alive loop will keep pinging the remote server and after it has
// missed a certain number of keep-alive requests it will cancel the
// closeContext which signals the server to shutdown.
go srv.StartKeepAliveLoop(srv.KeepAliveParams{
Conns: []srv.RequestSender{
sconn,
},
Interval: clusterConfig.GetKeepAliveInterval(),
MaxCount: clusterConfig.GetKeepAliveCountMax(),
CloseContext: closeContext,
CloseCancel: closeCancel,
})
for {
// update ctx with the session ID:
if !s.proxyMode {
err := ctx.CreateOrJoinSession(s.reg)
if err != nil {
errorMessage := fmt.Sprintf("unable to update context: %v", err)
ctx.Errorf("Unable to update context: %v.", errorMessage)
// write the error to channel and close it
ch.Stderr().Write([]byte(errorMessage))
_, err := ch.SendRequest("exit-status", false, ssh.Marshal(struct{ C uint32 }{C: teleport.RemoteCommandFailure}))
if err != nil {
ctx.Errorf("Failed to send exit status %v.", errorMessage)
}
return
}
}
select {
case creq := <-ctx.SubsystemResultCh:
// this means that subsystem has finished executing and
// want us to close session and the channel
ctx.Debugf("Close session request: %v.", creq.Err)
return
case req := <-in:
if req == nil {
// this will happen when the client closes/drops the connection
ctx.Debugf("Client %v disconnected.", sconn.RemoteAddr())
return
}
if err := s.dispatch(ch, req, ctx); err != nil {
s.replyError(ch, req, err)
return
}
if req.WantReply {
req.Reply(true, nil)
}
case result := <-ctx.ExecResultCh:
ctx.Debugf("Exec request (%q) complete: %v", result.Command, result.Code)
// The exec process has finished and delivered the execution result, send
// the result back to the client, and close the session and channel.
_, err := ch.SendRequest("exit-status", false, ssh.Marshal(struct{ C uint32 }{C: uint32(result.Code)}))
if err != nil {
ctx.Infof("Failed to send exit status for %v: %v", result.Command, err)
}
return
case <-closeContext.Done():
log.Debugf("Closing session due to missed heartbeat.")
return
}
}
}
// dispatch receives an SSH request for a subsystem and disptaches the request to the
// appropriate subsystem implementation
func (s *Server) dispatch(ch ssh.Channel, req *ssh.Request, ctx *srv.ServerContext) error {
ctx.Debugf("Handling request %v, want reply %v.", req.Type, req.WantReply)
// If this SSH server is configured to only proxy, we do not support anything
// other than our own custom "subsystems" and environment manipulation.
if s.proxyMode {
switch req.Type {
case sshutils.SubsystemRequest:
return s.handleSubsystem(ch, req, ctx)
case sshutils.EnvRequest:
// we currently ignore setting any environment variables via SSH for security purposes
return s.handleEnv(ch, req, ctx)
case sshutils.AgentForwardRequest:
// process agent forwarding, but we will only forward agent to proxy in
// recording proxy mode.
err := s.handleAgentForwardProxy(req, ctx)
if err != nil {
log.Debug(err)
}
return nil
default:
return trace.BadParameter(
"(%v) proxy doesn't support request type '%v'", s.Component(), req.Type)
}
}
switch req.Type {
case sshutils.ExecRequest:
return s.termHandlers.HandleExec(ch, req, ctx)
case sshutils.PTYRequest:
return s.termHandlers.HandlePTYReq(ch, req, ctx)
case sshutils.ShellRequest:
return s.termHandlers.HandleShell(ch, req, ctx)
case sshutils.WindowChangeRequest:
return s.termHandlers.HandleWinChange(ch, req, ctx)
case sshutils.EnvRequest:
return s.handleEnv(ch, req, ctx)
case sshutils.SubsystemRequest:
// subsystems are SSH subsystems defined in http://tools.ietf.org/html/rfc4254 6.6
// they are in essence SSH session extensions, allowing to implement new SSH commands
return s.handleSubsystem(ch, req, ctx)
case sshutils.AgentForwardRequest:
// This happens when SSH client has agent forwarding enabled, in this case
// client sends a special request, in return SSH server opens new channel
// that uses SSH protocol for agent drafted here:
// https://tools.ietf.org/html/draft-ietf-secsh-agent-02
// the open ssh proto spec that we implement is here:
// http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.agent
// to maintain interoperability with OpenSSH, agent forwarding requests
// should never fail, all errors should be logged and we should continue