-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathforwarder.go
2826 lines (2546 loc) · 99.4 KB
/
forwarder.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 proxy
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"maps"
"net"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/google/uuid"
gwebsocket "github.com/gorilla/websocket"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/julienschmidt/httprouter"
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
oteltrace "go.opentelemetry.io/otel/trace"
kubeerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/util/httpstream"
httpstreamspdy "k8s.io/apimachinery/pkg/util/httpstream/spdy"
"k8s.io/apimachinery/pkg/util/httpstream/wsstream"
utilnet "k8s.io/apimachinery/pkg/util/net"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/portforward"
"k8s.io/client-go/tools/remotecommand"
"k8s.io/client-go/transport/spdy"
kwebsocket "k8s.io/client-go/transport/websocket"
kubeexec "k8s.io/client-go/util/exec"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/client/proto"
"github.com/gravitational/teleport/api/constants"
apidefaults "github.com/gravitational/teleport/api/defaults"
"github.com/gravitational/teleport/api/observability/tracing"
tracehttp "github.com/gravitational/teleport/api/observability/tracing/http"
"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/entitlements"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/auth/authclient"
"github.com/gravitational/teleport/lib/authz"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/httplib"
"github.com/gravitational/teleport/lib/httplib/reverseproxy"
"github.com/gravitational/teleport/lib/kube/proxy/responsewriters"
"github.com/gravitational/teleport/lib/kube/proxy/streamproto"
"github.com/gravitational/teleport/lib/modules"
"github.com/gravitational/teleport/lib/multiplexer"
"github.com/gravitational/teleport/lib/reversetunnelclient"
"github.com/gravitational/teleport/lib/service/servicecfg"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/srv"
"github.com/gravitational/teleport/lib/sshca"
"github.com/gravitational/teleport/lib/utils"
logutils "github.com/gravitational/teleport/lib/utils/log"
)
// KubeServiceType specifies a Teleport service type which can forward Kubernetes requests
type KubeServiceType = string
const (
// KubeService is a Teleport kubernetes_service. A KubeService always forwards
// requests directly to a Kubernetes endpoint.
KubeService = "kube_service"
// ProxyService is a Teleport proxy_service with kube_listen_addr/
// kube_public_addr enabled. A ProxyService always forwards requests to a
// Teleport KubeService or LegacyProxyService.
ProxyService = "kube_proxy"
// LegacyProxyService is a Teleport proxy_service with the kubernetes section
// enabled. A LegacyProxyService can forward requests directly to a Kubernetes
// endpoint, or to another Teleport LegacyProxyService or KubeService.
LegacyProxyService = "legacy_proxy"
)
// ForwarderConfig specifies configuration for proxy forwarder
type ForwarderConfig struct {
// ReverseTunnelSrv is the teleport reverse tunnel server
ReverseTunnelSrv reversetunnelclient.Server
// ClusterName is a local cluster name
ClusterName string
// Keygen points to a key generator implementation
Keygen sshca.Authority
// Authz authenticates user
Authz authz.Authorizer
// AuthClient is a auth server client.
AuthClient authclient.ClientI
// CachingAuthClient is a caching auth server client for read-only access.
CachingAuthClient authclient.ReadKubernetesAccessPoint
// Emitter is used to emit audit events
Emitter apievents.Emitter
// DataDir is a data dir to store logs
DataDir string
// Namespace is a namespace of the proxy server (not a K8s namespace)
Namespace string
// HostID is a unique ID of a proxy server
HostID string
// ClusterOverride if set, routes all requests
// to the cluster name, used in tests
ClusterOverride string
// Context passes the optional external context
// passing global close to all forwarder operations
Context context.Context
// KubeconfigPath is a path to kubernetes configuration
KubeconfigPath string
// KubeServiceType specifies which Teleport service type this forwarder is for
KubeServiceType KubeServiceType
// KubeClusterName is the name of the kubernetes cluster that this
// forwarder handles.
KubeClusterName string
// Clock is a server clock, could be overridden in tests
Clock clockwork.Clock
// ConnPingPeriod is a period for sending ping messages on the incoming
// connection.
ConnPingPeriod time.Duration
// Component name to include in log output.
Component string
// LockWatcher is a lock watcher.
LockWatcher *services.LockWatcher
// CheckImpersonationPermissions is an optional override of the default
// impersonation permissions check, for use in testing
CheckImpersonationPermissions servicecfg.ImpersonationPermissionsChecker
// PublicAddr is the address that can be used to reach the kube cluster
PublicAddr string
// PROXYSigner is used to sign PROXY headers for securely propagating client IP address
PROXYSigner multiplexer.PROXYHeaderSigner
// log is the logger function
log *slog.Logger
// TracerProvider is used to create tracers capable
// of starting spans.
TracerProvider oteltrace.TracerProvider
// Tracer is used to start spans.
tracer oteltrace.Tracer
// GetConnTLSCertificate returns the TLS client certificate to use when
// connecting to the upstream Teleport proxy or Kubernetes service when
// forwarding requests using the forward identity (i.e. proxy impersonating
// a user) method. Paired with GetConnTLSRoots and ConnTLSCipherSuites to
// generate the correct [*tls.Config] on demand.
GetConnTLSCertificate utils.GetCertificateFunc
// GetConnTLSRoots returns the [*x509.CertPool] used to validate TLS
// connections to the upstream Teleport proxy or Kubernetes service.
GetConnTLSRoots utils.GetRootsFunc
// ConnTLSCipherSuites optionally contains a list of TLS ciphersuites to use
// when connecting to the upstream Teleport Proxy or Kubernetes service.
ConnTLSCipherSuites []uint16
// ClusterFeaturesGetter is a function that returns the Teleport cluster licensed features.
// It is used to determine if the cluster is licensed for Kubernetes usage.
ClusterFeatures ClusterFeaturesGetter
}
// ClusterFeaturesGetter is a function that returns the Teleport cluster licensed features.
type ClusterFeaturesGetter func() proto.Features
func (f ClusterFeaturesGetter) GetEntitlement(e entitlements.EntitlementKind) modules.EntitlementInfo {
al, ok := f().Entitlements[string(e)]
if !ok {
return modules.EntitlementInfo{}
}
return modules.EntitlementInfo{
Enabled: al.Enabled,
Limit: al.Limit,
}
}
// CheckAndSetDefaults checks and sets default values
func (f *ForwarderConfig) CheckAndSetDefaults() error {
if f.AuthClient == nil {
return trace.BadParameter("missing parameter AuthClient")
}
if f.CachingAuthClient == nil {
return trace.BadParameter("missing parameter CachingAuthClient")
}
if f.Authz == nil {
return trace.BadParameter("missing parameter Authz")
}
if f.Emitter == nil {
return trace.BadParameter("missing parameter Emitter")
}
if f.ClusterName == "" {
return trace.BadParameter("missing parameter ClusterName")
}
if f.Keygen == nil {
return trace.BadParameter("missing parameter Keygen")
}
if f.DataDir == "" {
return trace.BadParameter("missing parameter DataDir")
}
if f.HostID == "" {
return trace.BadParameter("missing parameter ServerID")
}
if f.ClusterFeatures == nil {
return trace.BadParameter("missing parameter ClusterFeatures")
}
if f.KubeServiceType != KubeService && f.PROXYSigner == nil {
return trace.BadParameter("missing parameter PROXYSigner")
}
if f.Namespace == "" {
f.Namespace = apidefaults.Namespace
}
if f.Context == nil {
f.Context = context.TODO()
}
if f.Clock == nil {
f.Clock = clockwork.NewRealClock()
}
if f.ConnPingPeriod == 0 {
f.ConnPingPeriod = defaults.HighResPollingPeriod
}
if f.Component == "" {
f.Component = "kube_forwarder"
}
if f.CheckImpersonationPermissions == nil {
f.CheckImpersonationPermissions = checkImpersonationPermissions
}
if f.TracerProvider == nil {
f.TracerProvider = tracing.DefaultProvider()
}
f.tracer = f.TracerProvider.Tracer("kube")
switch f.KubeServiceType {
case KubeService:
case ProxyService, LegacyProxyService:
if f.GetConnTLSCertificate == nil {
return trace.BadParameter("missing parameter GetConnTLSCertificate")
}
if f.GetConnTLSRoots == nil {
return trace.BadParameter("missing parameter GetConnTLSRoots")
}
default:
return trace.BadParameter("unknown value for KubeServiceType")
}
if f.KubeClusterName == "" && f.KubeconfigPath == "" && f.KubeServiceType == LegacyProxyService {
// Running without a kubeconfig and explicit k8s cluster name. Use
// teleport cluster name instead, to ask kubeutils.GetKubeConfig to
// attempt loading the in-cluster credentials.
f.KubeClusterName = f.ClusterName
}
if f.log == nil {
f.log = slog.Default()
}
return nil
}
// transportCacheTTL is the TTL for the transport cache.
const transportCacheTTL = 5 * time.Hour
// NewForwarder returns new instance of Kubernetes request
// forwarding proxy.
func NewForwarder(cfg ForwarderConfig) (*Forwarder, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
// TODO (tigrato): remove this once we have a better way to handle
// deleting expired entried clusters and kube_servers entries.
// In the meantime, we need to make sure that the cache is cleaned
// from time to time.
transportClients, err := utils.NewFnCache(utils.FnCacheConfig{
TTL: transportCacheTTL,
Clock: cfg.Clock,
})
if err != nil {
return nil, trace.Wrap(err)
}
closeCtx, close := context.WithCancel(cfg.Context)
fwd := &Forwarder{
log: cfg.log,
cfg: cfg,
activeRequests: make(map[string]context.Context),
ctx: closeCtx,
close: close,
sessions: make(map[uuid.UUID]*session),
upgrader: gwebsocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
},
clusterDetails: make(map[string]*kubeDetails),
cachedTransport: transportClients,
}
router := httprouter.New()
router.UseRawPath = true
router.GET("/version", fwd.withAuth(
func(ctx *authContext, w http.ResponseWriter, r *http.Request, _ httprouter.Params) (any, error) {
// Forward version requests to the cluster.
return fwd.catchAll(ctx, w, r)
},
withCustomErrFormatter(fwd.writeResponseErrorToBody),
))
router.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/exec", fwd.withAuth(fwd.exec))
router.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/exec", fwd.withAuth(fwd.exec))
router.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/attach", fwd.withAuth(fwd.exec))
router.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/attach", fwd.withAuth(fwd.exec))
router.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/portforward", fwd.withAuth(fwd.portForward))
router.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/portforward", fwd.withAuth(fwd.portForward))
router.POST("/apis/authorization.k8s.io/:ver/selfsubjectaccessreviews", fwd.withAuth(fwd.selfSubjectAccessReviews))
router.PATCH("/api/:ver/namespaces/:podNamespace/pods/:podName/ephemeralcontainers", fwd.withAuth(fwd.ephemeralContainers))
router.PUT("/api/:ver/namespaces/:podNamespace/pods/:podName/ephemeralcontainers", fwd.withAuth(fwd.ephemeralContainers))
router.GET("/api/:ver/teleport/join/:session", fwd.withAuthPassthrough(fwd.join))
for _, method := range allHTTPMethods() {
router.Handle(method, "/v1/teleport/:base64Cluster/:base64KubeCluster/*path", fwd.singleCertHandler())
}
router.NotFound = fwd.withAuthStd(fwd.catchAll)
fwd.router = instrumentHTTPHandler(fwd.cfg.KubeServiceType, router)
if cfg.ClusterOverride != "" {
fwd.log.DebugContext(closeCtx, "Cluster override is set, forwarder will send all requests to remote cluster", "cluster_override", cfg.ClusterOverride)
}
if len(cfg.KubeClusterName) > 0 || len(cfg.KubeconfigPath) > 0 || cfg.KubeServiceType != KubeService {
if err := fwd.getKubeDetails(cfg.Context); err != nil {
return nil, trace.Wrap(err)
}
}
return fwd, nil
}
// Forwarder intercepts kubernetes requests, acting as Kubernetes API proxy.
// it blindly forwards most of the requests on HTTPS protocol layer,
// however some requests like exec sessions it intercepts and records.
type Forwarder struct {
mu sync.Mutex
log *slog.Logger
router http.Handler
cfg ForwarderConfig
// activeRequests is a map used to serialize active CSR requests to the auth server
activeRequests map[string]context.Context
// close is a close function
close context.CancelFunc
// ctx is a global context signaling exit
ctx context.Context
// clusterDetails contain kubernetes credentials for multiple clusters.
// map key is cluster name.
clusterDetails map[string]*kubeDetails
rwMutexDetails sync.RWMutex
// sessions tracks in-flight sessions
sessions map[uuid.UUID]*session
// upgrades connections to websockets
upgrader gwebsocket.Upgrader
// getKubernetesServersForKubeCluster is a function that returns a list of
// kubernetes servers for a given kube cluster but uses different methods
// depending on the service type.
// For example, if the service type is KubeService, it will use the
// local kubernetes clusters. If the service type is Proxy, it will
// use the heartbeat clusters.
getKubernetesServersForKubeCluster getKubeServersByNameFunc
// cachedTransport is a cache of cachedTransportEntry objects used to
// connect to Teleport services.
// TODO(tigrato): Implement a cache eviction policy using watchers.
cachedTransport *utils.FnCache
}
// cachedTransportEntry is a cached transport entry used to connect to
// Teleport services. It contains a cached http.RoundTripper and a cached
// tls.Config.
type cachedTransportEntry struct {
transport http.RoundTripper
tlsConfig *tls.Config
}
// getKubeServersByNameFunc is a function that returns a list of
// kubernetes servers for a given kube cluster.
type getKubeServersByNameFunc = func(ctx context.Context, name string) ([]types.KubeServer, error)
// Close signals close to all outstanding or background operations
// to complete
func (f *Forwarder) Close() error {
f.close()
return nil
}
func (f *Forwarder) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
f.router.ServeHTTP(rw, r)
}
// authContext is a context of authenticated user,
// contains information about user, target cluster and authenticated groups
type authContext struct {
authz.Context
kubeGroups map[string]struct{}
kubeUsers map[string]struct{}
kubeClusterLabels map[string]string
kubeClusterName string
teleportCluster teleportClusterClient
recordingConfig types.SessionRecordingConfig
// clientIdleTimeout sets information on client idle timeout
clientIdleTimeout time.Duration
// clientIdleTimeoutMessage is the message to be displayed to the user
// when the client idle timeout is reached
clientIdleTimeoutMessage string
// disconnectExpiredCert if set, controls the time when the connection
// should be disconnected because the client cert expires
disconnectExpiredCert time.Time
// certExpires is the client certificate expiration timestamp.
certExpires time.Time
// sessionTTL specifies the duration of the user's session
sessionTTL time.Duration
// kubeCluster is the Kubernetes cluster the request is targeted to.
// It's only available after authorization layer.
kubeCluster types.KubeCluster
// kubeResource is the kubernetes resource the request is targeted at.
// Can be nil, if the resource is not a pod or the request is not targeted
// at a specific pod.
// If non empty, kubeResource.Kind is populated with type "pod",
// kubeResource.Namespace is the resource namespace and kubeResource.Name
// is the resource name.
kubeResource *types.KubernetesResource
// requestVerb is the Kubernetes Verb.
requestVerb string
// kubeServers are the registered agents for the kubernetes cluster the request
// is targeted to.
kubeServers []types.KubeServer
// apiResource holds the information about the requested API resource.
apiResource apiResource
// isLocalKubernetesCluster is true if the target cluster is served by this teleport service.
// It is false if the target cluster is served by another teleport service or a different
// Teleport cluster.
isLocalKubernetesCluster bool
}
func (c authContext) String() string {
return fmt.Sprintf("user: %v, users: %v, groups: %v, teleport cluster: %v, kube cluster: %v", c.User.GetName(), c.kubeUsers, c.kubeGroups, c.teleportCluster.name, c.kubeClusterName)
}
func (c *authContext) key() string {
// it is important that the context key contains user, kubernetes groups and certificate expiry,
// so that new logins with different parameters will not reuse this context
return fmt.Sprintf("%v:%v:%v:%v:%v:%v:%v", c.teleportCluster.name, c.User.GetName(), c.kubeUsers, c.kubeGroups, c.kubeClusterName, c.certExpires.Unix(), c.Identity.GetIdentity().ActiveRequests)
}
func (c *authContext) eventClusterMeta(req *http.Request) apievents.KubernetesClusterMetadata {
var kubeUsers, kubeGroups []string
if impersonateUser, impersonateGroups, err := computeImpersonatedPrincipals(c.kubeUsers, c.kubeGroups, req.Header); err == nil {
kubeUsers = []string{impersonateUser}
kubeGroups = impersonateGroups
} else {
kubeUsers = utils.StringsSliceFromSet(c.kubeUsers)
kubeGroups = utils.StringsSliceFromSet(c.kubeGroups)
}
return apievents.KubernetesClusterMetadata{
KubernetesCluster: c.kubeClusterName,
KubernetesUsers: kubeUsers,
KubernetesGroups: kubeGroups,
KubernetesLabels: c.kubeClusterLabels,
}
}
func (c *authContext) eventUserMeta() apievents.UserMetadata {
name := c.User.GetName()
meta := c.Identity.GetIdentity().GetUserMetadata()
meta.User = name
meta.Login = name
return meta
}
func (c *authContext) eventUserMetaWithLogin(login string) apievents.UserMetadata {
meta := c.eventUserMeta()
meta.Login = login
return meta
}
// teleportClusterClient is a client for either a k8s endpoint in local cluster or a
// proxy endpoint in a remote cluster.
type teleportClusterClient struct {
remoteAddr utils.NetAddr
name string
isRemote bool
}
// handlerWithAuthFunc is http handler with passed auth context
type handlerWithAuthFunc func(ctx *authContext, w http.ResponseWriter, r *http.Request, p httprouter.Params) (any, error)
// handlerWithAuthFuncStd is http handler with passed auth context
type handlerWithAuthFuncStd func(ctx *authContext, w http.ResponseWriter, r *http.Request) (any, error)
// accessDeniedMsg is a message returned to the client when access is denied.
const accessDeniedMsg = "[00] access denied"
// authenticate function authenticates request
func (f *Forwarder) authenticate(req *http.Request) (*authContext, error) {
// If the cluster is not licensed for Kubernetes, return an error to the client.
if !f.cfg.ClusterFeatures.GetEntitlement(entitlements.K8s).Enabled {
// If the cluster is not licensed for Kubernetes, return an error to the client.
return nil, trace.AccessDenied("Teleport cluster is not licensed for Kubernetes")
}
ctx, span := f.cfg.tracer.Start(
req.Context(),
"kube.Forwarder/authenticate",
oteltrace.WithSpanKind(oteltrace.SpanKindServer),
oteltrace.WithAttributes(
semconv.RPCServiceKey.String(f.cfg.KubeServiceType),
semconv.RPCSystemKey.String("kube"),
),
)
defer span.End()
var isRemoteUser bool
userTypeI, err := authz.UserFromContext(ctx)
if err != nil {
f.log.WarnContext(ctx, "error getting user from context", "error", err)
return nil, trace.AccessDenied("%s", accessDeniedMsg)
}
switch userTypeI.(type) {
case authz.LocalUser:
case authz.RemoteUser:
isRemoteUser = true
case authz.BuiltinRole:
f.log.WarnContext(ctx, "Denying proxy access to unauthenticated user - this can sometimes be caused by inadvertently using an HTTP load balancer instead of a TCP load balancer on the Kubernetes port",
"user_type", logutils.TypeAttr(userTypeI),
)
return nil, trace.AccessDenied("%s", accessDeniedMsg)
default:
f.log.WarnContext(ctx, "Denying proxy access to unsupported user type", "user_type", logutils.TypeAttr(userTypeI))
return nil, trace.AccessDenied("%s", accessDeniedMsg)
}
userContext, err := f.cfg.Authz.Authorize(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
authContext, err := f.setupContext(ctx, *userContext, req, isRemoteUser)
if err != nil {
f.log.WarnContext(ctx, "Unable to setup context", "error", err)
if trace.IsAccessDenied(err) {
return nil, trace.AccessDenied("%s", accessDeniedMsg)
}
return nil, trace.Wrap(err)
}
return authContext, nil
}
func (f *Forwarder) withAuthStd(handler handlerWithAuthFuncStd) http.HandlerFunc {
return httplib.MakeStdHandlerWithErrorWriter(func(w http.ResponseWriter, req *http.Request) (any, error) {
ctx, span := f.cfg.tracer.Start(
req.Context(),
"kube.Forwarder/withAuthStd",
oteltrace.WithSpanKind(oteltrace.SpanKindServer),
oteltrace.WithAttributes(
semconv.RPCServiceKey.String(f.cfg.KubeServiceType),
semconv.RPCSystemKey.String("kube"),
),
)
req = req.WithContext(ctx)
defer span.End()
authContext, err := f.authenticate(req)
if err != nil {
return nil, trace.Wrap(err)
}
if err := f.authorize(ctx, authContext); err != nil {
return nil, trace.Wrap(err)
}
return handler(authContext, w, req)
}, f.formatStatusResponseError)
}
// acquireConnectionLockWithIdentity acquires a connection lock under a given identity.
func (f *Forwarder) acquireConnectionLockWithIdentity(ctx context.Context, identity *authContext) error {
ctx, span := f.cfg.tracer.Start(
ctx,
"kube.Forwarder/acquireConnectionLockWithIdentity",
oteltrace.WithSpanKind(oteltrace.SpanKindServer),
oteltrace.WithAttributes(
semconv.RPCServiceKey.String(f.cfg.KubeServiceType),
semconv.RPCSystemKey.String("kube"),
),
)
defer span.End()
user := identity.Identity.GetIdentity().Username
roles, err := getRolesByName(f, identity.Identity.GetIdentity().Groups)
if err != nil {
return trace.Wrap(err)
}
if err := f.acquireConnectionLock(ctx, user, roles); err != nil {
return trace.Wrap(err)
}
return nil
}
// authOption is a functional option for authOptions.
type authOption func(*authOptions)
// authOptions is a set of options for withAuth handler.
type authOptions struct {
// errFormater is a function that formats the error response.
errFormater func(http.ResponseWriter, error)
}
// withCustomErrFormatter allows to override the default error formatter.
func withCustomErrFormatter(f func(http.ResponseWriter, error)) authOption {
return func(o *authOptions) {
o.errFormater = f
}
}
func (f *Forwarder) withAuth(handler handlerWithAuthFunc, opts ...authOption) httprouter.Handle {
authOpts := authOptions{
errFormater: f.formatStatusResponseError,
}
for _, opt := range opts {
opt(&authOpts)
}
return httplib.MakeHandlerWithErrorWriter(func(w http.ResponseWriter, req *http.Request, p httprouter.Params) (any, error) {
ctx, span := f.cfg.tracer.Start(
req.Context(),
"kube.Forwarder/withAuth",
oteltrace.WithSpanKind(oteltrace.SpanKindServer),
oteltrace.WithAttributes(
semconv.RPCServiceKey.String(f.cfg.KubeServiceType),
semconv.RPCSystemKey.String("kube"),
),
)
req = req.WithContext(ctx)
defer span.End()
authContext, err := f.authenticate(req)
if err != nil {
return nil, trace.Wrap(err)
}
if err := f.authorize(ctx, authContext); err != nil {
return nil, trace.Wrap(err)
}
err = f.acquireConnectionLockWithIdentity(ctx, authContext)
if err != nil {
return nil, trace.Wrap(err)
}
return handler(authContext, w, req, p)
}, authOpts.errFormater)
}
// withAuthPassthrough authenticates the request and fetches information but doesn't deny if the user
// doesn't have RBAC access to the Kubernetes cluster.
func (f *Forwarder) withAuthPassthrough(handler handlerWithAuthFunc) httprouter.Handle {
return httplib.MakeHandlerWithErrorWriter(func(w http.ResponseWriter, req *http.Request, p httprouter.Params) (any, error) {
ctx, span := f.cfg.tracer.Start(
req.Context(),
"kube.Forwarder/withAuthPassthrough",
oteltrace.WithSpanKind(oteltrace.SpanKindServer),
oteltrace.WithAttributes(
semconv.RPCServiceKey.String(f.cfg.KubeServiceType),
semconv.RPCSystemKey.String("kube"),
),
)
req = req.WithContext(ctx)
defer span.End()
authContext, err := f.authenticate(req)
if err != nil {
return nil, trace.Wrap(err)
}
err = f.acquireConnectionLockWithIdentity(req.Context(), authContext)
if err != nil {
return nil, trace.Wrap(err)
}
return handler(authContext, w, req, p)
}, f.formatStatusResponseError)
}
func (f *Forwarder) formatForwardResponseError(rw http.ResponseWriter, r *http.Request, respErr error) {
f.formatStatusResponseError(rw, respErr)
}
// writeResponseErrorToBody writes the error response to the body without any formatting.
// It is used for the /version endpoint since Kubernetes doesn't expect a JSON response
// for that endpoint.
func (f *Forwarder) writeResponseErrorToBody(rw http.ResponseWriter, respErr error) {
http.Error(rw, respErr.Error(), http.StatusInternalServerError)
}
// formatStatusResponseError formats the error response into a kube Status object.
func (f *Forwarder) formatStatusResponseError(rw http.ResponseWriter, respErr error) {
code := trace.ErrorToCode(respErr)
status := &metav1.Status{
Status: metav1.StatusFailure,
// Don't trace.Unwrap the error, in case it was wrapped with a
// user-friendly message. The underlying root error is likely too
// low-level to be useful.
Message: respErr.Error(),
Code: int32(code),
Reason: errorToKubeStatusReason(respErr, code),
}
data, err := runtime.Encode(globalKubeCodecs.LegacyCodec(), status)
if err != nil {
f.log.WarnContext(f.ctx, "Failed encoding error into kube Status object", "error", err)
trace.WriteError(rw, respErr)
return
}
rw.Header().Set(responsewriters.ContentTypeHeader, "application/json")
// Always write the correct error code in the response so kubectl can parse
// it correctly. If response code and status.Code drift, kubectl prints
// `Error from server (InternalError): an error on the server ("unknown")
// has prevented the request from succeeding`` instead of the correct reason.
rw.WriteHeader(trace.ErrorToCode(respErr))
if _, err := rw.Write(data); err != nil {
f.log.WarnContext(f.ctx, "Failed writing kube error response body", "error", err)
}
}
func (f *Forwarder) setupContext(
ctx context.Context,
authCtx authz.Context,
req *http.Request,
isRemoteUser bool,
) (*authContext, error) {
ctx, span := f.cfg.tracer.Start(
ctx,
"kube.Forwarder/setupContext",
oteltrace.WithSpanKind(oteltrace.SpanKindServer),
oteltrace.WithAttributes(
semconv.RPCServiceKey.String(f.cfg.KubeServiceType),
semconv.RPCSystemKey.String("kube"),
),
)
defer span.End()
roles := authCtx.Checker
// adjust session ttl to the smaller of two values: the session
// ttl requested in tsh or the session ttl for the role.
sessionTTL := roles.AdjustSessionTTL(time.Hour)
identity := authCtx.Identity.GetIdentity()
teleportClusterName := identity.RouteToCluster
if teleportClusterName == "" {
teleportClusterName = f.cfg.ClusterName
}
isRemoteCluster := f.cfg.ClusterName != teleportClusterName
if isRemoteCluster && isRemoteUser {
return nil, trace.AccessDenied("access denied: remote user can not access remote cluster")
}
var (
kubeServers []types.KubeServer
kubeResource *types.KubernetesResource
apiResource apiResource
err error
)
kubeCluster := identity.KubernetesCluster
// Only check k8s principals for local clusters.
//
// For remote clusters, everything will be remapped to new roles on the
// leaf and checked there.
if !isRemoteCluster {
kubeServers, err = f.getKubernetesServersForKubeCluster(ctx, kubeCluster)
if err != nil || len(kubeServers) == 0 {
return nil, trace.NotFound("Kubernetes cluster %q not found", kubeCluster)
}
}
isLocalKubernetesCluster := f.isLocalKubeCluster(isRemoteCluster, kubeCluster)
if isLocalKubernetesCluster {
kubeResource, apiResource, err = f.parseResourceFromRequest(req, kubeCluster)
if err != nil {
return nil, trace.Wrap(err)
}
}
netConfig, err := f.cfg.CachingAuthClient.GetClusterNetworkingConfig(f.ctx)
if err != nil {
return nil, trace.Wrap(err)
}
recordingConfig, err := f.cfg.CachingAuthClient.GetSessionRecordingConfig(f.ctx)
if err != nil {
return nil, trace.Wrap(err)
}
authPref, err := f.cfg.CachingAuthClient.GetAuthPreference(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
return &authContext{
clientIdleTimeout: roles.AdjustClientIdleTimeout(netConfig.GetClientIdleTimeout()),
clientIdleTimeoutMessage: netConfig.GetClientIdleTimeoutMessage(),
sessionTTL: sessionTTL,
Context: authCtx,
recordingConfig: recordingConfig,
kubeClusterName: kubeCluster,
certExpires: identity.Expires,
disconnectExpiredCert: authCtx.GetDisconnectCertExpiry(authPref),
teleportCluster: teleportClusterClient{
name: teleportClusterName,
remoteAddr: utils.NetAddr{AddrNetwork: "tcp", Addr: req.RemoteAddr},
isRemote: isRemoteCluster,
},
kubeServers: kubeServers,
requestVerb: apiResource.getVerb(req),
apiResource: apiResource,
kubeResource: kubeResource,
isLocalKubernetesCluster: isLocalKubernetesCluster,
}, nil
}
func (f *Forwarder) parseResourceFromRequest(req *http.Request, kubeClusterName string) (*types.KubernetesResource, apiResource, error) {
switch f.cfg.KubeServiceType {
case LegacyProxyService:
if details, err := f.findKubeDetailsByClusterName(kubeClusterName); err == nil {
resource, apiRes, err := getResourceFromRequest(req, details)
return resource, apiRes, trace.Wrap(err)
}
// When the cluster is not being served by the local service, the LegacyProxy
// is working as a normal proxy and will forward the request to the remote
// service. When this happens, proxy won't enforce any Kubernetes RBAC rules
// and will forward the request as is to the remote service. The remote
// service will enforce RBAC rules and will return an error if the user is
// not authorized.
fallthrough
case ProxyService:
// When the service is acting as a proxy (ProxyService or LegacyProxyService
// if the local cluster wasn't found), the proxy will forward the request
// to the remote service without enforcing any RBAC rules - we send the
// details = nil to indicate that we don't want to extract the kube resource
// from the request.
resource, apiRes, err := getResourceFromRequest(req, nil /*details*/)
return resource, apiRes, trace.Wrap(err)
case KubeService:
details, err := f.findKubeDetailsByClusterName(kubeClusterName)
if err != nil {
return nil, apiResource{}, trace.Wrap(err)
}
resource, apiRes, err := getResourceFromRequest(req, details)
return resource, apiRes, trace.Wrap(err)
default:
return nil, apiResource{}, trace.BadParameter("unsupported kube service type: %q", f.cfg.KubeServiceType)
}
}
// emitAuditEvent emits the audit event for a `kube.request` event if the session
// requires audit events.
func (f *Forwarder) emitAuditEvent(req *http.Request, sess *clusterSession, status int) {
_, span := f.cfg.tracer.Start(
req.Context(),
"kube.Forwarder/emitAuditEvent",
oteltrace.WithSpanKind(oteltrace.SpanKindServer),
oteltrace.WithAttributes(
semconv.RPCServiceKey.String(f.cfg.KubeServiceType),
semconv.RPCSystemKey.String("kube"),
),
)
defer span.End()
// If the session is not local, don't emit the event.
if !sess.isLocalKubernetesCluster {
return
}
r := sess.apiResource
if r.skipEvent {
return
}
// Emit audit event.
event := &apievents.KubeRequest{
Metadata: apievents.Metadata{
Type: events.KubeRequestEvent,
Code: events.KubeRequestCode,
},
UserMetadata: sess.eventUserMeta(),
ConnectionMetadata: apievents.ConnectionMetadata{
RemoteAddr: req.RemoteAddr,
LocalAddr: sess.kubeAddress,
Protocol: events.EventProtocolKube,
},
ServerMetadata: sess.getServerMetadata(),
RequestPath: req.URL.Path,
Verb: req.Method,
ResponseCode: int32(status),
KubernetesClusterMetadata: sess.eventClusterMeta(req),
SessionMetadata: apievents.SessionMetadata{
WithMFA: sess.Identity.GetIdentity().MFAVerified,
},
}
r.populateEvent(event)
if err := f.cfg.AuthClient.EmitAuditEvent(f.ctx, event); err != nil {
f.log.WarnContext(f.ctx, "Failed to emit event", "error", err)
}
}
// fillDefaultKubePrincipalDetails fills the default details in order to keep
// the correct behavior when forwarding the request to the Kubernetes API.
// By default, if no kubernetes_users are set (which will be a majority), a
// user will impersonate himself, which is the backwards-compatible behavior.
// We also append teleport.KubeSystemAuthenticated to kubernetes_groups, which is
// a builtin group that allows any user to access common API methods,
// e.g. discovery methods required for initial client usage, without it,
// restricted user's kubectl clients will not work.
func fillDefaultKubePrincipalDetails(kubeUsers []string, kubeGroups []string, username string) ([]string, []string) {
if len(kubeUsers) == 0 {
kubeUsers = append(kubeUsers, username)
}
if !slices.Contains(kubeGroups, teleport.KubeSystemAuthenticated) {
kubeGroups = append(kubeGroups, teleport.KubeSystemAuthenticated)
}
return kubeUsers, kubeGroups
}
// kubeAccessDetails holds the allowed kube groups/users names and the cluster labels for a local kube cluster.
type kubeAccessDetails struct {
// list of allowed kube users
kubeUsers []string
// list of allowed kube groups
kubeGroups []string
// kube cluster labels
clusterLabels map[string]string
}
// getKubeAccessDetails returns the allowed kube groups/users names and the cluster labels for a local kube cluster.
func (f *Forwarder) getKubeAccessDetails(
kubeServers []types.KubeServer,
accessChecker services.AccessChecker,
kubeClusterName string,
sessionTTL time.Duration,
kubeResource *types.KubernetesResource,
) (kubeAccessDetails, error) {
// Find requested kubernetes cluster name and get allowed kube users/groups names.
for _, s := range kubeServers {
c := s.GetCluster()
if c.GetName() != kubeClusterName {
continue
}
// Get list of allowed kube user/groups based on kubernetes service labels.
labels := types.CombineLabels(c.GetStaticLabels(), types.LabelsToV2(c.GetDynamicLabels()))
matchers := make([]services.RoleMatcher, 0, 2)
// Creates a matcher that matches the cluster labels against `kubernetes_labels`
// defined for each user's role.
matchers = append(matchers,
services.NewKubernetesClusterLabelMatcher(labels, accessChecker.Traits()),
)
// If the kubeResource is available, append an extra matcher that validates
// if the kubernetes resource is allowed by the user roles that satisfy the
// target cluster labels.
// Each role defines `kubernetes_resources` and when kubeResource is available,
// KubernetesResourceMatcher will match roles that statisfy the resources at the
// same time that ClusterLabelMatcher matches the role's "kubernetes_labels".
// The call to roles.CheckKubeGroupsAndUsers when both matchers are provided
// results in the intersection of roles that match the "kubernetes_labels" and
// roles that allow access to the desired "kubernetes_resource".
// If from the intersection results an empty set, the request is denied.
if kubeResource != nil {