-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathsess.go
1680 lines (1422 loc) · 50.2 KB
/
sess.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-2020 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 srv
import (
"context"
"encoding/json"
"fmt"
"io"
"path/filepath"
"sync"
"time"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/types"
apievents "github.com/gravitational/teleport/api/types/events"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/bpf"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/events/filesessions"
"github.com/gravitational/teleport/lib/services"
rsession "github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/sshutils"
"github.com/gravitational/teleport/lib/utils"
"github.com/google/uuid"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/moby/term"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
)
const sessionRecorderID = "session-recorder"
const PresenceVerifyInterval = time.Second * 15
const PresenceMaxDifference = time.Minute
// SessionControlsInfoBroadcast is sent in tandem with session creation
// to inform any joining users about the session controls.
const SessionControlsInfoBroadcast = "Controls\r\n - CTRL-C: Leave the session\r\n - t: Forcefully terminate the session (moderators only)"
var serverSessions = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: teleport.MetricServerInteractiveSessions,
Help: "Number of active sessions to this host",
},
)
// SessionRegistry holds a map of all active sessions on a given
// SSH server
type SessionRegistry struct {
SessionRegistryConfig
// log holds the structured logger
log *log.Entry
// sessions holds a map between session ID and the session object. Used to
// find active sessions as well as close all sessions when the registry
// is closing.
sessions map[rsession.ID]*session
sessionsMux sync.Mutex
}
type SessionRegistryConfig struct {
// clock is the registry's internal clock. used in testing.
clock clockwork.Clock
// srv refers to the upon which this session registry is created.
Srv Server
// sessiontrackerService is used to share session activity to
// other teleport components through the auth server.
SessionTrackerService services.SessionTrackerService
}
func (sc *SessionRegistryConfig) CheckAndSetDefaults() error {
if sc.SessionTrackerService == nil {
return trace.BadParameter("session tracker service is required")
}
if sc.Srv == nil {
return trace.BadParameter("server is required")
}
if sc.Srv.GetSessionServer() == nil {
return trace.BadParameter("session server is required")
}
if sc.clock == nil {
sc.clock = sc.Srv.GetClock()
}
return nil
}
func NewSessionRegistry(cfg SessionRegistryConfig) (*SessionRegistry, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
err := utils.RegisterPrometheusCollectors(serverSessions)
if err != nil {
return nil, trace.Wrap(err)
}
return &SessionRegistry{
SessionRegistryConfig: cfg,
log: log.WithFields(log.Fields{
trace.Component: teleport.Component(teleport.ComponentSession, cfg.Srv.Component()),
}),
sessions: make(map[rsession.ID]*session),
}, nil
}
func (s *SessionRegistry) addSession(sess *session) {
s.sessionsMux.Lock()
defer s.sessionsMux.Unlock()
s.sessions[sess.id] = sess
}
func (s *SessionRegistry) removeSession(sess *session) {
s.sessionsMux.Lock()
defer s.sessionsMux.Unlock()
delete(s.sessions, sess.id)
}
func (s *SessionRegistry) findSessionLocked(id rsession.ID) (*session, bool) {
sess, found := s.sessions[id]
return sess, found
}
func (s *SessionRegistry) findSession(id rsession.ID) (*session, bool) {
s.sessionsMux.Lock()
defer s.sessionsMux.Unlock()
return s.findSessionLocked(id)
}
func (s *SessionRegistry) Close() {
s.sessionsMux.Lock()
defer s.sessionsMux.Unlock()
// End all sessions and allow session cleanup
// goroutines to complete.
for _, se := range s.sessions {
se.Stop()
}
s.log.Debug("Closing Session Registry.")
}
// OpenSession either joins an existing session or starts a new session.
func (s *SessionRegistry) OpenSession(ch ssh.Channel, ctx *ServerContext) error {
session := ctx.getSession()
if session != nil {
ctx.Infof("Joining existing session %v.", session.id)
mode := types.SessionParticipantMode(ctx.env[teleport.EnvSSHJoinMode])
switch mode {
case types.SessionModeratorMode, types.SessionObserverMode:
default:
if mode == types.SessionPeerMode || len(mode) == 0 {
mode = types.SessionPeerMode
} else {
return trace.BadParameter("Unrecognized session participant mode: %v", mode)
}
}
// Update the in-memory data structure that a party member has joined.
_, err := session.join(ch, ctx, mode)
if err != nil {
return trace.Wrap(err)
}
return nil
}
if ctx.JoinOnly {
return trace.AccessDenied("join-only mode was used to create this connection but attempted to create a new session.")
}
// session not found? need to create one. start by getting/generating an ID for it
sid, found := ctx.GetEnv(sshutils.SessionEnvVar)
if !found {
sid = string(rsession.NewID())
ctx.SetEnv(sshutils.SessionEnvVar, sid)
}
// This logic allows concurrent request to create a new session
// to fail, what is ok because we should never have this condition
sess, err := newSession(rsession.ID(sid), s, ctx)
if err != nil {
return trace.Wrap(err)
}
ctx.setSession(sess)
s.addSession(sess)
ctx.Infof("Creating (interactive) session %v.", sid)
// Start an interactive session (TTY attached). Close the session if an error
// occurs, otherwise it will be closed by the callee.
if err := sess.startInteractive(ch, ctx); err != nil {
sess.Close()
return trace.Wrap(err)
}
return nil
}
// OpenExecSession opens an non-interactive exec session.
func (s *SessionRegistry) OpenExecSession(channel ssh.Channel, ctx *ServerContext) error {
// Create a new session ID. These sessions can not be joined so no point in
// looking for an exisiting one.
sessionID := rsession.NewID()
// This logic allows concurrent request to create a new session
// to fail, what is ok because we should never have this condition.
sess, err := newSession(sessionID, s, ctx)
if err != nil {
return trace.Wrap(err)
}
ctx.Infof("Creating (exec) session %v.", sessionID)
canStart, _, err := sess.checkIfStart()
if err != nil {
return trace.Wrap(err)
}
if !canStart {
return trace.AccessDenied("lacking privileges to start unattended session")
}
// Start a non-interactive session (TTY attached). Close the session if an error
// occurs, otherwise it will be closed by the callee.
ctx.setSession(sess)
err = sess.startExec(channel, ctx)
if err != nil {
sess.Close()
return trace.Wrap(err)
}
return nil
}
func (s *SessionRegistry) ForceTerminate(ctx *ServerContext) error {
sess := ctx.getSession()
if sess == nil {
s.log.Debug("Unable to terminate session, no session found in context.")
return nil
}
sess.BroadcastMessage("Forcefully terminating session...")
// Stop session, it will be cleaned up in the background to ensure
// the session recording is uploaded.
sess.Stop()
return nil
}
// GetTerminalSize fetches the terminal size of an active SSH session.
func (s *SessionRegistry) GetTerminalSize(sessionID string) (*term.Winsize, error) {
s.sessionsMux.Lock()
defer s.sessionsMux.Unlock()
sess := s.sessions[rsession.ID(sessionID)]
if sess == nil {
return nil, trace.NotFound("No session found in context.")
}
return sess.term.GetWinSize()
}
// NotifyWinChange is called to notify all members in the party that the PTY
// size has changed. The notification is sent as a global SSH request and it
// is the responsibility of the client to update it's window size upon receipt.
func (s *SessionRegistry) NotifyWinChange(params rsession.TerminalParams, ctx *ServerContext) error {
session := ctx.getSession()
if session == nil {
s.log.Debug("Unable to update window size, no session found in context.")
return nil
}
sid := session.id
// Build the resize event.
resizeEvent := &apievents.Resize{
Metadata: apievents.Metadata{
Type: events.ResizeEvent,
Code: events.TerminalResizeCode,
ClusterName: ctx.ClusterName,
},
ServerMetadata: apievents.ServerMetadata{
ServerID: ctx.srv.HostUUID(),
ServerLabels: ctx.srv.GetInfo().GetAllLabels(),
ServerNamespace: s.Srv.GetNamespace(),
ServerHostname: s.Srv.GetInfo().GetHostname(),
ServerAddr: ctx.ServerConn.LocalAddr().String(),
},
SessionMetadata: apievents.SessionMetadata{
SessionID: string(sid),
},
UserMetadata: ctx.Identity.GetUserMetadata(),
TerminalSize: params.Serialize(),
}
// Report the updated window size to the event log (this is so the sessions
// can be replayed correctly).
if err := session.recorder.EmitAuditEvent(s.Srv.Context(), resizeEvent); err != nil {
s.log.WithError(err).Warn("Failed to emit resize audit event.")
}
// Update the size of the server side PTY.
err := session.term.SetWinSize(params)
if err != nil {
return trace.Wrap(err)
}
// If sessions are being recorded at the proxy, sessions can not be shared.
// In that situation, PTY size information does not need to be propagated
// back to all clients and we can return right away.
if services.IsRecordAtProxy(ctx.SessionRecordingConfig.GetMode()) {
return nil
}
// Notify all members of the party (except originator) that the size of the
// window has changed so the client can update it's own local PTY. Note that
// OpenSSH clients will ignore this and not update their own local PTY.
for _, p := range session.getParties() {
// Don't send the window change notification back to the originator.
if p.ctx.ID() == ctx.ID() {
continue
}
eventPayload, err := json.Marshal(resizeEvent)
if err != nil {
s.log.Warnf("Unable to marshal resize event for %v: %v.", p.sconn.RemoteAddr(), err)
continue
}
// Send the message as a global request.
_, _, err = p.sconn.SendRequest(teleport.SessionEvent, false, eventPayload)
if err != nil {
s.log.Warnf("Unable to resize event to %v: %v.", p.sconn.RemoteAddr(), err)
continue
}
s.log.Debugf("Sent resize event %v to %v.", params, p.sconn.RemoteAddr())
}
return nil
}
func (s *SessionRegistry) broadcastResult(sid rsession.ID, r ExecResult) error {
s.sessionsMux.Lock()
defer s.sessionsMux.Unlock()
sess, found := s.findSessionLocked(sid)
if !found {
return trace.NotFound("session %v not found", sid)
}
sess.broadcastResult(r)
return nil
}
// session struct describes an active (in progress) SSH session. These sessions
// are managed by 'SessionRegistry' containers which are attached to SSH servers.
type session struct {
mu sync.RWMutex
// log holds the structured logger
log *log.Entry
// session ID. unique GUID, this is what people use to "join" sessions
id rsession.ID
// parent session container
registry *SessionRegistry
// parties is the set of current connected clients/users. This map may grow
// and shrink as members join and leave the session.
parties map[rsession.ID]*party
// participants is the set of users that have joined this session. Users are
// never removed from this map as it's used to report the full list of
// participants at the end of a session.
participants map[rsession.ID]*party
io *TermManager
inWriter io.Writer
term Terminal
// stopC channel is used to kill all goroutines owned
// by the session
stopC chan struct{}
// startTime is the time when this session was created.
startTime time.Time
// login stores the login of the initial session creator
login string
recorder events.StreamWriter
// hasEnhancedRecording returns true if this session has enhanced session
// recording events associated.
hasEnhancedRecording bool
// serverCtx is used to control clean up of internal resources
serverCtx context.Context
access auth.SessionAccessEvaluator
tracker *SessionTracker
initiator string
scx *ServerContext
presenceEnabled bool
doneCh chan struct{}
displayParticipantRequirements bool
// endingContext is the server context which closed this session.
endingContext *ServerContext
// lingerAndDieCancel is a context cancel func which will cancel
// an ongoing lingerAndDie goroutine. This is used by joining parties
// to cancel the goroutine and prevent the session from closing prematurely.
lingerAndDieCancel func()
}
// newSession creates a new session with a given ID within a given context.
func newSession(id rsession.ID, r *SessionRegistry, ctx *ServerContext) (*session, error) {
serverSessions.Inc()
startTime := time.Now().UTC()
rsess := rsession.Session{
ID: id,
TerminalParams: rsession.TerminalParams{
W: teleport.DefaultTerminalWidth,
H: teleport.DefaultTerminalHeight,
},
Login: ctx.Identity.Login,
Created: startTime,
LastActive: startTime,
ServerID: ctx.srv.ID(),
Namespace: r.Srv.GetNamespace(),
ServerHostname: ctx.srv.GetInfo().GetHostname(),
ServerAddr: ctx.ServerConn.LocalAddr().String(),
ClusterName: ctx.ClusterName,
}
term := ctx.GetTerm()
if term != nil {
winsize, err := term.GetWinSize()
if err != nil {
return nil, trace.Wrap(err)
}
rsess.TerminalParams.W = int(winsize.Width)
rsess.TerminalParams.H = int(winsize.Height)
}
// get the session server where session information lives. if the recording
// proxy is being used and this is a node, then a discard session server will
// be returned here.
sessionServer := r.Srv.GetSessionServer()
err := sessionServer.CreateSession(rsess)
if err != nil {
if trace.IsAlreadyExists(err) {
// if session already exists, make sure they are compatible
// Login matches existing login
existing, err := sessionServer.GetSession(r.Srv.GetNamespace(), id)
if err != nil {
return nil, trace.Wrap(err)
}
if existing.Login != rsess.Login {
return nil, trace.AccessDenied(
"can't switch users from %v to %v for session %v",
rsess.Login, existing.Login, id)
}
}
// return nil, trace.Wrap(err)
// No need to abort. Perhaps the auth server is down?
// Log the error and continue:
r.log.Errorf("Failed to create new session: %v.", err)
}
var policySets []*types.SessionTrackerPolicySet
for _, role := range ctx.Identity.RoleSet {
policySet := role.GetSessionPolicySet()
policySets = append(policySets, &policySet)
}
sess := &session{
log: log.WithFields(log.Fields{
trace.Component: teleport.Component(teleport.ComponentSession, r.Srv.Component()),
}),
id: id,
registry: r,
parties: make(map[rsession.ID]*party),
participants: make(map[rsession.ID]*party),
login: ctx.Identity.Login,
stopC: make(chan struct{}),
startTime: startTime,
serverCtx: ctx.srv.Context(),
access: auth.NewSessionAccessEvaluator(policySets, types.SSHSessionKind),
scx: ctx,
presenceEnabled: ctx.Identity.Certificate.Extensions[teleport.CertExtensionMFAVerified] != "",
io: NewTermManager(),
doneCh: make(chan struct{}),
initiator: ctx.Identity.TeleportUser,
displayParticipantRequirements: utils.AsBool(ctx.env[teleport.EnvSSHSessionDisplayParticipantRequirements]),
}
sess.io.OnWriteError = func(idString string, err error) {
if idString == sessionRecorderID {
sess.log.Error("Failed to write to session recorder, stopping session.")
// stop in goroutine to avoid deadlock
go sess.Stop()
}
}
go func() {
if _, open := <-sess.io.TerminateNotifier(); open {
err := sess.registry.ForceTerminate(sess.scx)
if err != nil {
sess.log.Errorf("Failed to terminate session: %v.", err)
}
}
}()
if err = sess.trackSession(ctx.Identity.TeleportUser, policySets); err != nil {
if trace.IsNotImplemented(err) {
return nil, trace.NotImplemented("Attempted to use Moderated Sessions with an Auth Server below the minimum version of 9.0.0.")
}
return nil, trace.Wrap(err)
}
sess.recorder, err = newRecorder(sess, ctx)
if err != nil {
return nil, trace.Wrap(err)
}
return sess, nil
}
// ID returns a string representation of the session ID.
func (s *session) ID() string {
s.mu.RLock()
defer s.mu.RUnlock()
return s.id.String()
}
// PID returns the PID of the Teleport process under which the shell is running.
func (s *session) PID() int {
s.mu.RLock()
defer s.mu.RUnlock()
return s.term.PID()
}
// Recorder returns a StreamWriter which can be used to emit events
// to a session as well as the audit log.
func (s *session) Recorder() events.StreamWriter {
s.mu.RLock()
defer s.mu.RUnlock()
return s.recorder
}
// Stop ends the active session and forces all clients to disconnect.
// This will trigger background goroutines to complete session cleanup.
func (s *session) Stop() {
s.mu.Lock()
defer s.mu.Unlock()
select {
case <-s.stopC:
return
default:
close(s.stopC)
}
s.BroadcastMessage("Stopping session...")
s.log.Infof("Stopping session %v.", s.id)
// close io copy loops
s.io.Close()
// remove session from server context to prevent new requests
// from attempting to join the session during cleanup
s.scx.setSession(nil)
// Close and kill terminal
if s.term != nil {
if err := s.term.Close(); err != nil {
s.log.WithError(err).Debug("Failed to close the shell")
}
if err := s.term.Kill(); err != nil {
s.log.WithError(err).Debug("Failed to kill the shell")
}
}
// Close session tracker and mark it as terminated
if err := s.tracker.Close(s.serverCtx); err != nil {
s.log.WithError(err).Debug("Failed to close session tracker")
}
}
// Close ends the active session and frees all resources. This should only be called
// by the creator of the session, other closers should use Stop instead. Calling this
// prematurely can result in missing audit events, session recordings, and other
// unexpected errors.
func (s *session) Close() error {
s.Stop()
s.BroadcastMessage("Closing session...")
s.log.Infof("Closing session %v.", s.id)
serverSessions.Dec()
// Remove session parties and close client connections.
for _, p := range s.getParties() {
p.Close()
}
s.registry.removeSession(s)
// Remove the session from the backend.
if s.scx.srv.GetSessionServer() != nil {
err := s.scx.srv.GetSessionServer().DeleteSession(s.getNamespace(), s.id)
if err != nil {
s.log.Errorf("Failed to remove active session: %v: %v. "+
"Access to backend may be degraded, check connectivity to backend.",
s.id, err)
}
}
// Complete the session recording
if s.recorder != nil {
if err := s.recorder.Complete(s.serverCtx); err != nil {
s.log.WithError(err).Warn("Failed to close recorder.")
}
}
return nil
}
func (s *session) BroadcastMessage(format string, args ...interface{}) {
if s.access.IsModerated() && !services.IsRecordAtProxy(s.scx.SessionRecordingConfig.GetMode()) {
s.io.BroadcastMessage(fmt.Sprintf(format, args...))
}
}
// emitSessionStartEvent emits a session start event.
func (s *session) emitSessionStartEvent(ctx *ServerContext) {
sessionStartEvent := &apievents.SessionStart{
Metadata: apievents.Metadata{
Type: events.SessionStartEvent,
Code: events.SessionStartCode,
ClusterName: ctx.ClusterName,
ID: uuid.New().String(),
},
ServerMetadata: apievents.ServerMetadata{
ServerID: ctx.srv.HostUUID(),
ServerLabels: ctx.srv.GetInfo().GetAllLabels(),
ServerHostname: ctx.srv.GetInfo().GetHostname(),
ServerAddr: ctx.ServerConn.LocalAddr().String(),
ServerNamespace: ctx.srv.GetNamespace(),
},
SessionMetadata: apievents.SessionMetadata{
SessionID: string(s.id),
},
UserMetadata: ctx.Identity.GetUserMetadata(),
ConnectionMetadata: apievents.ConnectionMetadata{
RemoteAddr: ctx.ServerConn.RemoteAddr().String(),
},
SessionRecording: ctx.SessionRecordingConfig.GetMode(),
}
if s.term != nil {
params := s.term.GetTerminalParams()
sessionStartEvent.TerminalSize = params.Serialize()
}
// Local address only makes sense for non-tunnel nodes.
if !ctx.srv.UseTunnel() {
sessionStartEvent.ConnectionMetadata.LocalAddr = ctx.ServerConn.LocalAddr().String()
}
if err := s.recorder.EmitAuditEvent(ctx.srv.Context(), sessionStartEvent); err != nil {
s.log.WithError(err).Warn("Failed to emit session start event.")
}
}
// emitSessionJoinEvent emits a session join event to both the Audit Log as
// well as sending a "x-teleport-event" global request on the SSH connection.
// Must be called under session Lock.
func (s *session) emitSessionJoinEvent(ctx *ServerContext) {
sessionJoinEvent := &apievents.SessionJoin{
Metadata: apievents.Metadata{
Type: events.SessionJoinEvent,
Code: events.SessionJoinCode,
ClusterName: ctx.ClusterName,
},
ServerMetadata: apievents.ServerMetadata{
ServerID: ctx.srv.HostUUID(),
ServerLabels: ctx.srv.GetInfo().GetAllLabels(),
ServerNamespace: s.getNamespace(),
ServerHostname: s.getHostname(),
ServerAddr: ctx.ServerConn.LocalAddr().String(),
},
SessionMetadata: apievents.SessionMetadata{
SessionID: string(ctx.SessionID()),
},
UserMetadata: ctx.Identity.GetUserMetadata(),
ConnectionMetadata: apievents.ConnectionMetadata{
RemoteAddr: ctx.ServerConn.RemoteAddr().String(),
},
}
// Local address only makes sense for non-tunnel nodes.
if !ctx.srv.UseTunnel() {
sessionJoinEvent.ConnectionMetadata.LocalAddr = ctx.ServerConn.LocalAddr().String()
}
// Emit session join event to Audit Log.
if err := s.recorder.EmitAuditEvent(ctx.srv.Context(), sessionJoinEvent); err != nil {
s.log.WithError(err).Warn("Failed to emit session join event.")
}
// Notify all members of the party that a new member has joined over the
// "x-teleport-event" channel.
for _, p := range s.parties {
eventPayload, err := json.Marshal(sessionJoinEvent)
if err != nil {
s.log.Warnf("Unable to marshal %v for %v: %v.", events.SessionJoinEvent, p.sconn.RemoteAddr(), err)
continue
}
_, _, err = p.sconn.SendRequest(teleport.SessionEvent, false, eventPayload)
if err != nil {
s.log.Warnf("Unable to send %v to %v: %v.", events.SessionJoinEvent, p.sconn.RemoteAddr(), err)
continue
}
s.log.Debugf("Sent %v to %v.", events.SessionJoinEvent, p.sconn.RemoteAddr())
}
}
// emitSessionLeaveEvent emits a session leave event to both the Audit Log as
// well as sending a "x-teleport-event" global request on the SSH connection.
// Must be called under session Lock.
func (s *session) emitSessionLeaveEvent(ctx *ServerContext) {
sessionLeaveEvent := &apievents.SessionLeave{
Metadata: apievents.Metadata{
Type: events.SessionLeaveEvent,
Code: events.SessionLeaveCode,
ClusterName: ctx.ClusterName,
},
ServerMetadata: apievents.ServerMetadata{
ServerID: ctx.srv.HostUUID(),
ServerLabels: ctx.srv.GetInfo().GetAllLabels(),
ServerNamespace: s.getNamespace(),
ServerHostname: s.getHostname(),
ServerAddr: ctx.ServerConn.LocalAddr().String(),
},
SessionMetadata: apievents.SessionMetadata{
SessionID: string(s.id),
},
UserMetadata: ctx.Identity.GetUserMetadata(),
}
// Emit session leave event to Audit Log.
if err := s.recorder.EmitAuditEvent(ctx.srv.Context(), sessionLeaveEvent); err != nil {
s.log.WithError(err).Warn("Failed to emit session leave event.")
}
// Notify all members of the party that a new member has left over the
// "x-teleport-event" channel.
for _, p := range s.parties {
eventPayload, err := utils.FastMarshal(sessionLeaveEvent)
if err != nil {
s.log.Warnf("Unable to marshal %v for %v: %v.", events.SessionLeaveEvent, p.sconn.RemoteAddr(), err)
continue
}
_, _, err = p.sconn.SendRequest(teleport.SessionEvent, false, eventPayload)
if err != nil {
// The party's connection may already be closed, in which case we expect an EOF
if !trace.IsEOF(err) {
s.log.Warnf("Unable to send %v to %v: %v.", events.SessionLeaveEvent, p.sconn.RemoteAddr(), err)
}
continue
}
s.log.Debugf("Sent %v to %v.", events.SessionLeaveEvent, p.sconn.RemoteAddr())
}
}
// emitSessionEndEvent emits a session end event.
func (s *session) emitSessionEndEvent() {
s.mu.Lock()
defer s.mu.Unlock()
ctx := s.scx
if s.endingContext != nil {
ctx = s.endingContext
}
start, end := s.startTime, time.Now().UTC()
sessionEndEvent := &apievents.SessionEnd{
Metadata: apievents.Metadata{
Type: events.SessionEndEvent,
Code: events.SessionEndCode,
ClusterName: ctx.ClusterName,
},
ServerMetadata: apievents.ServerMetadata{
ServerID: ctx.srv.HostUUID(),
ServerLabels: ctx.srv.GetInfo().GetAllLabels(),
ServerNamespace: s.getNamespace(),
ServerHostname: s.getHostname(),
ServerAddr: ctx.ServerConn.LocalAddr().String(),
},
SessionMetadata: apievents.SessionMetadata{
SessionID: string(s.id),
},
UserMetadata: ctx.Identity.GetUserMetadata(),
EnhancedRecording: s.hasEnhancedRecording,
Interactive: s.term != nil,
StartTime: start,
EndTime: end,
SessionRecording: ctx.SessionRecordingConfig.GetMode(),
}
for _, p := range s.participants {
sessionEndEvent.Participants = append(sessionEndEvent.Participants, p.user)
}
// If there are 0 participants, this is an exec session.
// Use the user from the session context.
if len(s.participants) == 0 {
sessionEndEvent.Participants = []string{s.scx.Identity.TeleportUser}
}
if err := s.recorder.EmitAuditEvent(ctx.srv.Context(), sessionEndEvent); err != nil {
s.log.WithError(err).Warn("Failed to emit session end event.")
}
}
func (s *session) setEndingContext(ctx *ServerContext) {
s.mu.Lock()
defer s.mu.Unlock()
s.endingContext = ctx
}
func (s *session) setHasEnhancedRecording(val bool) {
s.mu.Lock()
defer s.mu.Unlock()
s.hasEnhancedRecording = val
}
// launch launches the session.
// Must be called under session Lock.
func (s *session) launch(ctx *ServerContext) error {
s.log.Debugf("Launching session %v.", s.id)
s.BroadcastMessage("Connecting to %v over SSH", ctx.srv.GetInfo().GetHostname())
s.io.On()
if err := s.tracker.UpdateState(s.serverCtx, types.SessionState_SessionStateRunning); err != nil {
s.log.Warnf("Failed to set tracker state to %v", types.SessionState_SessionStateRunning)
}
// If the identity is verified with an MFA device, we enabled MFA-based presence for the session.
if s.presenceEnabled {
go func() {
ticker := time.NewTicker(PresenceVerifyInterval)
defer ticker.Stop()
outer:
for {
select {
case <-ticker.C:
err := s.checkPresence()
if err != nil {
s.log.WithError(err).Error("Failed to check presence, terminating session as a security measure")
s.Stop()
}
case <-s.stopC:
break outer
}
}
}()
}
// copy everything from the pty to the writer. this lets us capture all input
// and output of the session (because input is echoed to stdout in the pty).
// the writer contains multiple writers: the session logger and a direct
// connection to members of the "party" (other people in the session).
s.term.AddParty(1)
go func() {
defer s.term.AddParty(-1)
// once everything has been copied, notify the goroutine below. if this code
// is running in a teleport node, when the exec.Cmd is done it will close
// the PTY, allowing io.Copy to return. if this is a teleport forwarding
// node, when the remote side closes the channel (which is what s.term.PTY()
// returns) io.Copy will return.
defer close(s.doneCh)
_, err := io.Copy(s.io, s.term.PTY())
s.log.Debugf("Copying from PTY to writer completed with error %v.", err)
}()
s.term.AddParty(1)
go func() {
defer s.term.AddParty(-1)
_, err := io.Copy(s.term.PTY(), s.io)
s.log.Debugf("Copying from reader to PTY completed with error %v.", err)
}()
// wait for exec.Cmd (or receipt of "exit-status" for a forwarding node),
// once it is received wait for the io.Copy above to finish, then broadcast
// the "exit-status" to the client.
go func() {
result, err := s.term.Wait()
if err != nil {
ctx.Errorf("Received error waiting for the interactive session %v to finish: %v.", s.id, err)
}
// wait for copying from the pty to be complete or a timeout before
// broadcasting the result (which will close the pty) if it has not been
// closed already.
select {
case <-time.After(defaults.WaitCopyTimeout):
s.log.Errorf("Timed out waiting for PTY copy to finish, session data for %v may be missing.", s.id)
case <-s.doneCh:
}
if ctx.ExecRequest.GetCommand() != "" {
emitExecAuditEvent(ctx, ctx.ExecRequest.GetCommand(), err)
}
if result != nil {
if err := s.registry.broadcastResult(s.id, *result); err != nil {
s.log.Warningf("Failed to broadcast session result: %v", err)
}
}
s.emitSessionEndEvent()
s.Close()
}()
return nil
}
// startInteractive starts a new interactive process (or a shell) in the
// current session.
func (s *session) startInteractive(ch ssh.Channel, ctx *ServerContext) error {
inReader, inWriter := io.Pipe()
s.inWriter = inWriter
s.io.AddReader("reader", inReader)
s.io.AddWriter(sessionRecorderID, utils.WriteCloserWithContext(ctx.srv.Context(), s.recorder))
s.BroadcastMessage("Creating session with ID: %v...", s.id)
s.BroadcastMessage(SessionControlsInfoBroadcast)
if err := s.startTerminal(ctx); err != nil {
return trace.Wrap(err)
}
// Emit a session.start event for the interactive session.
s.emitSessionStartEvent(ctx)
// create a new "party" (connected client) and launch/join the session.
p := newParty(s, types.SessionPeerMode, ch, ctx)
if err := s.addParty(p, types.SessionPeerMode); err != nil {
return trace.Wrap(err)
}
// Open a BPF recording session. If BPF was not configured, not available,
// or running in a recording proxy, OpenSession is a NOP.
sessionContext := &bpf.SessionContext{
Context: ctx.srv.Context(),
PID: s.term.PID(),
Emitter: s.recorder,
Namespace: ctx.srv.GetNamespace(),
SessionID: s.id.String(),
ServerID: ctx.srv.HostUUID(),
Login: ctx.Identity.Login,
User: ctx.Identity.TeleportUser,
Events: ctx.Identity.RoleSet.EnhancedRecordingSet(),
}