-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathctx.go
1302 lines (1093 loc) · 41.1 KB
/
ctx.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 (
"context"
"fmt"
"io"
"log/slog"
"net"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/crypto/ssh"
"github.com/gravitational/teleport"
tracessh "github.com/gravitational/teleport/api/observability/tracing/ssh"
"github.com/gravitational/teleport/api/types"
apievents "github.com/gravitational/teleport/api/types/events"
apiutils "github.com/gravitational/teleport/api/utils"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/auth/authclient"
"github.com/gravitational/teleport/lib/bpf"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/service/servicecfg"
"github.com/gravitational/teleport/lib/services"
rsession "github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/srv/uacc"
"github.com/gravitational/teleport/lib/sshca"
"github.com/gravitational/teleport/lib/sshutils"
"github.com/gravitational/teleport/lib/sshutils/x11"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/utils/envutils"
"github.com/gravitational/teleport/lib/utils/parse"
)
var ctxID int32
var (
serverTX = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "tx",
Help: "Number of bytes transmitted.",
},
)
serverRX = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "rx",
Help: "Number of bytes received.",
},
)
)
var (
ErrNodeFileCopyingNotPermitted = trace.AccessDenied("node does not allow file copying via SCP or SFTP")
errCannotStartUnattendedSession = trace.AccessDenied("lacking privileges to start unattended session")
)
func init() {
prometheus.MustRegister(serverTX)
prometheus.MustRegister(serverRX)
}
// AccessPoint is the access point contract required by a Server
type AccessPoint interface {
// Announcer adds methods used to announce presence
authclient.Announcer
// Semaphores provides semaphore operations
types.Semaphores
// GetClusterName returns cluster name
GetClusterName(opts ...services.MarshalOption) (types.ClusterName, error)
// GetClusterNetworkingConfig returns cluster networking configuration.
GetClusterNetworkingConfig(ctx context.Context) (types.ClusterNetworkingConfig, error)
// GetSessionRecordingConfig returns session recording configuration.
GetSessionRecordingConfig(ctx context.Context) (types.SessionRecordingConfig, error)
// GetAuthPreference returns the cluster authentication configuration.
GetAuthPreference(ctx context.Context) (types.AuthPreference, error)
// GetRole returns role by name
GetRole(ctx context.Context, name string) (types.Role, error)
// GetCertAuthorities returns a list of cert authorities
GetCertAuthorities(ctx context.Context, caType types.CertAuthType, loadKeys bool) ([]types.CertAuthority, error)
// ConnectionDiagnosticTraceAppender adds a method to append traces into ConnectionDiagnostics.
services.ConnectionDiagnosticTraceAppender
}
// Server is regular or forwarding SSH server.
type Server interface {
// StreamEmitter allows server to emit audit events and create
// event streams for recording sessions
events.StreamEmitter
// ID is the unique ID of the server.
ID() string
// HostUUID is the UUID of the underlying host. For the forwarding
// server this is the proxy the forwarding server is running in.
HostUUID() string
// GetNamespace returns the namespace the server was created in.
GetNamespace() string
// AdvertiseAddr is the publicly addressable address of this server.
AdvertiseAddr() string
// Component is the type of server, forwarding or regular.
Component() string
// PermitUserEnvironment returns if reading environment variables upon
// startup is allowed.
PermitUserEnvironment() bool
// GetAccessPoint returns an AccessPoint for this cluster.
GetAccessPoint() AccessPoint
// GetDataDir returns data directory of the server
GetDataDir() string
// GetPAM returns PAM configuration for this server.
GetPAM() (*servicecfg.PAMConfig, error)
// GetClock returns a clock setup for the server
GetClock() clockwork.Clock
// GetInfo returns a services.Server that represents this server.
GetInfo() types.Server
// UseTunnel used to determine if this node has connected to this cluster
// using reverse tunnel.
UseTunnel() bool
// GetBPF returns the BPF service used for enhanced session recording.
GetBPF() bpf.BPF
// Context returns server shutdown context
Context() context.Context
// GetUserAccountingPaths returns the path of the user accounting database and log. Returns empty for system defaults.
GetUserAccountingPaths() (utmp, wtmp, btmp string)
// GetLockWatcher gets the server's lock watcher.
GetLockWatcher() *services.LockWatcher
// GetCreateHostUser returns whether the node should create
// temporary teleport users or not
GetCreateHostUser() bool
// GetHostUsers returns the HostUsers instance being used to manage
// host user provisioning
GetHostUsers() HostUsers
// GetHostSudoers returns the HostSudoers instance being used to manage
// sudoer file provisioning
GetHostSudoers() HostSudoers
// TargetMetadata returns metadata about the session target node.
TargetMetadata() apievents.ServerMetadata
}
// IdentityContext holds all identity information associated with the user
// logged on the connection.
type IdentityContext struct {
// UnmappedIdentity is the base identity of the user derived from the cert, without any
// cross-cluster mapping applied.
UnmappedIdentity *sshca.Identity
// TeleportUser is the Teleport user associated with the connection.
TeleportUser string
// Impersonator is a user acting on behalf of other user
Impersonator string
// Login is the operating system user associated with the connection.
Login string
// CertAuthority is the Certificate Authority that signed the Certificate.
CertAuthority types.CertAuthority
// AccessChecker is used to check RBAC permissions.
AccessChecker services.AccessChecker
// UnmappedRoles lists the original roles of this Teleport user without
// trusted-cluster-related role mapping being applied.
UnmappedRoles []string
// CertValidBefore is set to the expiry time of a certificate, or
// empty, if cert does not expire
CertValidBefore time.Time
// RouteToCluster is derived from the certificate
RouteToCluster string
// ActiveRequests is active access request IDs
ActiveRequests []string
// DisallowReissue is a flag that, if set, instructs the auth server to
// deny any requests from this identity to generate new certificates.
DisallowReissue bool
// Renewable indicates this certificate is renewable.
Renewable bool
// Generation counts the number of times this identity's certificate has
// been renewed.
Generation uint64
// BotName is the name of the Machine ID bot this identity is associated
// with, if any.
BotName string
// BotInstanceID is the unique identifier of the Machine ID bot instance
// this identity is associated with, if any.
BotInstanceID string
// AllowedResourceIDs lists the resources this identity should be allowed to
// access
AllowedResourceIDs []types.ResourceID
// PreviousIdentityExpires is the expiry time of the identity/cert that this
// identity/cert was derived from. It is used to determine a session's hard
// deadline in cases where both require_session_mfa and disconnect_expired_cert
// are enabled. See https://github.com/gravitational/teleport/issues/18544.
PreviousIdentityExpires time.Time
}
// ServerContext holds session specific context, such as SSH auth agents, PTYs,
// and other resources. SessionContext also holds a ServerContext which can be
// used to access resources on the underlying server. SessionContext can also
// be used to attach resources that should be closed once the session closes.
//
// Any events that need to be recorded should be emitted via session and not
// ServerContext directly. Failure to use the session emitted will result in
// incorrect event indexes that may ultimately cause events to be overwritten.
type ServerContext struct {
// ConnectionContext is the parent context which manages connection-level
// resources.
*sshutils.ConnectionContext
Logger *slog.Logger
mu sync.RWMutex
// env is a list of environment variables passed to the session.
env map[string]string
// srv is the server that is holding the context.
srv Server
// id is the server specific incremental session id.
id int
// term holds PTY if it was requested by the session.
term Terminal
// sessionID holds the session ID that will be used when a new
// session is created.
sessionID rsession.ID
// session holds the active session (if there's an active one).
session *session
// closers is a list of io.Closer that will be called when session closes
// this is handy as sometimes client closes session, in this case resources
// will be properly closed and deallocated, otherwise they could be kept hanging.
closers []io.Closer
// Identity holds the identity of the user that is currently logged in on
// the Conn.
Identity IdentityContext
// ExecResultCh is a Go channel which will be used to send and receive the
// result of a "exec" request.
ExecResultCh chan ExecResult
// SubsystemResultCh is a Go channel which will be used to send and receive
// the result of a "subsystem" request.
SubsystemResultCh chan SubsystemResult
// IsTestStub is set to true by tests.
IsTestStub bool
// execRequest is the command to be executed within this session context. Do
// not get or set this field directly, use (Get|Set)ExecRequest.
execRequest Exec
// ClusterName is the name of the cluster current user is authenticated with.
ClusterName string
// SessionRecordingConfig holds the session recording configuration at the
// time this context was created.
SessionRecordingConfig types.SessionRecordingConfig
// RemoteClient holds an SSH client to a remote server. Only used by the
// recording proxy.
RemoteClient *tracessh.Client
// RemoteSession holds an SSH session to a remote server. Only used by the
// recording proxy.
RemoteSession *tracessh.Session
// disconnectExpiredCert is set to time when/if the certificate should
// be disconnected, set to empty if no disconnect is necessary
disconnectExpiredCert time.Time
// clientIdleTimeout is set to the timeout on
// client inactivity, set to 0 if not setup
clientIdleTimeout time.Duration
// cancelContext signals closure to all outstanding operations
cancelContext context.Context
// cancel is called whenever server context is closed
cancel context.CancelFunc
// termAllocated is used to track if a terminal has been allocated. This has
// to be tracked because the terminal is set to nil after it's "taken" in the
// session. Terminals can be allocated for both "exec" or "session" requests.
termAllocated bool
// ttyName is the name of the TTY used for a session, ex: /dev/pts/0
ttyName string
// sshRequest is the SSH request that was issued by the client. Do not get or
// set this field directly, use (Get|Set)SSHRequest instead.
sshRequest *ssh.Request
// cmd{r,w} are used to send the command from the parent process to the
// child process.
cmdr *os.File
cmdw *os.File
// cont{r,w} is used to send the continue signal from the parent process
// to the child process.
contr *os.File
contw *os.File
// ready{r,w} is used to send the ready signal from the child process
// to the parent process.
readyr *os.File
readyw *os.File
// killShell{r,w} are used to send kill signal to the child process
// to terminate the shell.
killShellr *os.File
killShellw *os.File
// ExecType holds the type of the channel or request. For example "session" or
// "direct-tcpip". Used to create correct subcommand during re-exec.
ExecType string
// SrcAddr is the source address of the request. This the originator IP
// address and port in an SSH "direct-tcpip" or "tcpip-forward" request. This
// value is only populated for port forwarding requests.
SrcAddr string
// DstAddr is the destination address of the request. This is the host and
// port to connect to in a "direct-tcpip" or "tcpip-forward" request. This
// value is only populated for port forwarding requests.
DstAddr string
// allowFileCopying controls if remote file operations via SCP/SFTP are allowed
// by the server.
AllowFileCopying bool
// JoinOnly is set if the connection was created using a join-only principal and may only be used to join other sessions.
JoinOnly bool
// ServerSubKind if the sub kind of the node this context is for.
ServerSubKind string
// approvedFileReq is an approved file transfer request that will only be
// set when the session's pending file transfer request is approved.
approvedFileReq *FileTransferRequest
}
// NewServerContext creates a new *ServerContext which is used to pass and
// manage resources, and an associated context.Context which is canceled when
// the ServerContext is closed. The ctx parameter should be a child of the ctx
// associated with the scope of the parent ConnectionContext to ensure that
// cancellation of the ConnectionContext propagates to the ServerContext.
func NewServerContext(ctx context.Context, parent *sshutils.ConnectionContext, srv Server, identityContext IdentityContext, monitorOpts ...func(*MonitorConfig)) (*ServerContext, error) {
netConfig, err := srv.GetAccessPoint().GetClusterNetworkingConfig(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
recConfig, err := srv.GetAccessPoint().GetSessionRecordingConfig(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
cancelContext, cancel := context.WithCancel(ctx)
child := &ServerContext{
ConnectionContext: parent,
id: int(atomic.AddInt32(&ctxID, int32(1))),
env: make(map[string]string),
srv: srv,
ExecResultCh: make(chan ExecResult, 10),
SubsystemResultCh: make(chan SubsystemResult, 10),
ClusterName: parent.ServerConn.Permissions.Extensions[utils.CertTeleportClusterName],
SessionRecordingConfig: recConfig,
Identity: identityContext,
clientIdleTimeout: identityContext.AccessChecker.AdjustClientIdleTimeout(netConfig.GetClientIdleTimeout()),
cancelContext: cancelContext,
cancel: cancel,
ServerSubKind: srv.TargetMetadata().ServerSubKind,
}
child.Logger = slog.With(
teleport.ComponentKey, srv.Component(),
"local_addr", child.ServerConn.LocalAddr(),
"remote_addr", child.ServerConn.RemoteAddr(),
"login", child.Identity.Login,
"teleport_user", child.Identity.TeleportUser,
"id", child.id,
)
if identityContext.Login == teleport.SSHSessionJoinPrincipal {
child.JoinOnly = true
}
authPref, err := srv.GetAccessPoint().GetAuthPreference(ctx)
if err != nil {
childErr := child.Close()
return nil, trace.NewAggregate(err, childErr)
}
child.disconnectExpiredCert = getDisconnectExpiredCertFromIdentityContext(
identityContext.AccessChecker, authPref, &identityContext,
)
// Update log entry fields.
if !child.disconnectExpiredCert.IsZero() {
child.Logger = child.Logger.With("cert", child.disconnectExpiredCert)
}
if child.clientIdleTimeout != 0 {
child.Logger = child.Logger.With("idle", child.clientIdleTimeout)
}
clusterName, err := srv.GetAccessPoint().GetClusterName()
if err != nil {
childErr := child.Close()
return nil, trace.NewAggregate(err, childErr)
}
monitorConfig := MonitorConfig{
LockWatcher: child.srv.GetLockWatcher(),
LockTargets: ComputeLockTargets(clusterName.GetClusterName(), srv.HostUUID(), identityContext),
LockingMode: identityContext.AccessChecker.LockingMode(authPref.GetLockingMode()),
DisconnectExpiredCert: child.disconnectExpiredCert,
ClientIdleTimeout: child.clientIdleTimeout,
Clock: child.srv.GetClock(),
Tracker: child,
Conn: child.ServerConn,
Context: cancelContext,
TeleportUser: child.Identity.TeleportUser,
Login: child.Identity.Login,
ServerID: child.srv.ID(),
Logger: child.Logger,
Emitter: child.srv,
EmitterContext: ctx,
}
for _, opt := range monitorOpts {
opt(&monitorConfig)
}
err = StartMonitor(monitorConfig)
if err != nil {
childErr := child.Close()
return nil, trace.NewAggregate(err, childErr)
}
// Create pipe used to send command to child process.
child.cmdr, child.cmdw, err = os.Pipe()
if err != nil {
childErr := child.Close()
return nil, trace.NewAggregate(err, childErr)
}
child.AddCloser(child.cmdr)
child.AddCloser(child.cmdw)
// Create pipe used to signal continue to child process.
child.contr, child.contw, err = os.Pipe()
if err != nil {
childErr := child.Close()
return nil, trace.NewAggregate(err, childErr)
}
child.AddCloser(child.contr)
child.AddCloser(child.contw)
// Create pipe used to signal continue to parent process.
child.readyr, child.readyw, err = os.Pipe()
if err != nil {
childErr := child.Close()
return nil, trace.NewAggregate(err, childErr)
}
child.AddCloser(child.readyr)
child.AddCloser(child.readyw)
child.killShellr, child.killShellw, err = os.Pipe()
if err != nil {
childErr := child.Close()
return nil, trace.NewAggregate(err, childErr)
}
child.AddCloser(child.killShellr)
child.AddCloser(child.killShellw)
return child, nil
}
// Parent grants access to the connection-level context of which this
// is a subcontext. Useful for unambiguously accessing methods which
// this subcontext overrides (e.g. child.Parent().SetEnv(...)).
func (c *ServerContext) Parent() *sshutils.ConnectionContext {
return c.ConnectionContext
}
// ID returns ID of this context
func (c *ServerContext) ID() int {
return c.id
}
// SessionID returns the ID of the session in the context.
func (c *ServerContext) SessionID() rsession.ID {
c.mu.RLock()
defer c.mu.RUnlock()
if c.session == nil {
return c.sessionID
}
return c.session.id
}
// GetServer returns the underlying server which this context was created in.
func (c *ServerContext) GetServer() Server {
return c.srv
}
// CreateOrJoinSession will look in the SessionRegistry for the session ID. If
// no session is found, a new one is created. If one is found, it is returned.
func (c *ServerContext) CreateOrJoinSession(ctx context.Context, reg *SessionRegistry) error {
c.mu.Lock()
defer c.mu.Unlock()
// As SSH conversation progresses, at some point a session will be created and
// its ID will be added to the environment
ssid, found := c.getEnvLocked(sshutils.SessionEnvVar)
if !found {
c.sessionID = rsession.NewID()
c.Logger.DebugContext(ctx, "Will create new session for SSH connection")
return nil
}
// make sure whatever session is requested is a valid session
id, err := rsession.ParseID(ssid)
if err != nil {
return trace.BadParameter("invalid session ID")
}
// update ctx with the session if it exists
if sess, found := reg.findSession(*id); found {
c.sessionID = *id
c.session = sess
c.Logger.DebugContext(ctx, "Joining active SSH session", "session_id", c.session.id)
} else {
// TODO(capnspacehook): DELETE IN 17.0.0 - by then all supported
// clients should only set TELEPORT_SESSION when they want to
// join a session. Always return an error instead of using a
// new ID.
//
// to prevent the user from controlling the session ID, generate
// a new one
c.sessionID = rsession.NewID()
c.Logger.DebugContext(ctx, "Creating new SSH session")
}
return nil
}
// TrackActivity keeps track of all activity on ssh.Channel. The caller should
// use the returned ssh.Channel instead of the original one.
func (c *ServerContext) TrackActivity(ch ssh.Channel) ssh.Channel {
return newTrackingChannel(ch, c)
}
// AddCloser adds any closer in ctx that will be called
// whenever server closes session channel
func (c *ServerContext) AddCloser(closer io.Closer) {
c.mu.Lock()
defer c.mu.Unlock()
c.closers = append(c.closers, closer)
}
// GetTerm returns a Terminal.
func (c *ServerContext) GetTerm() Terminal {
c.mu.RLock()
defer c.mu.RUnlock()
return c.term
}
// SetTerm set a Terminal.
func (c *ServerContext) SetTerm(t Terminal) {
c.mu.Lock()
defer c.mu.Unlock()
c.term = t
}
// VisitEnv grants visitor-style access to env variables.
func (c *ServerContext) VisitEnv(visit func(key, val string)) {
c.mu.RLock()
defer c.mu.RUnlock()
// visit the parent env first since locally defined variables
// effectively "override" parent defined variables.
c.Parent().VisitEnv(visit)
for key, val := range c.env {
visit(key, val)
}
}
// SetEnv sets a environment variable within this context.
func (c *ServerContext) SetEnv(key, val string) {
c.mu.Lock()
c.env[key] = val
c.mu.Unlock()
}
// GetEnv returns a environment variable within this context.
func (c *ServerContext) GetEnv(key string) (string, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.getEnvLocked(key)
}
func (c *ServerContext) getEnvLocked(key string) (string, bool) {
val, ok := c.env[key]
if ok {
return val, true
}
return c.Parent().GetEnv(key)
}
// setSession sets the context's session
func (c *ServerContext) setSession(ctx context.Context, sess *session, ch ssh.Channel) {
c.mu.Lock()
defer c.mu.Unlock()
c.session = sess
// inform the client of the session ID that is being used in a new
// goroutine to reduce latency
go func() {
c.Logger.DebugContext(ctx, "Sending current session ID")
_, err := ch.SendRequest(teleport.CurrentSessionIDRequest, false, []byte(sess.ID()))
if err != nil {
c.Logger.DebugContext(ctx, "Failed to send the current session ID", "error", err)
}
}()
}
// getSession returns the context's session
func (c *ServerContext) getSession() *session {
c.mu.RLock()
defer c.mu.RUnlock()
return c.session
}
func (c *ServerContext) SetAllowFileCopying(allow bool) {
c.AllowFileCopying = allow
}
// CheckFileCopyingAllowed returns an error if remote file operations via
// SCP or SFTP are not allowed by the user's role or the node's config.
func (c *ServerContext) CheckFileCopyingAllowed() error {
// Check if remote file operations are disabled for this node.
if !c.AllowFileCopying {
return trace.Wrap(ErrNodeFileCopyingNotPermitted)
}
// Check if the user's RBAC role allows remote file operations.
if !c.Identity.AccessChecker.CanCopyFiles() {
return trace.Wrap(errRoleFileCopyingNotPermitted)
}
return nil
}
// CheckSFTPAllowed returns an error if remote file operations via SCP
// or SFTP are not allowed by the user's role or the node's config, or
// if the user is not allowed to start unattended sessions.
func (c *ServerContext) CheckSFTPAllowed(registry *SessionRegistry) error {
if err := c.CheckFileCopyingAllowed(); err != nil {
return trace.Wrap(err)
}
// ensure moderated session policies allow starting an unattended session
policySets := c.Identity.AccessChecker.SessionPolicySets()
checker := auth.NewSessionAccessEvaluator(policySets, types.SSHSessionKind, c.Identity.TeleportUser)
canStart, _, err := checker.FulfilledFor(nil)
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 {
return nil
}
if registry == nil {
return trace.Wrap(errCannotStartUnattendedSession)
}
approved, err := registry.isApprovedFileTransfer(c)
if err != nil {
return trace.Wrap(err)
}
if !approved {
return trace.Wrap(errCannotStartUnattendedSession)
}
return nil
}
// OpenXServerListener opens a new XServer unix listener.
func (c *ServerContext) HandleX11Listener(ctx context.Context, l net.Listener, singleConnection bool) error {
display, err := x11.ParseDisplayFromUnixSocket(l.Addr().String())
if err != nil {
return trace.Wrap(err)
}
c.Parent().SetEnv(x11.DisplayEnv, display.String())
// Prepare X11 channel request payload
originHost, originPort, err := net.SplitHostPort(c.ServerConn.LocalAddr().String())
if err != nil {
return trace.Wrap(err)
}
originPortI, err := strconv.Atoi(originPort)
if err != nil {
return trace.Wrap(err)
}
x11ChannelReqPayload := ssh.Marshal(x11.ChannelRequestPayload{
OriginatorAddress: originHost,
OriginatorPort: uint32(originPortI),
})
go func() {
for {
xconn, err := l.Accept()
if err != nil {
if !utils.IsOKNetworkError(err) {
c.Logger.DebugContext(ctx, "Encountered error accepting XServer connection", "error", err)
}
return
}
go func() {
defer xconn.Close()
xchan, sin, err := c.ServerConn.OpenChannel(x11.ChannelRequest, x11ChannelReqPayload)
if err != nil {
c.Logger.DebugContext(ctx, "Failed to open a new X11 channel", "error", err)
return
}
defer xchan.Close()
// Forward ssh requests on the X11 channels until X11 forwarding is complete
ctx, cancel := context.WithCancel(c.cancelContext)
defer cancel()
go func() {
err := sshutils.ForwardRequests(ctx, sin, c.RemoteSession)
if err != nil {
c.Logger.DebugContext(ctx, "Failed to forward ssh request from server during X11 forwarding", "error", err)
}
}()
if err := utils.ProxyConn(ctx, xconn, xchan); err != nil {
c.Logger.DebugContext(ctx, "Encountered error during X11 forwarding", "error", err)
}
}()
if singleConnection {
l.Close()
return
}
}
}()
return nil
}
// takeClosers returns all resources that should be closed and sets the properties to null
// we do this to avoid calling Close() under lock to avoid potential deadlocks
func (c *ServerContext) takeClosers() []io.Closer {
// this is done to avoid any operation holding the lock for too long
c.mu.Lock()
defer c.mu.Unlock()
closers := []io.Closer{}
if c.term != nil {
closers = append(closers, c.term)
c.term = nil
}
closers = append(closers, c.closers...)
c.closers = nil
return closers
}
// When the ServerContext (connection) is closed, emit "session.data" event
// containing how much data was transmitted and received over the net.Conn.
func (c *ServerContext) reportStats(conn utils.Stater) {
// We may not want to record session data for this connection context, e.g. if this is
// for a networking subprocess tied to a shell process.
if c.SessionRecordingConfig.GetMode() == types.RecordOff {
return
}
// Never emit session data events for the proxy or from a Teleport node if
// sessions are being recorded at the proxy (this would result in double
// events).
// Do not emit session data for git commands as they have their own events.
if c.GetServer().Component() == teleport.ComponentProxy ||
c.GetServer().Component() == teleport.ComponentForwardingGit {
return
}
if services.IsRecordAtProxy(c.SessionRecordingConfig.GetMode()) &&
c.GetServer().Component() == teleport.ComponentNode {
return
}
// Get the TX and RX bytes.
txBytes, rxBytes := conn.Stat()
// Build and emit session data event. Note that TX and RX are reversed
// below, that is because the connection is held from the perspective of
// the server not the client, but the logs are from the perspective of the
// client.
sessionDataEvent := &apievents.SessionData{
Metadata: apievents.Metadata{
Index: events.SessionDataIndex,
Type: events.SessionDataEvent,
Code: events.SessionDataCode,
},
ServerMetadata: c.srv.TargetMetadata(),
SessionMetadata: c.GetSessionMetadata(),
UserMetadata: c.Identity.GetUserMetadata(),
ConnectionMetadata: apievents.ConnectionMetadata{
RemoteAddr: c.ServerConn.RemoteAddr().String(),
},
BytesTransmitted: rxBytes,
BytesReceived: txBytes,
}
if !c.srv.UseTunnel() {
sessionDataEvent.ConnectionMetadata.LocalAddr = c.ServerConn.LocalAddr().String()
}
if err := c.GetServer().EmitAuditEvent(c.GetServer().Context(), sessionDataEvent); err != nil {
c.Logger.WarnContext(c.GetServer().Context(), "Failed to emit session data event", "error", err)
}
// Emit TX and RX bytes to their respective Prometheus counters.
serverTX.Add(float64(txBytes))
serverRX.Add(float64(rxBytes))
}
func (c *ServerContext) Close() error {
// If the underlying connection is holding tracking information, report that
// to the audit log at close.
if stats, ok := c.NetConn.(*utils.TrackingConn); ok {
defer c.reportStats(stats)
}
// Unblock any goroutines waiting until session is closed.
c.cancel()
// Close and release all resources.
err := closeAll(c.takeClosers()...)
if err != nil {
return trace.Wrap(err)
}
return nil
}
// CancelContext is a context associated with server context,
// closed whenever this server context is closed
func (c *ServerContext) CancelContext() context.Context {
return c.cancelContext
}
// CancelFunc gets the context.CancelFunc associated with
// this context. Not a substitute for calling the
// ServerContext.Close method.
func (c *ServerContext) CancelFunc() context.CancelFunc {
return c.cancel
}
// SendExecResult sends the result of execution of the "exec" command over the
// ExecResultCh.
func (c *ServerContext) SendExecResult(ctx context.Context, r ExecResult) {
select {
case c.ExecResultCh <- r:
default:
c.Logger.InfoContext(ctx, "Blocked on sending exec result", "code", r.Code, "command", r.Command)
}
}
// SendSubsystemResult sends the result of running the subsystem over the
// SubsystemResultCh.
func (c *ServerContext) SendSubsystemResult(ctx context.Context, r SubsystemResult) {
select {
case c.SubsystemResultCh <- r:
default:
c.Logger.InfoContext(ctx, "Blocked on sending subsystem result")
}
}
func (c *ServerContext) String() string {
return fmt.Sprintf("ServerContext(%v->%v, user=%v, id=%v)", c.ServerConn.RemoteAddr(), c.ServerConn.LocalAddr(), c.ServerConn.User(), c.id)
}
func (c *ServerContext) LogValue() slog.Value {
return slog.GroupValue(
slog.String("remote_addr", c.ServerConn.RemoteAddr().String()),
slog.String("local_addr", c.ServerConn.LocalAddr().String()),
slog.String("user", c.ServerConn.User()),
slog.Int("id", c.id),
)
}
func getPAMConfig(c *ServerContext) (*PAMConfig, error) {
// PAM should be disabled.
if c.srv.Component() != teleport.ComponentNode {
return nil, nil
}
localPAMConfig, err := c.srv.GetPAM()
if err != nil {
return nil, trace.Wrap(err)
}
// We use nil/empty to figure out if PAM is disabled later.
if !localPAMConfig.Enabled {
return nil, nil
}
// If the identity has roles, extract the role names.
roleNames := c.Identity.AccessChecker.RoleNames()
// Fill in the environment variables from the config and interpolate them if needed.
environment := make(map[string]string)
environment["TELEPORT_USERNAME"] = c.Identity.TeleportUser
environment["TELEPORT_LOGIN"] = c.Identity.Login
environment["TELEPORT_ROLES"] = strings.Join(roleNames, " ")
if localPAMConfig.Environment != nil {
for key, value := range localPAMConfig.Environment {
expr, err := parse.NewTraitsTemplateExpression(value)
if err != nil {
return nil, trace.Wrap(err)
}
varValidation := func(namespace, name string) error {
if namespace != teleport.TraitExternalPrefix {
return trace.BadParameter("PAM environment interpolation only supports external traits, found %q", value)
}
return nil
}
result, err := expr.Interpolate(varValidation, c.Identity.UnmappedIdentity.Traits)
if err != nil {
// If the trait isn't passed by the IdP due to misconfiguration
// we fallback to setting a value which will indicate this.
if trace.IsNotFound(err) {
c.Logger.WarnContext(
c.CancelContext(),
"Attempted to interpolate custom PAM environment with external trait but received SAML response does not contain claim",
"error", err,
)