-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathsess.go
2417 lines (2065 loc) · 77.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
/*
* Teleport
* Copyright (C) 2023 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package srv
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"os"
"os/user"
"path/filepath"
"slices"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/moby/term"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel/attribute"
oteltrace "go.opentelemetry.io/otel/trace"
"golang.org/x/crypto/ssh"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/constants"
"github.com/gravitational/teleport/api/observability/tracing"
"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/recorder"
"github.com/gravitational/teleport/lib/observability/metrics"
"github.com/gravitational/teleport/lib/services"
rsession "github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/sshutils/sftp"
"github.com/gravitational/teleport/lib/utils"
logutils "github.com/gravitational/teleport/lib/utils/log"
)
const sessionRecorderID = "session-recorder"
const (
PresenceVerifyInterval = time.Second * 15
PresenceMaxDifference = time.Minute
)
const (
// sessionRecordingWarningMessage is sent when the session recording is
// going to be disabled.
sessionRecordingWarningMessage = "Warning: node error. This might cause some functionalities not to work correctly."
// sessionRecordingErrorMessage is sent when session recording has some
// error and the session is terminated.
sessionRecordingErrorMessage = "Session terminating due to node error."
)
var serverSessions = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: teleport.MetricServerInteractiveSessions,
Help: "Number of active sessions to this host",
},
)
func MsgParticipantCtrls(w io.Writer, m types.SessionParticipantMode) error {
var modeCtrl bytes.Buffer
modeCtrl.WriteString(fmt.Sprintf("\r\nTeleport > Joining session with participant mode: %s\r\n", string(m)))
modeCtrl.WriteString("Teleport > Controls\r\n")
modeCtrl.WriteString("Teleport > - CTRL-C: Leave the session\r\n")
if m == types.SessionModeratorMode {
modeCtrl.WriteString("Teleport > - t: Forcefully terminate the session\r\n")
}
_, err := w.Write(modeCtrl.Bytes())
if err != nil {
return fmt.Errorf("could not write bytes: %w", err)
}
return nil
}
// SessionRegistry holds a map of all active sessions on a given
// SSH server
type SessionRegistry struct {
SessionRegistryConfig
// logger holds the structured logger
logger *slog.Logger
// 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
// users is used for automatic user creation when new sessions are
// started
users HostUsers
// sudoers is used to create sudoers files at session start
sudoers HostSudoers
sessionsByUser *userSessions
}
type userSessions struct {
sessionsByUser map[string]int
m sync.Mutex
}
func (us *userSessions) add(user string) {
us.m.Lock()
defer us.m.Unlock()
count := us.sessionsByUser[user]
us.sessionsByUser[user] = count + 1
}
func (us *userSessions) del(user string) int {
us.m.Lock()
defer us.m.Unlock()
count := us.sessionsByUser[user]
count -= 1
us.sessionsByUser[user] = count
return count
}
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.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 := metrics.RegisterPrometheusCollectors(serverSessions)
if err != nil {
return nil, trace.Wrap(err)
}
return &SessionRegistry{
SessionRegistryConfig: cfg,
logger: slog.With(teleport.ComponentKey, teleport.Component(teleport.ComponentSession, cfg.Srv.Component())),
sessions: make(map[rsession.ID]*session),
users: cfg.Srv.GetHostUsers(),
sudoers: cfg.Srv.GetHostSudoers(),
sessionsByUser: &userSessions{
sessionsByUser: make(map[string]int),
},
}, 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.logger.DebugContext(s.Srv.Context(), "Closing Session Registry.")
}
type sudoersCloser struct {
username string
userSessions *userSessions
cleanup func(name string) error
}
func (sc *sudoersCloser) Close() error {
count := sc.userSessions.del(sc.username)
if count != 0 {
return nil
}
if err := sc.cleanup(sc.username); err != nil {
return trace.Wrap(err)
}
return nil
}
// WriteSudoersFile tries to write the needed sudoers entry to the sudoers
// file, if any. If the returned closer is not nil, it must be called at the
// end of the session to cleanup the sudoers file.
func (s *SessionRegistry) WriteSudoersFile(identityContext IdentityContext) (io.Closer, error) {
if identityContext.Login == teleport.SSHSessionJoinPrincipal {
return nil, nil
}
// Pulling sudoers directly from the Srv so WriteSudoersFile always
// respects the invariant that we shouldn't write sudoers on proxy servers.
// This might invalidate the cached sudoers field on SessionRegistry, so
// we may be able to remove that in a future PR
sudoWriter := s.Srv.GetHostSudoers()
if sudoWriter == nil {
return nil, nil
}
sudoers, err := identityContext.AccessChecker.HostSudoers(s.Srv.GetInfo())
if err != nil {
return nil, trace.Wrap(err)
}
if len(sudoers) == 0 {
// not an error, sudoers may not be configured.
return nil, nil
}
if err := sudoWriter.WriteSudoers(identityContext.Login, sudoers); err != nil {
return nil, trace.Wrap(err)
}
s.sessionsByUser.add(identityContext.Login)
return &sudoersCloser{
username: identityContext.Login,
userSessions: s.sessionsByUser,
cleanup: sudoWriter.RemoveSudoers,
}, nil
}
// ObtainFallbackUIDFunc should return (uid, true, nil) if a fallback UID is
// configured, (_, false, nil) if no fallback is configured.
type ObtainFallbackUIDFunc = func(ctx context.Context, username string) (uid int32, ok bool, _ error)
// UpsertHostUser attempts to create or update a local user on the host if needed.
// If the returned closer is not nil, it must be called at the end of the session to
// clean up the local user.
func (s *SessionRegistry) UpsertHostUser(identityContext IdentityContext, obtainFallbackUID ObtainFallbackUIDFunc) (bool, io.Closer, error) {
ctx := s.Srv.Context()
log := s.logger.With("host_username", identityContext.Login)
if identityContext.Login == teleport.SSHSessionJoinPrincipal {
return false, nil, nil
}
if !s.Srv.GetCreateHostUser() || s.users == nil {
log.DebugContext(ctx, "Not creating host user: node has disabled host user creation.")
return false, nil, nil // not an error to not be able to create host users
}
log.DebugContext(ctx, "Checking if user provisioning is allowed")
ui, err := identityContext.AccessChecker.HostUsers(s.Srv.GetInfo())
if err != nil {
if trace.IsAccessDenied(err) {
if existsErr := s.users.UserExists(identityContext.Login); existsErr != nil {
if trace.IsNotFound(existsErr) {
return false, nil, trace.WrapWithMessage(err, "insufficient permissions for host user creation")
}
return false, nil, trace.Wrap(existsErr)
}
}
return false, nil, trace.Wrap(err)
}
if obtainFallbackUID != nil && ui.Mode == services.HostUserModeKeep && ui.UID == "" {
if err := s.users.UserExists(identityContext.Login); err != nil {
if !trace.IsNotFound(err) {
return false, nil, trace.Wrap(err)
}
log.DebugContext(ctx, "Host user does not exist and no UID is configured, obtaining UID from control plane")
fallbackUID, ok, err := obtainFallbackUID(ctx, identityContext.Login)
if err != nil {
log.ErrorContext(ctx, "Failed to obtain UID from control plane", "error", err)
return false, nil, trace.Wrap(err)
}
if ok {
log.DebugContext(ctx, "Obtained UID from control plane", "uid", fallbackUID)
ui.UID = strconv.Itoa(int(fallbackUID))
if ui.GID == "" {
ui.GID = ui.UID
}
} else {
log.DebugContext(ctx, "No UID configured in the cluster")
}
}
}
log.DebugContext(ctx, "Attempting to upsert host user")
userCloser, err := s.users.UpsertUser(identityContext.Login, *ui)
if err != nil {
log.DebugContext(ctx, "Error creating user", "error", err)
if errors.Is(err, unmanagedUserErr) {
log.WarnContext(ctx, "User is not managed by teleport. Either manually delete the user from this machine or update the host_groups defined in their role to include 'teleport-keep'. https://goteleport.com/docs/enroll-resources/server-access/guides/host-user-creation/#migrating-unmanaged-users")
return false, nil, nil
}
if !trace.IsAlreadyExists(err) {
return false, nil, trace.Wrap(err)
}
log.DebugContext(ctx, "Host user already exists")
}
return true, userCloser, nil
}
// OpenSession either joins an existing active session or starts a new session.
func (s *SessionRegistry) OpenSession(ctx context.Context, ch ssh.Channel, scx *ServerContext) error {
session := scx.getSession()
if session != nil && !session.isStopped() {
scx.Logger.InfoContext(ctx, "Joining existing session", "session_id", session.id)
mode := types.SessionParticipantMode(scx.env[teleport.EnvSSHJoinMode])
if mode == "" {
mode = types.SessionPeerMode
}
switch mode {
case types.SessionModeratorMode, types.SessionObserverMode, types.SessionPeerMode:
default:
return trace.BadParameter("Unrecognized session participant mode: %v", mode)
}
// Update the in-memory data structure that a party member has joined.
if err := session.join(ch, scx, mode); err != nil {
return trace.Wrap(err)
}
return nil
}
if scx.JoinOnly {
return trace.AccessDenied("join-only mode was used to create this connection but attempted to create a new session.")
}
sid := scx.SessionID()
if sid.IsZero() {
return trace.BadParameter("session ID is not set")
}
// This logic allows concurrent request to create a new session
// to fail, what is ok because we should never have this condition
sess, p, err := newSession(ctx, sid, s, scx, ch, sessionTypeInteractive)
if err != nil {
return trace.Wrap(err)
}
scx.setSession(ctx, sess, ch)
s.addSession(sess)
scx.Logger.InfoContext(ctx, "Creating interactive session", "session_id", 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(ctx, scx, p); err != nil {
sess.Close()
return trace.Wrap(err)
}
return nil
}
// OpenExecSession opens a non-interactive exec session.
func (s *SessionRegistry) OpenExecSession(ctx context.Context, channel ssh.Channel, scx *ServerContext) error {
sessionID := scx.SessionID()
if sessionID.IsZero() {
sessionID = rsession.NewID()
scx.Logger.Log(ctx, logutils.TraceLevel, "Session not found, creating a new session", "session_id", sessionID)
} else {
// Use passed session ID. Assist uses this "feature" to record
// the execution output.
scx.Logger.Log(ctx, logutils.TraceLevel, "Session found, reusing it", "session_id", sessionID)
}
// 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(ctx, sessionID, s, scx, channel, sessionTypeNonInteractive)
if err != nil {
return trace.Wrap(err)
}
scx.Logger.InfoContext(ctx, "Creating exec session", "session_id", sessionID)
approved, err := s.isApprovedFileTransfer(scx)
if err != nil {
return trace.Wrap(err)
}
sess.mu.Lock()
canStart, _, err := sess.checkIfStartUnderLock()
sess.mu.Unlock()
if err != nil {
return trace.Wrap(err)
}
// canStart will be true for non-moderated sessions. If canStart is false, check to
// see if the request has been approved through a moderated session next.
if !canStart && !approved {
return errCannotStartUnattendedSession
}
// Start a non-interactive session (TTY attached). Close the session if an error
// occurs, otherwise it will be closed by the callee.
scx.setSession(ctx, sess, channel)
err = sess.startExec(ctx, channel, scx)
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.logger.DebugContext(s.Srv.Context(), "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()
}
func (s *SessionRegistry) isApprovedFileTransfer(scx *ServerContext) (bool, error) {
// If the TELEPORT_MODERATED_SESSION_ID environment variable was not
// set, return not approved and no error. This means the file
// transfer came from a non-moderated session. sessionID will be
// passed after a moderated session approval process has completed.
sessID, _ := scx.GetEnv(string(sftp.ModeratedSessionID))
if sessID == "" {
return false, nil
}
// fetch session from registry with sessionID
s.sessionsMux.Lock()
sess := s.sessions[rsession.ID(sessID)]
s.sessionsMux.Unlock()
if sess == nil {
// If they sent a sessionID and it wasn't found, send an actual error
return false, trace.NotFound("Session not found")
}
// acquire the session mutex lock so sess.fileTransferReq doesn't get
// written while we're reading it
sess.mu.Lock()
defer sess.mu.Unlock()
if sess.fileTransferReq == nil {
return false, trace.NotFound("Session does not have a pending file transfer request")
}
if sess.fileTransferReq.Requester != scx.Identity.TeleportUser {
// to be safe deny and remove the pending request if the user
// doesn't match what we expect
req := sess.fileTransferReq
sess.fileTransferReq = nil
sess.BroadcastMessage("file transfer request %s denied due to %s attempting to transfer files", req.ID, scx.Identity.TeleportUser)
_ = s.notifyFileTransferRequestUnderLock(req, FileTransferDenied, scx)
return false, trace.AccessDenied("Teleport user does not match original requester")
}
approved, err := sess.checkIfFileTransferApproved(sess.fileTransferReq)
if err != nil {
return false, trace.Wrap(err)
}
if approved {
scx.setApprovedFileTransferRequest(sess.fileTransferReq)
sess.fileTransferReq = nil
}
return approved, nil
}
// FileTransferRequestEvent is an event used to Notify party members during File Transfer Request approval process
type FileTransferRequestEvent string
const (
// FileTransferUpdate is used when a file transfer request is created or updated.
// An update will happen if a file transfer request was approved but the policy still isn't fulfilled
FileTransferUpdate FileTransferRequestEvent = "file_transfer_request"
// FileTransferApproved is used when a file transfer request has received an approval decision
// and the policy is fulfilled. This lets the client know that the file transfer is ready to download/upload
// and be removed from any pending state.
FileTransferApproved FileTransferRequestEvent = "file_transfer_request_approve"
// FileTransferDenied is used when a file transfer request is denied. This lets the client know to remove
// this file transfer from any pending state.
FileTransferDenied FileTransferRequestEvent = "file_transfer_request_deny"
)
// notifyFileTransferRequestUnderLock is called to notify all members of a party that a file transfer request has been created/approved/denied.
// The notification is a global ssh request and requires the client to update its UI state accordingly.
func (s *SessionRegistry) notifyFileTransferRequestUnderLock(req *FileTransferRequest, res FileTransferRequestEvent, scx *ServerContext) error {
session := scx.getSession()
if session == nil {
s.logger.DebugContext(
s.Srv.Context(), "Unable to notify event, no session found in context.",
"event", res,
)
return trace.NotFound("no session found in context")
}
fileTransferEvent := &apievents.FileTransferRequestEvent{
Metadata: apievents.Metadata{
Type: string(res),
ClusterName: scx.ClusterName,
},
SessionMetadata: session.scx.GetSessionMetadata(),
RequestID: req.ID,
Requester: req.Requester,
Location: req.Location,
Filename: req.Filename,
Download: req.Download,
Approvers: make([]string, 0),
}
for _, approver := range req.approvers {
fileTransferEvent.Approvers = append(fileTransferEvent.Approvers, approver.user)
}
eventPayload, err := json.Marshal(fileTransferEvent)
if err != nil {
s.logger.WarnContext(
s.Srv.Context(), "Unable to marshal event.",
"event", res,
"error", err,
)
return trace.Wrap(err)
}
for _, p := range session.parties {
// Send the message as a global request.
_, _, err = p.sconn.SendRequest(teleport.SessionEvent, false, eventPayload)
if err != nil {
s.logger.WarnContext(
s.Srv.Context(), "Unable to send event to session party.",
"event", res,
"error", err,
"party", p,
)
continue
}
s.logger.DebugContext(
s.Srv.Context(), "Sent event to session party.",
"event", res,
"party", p,
)
}
return nil
}
// 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(ctx context.Context, params rsession.TerminalParams, scx *ServerContext) error {
session := scx.getSession()
if session == nil {
s.logger.DebugContext(ctx, "Unable to update window size, no session found in context.")
return nil
}
// Build the resize event.
resizeEvent, err := session.Recorder().PrepareSessionEvent(&apievents.Resize{
Metadata: apievents.Metadata{
Type: events.ResizeEvent,
Code: events.TerminalResizeCode,
ClusterName: scx.ClusterName,
},
ServerMetadata: session.serverMeta,
SessionMetadata: session.scx.GetSessionMetadata(),
UserMetadata: scx.Identity.GetUserMetadata(),
TerminalSize: params.Serialize(),
})
if err == nil {
// Report the updated window size to the session stream (this is so the sessions
// can be replayed correctly).
if err := session.recordEvent(s.Srv.Context(), resizeEvent); err != nil {
s.logger.WarnContext(ctx, "Failed to record resize session event.", "error", err)
}
} else {
s.logger.WarnContext(ctx, "Failed to set up resize session event - event will not be recorded.", "error", err)
}
// Update the size of the server side PTY.
err = session.term.SetWinSize(ctx, 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(scx.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() == scx.ID() {
continue
}
eventPayload, err := json.Marshal(resizeEvent.GetAuditEvent())
if err != nil {
s.logger.WarnContext(ctx, "Unable to marshal resize event for session party.", "error", err, "party", p)
continue
}
// Send the message as a global request.
_, _, err = p.sconn.SendRequest(teleport.SessionEvent, false, eventPayload)
if err != nil {
s.logger.WarnContext(ctx, "Unable to send resize event to session party.", "error", err, "party", p)
continue
}
s.logger.DebugContext(ctx, "Sent resize event to session party.", "event", params, "party", p)
}
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
}
// SessionAccessEvaluator is the interface that defines criteria needed to be met
// in order to start and join sessions.
type SessionAccessEvaluator interface {
IsModerated() bool
FulfilledFor(participants []auth.SessionAccessContext) (bool, auth.PolicyOptions, error)
PrettyRequirementsList() string
CanJoin(user auth.SessionAccessContext) []types.SessionParticipantMode
}
// 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
// logger holds the logger for this session.
logger *slog.Logger
// 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
// fileTransferReq a pending file transfer request for this session.
// If the request is denied or approved it should be set to nil to
// prevent its reuse.
fileTransferReq *FileTransferRequest
io *TermManager
inWriter io.WriteCloser
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.SessionPreparerRecorder
recorderMu sync.RWMutex
emitter apievents.Emitter
// 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 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()
// serverMeta contains metadata about the target node of this session.
serverMeta apievents.ServerMetadata
// started is true after the session start.
started atomic.Bool
}
type sessionType bool
const (
sessionTypeInteractive sessionType = true
sessionTypeNonInteractive sessionType = false
)
// newSession creates a new session with a given ID within a given context.
func newSession(ctx context.Context, id rsession.ID, r *SessionRegistry, scx *ServerContext, ch ssh.Channel, sessType sessionType) (*session, *party, error) {
serverSessions.Inc()
startTime := time.Now().UTC()
rsess := rsession.Session{
Kind: types.SSHSessionKind,
ID: id,
TerminalParams: rsession.TerminalParams{
W: teleport.DefaultTerminalWidth,
H: teleport.DefaultTerminalHeight,
},
Login: scx.Identity.Login,
Created: startTime,
LastActive: startTime,
ServerID: scx.srv.ID(),
Namespace: r.Srv.GetNamespace(),
ServerHostname: scx.srv.GetInfo().GetHostname(),
ServerAddr: scx.ServerConn.LocalAddr().String(),
ClusterName: scx.ClusterName,
}
term := scx.GetTerm()
if term != nil {
winsize, err := term.GetWinSize()
if err != nil {
return nil, nil, trace.Wrap(err)
}
rsess.TerminalParams.W = int(winsize.Width)
rsess.TerminalParams.H = int(winsize.Height)
}
policySets := scx.Identity.AccessChecker.SessionPolicySets()
access := auth.NewSessionAccessEvaluator(policySets, types.SSHSessionKind, scx.Identity.TeleportUser)
sess := &session{
logger: slog.With(
teleport.ComponentKey, teleport.Component(teleport.ComponentSession, r.Srv.Component()),
"session_id", id,
),
id: id,
registry: r,
parties: make(map[rsession.ID]*party),
participants: make(map[rsession.ID]*party),
login: scx.Identity.Login,
stopC: make(chan struct{}),
startTime: startTime,
emitter: scx.srv,
serverCtx: scx.srv.Context(),
access: &access,
scx: scx,
presenceEnabled: scx.Identity.UnmappedIdentity.MFAVerified != "",
io: NewTermManager(),
doneCh: make(chan struct{}),
initiator: scx.Identity.TeleportUser,
displayParticipantRequirements: utils.AsBool(scx.env[teleport.EnvSSHSessionDisplayParticipantRequirements]),
serverMeta: scx.srv.TargetMetadata(),
}
sess.io.OnWriteError = sess.onWriteError
go func() {
if _, open := <-sess.io.TerminateNotifier(); open {
err := sess.registry.ForceTerminate(sess.scx)
if err != nil {
sess.logger.ErrorContext(sess.serverCtx, "Failed to terminate session.", "error", err)
}
}
}()
// create a new "party" (connected client) and launch/join the session.
p := newParty(sess, types.SessionPeerMode, ch, scx)
sess.parties[p.id] = p
sess.participants[p.id] = p
var err error
if err = sess.trackSession(ctx, scx.Identity.TeleportUser, policySets, p, sessType); err != nil {
if trace.IsNotImplemented(err) {
return nil, nil, trace.NotImplemented("Attempted to use Moderated Sessions with an Auth Server below the minimum version of 9.0.0.")
}
return nil, nil, trace.Wrap(err)
}
sess.recorder, err = newRecorder(sess, scx)
if err != nil {
return nil, nil, trace.Wrap(err)
}
return sess, p, 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 SessionRecorder which can be used to record session
// events.
func (s *session) Recorder() events.SessionPreparerRecorder {
s.recorderMu.RLock()
defer s.recorderMu.RUnlock()
return s.recorder
}
func (s *session) setRecorder(rec events.SessionPreparerRecorder) {
s.recorderMu.Lock()
defer s.recorderMu.Unlock()
s.recorder = rec
}
// 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.logger.InfoContext(s.serverCtx, "Stopping session.")
// Close io copy loops
if s.inWriter != nil {
if err := s.inWriter.Close(); err != nil {
s.logger.DebugContext(s.serverCtx, "Failed to close session writer.", "error", err)
}
}
s.io.Close()
// Make sure that the terminal has been closed
s.haltTerminal()
// Close session tracker and mark it as terminated
if err := s.tracker.Close(s.serverCtx); err != nil {
s.logger.DebugContext(s.serverCtx, "Failed to close session tracker.", "error", err)
}
}
// haltTerminal closes the terminal. Then is tried to terminate the terminal in a graceful way
// and kill by sending SIGKILL if the graceful termination fails.
func (s *session) haltTerminal() {
if s.term == nil {
return
}
if err := s.term.Close(); err != nil {
s.logger.DebugContext(s.serverCtx, "Failed to close the shell.", "error", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.term.KillUnderlyingShell(ctx); err != nil {
s.logger.DebugContext(s.serverCtx, "Failed to terminate the shell.", "error", err)
} else {
// Return before we send SIGKILL to the child process, as doing that
// could interrupt the "graceful shutdown" process.
return
}
if err := s.term.Kill(context.TODO()); err != nil {
s.logger.DebugContext(s.serverCtx, "Failed to kill the shell.", "error", err)
}
}
// 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.BroadcastMessage("Closing session...")
s.logger.InfoContext(s.serverCtx, "Closing session.")
// Remove session parties and close client connections. Since terminals
// might await for all the parties to be released, we must close them first.
// Closing the parties will cause their SSH channel to be closed, meaning
// any goroutine reading from it will be released.