-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
server.go
1140 lines (984 loc) · 34.6 KB
/
server.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 2020 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package app runs the application proxy process. It keeps dynamic labels
// updated, heart beats its presence, checks access controls, and forwards
// connections between the tunnel and the target host.
package app
import (
"context"
"crypto/tls"
"errors"
"net"
"net/http"
"strconv"
"sync"
"time"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/sirupsen/logrus"
"github.com/gravitational/teleport"
apidefaults "github.com/gravitational/teleport/api/defaults"
"github.com/gravitational/teleport/api/types"
"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/authz"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/httplib"
"github.com/gravitational/teleport/lib/labels"
"github.com/gravitational/teleport/lib/reversetunnel"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/srv"
appaws "github.com/gravitational/teleport/lib/srv/app/aws"
appazure "github.com/gravitational/teleport/lib/srv/app/azure"
"github.com/gravitational/teleport/lib/srv/app/common"
appgcp "github.com/gravitational/teleport/lib/srv/app/gcp"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
awsutils "github.com/gravitational/teleport/lib/utils/aws"
)
type appServerContextKey string
const (
connContextKey appServerContextKey = "teleport-connContextKey"
)
// ConnMonitor monitors authorized connections and terminates them when
// session controls dictate so.
type ConnMonitor interface {
MonitorConn(ctx context.Context, authzCtx *authz.Context, conn net.Conn) (context.Context, net.Conn, error)
}
// Config is the configuration for an application server.
type Config struct {
// Clock is used to control time.
Clock clockwork.Clock
// DataDir is the path to the data directory for the server.
DataDir string
// AuthClient is a client directly connected to the Auth server.
AuthClient *auth.Client
// AccessPoint is a caching client connected to the Auth Server.
AccessPoint auth.AppsAccessPoint
// TLSConfig is the *tls.Config for this server.
TLSConfig *tls.Config
// CipherSuites is the list of TLS cipher suites that have been configured
// for this process.
CipherSuites []uint16
// Hostname is the hostname where this application agent is running.
Hostname string
// HostID is the id of the host where this application agent is running.
HostID string
// Authorizer is used to authorize requests.
Authorizer authz.Authorizer
// GetRotation returns the certificate rotation state.
GetRotation services.RotationGetter
// Apps is a list of statically registered apps this agent proxies.
Apps types.Apps
// CloudLabels is a service that imports labels from a cloud provider. The labels are shared
// between all apps.
CloudLabels labels.Importer
// OnHeartbeat is called after every heartbeat. Used to update process state.
OnHeartbeat func(error)
// Cloud provides cloud provider access related functionality.
Cloud Cloud
// ResourceMatchers is a list of app resource matchers.
ResourceMatchers []services.ResourceMatcher
// OnReconcile is called after each database resource reconciliation.
OnReconcile func(types.Apps)
// ConnectedProxyGetter gets the proxies teleport is connected to.
ConnectedProxyGetter *reversetunnel.ConnectedProxyGetter
// Emitter is an event emitter.
Emitter events.Emitter
// ConnectionMonitor monitors connections and terminates any if
// any session controls prevent them.
ConnectionMonitor ConnMonitor
}
// CheckAndSetDefaults makes sure the configuration has the minimum required
// to function.
func (c *Config) CheckAndSetDefaults() error {
if c.Clock == nil {
c.Clock = clockwork.NewRealClock()
}
if c.DataDir == "" {
return trace.BadParameter("data dir missing")
}
if c.AuthClient == nil {
return trace.BadParameter("auth client log missing")
}
if c.AccessPoint == nil {
return trace.BadParameter("access point missing")
}
if c.TLSConfig == nil {
return trace.BadParameter("tls config missing")
}
if len(c.CipherSuites) == 0 {
return trace.BadParameter("ciphersuites missing")
}
if c.Hostname == "" {
return trace.BadParameter("hostname missing")
}
if c.HostID == "" {
return trace.BadParameter("host id missing")
}
if c.Authorizer == nil {
return trace.BadParameter("authorizer missing")
}
if c.GetRotation == nil {
return trace.BadParameter("rotation getter missing")
}
if c.OnHeartbeat == nil {
return trace.BadParameter("heartbeat missing")
}
if c.Cloud == nil {
cloud, err := NewCloud(CloudConfig{})
if err != nil {
return trace.Wrap(err)
}
c.Cloud = cloud
}
if c.ConnectedProxyGetter == nil {
c.ConnectedProxyGetter = reversetunnel.NewConnectedProxyGetter()
}
return nil
}
// Server is an application server. It authenticates requests from the web
// proxy and forwards them to internal applications.
type Server struct {
c *Config
log *logrus.Entry
closeContext context.Context
closeFunc context.CancelFunc
httpServer *http.Server
tcpServer *tcpServer
tlsConfig *tls.Config
mu sync.RWMutex
heartbeats map[string]*srv.Heartbeat
dynamicLabels map[string]*labels.Dynamic
connAuthMu sync.Mutex
// connAuth is used to map an initial failure of authorization to a connection.
// This will force the HTTP server to serve an error and close the connection.
connAuth map[net.Conn]error
// apps are all apps this server currently proxies. Proxied apps are
// reconciled against monitoredApps below.
apps map[string]types.Application
// monitoredApps contains all cluster apps the proxied apps are
// reconciled against.
monitoredApps monitoredApps
// reconcileCh triggers reconciliation of proxied apps.
reconcileCh chan struct{}
proxyPort string
cache *sessionChunkCache
awsHandler http.Handler
azureHandler http.Handler
gcpHandler http.Handler
// watcher monitors changes to application resources.
watcher *services.AppWatcher
// authMiddleware allows wrapping connections with identity information.
authMiddleware *auth.Middleware
}
// monitoredApps is a collection of applications from different sources
// like configuration file and dynamic resources.
//
// It's updated by respective watchers and is used for reconciling with the
// currently proxied apps.
type monitoredApps struct {
// static are apps from the agent's YAML configuration.
static types.Apps
// resources are apps created via CLI or API.
resources types.Apps
// mu protects access to the fields.
mu sync.Mutex
}
func (m *monitoredApps) setResources(apps types.Apps) {
m.mu.Lock()
defer m.mu.Unlock()
m.resources = apps
}
func (m *monitoredApps) get() types.ResourcesWithLabelsMap {
m.mu.Lock()
defer m.mu.Unlock()
return append(m.static, m.resources...).AsResources().ToMap()
}
// New returns a new application server.
func New(ctx context.Context, c *Config) (*Server, error) {
err := c.CheckAndSetDefaults()
if err != nil {
return nil, trace.Wrap(err)
}
closeContext, closeFunc := context.WithCancel(ctx)
// in case of errors cancel context to avoid context leak
callClose := true
defer func() {
if callClose {
closeFunc()
}
}()
awsSigner, err := awsutils.NewSigningService(awsutils.SigningServiceConfig{})
if err != nil {
return nil, trace.Wrap(err)
}
awsHandler, err := appaws.NewAWSSignerHandler(closeContext, appaws.SignerHandlerConfig{
SigningService: awsSigner,
})
if err != nil {
return nil, trace.Wrap(err)
}
azureHandler, err := appazure.NewAzureHandler(closeContext, appazure.HandlerConfig{})
if err != nil {
return nil, trace.Wrap(err)
}
gcpHandler, err := appgcp.NewGCPHandler(closeContext, appgcp.HandlerConfig{})
if err != nil {
return nil, trace.Wrap(err)
}
s := &Server{
c: c,
log: logrus.WithFields(logrus.Fields{
trace.Component: teleport.ComponentApp,
}),
heartbeats: make(map[string]*srv.Heartbeat),
dynamicLabels: make(map[string]*labels.Dynamic),
apps: make(map[string]types.Application),
connAuth: make(map[net.Conn]error),
awsHandler: awsHandler,
azureHandler: azureHandler,
gcpHandler: gcpHandler,
monitoredApps: monitoredApps{
static: c.Apps,
},
reconcileCh: make(chan struct{}),
closeFunc: closeFunc,
closeContext: closeContext,
}
// Make copy of server's TLS configuration and update it with the specific
// functionality this server needs, like requiring client certificates.
s.tlsConfig = CopyAndConfigureTLS(s.log, s.c.AccessPoint, s.c.TLSConfig)
if err != nil {
return nil, trace.Wrap(err)
}
clustername, err := s.c.AccessPoint.GetClusterName()
if err != nil {
return nil, trace.Wrap(err)
}
// Create and configure HTTP server with authorizing middleware.
s.httpServer = s.newHTTPServer(clustername.GetClusterName())
// TCP server will handle TCP applications.
tcpServer, err := s.newTCPServer()
if err != nil {
return nil, trace.Wrap(err)
}
s.tcpServer = tcpServer
// Create a new session cache, this holds sessions that can be used to
// forward requests.
s.cache, err = s.newSessionChunkCache()
if err != nil {
return nil, trace.Wrap(err)
}
// Figure out the port the proxy is running on.
s.proxyPort = s.getProxyPort()
callClose = false
return s, nil
}
// startApp registers the specified application.
func (s *Server) startApp(ctx context.Context, app types.Application) error {
// Start a goroutine that will be updating apps's command labels (if any)
// on the defined schedule.
if err := s.startDynamicLabels(ctx, app); err != nil {
return trace.Wrap(err)
}
// Heartbeat will periodically report the presence of this proxied app
// to the auth server.
if err := s.startHeartbeat(ctx, app); err != nil {
return trace.Wrap(err)
}
s.log.Debugf("Started %v.", app)
return nil
}
// stopApp uninitializes the app with the specified name.
func (s *Server) stopApp(ctx context.Context, name string) error {
s.stopDynamicLabels(name)
if err := s.stopHeartbeat(name); err != nil {
return trace.Wrap(err)
}
s.log.Debugf("Stopped app %q.", name)
return nil
}
// removeAppServer deletes app server for the specified app.
func (s *Server) removeAppServer(ctx context.Context, name string) error {
return s.c.AuthClient.DeleteApplicationServer(ctx, apidefaults.Namespace,
s.c.HostID, name)
}
// stopAndRemoveApp uninitializes and deletes the app with the specified name.
func (s *Server) stopAndRemoveApp(ctx context.Context, name string) error {
if err := s.stopApp(ctx, name); err != nil {
return trace.Wrap(err)
}
// Heartbeat is stopped but if we don't remove this app server,
// it can linger for up to ~10m until its TTL expires.
if err := s.removeAppServer(ctx, name); err != nil && !trace.IsNotFound(err) {
return trace.Wrap(err)
}
return nil
}
// startDynamicLabels starts dynamic labels for the app if it has them.
func (s *Server) startDynamicLabels(ctx context.Context, app types.Application) error {
if len(app.GetDynamicLabels()) == 0 {
return nil // Nothing to do.
}
dynamic, err := labels.NewDynamic(ctx, &labels.DynamicConfig{
Labels: app.GetDynamicLabels(),
Log: s.log,
})
if err != nil {
return trace.Wrap(err)
}
dynamic.Sync()
dynamic.Start()
s.mu.Lock()
defer s.mu.Unlock()
s.dynamicLabels[app.GetName()] = dynamic
return nil
}
// stopDynamicLabels stops dynamic labels for the specified app.
func (s *Server) stopDynamicLabels(name string) {
s.mu.Lock()
defer s.mu.Unlock()
dynamic, ok := s.dynamicLabels[name]
if !ok {
return
}
delete(s.dynamicLabels, name)
dynamic.Close()
}
// startHeartbeat starts the registration heartbeat to the auth server.
func (s *Server) startHeartbeat(ctx context.Context, app types.Application) error {
heartbeat, err := srv.NewHeartbeat(srv.HeartbeatConfig{
Context: s.closeContext,
Component: teleport.ComponentApp,
Mode: srv.HeartbeatModeApp,
Announcer: s.c.AccessPoint,
GetServerInfo: s.getServerInfoFunc(app),
KeepAlivePeriod: apidefaults.ServerKeepAliveTTL(),
AnnouncePeriod: apidefaults.ServerAnnounceTTL/2 + utils.RandomDuration(apidefaults.ServerAnnounceTTL/10),
CheckPeriod: defaults.HeartbeatCheckPeriod,
ServerTTL: apidefaults.ServerAnnounceTTL,
OnHeartbeat: s.c.OnHeartbeat,
})
if err != nil {
return trace.Wrap(err)
}
go heartbeat.Run()
s.mu.Lock()
defer s.mu.Unlock()
s.heartbeats[app.GetName()] = heartbeat
return nil
}
// stopHeartbeat stops the heartbeat for the specified app.
func (s *Server) stopHeartbeat(name string) error {
s.mu.Lock()
defer s.mu.Unlock()
heartbeat, ok := s.heartbeats[name]
if !ok {
return nil
}
delete(s.heartbeats, name)
return heartbeat.Close()
}
// getServerInfoFunc returns function that the heartbeater uses to report the
// provided application to the auth server.
func (s *Server) getServerInfoFunc(app types.Application) func() (types.Resource, error) {
return func() (types.Resource, error) {
return s.getServerInfo(app)
}
}
// getServerInfo returns up-to-date app resource.
func (s *Server) getServerInfo(app types.Application) (types.Resource, error) {
// Make sure to return a new object, because it gets cached by
// heartbeat and will always compare as equal otherwise.
s.mu.RLock()
copy := s.appWithUpdatedLabelsLocked(app)
s.mu.RUnlock()
expires := s.c.Clock.Now().UTC().Add(apidefaults.ServerAnnounceTTL)
server, err := types.NewAppServerV3(types.Metadata{
Name: copy.GetName(),
Expires: &expires,
}, types.AppServerSpecV3{
Version: teleport.Version,
Hostname: s.c.Hostname,
HostID: s.c.HostID,
Rotation: s.getRotationState(),
App: copy,
ProxyIDs: s.c.ConnectedProxyGetter.GetProxyIDs(),
})
if err != nil {
return nil, trace.Wrap(err)
}
return server, nil
}
// getRotationState is a helper to return this server's CA rotation state.
func (s *Server) getRotationState() types.Rotation {
rotation, err := s.c.GetRotation(types.RoleApp)
if err != nil && !trace.IsNotFound(err) {
s.log.WithError(err).Warn("Failed to get rotation state.")
}
if rotation != nil {
return *rotation
}
return types.Rotation{}
}
// registerApp starts proxying the app.
func (s *Server) registerApp(ctx context.Context, app types.Application) error {
if err := s.startApp(ctx, app); err != nil {
return trace.Wrap(err)
}
s.mu.Lock()
defer s.mu.Unlock()
s.apps[app.GetName()] = app
return nil
}
// updateApp updates application that is already registered.
func (s *Server) updateApp(ctx context.Context, app types.Application) error {
// Stop heartbeat and dynamic labels before starting new ones.
if err := s.stopAndRemoveApp(ctx, app.GetName()); err != nil {
return trace.Wrap(err)
}
if err := s.registerApp(ctx, app); err != nil {
// If we failed to re-register, don't keep proxying the old app.
if errUnregister := s.unregisterAndRemoveApp(ctx, app.GetName()); errUnregister != nil {
return trace.NewAggregate(err, errUnregister)
}
return trace.Wrap(err)
}
return nil
}
// unregisterApp stops proxying the app.
func (s *Server) unregisterApp(ctx context.Context, name string) error {
if err := s.stopApp(ctx, name); err != nil {
return trace.Wrap(err)
}
s.mu.Lock()
defer s.mu.Unlock()
delete(s.apps, name)
return nil
}
// unregisterAndRemoveApp stops proxying the app and deltes it.
func (s *Server) unregisterAndRemoveApp(ctx context.Context, name string) error {
if err := s.stopAndRemoveApp(ctx, name); err != nil {
return trace.Wrap(err)
}
s.mu.Lock()
defer s.mu.Unlock()
delete(s.apps, name)
return nil
}
// getApps returns a list of all apps this server is proxying.
func (s *Server) getApps() (apps types.Apps) {
s.mu.RLock()
defer s.mu.RUnlock()
for _, app := range s.apps {
apps = append(apps, app)
}
return apps
}
// Start starts proxying all registered apps.
func (s *Server) Start(ctx context.Context) (err error) {
// Register all apps from static configuration.
for _, app := range s.c.Apps {
if err := s.registerApp(ctx, app); err != nil {
return trace.Wrap(err)
}
}
// Start reconciler that will be reconciling proxied apps with
// application resources.
if err := s.startReconciler(ctx); err != nil {
return trace.Wrap(err)
}
// Initialize watcher that will be dynamically (un-)registering
// proxied apps based on the application resources.
if s.watcher, err = s.startResourceWatcher(ctx); err != nil {
return trace.Wrap(err)
}
return nil
}
// Close will shut the server down and unblock any resources.
func (s *Server) Close() error {
return trace.Wrap(s.close(s.closeContext))
}
// Shutdown performs a graceful shutdown.
func (s *Server) Shutdown(ctx context.Context) error {
// TODO wait active connections.
return trace.Wrap(s.close(ctx))
}
func (s *Server) close(ctx context.Context) error {
var errs []error
// Stop all proxied apps.
for _, app := range s.getApps() {
if services.ShouldDeleteServerHeartbeatsOnShutdown(ctx) {
errs = append(errs, trace.Wrap(s.unregisterAndRemoveApp(ctx, app.GetName())))
} else {
errs = append(errs, trace.Wrap(s.unregisterApp(ctx, app.GetName())))
}
}
// Stop HTTP server.
if err := s.httpServer.Close(); err != nil {
errs = append(errs, err)
}
// Close the session cache and its remaining sessions. Sessions
// use server.closeContext to complete cleanup, so we must wait
// for sessions to finish closing before closing the context.
s.cache.closeAllSessions()
// Signal to any blocking go routine that it should exit.
s.closeFunc()
// Stop the database resource watcher.
if s.watcher != nil {
s.watcher.Close()
}
return trace.NewAggregate(errs...)
}
// Wait will block while the server is running.
func (s *Server) Wait() error {
<-s.closeContext.Done()
return s.closeContext.Err()
}
// ForceHeartbeat is used in tests to force updating of app servers.
func (s *Server) ForceHeartbeat() error {
s.mu.RLock()
defer s.mu.RUnlock()
for name, heartbeat := range s.heartbeats {
s.log.Debugf("Forcing heartbeat for %q.", name)
if err := heartbeat.ForceSend(time.Second); err != nil {
return trace.Wrap(err)
}
}
return nil
}
func (s *Server) getAndDeleteConnAuth(conn net.Conn) error {
s.connAuthMu.Lock()
defer s.connAuthMu.Unlock()
err := s.connAuth[conn]
delete(s.connAuth, conn)
return err
}
func (s *Server) setConnAuth(conn net.Conn, err error) {
s.connAuthMu.Lock()
defer s.connAuthMu.Unlock()
s.connAuth[conn] = err
}
func (s *Server) deleteConnAuth(conn net.Conn) {
s.connAuthMu.Lock()
defer s.connAuthMu.Unlock()
delete(s.connAuth, conn)
}
// HandleConnection takes a connection and wraps it in a listener, so it can
// be passed to http.Serve to process as a HTTP request.
func (s *Server) HandleConnection(conn net.Conn) {
// Wrap conn in a CloserConn to detect when it is closed.
// Returning early will close conn before it has been serviced.
// httpServer will initiate the close call.
closerConn := utils.NewCloserConn(conn)
cleanup, err := s.handleConnection(closerConn)
// Make sure that the cleanup function is run
if cleanup != nil {
defer cleanup()
}
if err != nil {
if !utils.IsOKNetworkError(err) {
s.log.WithError(err).Warn("Failed to handle client connection.")
}
if err := conn.Close(); err != nil && !utils.IsOKNetworkError(err) {
s.log.WithError(err).Warn("Failed to close client connection.")
}
return
}
// Wait for connection to close.
closerConn.Wait()
}
func (s *Server) handleConnection(conn net.Conn) (func(), error) {
ctx, cancel := context.WithCancel(s.closeContext)
tc, err := srv.NewTrackingReadConn(srv.TrackingReadConnConfig{
Conn: conn,
Clock: s.c.Clock,
Context: ctx,
Cancel: cancel,
})
if err != nil {
return nil, trace.Wrap(err)
}
// Proxy sends a X.509 client certificate to pass identity information,
// extract it and run authorization checks on it.
tlsConn, user, app, err := s.getConnectionInfo(s.closeContext, tc)
if err != nil {
return nil, trace.Wrap(err)
}
ctx = authz.ContextWithUser(s.closeContext, user)
ctx = authz.ContextWithClientAddr(ctx, conn.RemoteAddr())
authCtx, _, err := s.authorizeContext(ctx)
// The behavior here is a little hard to track. To be clear here, if authorization fails
// the following will occur:
// 1. If the application is a TCP application, error out immediately as expected.
// 2. If the application is an HTTP application, store the error and let the HTTP handler
// serve the error directly so that it's properly converted to an HTTP status code.
// This will ensure users will get a 403 when authorization fails.
if err != nil {
if !app.IsTCP() {
s.setConnAuth(tlsConn, err)
} else {
return nil, trace.Wrap(err)
}
} else {
// Monitor the connection an update the context.
ctx, _, err = s.c.ConnectionMonitor.MonitorConn(ctx, authCtx, tc)
if err != nil {
return nil, trace.Wrap(err)
}
}
// Application access supports plain TCP connections which are handled
// differently than HTTP requests from web apps.
if app.IsTCP() {
identity := authCtx.Identity.GetIdentity()
return nil, s.handleTCPApp(ctx, tlsConn, &identity, app)
}
return func() {
s.deleteConnAuth(tlsConn)
}, s.handleHTTPApp(ctx, tlsConn)
}
// handleTCPApp handles connection for a TCP application.
func (s *Server) handleTCPApp(ctx context.Context, conn net.Conn, identity *tlsca.Identity, app types.Application) error {
err := s.tcpServer.handleConnection(ctx, conn, identity, app)
if err != nil {
return trace.Wrap(err)
}
return nil
}
// handleHTTPApp handles connection for an HTTP application.
func (s *Server) handleHTTPApp(ctx context.Context, conn net.Conn) error {
// Wrap a TLS authorizing conn in a single-use listener.
listener := newListener(ctx, conn)
// Serve will return as soon as tlsConn is running in its own goroutine
err := s.httpServer.Serve(listener)
if err != nil && !errors.Is(err, errListenerConnServed) {
// okay to ignore errListenerConnServed; it is a signal that our
// single-use listener has passed the connection to http.Serve
// and conn is being served. See listener.Accept for details.
return trace.Wrap(err)
}
return nil
}
// ServeHTTP will forward the *http.Request to the target application.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// See if the initial auth failed. If it didn't, serve the HTTP regularly, which
// will include subsequent auth attempts to prevent race-type conditions.
conn, ok := r.Context().Value(connContextKey).(net.Conn)
if !ok {
s.log.Errorf("unable to extract connection from context")
}
err := s.getAndDeleteConnAuth(conn)
if err == nil {
err = s.serveHTTP(w, r)
}
if err != nil {
s.log.WithError(err).Warnf("Failed to serve request")
// Covert trace error type to HTTP and write response, make sure we close the
// connection afterwards so that the monitor is recreated if needed.
code := trace.ErrorToCode(err)
w.Header().Set("Connection", "close")
http.Error(w, http.StatusText(code), code)
}
}
func (s *Server) serveHTTP(w http.ResponseWriter, r *http.Request) error {
// Extract the identity and application being requested from the certificate
// and check if the caller has access.
authCtx, app, err := s.authorizeContext(r.Context())
if err != nil {
return trace.Wrap(err)
}
identity := authCtx.Identity.GetIdentity()
switch {
case app.IsAWSConsole():
// Requests from AWS applications are signed by AWS Signature Version 4
// algorithm. AWS CLI and AWS SDKs automatically use SigV4 for all
// services that support it (All services expect Amazon SimpleDB but
// this AWS service has been deprecated)
//
// Also check header common.TeleportAWSAssumedRole which is added by
// the local proxy for AWS requests signed by assumed roles.
if awsutils.IsSignedByAWSSigV4(r) || r.Header.Get(common.TeleportAWSAssumedRole) != "" {
return s.serveSession(w, r, &identity, app, s.withAWSSigner)
}
// Request for AWS console access originated from Teleport Proxy WebUI
// is not signed by SigV4.
return s.serveAWSWebConsole(w, r, &identity, app)
case app.IsAzureCloud():
return s.serveSession(w, r, &identity, app, s.withAzureHandler)
case app.IsGCP():
return s.serveSession(w, r, &identity, app, s.withGCPHandler)
default:
return s.serveSession(w, r, &identity, app, s.withJWTTokenForwarder)
}
}
// serveAWSWebConsole generates a sign-in URL for AWS management console and
// redirects the user to it.
func (s *Server) serveAWSWebConsole(w http.ResponseWriter, r *http.Request, identity *tlsca.Identity, app types.Application) error {
s.log.Debugf("Redirecting %v to AWS management console with role %v.",
identity.Username, identity.RouteToApp.AWSRoleARN)
url, err := s.c.Cloud.GetAWSSigninURL(AWSSigninRequest{
Identity: identity,
TargetURL: app.GetURI(),
Issuer: app.GetPublicAddr(),
ExternalID: app.GetAWSExternalID(),
})
if err != nil {
return trace.Wrap(err)
}
http.Redirect(w, r, url.SigninURL, http.StatusFound)
return nil
}
// serveSession finds the app session and forwards the request.
func (s *Server) serveSession(w http.ResponseWriter, r *http.Request, identity *tlsca.Identity, app types.Application, opts ...sessionOpt) error {
// Fetch a cached request forwarder (or create one) that lives about 5
// minutes. Used to stream session chunks to the Audit Log.
session, err := s.getSession(r.Context(), identity, app, opts...)
if err != nil {
return trace.Wrap(err)
}
defer session.release()
// Create session context.
sessionCtx := &common.SessionContext{
Identity: identity,
App: app,
ChunkID: session.id,
Audit: session.audit,
}
// Forward request to the target application.
session.handler.ServeHTTP(w, common.WithSessionContext(r, sessionCtx))
return nil
}
// getConnectionInfo extracts identity information from the provided
// connection and runs authorization checks on it.
//
// The connection comes from the reverse tunnel and is expected to be TLS and
// carry identity in the client certificate.
func (s *Server) getConnectionInfo(ctx context.Context, conn net.Conn) (*tls.Conn, authz.IdentityGetter, types.Application, error) {
tlsConn := tls.Server(conn, s.tlsConfig)
if err := tlsConn.Handshake(); err != nil {
return nil, nil, nil, trace.Wrap(err, "TLS handshake failed")
}
user, err := s.authMiddleware.GetUser(tlsConn.ConnectionState())
if err != nil {
return nil, nil, nil, trace.Wrap(err)
}
app, err := s.getApp(ctx, user.GetIdentity().RouteToApp.PublicAddr)
if err != nil {
return nil, nil, nil, trace.Wrap(err)
}
return tlsConn, user, app, nil
}
// authorizeContext will check if the context carries identity information and
// runs authorization checks on it.
func (s *Server) authorizeContext(ctx context.Context) (*authz.Context, types.Application, error) {
// Only allow local and remote identities to proxy to an application.
userType, err := authz.UserFromContext(ctx)
if err != nil {
return nil, nil, trace.Wrap(err)
}
switch userType.(type) {
case authz.LocalUser, authz.RemoteUser:
default:
return nil, nil, trace.BadParameter("invalid identity: %T", userType)
}
// Extract authorizing context and identity of the user from the request.
authContext, err := s.c.Authorizer.Authorize(ctx)
if err != nil {
return nil, nil, trace.Wrap(err)
}
identity := authContext.Identity.GetIdentity()
// Fetch the application and check if the identity has access.
app, err := s.getApp(ctx, identity.RouteToApp.PublicAddr)
if err != nil {
return nil, nil, trace.Wrap(err)
}
authPref, err := s.c.AccessPoint.GetAuthPreference(ctx)
if err != nil {
return nil, nil, trace.Wrap(err)
}
// When accessing AWS management console, check permissions to assume
// requested IAM role as well.
var matchers []services.RoleMatcher
if app.IsAWSConsole() {
matchers = append(matchers, &services.AWSRoleARNMatcher{
RoleARN: identity.RouteToApp.AWSRoleARN,
})
}
// When accessing Azure API, check permissions to assume
// requested Azure identity as well.
if app.IsAzureCloud() {
matchers = append(matchers, &services.AzureIdentityMatcher{
Identity: identity.RouteToApp.AzureIdentity,
})
}
// When accessing GCP API, check permissions to assume
// requested GCP service account as well.
if app.IsGCP() {
matchers = append(matchers, &services.GCPServiceAccountMatcher{
ServiceAccount: identity.RouteToApp.GCPServiceAccount,
})
}
state := authContext.GetAccessState(authPref)
err = authContext.Checker.CheckAccess(
app,
state,
matchers...)
if err != nil {
s.log.WithError(err).Warnf("access denied to application %v", app.GetName())
return nil, nil, utils.OpaqueAccessDenied(err)
}
return authContext, app, nil
}
// getSession returns a request session used to proxy the request to the
// target application. Always checks if the session is valid first and if so,
// will return a cached session, otherwise will create one.
// The in-flight request count is automatically incremented on the session.
// The caller must call session.release() after finishing its use
func (s *Server) getSession(ctx context.Context, identity *tlsca.Identity, app types.Application, opts ...sessionOpt) (*sessionChunk, error) {
session, err := s.cache.get(identity.RouteToApp.SessionID)
// If a cached forwarder exists, return it right away.
if err == nil && session.acquire() == nil {
return session, nil
}
// Create a new session with a recorder and forwarder in it.
session, err = s.newSessionChunk(ctx, identity, app, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
return session, nil
}
// getApp returns an application matching the public address. If multiple