-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
terminal.go
1123 lines (943 loc) · 34.7 KB
/
terminal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2015 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package web
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/gogo/protobuf/proto"
"github.com/gorilla/websocket"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
oteltrace "go.opentelemetry.io/otel/trace"
"golang.org/x/crypto/ssh"
"golang.org/x/text/encoding"
"golang.org/x/text/encoding/unicode"
"github.com/gravitational/teleport"
authproto "github.com/gravitational/teleport/api/client/proto"
apidefaults "github.com/gravitational/teleport/api/defaults"
"github.com/gravitational/teleport/api/observability/tracing"
tracessh "github.com/gravitational/teleport/api/observability/tracing/ssh"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/api/utils/keys"
wanlib "github.com/gravitational/teleport/lib/auth/webauthn"
"github.com/gravitational/teleport/lib/client"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/modules"
"github.com/gravitational/teleport/lib/multiplexer"
"github.com/gravitational/teleport/lib/proxy"
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/teleagent"
"github.com/gravitational/teleport/lib/utils"
)
// TerminalRequest describes a request to create a web-based terminal
// to a remote SSH server.
type TerminalRequest struct {
// Server describes a server to connect to (serverId|hostname[:port]).
Server string `json:"server_id"`
// Login is Linux username to connect as.
Login string `json:"login"`
// Term is the initial PTY size.
Term session.TerminalParams `json:"term"`
// SessionID is a Teleport session ID to join as.
SessionID session.ID `json:"sid"`
// ProxyHostPort is the address of the server to connect to.
ProxyHostPort string `json:"-"`
// InteractiveCommand is a command to execute
InteractiveCommand []string `json:"-"`
// KeepAliveInterval is the interval for sending ping frames to web client.
// This value is pulled from the cluster network config and
// guaranteed to be set to a nonzero value as it's enforced by the configuration.
KeepAliveInterval time.Duration
// ParticipantMode is the mode that determines what you can do when you join an active session.
ParticipantMode types.SessionParticipantMode `json:"mode"`
}
// AuthProvider is a subset of the full Auth API.
type AuthProvider interface {
GetNodes(ctx context.Context, namespace string) ([]types.Server, error)
GetSessionEvents(namespace string, sid session.ID, after int, includePrintEvents bool) ([]events.EventFields, error)
GetSessionTracker(ctx context.Context, sessionID string) (types.SessionTracker, error)
IsMFARequired(ctx context.Context, req *authproto.IsMFARequiredRequest) (*authproto.IsMFARequiredResponse, error)
GenerateUserSingleUseCerts(ctx context.Context) (authproto.AuthService_GenerateUserSingleUseCertsClient, error)
}
// NewTerminal creates a web-based terminal based on WebSockets and returns a
// new TerminalHandler.
func NewTerminal(ctx context.Context, cfg TerminalHandlerConfig) (*TerminalHandler, error) {
err := cfg.CheckAndSetDefaults()
if err != nil {
return nil, trace.Wrap(err)
}
_, span := cfg.tracer.Start(ctx, "NewTerminal")
defer span.End()
return &TerminalHandler{
log: logrus.WithFields(logrus.Fields{
trace.Component: teleport.ComponentWebsocket,
"session_id": cfg.SessionData.ID.String(),
}),
ctx: cfg.SessionCtx,
authProvider: cfg.AuthProvider,
displayLogin: cfg.DisplayLogin,
sessionData: cfg.SessionData,
keepAliveInterval: cfg.KeepAliveInterval,
proxyHostPort: cfg.ProxyHostPort,
interactiveCommand: cfg.InteractiveCommand,
term: cfg.Term,
router: cfg.Router,
proxySigner: cfg.PROXYSigner,
tracer: cfg.tracer,
participantMode: cfg.ParticipantMode,
}, nil
}
// TerminalHandlerConfig contains the configuration options necessary to
// correctly setup the TerminalHandler
type TerminalHandlerConfig struct {
// term is the initial PTY size.
Term session.TerminalParams
// sctx is the context for the users web session.
SessionCtx *SessionContext
// authProvider is used to fetch nodes and sessions from the backend.
AuthProvider AuthProvider
// displayLogin is the login name to display in the UI.
DisplayLogin string
// sessionData is the data to send to the client on the initial session creation.
SessionData session.Session
// keepAliveInterval is the interval for sending ping frames to web client.
// This value is pulled from the cluster network config and
// guaranteed to be set to a nonzero value as it's enforced by the configuration.
KeepAliveInterval time.Duration
// proxyHostPort is the address of the server to connect to.
ProxyHostPort string
// interactiveCommand is a command to execute.
InteractiveCommand []string
// Router determines how connections to nodes are created
Router *proxy.Router
// TracerProvider is used to create the tracer
TracerProvider oteltrace.TracerProvider
// ProxySigner is used to sign PROXY header and securely propagate client IP information
PROXYSigner multiplexer.PROXYHeaderSigner
// tracer is used to create spans
tracer oteltrace.Tracer
// ParticipantMode is the mode that determines what you can do when you join an active session.
ParticipantMode types.SessionParticipantMode
}
func (t *TerminalHandlerConfig) CheckAndSetDefaults() error {
// Make sure whatever session is requested is a valid session id.
_, err := session.ParseID(t.SessionData.ID.String())
if err != nil {
return trace.BadParameter("sid: invalid session id")
}
if t.SessionData.Login == "" {
return trace.BadParameter("login: missing login")
}
if t.SessionData.ServerID == "" {
return trace.BadParameter("server: missing server")
}
if t.Term.W <= 0 || t.Term.H <= 0 ||
t.Term.W >= 4096 || t.Term.H >= 4096 {
return trace.BadParameter("term: bad dimensions(%dx%d)", t.Term.W, t.Term.H)
}
if t.AuthProvider == nil {
return trace.BadParameter("AuthProvider must be provided")
}
if t.SessionCtx == nil {
return trace.BadParameter("SessionCtx must be provided")
}
if t.Router == nil {
return trace.BadParameter("Router must be provided")
}
if t.TracerProvider == nil {
t.TracerProvider = tracing.DefaultProvider()
}
t.tracer = t.TracerProvider.Tracer("webterminal")
return nil
}
// TerminalHandler connects together an SSH session with a web-based
// terminal via a web socket.
type TerminalHandler struct {
// log holds the structured logger.
log *logrus.Entry
// ctx is a web session context for the currently logged in user.
ctx *SessionContext
// displayLogin is the login name to display in the UI.
displayLogin string
// sshSession holds the "shell" SSH channel to the node.
sshSession *tracessh.Session
// terminalContext is used to signal when the terminal sesson is closing.
terminalContext context.Context
// terminalCancel is used to signal when the terminal session is closing.
terminalCancel context.CancelFunc
// authProvider is used to fetch nodes and sessions from the backend.
authProvider AuthProvider
closeOnce sync.Once
// keepAliveInterval is the interval for sending ping frames to web client.
// This value is pulled from the cluster network config and
// guaranteed to be set to a nonzero value as it's enforced by the configuration.
keepAliveInterval time.Duration
// proxyHostPort is the address of the server to connect to.
proxyHostPort string
// interactiveCommand is a command to execute.
interactiveCommand []string
// term is the initial PTY size.
term session.TerminalParams
// The server data for the active session.
sessionData session.Session
// router is used to dial the host
router *proxy.Router
// proxySigner is used to sign PROXY header and securely propagate client IP information
proxySigner multiplexer.PROXYHeaderSigner
// tracer creates spans
tracer oteltrace.Tracer
// participantMode is the mode that determines what you can do when you join an active session.
participantMode types.SessionParticipantMode
// stream manages sending and receiving [Envelope] to the UI
// for the duration of the session
stream *TerminalStream
}
// ServeHTTP builds a connection to the remote node and then pumps back two types of
// events: raw input/output events for what's happening on the terminal itself
// and audit log events relevant to this session.
func (t *TerminalHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// This allows closing of the websocket if the user logs out before exiting
// the session.
t.ctx.AddClosers(t)
defer t.ctx.RemoveCloser(t)
upgrader := websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
errMsg := "Error upgrading to websocket"
t.log.WithError(err).Error(errMsg)
http.Error(w, errMsg, http.StatusInternalServerError)
return
}
err = ws.SetReadDeadline(deadlineForInterval(t.keepAliveInterval))
if err != nil {
t.log.WithError(err).Error("Error setting websocket readline")
return
}
sendError := func(errMsg string, err error, ws *websocket.Conn) {
envelope := &Envelope{
Version: defaults.WebsocketVersion,
Type: defaults.WebsocketError,
Payload: fmt.Sprintf("%s: %s", errMsg, err.Error()),
}
envelopeBytes, _ := proto.Marshal(envelope)
ws.WriteMessage(websocket.BinaryMessage, envelopeBytes)
}
var sessionMetadataResponse []byte
// If the displayLogin is set then use it in the session metadata instead of the
// login name used in the SSH connection. This is specifically for the use case
// when joining a session to avoid displaying "-teleport-internal-join" as the username.
if t.displayLogin != "" {
sessionDataTemp := t.sessionData
sessionDataTemp.Login = t.displayLogin
sessionMetadataResponse, err = json.Marshal(siteSessionGenerateResponse{Session: sessionDataTemp})
} else {
sessionMetadataResponse, err = json.Marshal(siteSessionGenerateResponse{Session: t.sessionData})
}
if err != nil {
sendError("unable to marshal session response", err, ws)
return
}
envelope := &Envelope{
Version: defaults.WebsocketVersion,
Type: defaults.WebsocketSessionMetadata,
Payload: string(sessionMetadataResponse),
}
envelopeBytes, err := proto.Marshal(envelope)
if err != nil {
sendError("unable to marshal session data event for web client", err, ws)
return
}
err = ws.WriteMessage(websocket.BinaryMessage, envelopeBytes)
if err != nil {
sendError("unable to write message to socket", err, ws)
return
}
t.handler(ws, r)
}
// Close the websocket stream.
func (t *TerminalHandler) Close() error {
t.closeOnce.Do(func() {
// Close the SSH connection to the remote node.
if t.sshSession != nil {
t.sshSession.Close()
}
// If the terminal handler was closed (most likely due to the *SessionContext
// closing) then the stream should be closed as well.
t.terminalCancel()
})
return nil
}
// startPingLoop starts a loop that will continuously send a ping frame through the websocket
// to prevent the connection between web client and teleport proxy from becoming idle.
// Interval is determined by the keep_alive_interval config set by user (or default).
// Loop will terminate when there is an error sending ping frame or when terminal session is closed.
func (t *TerminalHandler) startPingLoop(ws *websocket.Conn) {
t.log.Debugf("Starting websocket ping loop with interval %v.", t.keepAliveInterval)
tickerCh := time.NewTicker(t.keepAliveInterval)
defer tickerCh.Stop()
for {
select {
case <-tickerCh.C:
// A short deadline is used here to detect a broken connection quickly.
// If this is just a temporary issue, we will retry shortly anyway.
deadline := time.Now().Add(time.Second)
if err := ws.WriteControl(websocket.PingMessage, nil, deadline); err != nil {
t.log.WithError(err).Error("Unable to send ping frame to web client")
t.Close()
return
}
case <-t.terminalContext.Done():
t.log.Debug("Terminating websocket ping loop.")
return
}
}
}
// handler is the main websocket loop. It creates a Teleport client and then
// pumps raw events and audit events back to the client until the SSH session
// is complete.
func (t *TerminalHandler) handler(ws *websocket.Conn, r *http.Request) {
defer ws.Close()
// Create a terminal stream that wraps/unwraps the envelope used to
// communicate over the websocket.
resizeC := make(chan *session.TerminalParams, 1)
stream, err := NewTerminalStream(ws, WithTerminalStreamResizeHandler(resizeC))
if err != nil {
t.log.WithError(err).Info("Failed creating a terminal stream for session")
t.writeError(err)
return
}
t.stream = stream
// Create a context for signaling when the terminal session is over and
// link it first with the trace context from the request context
tctx := oteltrace.ContextWithRemoteSpanContext(context.Background(), oteltrace.SpanContextFromContext(r.Context()))
t.terminalContext, t.terminalCancel = context.WithCancel(tctx)
// Create a Teleport client, if not able to, show the reason to the user in
// the terminal.
tc, err := t.makeClient(r.Context(), ws)
if err != nil {
t.log.WithError(err).Info("Failed creating a client for session")
t.writeError(err)
return
}
t.log.Debug("Creating websocket stream")
// Update the read deadline upon receiving a pong message.
ws.SetPongHandler(func(_ string) error {
ws.SetReadDeadline(deadlineForInterval(t.keepAliveInterval))
return nil
})
// Start sending ping frames through websocket to client.
go t.startPingLoop(ws)
// Pump raw terminal in/out and audit events into the websocket.
go t.streamTerminal(ws, tc)
go t.streamEvents(tc)
// process window resizing
go t.handleWindowResize(resizeC)
// Block until the terminal session is complete.
<-t.terminalContext.Done()
t.log.Debug("Closing websocket stream")
}
// makeClient builds a *client.TeleportClient for the connection.
func (t *TerminalHandler) makeClient(ctx context.Context, ws *websocket.Conn) (*client.TeleportClient, error) {
ctx, span := tracing.DefaultProvider().Tracer("terminal").Start(ctx, "terminal/makeClient")
defer span.End()
clientConfig, err := makeTeleportClientConfig(ctx, t.ctx)
if err != nil {
return nil, trace.Wrap(err)
}
clientConfig.HostLogin = t.sessionData.Login
clientConfig.ForwardAgent = client.ForwardAgentLocal
clientConfig.Namespace = apidefaults.Namespace
clientConfig.Stdout = t.stream
clientConfig.Stderr = t.stream
clientConfig.Stdin = t.stream
clientConfig.SiteName = t.sessionData.ClusterName
if err := clientConfig.ParseProxyHost(t.proxyHostPort); err != nil {
return nil, trace.BadParameter("failed to parse proxy address: %v", err)
}
clientConfig.Host = t.sessionData.ServerHostname
clientConfig.HostPort = t.sessionData.ServerHostPort
clientConfig.SessionID = t.sessionData.ID.String()
clientConfig.ClientAddr = ws.RemoteAddr().String()
clientConfig.Tracer = t.tracer
if len(t.interactiveCommand) > 0 {
clientConfig.InteractiveCommand = true
}
tc, err := client.NewClient(clientConfig)
if err != nil {
return nil, trace.BadParameter("failed to create client: %v", err)
}
// Save the *ssh.Session after the shell has been created. The session is
// used to update all other parties window size to that of the web client and
// to allow future window changes.
tc.OnShellCreated = func(s *tracessh.Session, c *tracessh.Client, _ io.ReadWriteCloser) (bool, error) {
t.sshSession = s
t.windowChange(ctx, &t.term)
return false, nil
}
return tc, nil
}
// issueSessionMFACerts performs the mfa ceremony to retrieve new certs that can be
// used to access nodes which require per-session mfa. The ceremony is performed directly
// to make use of the authProvider already established for the session instead of leveraging
// the TeleportClient which would require dialing the auth server a second time.
func (t *TerminalHandler) issueSessionMFACerts(ctx context.Context, tc *client.TeleportClient) error {
ctx, span := t.tracer.Start(ctx, "terminal/issueSessionMFACerts")
defer span.End()
// Always acquire single-use certificates from the root cluster, that's where
// both the user and their devices are registered.
log.Debug("Attempting to issue a single-use user certificate with an MFA check.")
stream, err := t.ctx.cfg.RootClient.GenerateUserSingleUseCerts(ctx)
if err != nil {
return trace.Wrap(err)
}
defer func() {
stream.CloseSend()
stream.Recv()
}()
pk, err := keys.ParsePrivateKey(t.ctx.cfg.Session.GetPriv())
if err != nil {
return trace.Wrap(err)
}
key := &client.Key{
PrivateKey: pk,
Cert: t.ctx.cfg.Session.GetPub(),
TLSCert: t.ctx.cfg.Session.GetTLSCert(),
}
tlsCert, err := key.TeleportTLSCertificate()
if err != nil {
return trace.Wrap(err)
}
if err := stream.Send(
&authproto.UserSingleUseCertsRequest{
Request: &authproto.UserSingleUseCertsRequest_Init{
Init: &authproto.UserCertsRequest{
PublicKey: key.MarshalSSHPublicKey(),
Username: tlsCert.Subject.CommonName,
Expires: tlsCert.NotAfter,
RouteToCluster: t.sessionData.ClusterName,
NodeName: t.sessionData.ServerID,
Usage: authproto.UserCertsRequest_SSH,
Format: tc.CertificateFormat,
},
},
}); err != nil {
return trace.Wrap(err)
}
resp, err := stream.Recv()
if err != nil {
return trace.Wrap(err)
}
challenge := resp.GetMFAChallenge()
if challenge == nil {
return trace.BadParameter("server sent a %T on GenerateUserSingleUseCerts, expected MFAChallenge", resp.Response)
}
span.AddEvent("prompting user with mfa challenge")
assertion, err := promptMFAChallenge(t.stream, protobufMFACodec{})(ctx, tc.WebProxyAddr, challenge)
if err != nil {
return trace.Wrap(err)
}
span.AddEvent("user completed mfa challenge")
err = stream.Send(&authproto.UserSingleUseCertsRequest{Request: &authproto.UserSingleUseCertsRequest_MFAResponse{MFAResponse: assertion}})
if err != nil {
return trace.Wrap(err)
}
resp, err = stream.Recv()
if err != nil {
return trace.Wrap(err)
}
certResp := resp.GetCert()
if certResp == nil {
return trace.BadParameter("server sent a %T on GenerateUserSingleUseCerts, expected SingleUseUserCert", resp.Response)
}
switch crt := certResp.Cert.(type) {
case *authproto.SingleUseUserCert_SSH:
key.Cert = crt.SSH
default:
return trace.BadParameter("server sent a %T SingleUseUserCert in response", certResp.Cert)
}
key.ClusterName = t.sessionData.ClusterName
am, err := key.AsAuthMethod()
if err != nil {
return trace.Wrap(err)
}
tc.AuthMethods = []ssh.AuthMethod{am}
return nil
}
func promptMFAChallenge(
stream *TerminalStream,
codec mfaCodec,
) client.PromptMFAChallengeHandler {
return func(ctx context.Context, proxyAddr string, c *authproto.MFAAuthenticateChallenge) (*authproto.MFAAuthenticateResponse, error) {
var challenge *client.MFAAuthenticateChallenge
// Convert from proto to JSON types.
switch {
case c.GetWebauthnChallenge() != nil:
challenge = &client.MFAAuthenticateChallenge{
WebauthnChallenge: wanlib.CredentialAssertionFromProto(c.WebauthnChallenge),
}
default:
return nil, trace.AccessDenied("only hardware keys are supported on the web terminal, please register a hardware device to connect to this server")
}
if err := stream.writeChallenge(challenge, codec); err != nil {
return nil, trace.Wrap(err)
}
resp, err := stream.readChallenge(codec)
return resp, trace.Wrap(err)
}
}
// streamTerminal opens a SSH connection to the remote host and streams
// events back to the web client.
func (t *TerminalHandler) streamTerminal(ws *websocket.Conn, tc *client.TeleportClient) {
ctx, span := t.tracer.Start(t.terminalContext, "terminal/streamTerminal")
defer span.End()
defer t.terminalCancel()
accessChecker, err := t.ctx.GetUserAccessChecker()
if err != nil {
t.log.WithError(err).Warn("Unable to stream terminal - failed to get access checker")
t.writeError(err)
return
}
agentGetter := func() (teleagent.Agent, error) {
return teleagent.NopCloser(tc.LocalAgent()), nil
}
conn, _, err := t.router.DialHost(ctx, ws.RemoteAddr(), ws.LocalAddr(), t.sessionData.ServerID, strconv.Itoa(t.sessionData.ServerHostPort), tc.SiteName, accessChecker, agentGetter)
if err != nil {
t.log.WithError(err).Warn("Unable to stream terminal - failed to dial host.")
if errors.Is(err, trace.NotFound(teleport.NodeIsAmbiguous)) {
const message = "error: ambiguous host could match multiple nodes\n\nHint: try addressing the node by unique id (ex: user@node-id)\n"
t.writeError(trace.NotFound(message))
return
}
t.writeError(err)
return
}
defer func() {
if conn == nil {
return
}
if err := conn.Close(); err != nil && !utils.IsUseOfClosedNetworkError(err) {
t.log.WithError(err).Warn("Failed to close connection to host")
}
}()
sshConfig := &ssh.ClientConfig{
User: tc.HostLogin,
Auth: tc.AuthMethods,
HostKeyCallback: tc.HostKeyCallback,
}
nc, connectErr := client.NewNodeClient(ctx, sshConfig, conn, net.JoinHostPort(t.sessionData.ServerID, strconv.Itoa(t.sessionData.ServerHostPort)), tc, modules.GetModules().IsBoringBinary())
switch {
case connectErr != nil && !trace.IsAccessDenied(connectErr): // catastrophic error, return it
t.log.WithError(connectErr).Warn("Unable to stream terminal - failed to create node client")
t.writeError(connectErr)
return
case connectErr != nil && trace.IsAccessDenied(connectErr): // see if per session mfa would allow access
mfaRequiredResp, err := t.authProvider.IsMFARequired(ctx, &authproto.IsMFARequiredRequest{
Target: &authproto.IsMFARequiredRequest_Node{
Node: &authproto.NodeLogin{
Node: t.sessionData.ServerID,
Login: tc.HostLogin,
},
},
})
if err != nil {
t.log.WithError(err).Warn("Unable to stream terminal - failed to determine if per session mfa is required")
// write the original connect error
t.writeError(connectErr)
return
}
if !mfaRequiredResp.Required {
t.log.WithError(connectErr).Warn("Unable to stream terminal - user does not have access to host")
// write the original connect error
t.writeError(connectErr)
return
}
// perform mfa ceremony and retrieve new certs
if err := t.issueSessionMFACerts(ctx, tc); err != nil {
t.log.WithError(err).Warn("Unable to stream terminal - failed to perform mfa ceremony")
t.writeError(err)
return
}
// update auth methods
sshConfig.Auth = tc.AuthMethods
// connect to the node again with the new certs
conn, _, err = t.router.DialHost(ctx, ws.RemoteAddr(), ws.LocalAddr(), t.sessionData.ServerID, strconv.Itoa(t.sessionData.ServerHostPort), tc.SiteName, accessChecker, agentGetter)
if err != nil {
t.log.WithError(err).Warn("Unable to stream terminal - failed to dial host")
t.writeError(err)
return
}
nc, err = client.NewNodeClient(ctx, sshConfig, conn, net.JoinHostPort(t.sessionData.ServerID, strconv.Itoa(t.sessionData.ServerHostPort)), tc, modules.GetModules().IsBoringBinary())
if err != nil {
t.log.WithError(err).Warn("Unable to stream terminal - failed to create node client")
t.writeError(err)
return
}
}
// Establish SSH connection to the server. This function will block until
// either an error occurs or it completes successfully.
if err = nc.RunInteractiveShell(ctx, t.participantMode, nil); err != nil {
t.log.WithError(err).Warn("Unable to stream terminal - failure running interactive shell")
t.writeError(err)
return
}
if err := t.stream.Close(); err != nil {
t.log.WithError(err).Error("Unable to send close event to web client.")
return
}
t.log.Debug("Sent close event to web client.")
}
// streamEvents receives events over the SSH connection and forwards them to
// the web client.
func (t *TerminalHandler) streamEvents(tc *client.TeleportClient) {
for {
select {
// Send push events that come over the events channel to the web client.
case event := <-tc.EventsChannel():
logger := t.log.WithField("event", event.GetType())
data, err := json.Marshal(event)
if err != nil {
logger.WithError(err).Error("Unable to marshal audit event")
continue
}
logger.Debug("Sending audit event to web client.")
if err := t.stream.writeAuditEvent(data); err != nil {
if err != nil {
if errors.Is(err, websocket.ErrCloseSent) {
logger.WithError(err).Debug("Websocket was closed, no longer streaming events")
return
}
logger.WithError(err).Error("Unable to send audit event to web client")
continue
}
}
// Once the terminal stream is over (and the close envelope has been sent),
// close stop streaming envelopes.
case <-t.terminalContext.Done():
return
}
}
}
// handleWindowResize receives window resize events and forwards
// them to the SSH session.
func (t *TerminalHandler) handleWindowResize(resizeC <-chan *session.TerminalParams) {
for {
select {
case <-t.terminalContext.Done():
return
case params := <-resizeC:
// nil params indicates the channel was closed
if params == nil {
return
}
// process window change
t.windowChange(t.terminalContext, params)
}
}
}
// writeError displays an error in the terminal window.
func (t *TerminalHandler) windowChange(ctx context.Context, params *session.TerminalParams) {
if t.sshSession == nil {
return
}
if err := t.sshSession.WindowChange(ctx, params.H, params.W); err != nil {
t.log.Error(err)
}
}
// writeError displays an error in the terminal window.
func (t *TerminalHandler) writeError(err error) {
if writeErr := t.stream.writeError(err); writeErr != nil {
t.log.WithError(writeErr).Warnf("Unable to send error to terminal: %v", err)
}
}
// the defaultPort of 0 indicates that the port is
// unknown or was not provided and should be guessed
const defaultPort = 0
// resolveServerHostPort parses server name and attempts to resolve hostname
// and port.
func resolveServerHostPort(servername string, existingServers []types.Server) (string, int, error) {
if servername == "" {
return "", defaultPort, trace.BadParameter("empty server name")
}
// Check if servername is UUID.
for _, node := range existingServers {
if node.GetName() == servername {
return node.GetHostname(), defaultPort, nil
}
}
host, port, err := serverHostPort(servername)
return host, port, trace.Wrap(err)
}
// serverHostPort returns the host and port for [servername]
func serverHostPort(servername string) (string, int, error) {
if !strings.Contains(servername, ":") {
return servername, defaultPort, nil
}
// Check for explicitly specified port.
host, portString, err := utils.SplitHostPort(servername)
if err != nil {
return "", defaultPort, trace.Wrap(err)
}
port, err := strconv.Atoi(portString)
if err != nil {
return "", defaultPort, trace.BadParameter("invalid port: %v", err)
}
return host, port, nil
}
// WithTerminalStreamEncoder overrides the default stream encoder
func WithTerminalStreamEncoder(enc *encoding.Encoder) func(stream *TerminalStream) {
return func(stream *TerminalStream) {
stream.encoder = enc
}
}
// WithTerminalStreamDecoder overrides the default stream decoder
func WithTerminalStreamDecoder(dec *encoding.Decoder) func(stream *TerminalStream) {
return func(stream *TerminalStream) {
stream.decoder = dec
}
}
// WithTerminalStreamResizeHandler provides a channel to subscribe to
// terminal resize events
func WithTerminalStreamResizeHandler(resizeC chan<- *session.TerminalParams) func(stream *TerminalStream) {
return func(stream *TerminalStream) {
stream.resizeC = resizeC
}
}
// NewTerminalStream creates a stream that manages reading and writing
// data over the provided [websocket.Conn]
func NewTerminalStream(ws *websocket.Conn, opts ...func(*TerminalStream)) (*TerminalStream, error) {
switch {
case ws == nil:
return nil, trace.BadParameter("required parameter ws not provided")
}
t := &TerminalStream{
ws: ws,
encoder: unicode.UTF8.NewEncoder(),
decoder: unicode.UTF8.NewDecoder(),
}
for _, opt := range opts {
opt(t)
}
return t, nil
}
// TerminalStream manages the [websocket.Conn] to the web UI
// for a terminal session.
type TerminalStream struct {
// encoder is used to encode UTF-8 strings.
encoder *encoding.Encoder
// decoder is used to decode UTF-8 strings.
decoder *encoding.Decoder
// buffer is a buffer used to store the remaining payload data if it did not
// fit into the buffer provided by the callee to Read method
buffer []byte
// once ensures that resizeC is closed at most one time
once sync.Once
// resizeC a channel to forward resize events so that
// they happen out of band and don't block reads
resizeC chan<- *session.TerminalParams
// mu protects writes to ws
mu sync.Mutex
// ws the connection to the UI
ws *websocket.Conn
}
// Replace \n with \r\n so the message is correctly aligned.
var replacer = strings.NewReplacer("\r\n", "\r\n", "\n", "\r\n")
// writeError displays an error in the terminal window.
func (t *TerminalStream) writeError(err error) error {
_, writeErr := replacer.WriteString(t, err.Error())
return trace.Wrap(writeErr)
}
// writeChallenge encodes and writes the challenge to the
// websocket in the correct format.
func (t *TerminalStream) writeChallenge(challenge *client.MFAAuthenticateChallenge, codec mfaCodec) error {
// Send the challenge over the socket.
msg, err := codec.encode(challenge, defaults.WebsocketWebauthnChallenge)
if err != nil {
return trace.Wrap(err)
}
t.mu.Lock()
defer t.mu.Unlock()
return trace.Wrap(t.ws.WriteMessage(websocket.BinaryMessage, msg))
}
// readChallenge reads and decodes the challenge response from the
// websocket in the correct format.
func (t *TerminalStream) readChallenge(codec mfaCodec) (*authproto.MFAAuthenticateResponse, error) {
// Read the challenge response.
ty, bytes, err := t.ws.ReadMessage()
if err != nil {
return nil, trace.Wrap(err)
}
if ty != websocket.BinaryMessage {
return nil, trace.BadParameter("expected websocket.BinaryMessage, got %v", ty)
}
resp, err := codec.decode(bytes, defaults.WebsocketWebauthnChallenge)
return resp, trace.Wrap(err)
}
// writeAuditEvent encodes and writes the audit event to the
// websocket in the correct format.
func (t *TerminalStream) writeAuditEvent(event []byte) error {
// UTF-8 encode the error message and then wrap it in a raw envelope.
encodedPayload, err := t.encoder.String(string(event))
if err != nil {
return trace.Wrap(err)
}
envelope := &Envelope{
Version: defaults.WebsocketVersion,
Type: defaults.WebsocketAudit,
Payload: encodedPayload,
}
envelopeBytes, err := proto.Marshal(envelope)
if err != nil {
return trace.Wrap(err)
}
// Send bytes over the websocket to the web client.
t.mu.Lock()
defer t.mu.Unlock()
return trace.Wrap(t.ws.WriteMessage(websocket.BinaryMessage, envelopeBytes))
}
// Write wraps the data bytes in a raw envelope and sends.
func (t *TerminalStream) Write(data []byte) (n int, err error) {
// UTF-8 encode data and wrap it in a raw envelope.
encodedPayload, err := t.encoder.String(string(data))
if err != nil {
return 0, trace.Wrap(err)
}
envelope := &Envelope{
Version: defaults.WebsocketVersion,
Type: defaults.WebsocketRaw,
Payload: encodedPayload,
}
envelopeBytes, err := proto.Marshal(envelope)
if err != nil {
return 0, trace.Wrap(err)
}