-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
auth_with_roles.go
7641 lines (6628 loc) · 276 KB
/
auth_with_roles.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 auth
import (
"cmp"
"context"
"fmt"
"net/url"
"os"
"slices"
"strings"
"time"
"github.com/google/uuid"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
collectortracev1 "go.opentelemetry.io/proto/otlp/collector/trace/v1"
otlpcommonv1 "go.opentelemetry.io/proto/otlp/common/v1"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/client"
"github.com/gravitational/teleport/api/client/proto"
"github.com/gravitational/teleport/api/constants"
apidefaults "github.com/gravitational/teleport/api/defaults"
auditlogpb "github.com/gravitational/teleport/api/gen/proto/go/teleport/auditlog/v1"
headerv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/header/v1"
identitycenterv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/identitycenter/v1"
mfav1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/mfa/v1"
"github.com/gravitational/teleport/api/internalutils/stream"
"github.com/gravitational/teleport/api/metadata"
"github.com/gravitational/teleport/api/types"
apievents "github.com/gravitational/teleport/api/types/events"
"github.com/gravitational/teleport/api/types/wrappers"
apiutils "github.com/gravitational/teleport/api/utils"
"github.com/gravitational/teleport/api/utils/keys"
"github.com/gravitational/teleport/entitlements"
"github.com/gravitational/teleport/lib/auth/authclient"
"github.com/gravitational/teleport/lib/auth/clusterconfig/clusterconfigv1"
"github.com/gravitational/teleport/lib/auth/okta"
"github.com/gravitational/teleport/lib/authz"
"github.com/gravitational/teleport/lib/backend"
"github.com/gravitational/teleport/lib/defaults"
dtauthz "github.com/gravitational/teleport/lib/devicetrust/authz"
dtconfig "github.com/gravitational/teleport/lib/devicetrust/config"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/modules"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/services/local"
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/tlsca"
)
// ServerWithRoles is a wrapper around auth service
// methods that focuses on authorizing every request
type ServerWithRoles struct {
authServer *Server
alog events.AuditLogSessionStreamer
// context holds authorization context
context authz.Context
}
// CloseContext is closed when the auth server shuts down
func (a *ServerWithRoles) CloseContext() context.Context {
return a.authServer.closeCtx
}
// actionForResource will determine if a user has access to the given resource. This call respects where clauses.
func (a *ServerWithRoles) actionForResource(resource types.Resource, kind string, verbs ...string) error {
sctx := &services.Context{User: a.context.User}
if resource != nil {
sctx.Resource = resource
}
return trace.Wrap(a.actionWithContext(sctx, kind, verbs...))
}
// actionWithContext will determine if a user has access given a services.Context. This call respects where clauses.
func (a *ServerWithRoles) actionWithContext(ctx *services.Context, resource string, verbs ...string) error {
if len(verbs) == 0 {
return trace.BadParameter("no verbs provided for authorization check on resource %q", resource)
}
var errs []error
for _, verb := range verbs {
errs = append(errs, a.context.Checker.CheckAccessToRule(ctx, apidefaults.Namespace, resource, verb))
}
if err := trace.NewAggregate(errs...); err != nil {
return err
}
return nil
}
func (a *ServerWithRoles) actionNamespace(namespace, resource string, verbs ...string) error {
if len(verbs) == 0 {
return trace.BadParameter("no verbs provided for authorization check on resource %q", resource)
}
var errs []error
for _, verb := range verbs {
errs = append(errs, a.context.Checker.CheckAccessToRule(&services.Context{User: a.context.User}, namespace, resource, verb))
}
if err := trace.NewAggregate(errs...); err != nil {
return err
}
return nil
}
func (a *ServerWithRoles) action(resource string, verbs ...string) error {
return a.actionNamespace(apidefaults.Namespace, resource, verbs...)
}
// currentUserAction is a special checker that allows certain actions for users
// even if they are not admins, e.g. update their own passwords,
// or generate certificates, otherwise it will require admin privileges
func (a *ServerWithRoles) currentUserAction(username string) error {
if authz.IsCurrentUser(a.context, username) {
return nil
}
return a.context.Checker.CheckAccessToRule(&services.Context{User: a.context.User},
apidefaults.Namespace, types.KindUser, types.VerbCreate)
}
// authConnectorAction is a special checker that grants access to auth
// connectors. It first checks if you have access to the specific connector.
// If not, it checks if the requester has the meta KindAuthConnector access
// (which grants access to all connectors).
func (a *ServerWithRoles) authConnectorAction(resource string, verb string) error {
if err := a.context.Checker.CheckAccessToRule(&services.Context{User: a.context.User}, apidefaults.Namespace, resource, verb); err != nil {
if err := a.context.Checker.CheckAccessToRule(&services.Context{User: a.context.User}, apidefaults.Namespace, types.KindAuthConnector, verb); err != nil {
return trace.Wrap(err)
}
}
return nil
}
// identityCenterAction is a special checker that grants access to Identity Center
// resources. In order to simplify the writing of role condition statements, the
// various Identity Center resources are bundled up under an umbrella
// `KindIdentityCenter` resource kind. This means that if access to the target
// resource is not explicitly denied, then the user has a second chance to get
// access via the generic resource kind.
func (a *ServerWithRoles) identityCenterAction(namespace string, resource string, verbs ...string) error {
err := a.actionNamespace(namespace, resource, verbs...)
if err == nil || services.IsAccessExplicitlyDenied(err) {
return trace.Wrap(err)
}
return trace.Wrap(a.actionNamespace(namespace, types.KindIdentityCenter, verbs...))
}
// actionForListWithCondition extracts a restrictive filter condition to be
// added to a list query after a simple resource check fails.
func (a *ServerWithRoles) actionForListWithCondition(resource, identifier string) (*types.WhereExpr, error) {
origErr := a.action(resource, types.VerbList)
if origErr == nil || !trace.IsAccessDenied(origErr) {
return nil, trace.Wrap(origErr)
}
cond, err := a.context.Checker.ExtractConditionForIdentifier(&services.Context{User: a.context.User}, apidefaults.Namespace, resource, types.VerbList, identifier)
if trace.IsAccessDenied(err) {
log.WithError(err).Infof("Access to %v %v in namespace %v denied to %v.", types.VerbList, resource, apidefaults.Namespace, a.context.Checker)
// Return the original AccessDenied to avoid leaking information.
return nil, trace.Wrap(origErr)
}
return cond, trace.Wrap(err)
}
// actionWithExtendedContext performs an additional RBAC check with extended
// rule context after a simple resource check fails.
func (a *ServerWithRoles) actionWithExtendedContext(kind, verb string, extendContext func(*services.Context) error) error {
ruleCtx := &services.Context{User: a.context.User}
origErr := a.context.Checker.CheckAccessToRule(ruleCtx, apidefaults.Namespace, kind, verb)
if origErr == nil || !trace.IsAccessDenied(origErr) {
return trace.Wrap(origErr)
}
if err := extendContext(ruleCtx); err != nil {
log.WithError(err).Warning("Failed to extend context for second RBAC check.")
// Return the original AccessDenied to avoid leaking information.
return trace.Wrap(origErr)
}
return trace.Wrap(a.context.Checker.CheckAccessToRule(ruleCtx, apidefaults.Namespace, kind, verb))
}
// actionForKindSession is a special checker that grants access to session
// recordings. It can allow access to a specific recording based on the
// `where` section of the user's access rule for kind `session`.
func (a *ServerWithRoles) actionForKindSession(ctx context.Context, sid session.ID) (types.SessionKind, error) {
sessionEnd, err := a.findSessionEndEvent(ctx, sid)
extendContext := func(ctx *services.Context) error {
ctx.Session = sessionEnd
return trace.Wrap(err)
}
var sessionKind types.SessionKind
switch e := sessionEnd.(type) {
case *apievents.SessionEnd:
sessionKind = types.SSHSessionKind
if e.KubernetesCluster != "" {
sessionKind = types.KubernetesSessionKind
}
case *apievents.DatabaseSessionEnd:
sessionKind = types.DatabaseSessionKind
case *apievents.AppSessionEnd:
sessionKind = types.AppSessionKind
case *apievents.WindowsDesktopSessionEnd:
sessionKind = types.WindowsDesktopSessionKind
}
return sessionKind, trace.Wrap(a.actionWithExtendedContext(types.KindSession, types.VerbRead, extendContext))
}
// localServerAction returns an access denied error if the role is not one of the builtin server roles.
func (a *ServerWithRoles) localServerAction() error {
role, ok := a.context.Identity.(authz.BuiltinRole)
if !ok || !role.IsServer() {
return trace.AccessDenied("this request can be only executed by a teleport built-in server")
}
return nil
}
// remoteServerAction returns an access denied error if the role is not one of the remote builtin server roles.
func (a *ServerWithRoles) remoteServerAction() error {
role, ok := a.context.UnmappedIdentity.(authz.RemoteBuiltinRole)
if !ok || !role.IsRemoteServer() {
return trace.AccessDenied("this request can be only executed by a teleport remote server")
}
return nil
}
// isLocalOrRemoteServerAction returns true if the role is one of the builtin server roles (local or remote).
func (a *ServerWithRoles) isLocalOrRemoteServerAction() bool {
errLocal := a.localServerAction()
errRemote := a.remoteServerAction()
return errLocal == nil || errRemote == nil
}
// hasBuiltinRole checks that the attached identity is a builtin role and
// whether any of the given roles match the role set.
func (a *ServerWithRoles) hasBuiltinRole(roles ...types.SystemRole) bool {
for _, role := range roles {
if authz.HasBuiltinRole(a.context, string(role)) {
return true
}
}
return false
}
// HasBuiltinRole checks if the identity is a builtin role with the matching
// name.
// Deprecated: use authz.HasBuiltinRole instead.
func HasBuiltinRole(authContext authz.Context, name string) bool {
// TODO(jakule): This function can be removed once teleport.e is updated
// to use authz.HasBuiltinRole.
return authz.HasBuiltinRole(authContext, name)
}
// HasRemoteBuiltinRole checks if the identity is a remote builtin role with the
// matching name.
func HasRemoteBuiltinRole(authContext authz.Context, name string) bool {
if _, ok := authContext.UnmappedIdentity.(authz.RemoteBuiltinRole); !ok {
return false
}
if !authContext.Checker.HasRole(name) {
return false
}
return true
}
// hasRemoteBuiltinRole checks if the identity is a remote builtin role and the
// name matches.
func (a *ServerWithRoles) hasRemoteBuiltinRole(name string) bool {
return HasRemoteBuiltinRole(a.context, name)
}
// CreateSessionTracker creates a tracker resource for an active session.
func (a *ServerWithRoles) CreateSessionTracker(ctx context.Context, tracker types.SessionTracker) (types.SessionTracker, error) {
if err := a.localServerAction(); err != nil {
return nil, trace.Wrap(err)
}
tracker, err := a.authServer.CreateSessionTracker(ctx, tracker)
if err != nil {
return nil, trace.Wrap(err)
}
return tracker, nil
}
func (a *ServerWithRoles) filterSessionTracker(joinerRoles []types.Role, tracker types.SessionTracker, verb string) bool {
// Apply RFD 45 RBAC rules to the session if it's SSH.
// This is a bit of a hack. It converts to the old legacy format
// which we don't have all data for, luckily the fields we don't have aren't made available
// to the RBAC filter anyway.
if tracker.GetSessionKind() == types.SSHSessionKind {
ruleCtx := &services.Context{User: a.context.User}
ruleCtx.SSHSession = &session.Session{
Kind: tracker.GetSessionKind(),
ID: session.ID(tracker.GetSessionID()),
Namespace: apidefaults.Namespace,
Login: tracker.GetLogin(),
Created: tracker.GetCreated(),
LastActive: a.authServer.GetClock().Now(),
ServerID: tracker.GetAddress(),
ServerAddr: tracker.GetAddress(),
ServerHostname: tracker.GetHostname(),
ClusterName: tracker.GetClusterName(),
}
for _, participant := range tracker.GetParticipants() {
// We only need to fill in User here since other fields get discarded anyway.
ruleCtx.SSHSession.Parties = append(ruleCtx.SSHSession.Parties, session.Party{
User: participant.User,
})
}
// Skip past it if there's a deny rule in place blocking access.
if err := a.context.Checker.CheckAccessToRule(ruleCtx, apidefaults.Namespace, types.KindSSHSession, verb); err != nil {
return false
}
}
ruleCtx := &services.Context{User: a.context.User, SessionTracker: tracker}
if a.context.Checker.CheckAccessToRule(ruleCtx, apidefaults.Namespace, types.KindSessionTracker, types.VerbList) == nil {
return true
}
evaluator := NewSessionAccessEvaluator(tracker.GetHostPolicySets(), tracker.GetSessionKind(), tracker.GetHostUser())
modes := evaluator.CanJoin(SessionAccessContext{Username: a.context.User.GetName(), Roles: joinerRoles})
return len(modes) != 0
}
const (
forwardedTag = "teleport.forwarded.for"
)
// Export forwards OTLP traces to the upstream collector configured in the tracing service. This allows for
// tsh, tctl, etc to be able to export traces without having to know how to connect to the upstream collector
// for the cluster.
//
// All spans received will have a `teleport.forwarded.for` attribute added to them with the value being one of
// two things depending on the role of the forwarder:
// 1. User forwarded: `teleport.forwarded.for: alice`
// 2. Instance forwarded: `teleport.forwarded.for: Proxy.clustername:Proxy,Node,Instance`
//
// This allows upstream consumers of the spans to be able to identify forwarded spans and act on them accordingly.
func (a *ServerWithRoles) Export(ctx context.Context, req *collectortracev1.ExportTraceServiceRequest) (*collectortracev1.ExportTraceServiceResponse, error) {
var sb strings.Builder
sb.WriteString(a.context.User.GetName())
// if forwarded on behalf of a Teleport service add its system roles
if role, ok := a.context.Identity.(authz.BuiltinRole); ok {
sb.WriteRune(':')
sb.WriteString(role.Role.String())
if len(role.AdditionalSystemRoles) > 0 {
sb.WriteRune(',')
sb.WriteString(role.AdditionalSystemRoles.String())
}
}
// the forwarded attribute to add
value := &otlpcommonv1.KeyValue{
Key: forwardedTag,
Value: &otlpcommonv1.AnyValue{
Value: &otlpcommonv1.AnyValue_StringValue{
StringValue: sb.String(),
},
},
}
// returns the index at which the attribute with
// the forwardedTag key exists, -1 if not found
tagIndex := func(attrs []*otlpcommonv1.KeyValue) int {
for i, attr := range attrs {
if attr.Key == forwardedTag {
return i
}
}
return -1
}
for _, resourceSpans := range req.ResourceSpans {
// if there is a resource, tag it with the
// forwarded attribute instead of each of tagging
// each span
if resourceSpans.Resource != nil {
if index := tagIndex(resourceSpans.Resource.Attributes); index != -1 {
resourceSpans.Resource.Attributes[index] = value
} else {
resourceSpans.Resource.Attributes = append(resourceSpans.Resource.Attributes, value)
}
// override any span attributes with a forwarded tag,
// but we don't need to add one if the span isn't already
// tagged since we just tagged the resource
for _, scopeSpans := range resourceSpans.ScopeSpans {
for _, span := range scopeSpans.Spans {
if index := tagIndex(span.Attributes); index != -1 {
span.Attributes[index] = value
}
}
}
continue
}
// there was no resource, so we must now tag all the
// individual spans with the forwarded tag
for _, scopeSpans := range resourceSpans.ScopeSpans {
for _, span := range scopeSpans.Spans {
if index := tagIndex(span.Attributes); index != -1 {
span.Attributes[index] = value
} else {
span.Attributes = append(span.Attributes, value)
}
}
}
}
if err := a.authServer.traceClient.UploadTraces(ctx, req.ResourceSpans); err != nil {
return &collectortracev1.ExportTraceServiceResponse{}, trace.Wrap(err)
}
return &collectortracev1.ExportTraceServiceResponse{}, nil
}
// GetSessionTracker returns the current state of a session tracker for an active session.
func (a *ServerWithRoles) GetSessionTracker(ctx context.Context, sessionID string) (types.SessionTracker, error) {
tracker, err := a.authServer.GetSessionTracker(ctx, sessionID)
if err != nil {
return nil, trace.Wrap(err)
}
if err := a.localServerAction(); err == nil {
return tracker, nil
}
user := a.context.User
joinerRoles, err := services.FetchRoles(user.GetRoles(), a.authServer, user.GetTraits())
if err != nil {
return nil, trace.Wrap(err)
}
ok := a.filterSessionTracker(joinerRoles, tracker, types.VerbRead)
if !ok {
return nil, trace.NotFound("session %v not found", sessionID)
}
return tracker, nil
}
// GetActiveSessionTrackers returns a list of active session trackers.
func (a *ServerWithRoles) GetActiveSessionTrackers(ctx context.Context) ([]types.SessionTracker, error) {
sessions, err := a.authServer.GetActiveSessionTrackers(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
if err := a.localServerAction(); err == nil {
return sessions, nil
}
var filteredSessions []types.SessionTracker
user := a.context.User
joinerRoles, err := services.FetchRoles(user.GetRoles(), a.authServer, user.GetTraits())
if err != nil {
return nil, trace.Wrap(err)
}
for _, sess := range sessions {
ok := a.filterSessionTracker(joinerRoles, sess, types.VerbList)
if ok {
filteredSessions = append(filteredSessions, sess)
}
}
return filteredSessions, nil
}
// GetActiveSessionTrackersWithFilter returns a list of active sessions filtered by a filter.
func (a *ServerWithRoles) GetActiveSessionTrackersWithFilter(ctx context.Context, filter *types.SessionTrackerFilter) ([]types.SessionTracker, error) {
sessions, err := a.authServer.GetActiveSessionTrackersWithFilter(ctx, filter)
if err != nil {
return nil, trace.Wrap(err)
}
if err := a.localServerAction(); err == nil {
return sessions, nil
}
var filteredSessions []types.SessionTracker
user := a.context.User
joinerRoles, err := services.FetchRoles(user.GetRoles(), a.authServer, user.GetTraits())
if err != nil {
return nil, trace.Wrap(err)
}
for _, sess := range sessions {
ok := a.filterSessionTracker(joinerRoles, sess, types.VerbList)
if ok {
filteredSessions = append(filteredSessions, sess)
}
}
return filteredSessions, nil
}
// RemoveSessionTracker removes a tracker resource for an active session.
func (a *ServerWithRoles) RemoveSessionTracker(ctx context.Context, sessionID string) error {
if err := a.localServerAction(); err != nil {
return trace.Wrap(err)
}
return a.authServer.RemoveSessionTracker(ctx, sessionID)
}
// UpdateSessionTracker updates a tracker resource for an active session.
func (a *ServerWithRoles) UpdateSessionTracker(ctx context.Context, req *proto.UpdateSessionTrackerRequest) error {
if err := a.localServerAction(); err != nil {
return trace.Wrap(err)
}
return a.authServer.UpdateSessionTracker(ctx, req)
}
// AuthenticateWebUser authenticates web user, creates and returns a web session
// in case authentication is successful
func (a *ServerWithRoles) AuthenticateWebUser(ctx context.Context, req authclient.AuthenticateUserRequest) (types.WebSession, error) {
// authentication request has its own authentication, however this limits the requests
// types to proxies to make it harder to break
if !a.hasBuiltinRole(types.RoleProxy) {
return nil, trace.AccessDenied("this request can be only executed by a proxy")
}
return a.authServer.AuthenticateWebUser(ctx, req)
}
// AuthenticateSSHUser authenticates SSH console user, creates and returns a pair of signed TLS and SSH
// short lived certificates as a result
func (a *ServerWithRoles) AuthenticateSSHUser(ctx context.Context, req authclient.AuthenticateSSHRequest) (*authclient.SSHLoginResponse, error) {
// authentication request has its own authentication, however this limits the requests
// types to proxies to make it harder to break
if !a.hasBuiltinRole(types.RoleProxy) {
return nil, trace.AccessDenied("this request can be only executed by a proxy")
}
return a.authServer.AuthenticateSSHUser(ctx, req)
}
// GenerateOpenSSHCert signs a SSH certificate that can be used
// to connect to Agentless nodes.
func (a *ServerWithRoles) GenerateOpenSSHCert(ctx context.Context, req *proto.OpenSSHCertRequest) (*proto.OpenSSHCert, error) {
// this limits the requests types to proxies to make it harder to break
if !a.hasBuiltinRole(types.RoleProxy) && !a.hasRemoteBuiltinRole(string(types.RoleRemoteProxy)) {
return nil, trace.AccessDenied("this request can be only executed by a proxy")
}
return a.authServer.GenerateOpenSSHCert(ctx, req)
}
// CompareAndSwapCertAuthority updates existing cert authority if the existing cert authority
// value matches the value stored in the backend.
func (a *ServerWithRoles) CompareAndSwapCertAuthority(new, existing types.CertAuthority) error {
if err := a.action(types.KindCertAuthority, types.VerbCreate, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.CompareAndSwapCertAuthority(new, existing)
}
func (a *ServerWithRoles) GetDomainName(ctx context.Context) (string, error) {
// anyone can read it, no harm in that
return a.authServer.GetDomainName()
}
// getClusterCACert returns the PEM-encoded TLS certs for the local cluster
// without signing keys. If the cluster has multiple TLS certs, they will all
// be concatenated.
func (a *ServerWithRoles) GetClusterCACert(
ctx context.Context,
) (*proto.GetClusterCACertResponse, error) {
// Allow all roles to get the CA certs.
return a.authServer.GetClusterCACert(ctx)
}
// Deprecated: This method only exists to service the RegisterUsingToken HTTP
// RPC, which has been replaced by an RPC on the JoinServiceServer.
// JoinServiceServer directly invokes auth.Server and performs its own checks
// on metadata.
// TODO(strideynet): DELETE IN V18.0.0
func (a *ServerWithRoles) RegisterUsingToken(ctx context.Context, req *types.RegisterUsingTokenRequest) (*proto.Certs, error) {
isProxy := a.hasBuiltinRole(types.RoleProxy)
// We do not trust remote addr in the request unless it's coming from the Proxy.
if !isProxy || req.RemoteAddr == "" {
if err := setRemoteAddrFromContext(ctx, req); err != nil {
return nil, trace.Wrap(err)
}
}
// Similarly, do not trust bot instance IDs or generation values in the
// request unless from a component with the proxy role (e.g. the join
// service). They will be derived from the client certificate otherwise.
if !isProxy {
if req.BotInstanceID != "" {
log.WithFields(logrus.Fields{
"bot_instance_id": req.BotInstanceID,
}).Warnf("Untrusted client attempted to provide a bot instance ID, this will be ignored")
req.BotInstanceID = ""
}
if req.BotGeneration > 0 {
log.WithFields(logrus.Fields{
"bot_generation": req.BotGeneration,
}).Warnf("Untrusted client attempted to provide a bot generation, this will be ignored")
req.BotGeneration = 0
}
}
// If the identity has a BotInstanceID or BotGeneration included, copy it
// onto the request - but only if one wasn't already passed along via the
// proxy.
ident := a.context.Identity.GetIdentity()
req.BotInstanceID = cmp.Or(req.BotInstanceID, ident.BotInstanceID)
req.BotGeneration = cmp.Or(req.BotGeneration, int32(ident.Generation))
// tokens have authz mechanism on their own, no need to check
return a.authServer.RegisterUsingToken(ctx, req)
}
// GenerateHostCerts generates new host certificates (signed
// by the host certificate authority) for a node.
func (a *ServerWithRoles) GenerateHostCerts(ctx context.Context, req *proto.HostCertsRequest) (*proto.Certs, error) {
clusterName, err := a.authServer.GetDomainName()
if err != nil {
return nil, trace.Wrap(err)
}
// username is hostID + cluster name, so make sure server requests new keys for itself
if a.context.User.GetName() != authclient.HostFQDN(req.HostID, clusterName) {
return nil, trace.AccessDenied("username mismatch %q and %q", a.context.User.GetName(), authclient.HostFQDN(req.HostID, clusterName))
}
if req.Role == types.RoleInstance {
if err := a.checkAdditionalSystemRoles(ctx, req); err != nil {
return nil, trace.Wrap(err)
}
} else {
if len(req.SystemRoles) != 0 {
return nil, trace.AccessDenied("additional system role encoding not supported for certs of type %q", req.Role)
}
}
existingRoles, err := types.NewTeleportRoles(a.context.User.GetRoles())
if err != nil {
return nil, trace.Wrap(err)
}
// prohibit privilege escalations through role changes (except the instance cert exception, handled above).
if !a.hasBuiltinRole(req.Role) && req.Role != types.RoleInstance {
return nil, trace.AccessDenied("roles do not match: %v and %v", existingRoles, req.Role)
}
return a.authServer.GenerateHostCerts(ctx, req)
}
// checkAdditionalSystemRoles verifies additional system roles in host cert request.
func (a *ServerWithRoles) checkAdditionalSystemRoles(ctx context.Context, req *proto.HostCertsRequest) error {
// ensure requesting cert's primary role is a server role.
role, ok := a.context.Identity.(authz.BuiltinRole)
if !ok || !role.IsServer() {
return trace.AccessDenied("additional system roles can only be claimed by a teleport built-in server")
}
// check that additional system roles are theoretically valid (distinct from permissibility, which
// is checked in the following loop).
for _, r := range req.SystemRoles {
if r.Check() != nil {
return trace.AccessDenied("additional system role %q cannot be applied (not a valid system role)", r)
}
if !r.IsLocalService() {
return trace.AccessDenied("additional system role %q cannot be applied (not a builtin service role)", r)
}
}
// load system role assertions if relevant
var assertions proto.SystemRoleAssertionSet
var err error
if req.SystemRoleAssertionID != "" {
assertions, err = a.authServer.GetSystemRoleAssertions(ctx, req.HostID, req.SystemRoleAssertionID)
if err != nil {
// include this error in the logs, since it might be indicative of a bug if it occurs outside of the context
// of a general backend outage.
log.Warnf("Failed to load system role assertion set %q for instance %q: %v", req.SystemRoleAssertionID, req.HostID, err)
return trace.AccessDenied("failed to load system role assertion set with ID %q", req.SystemRoleAssertionID)
}
}
// check if additional system roles are permissible
Outer:
for _, requestedRole := range req.SystemRoles {
if a.hasBuiltinRole(requestedRole) {
// instance is already known to hold this role
continue Outer
}
for _, assertedRole := range assertions.SystemRoles {
if requestedRole == assertedRole {
// instance recently demonstrated that it holds this role
continue Outer
}
}
return trace.AccessDenied("additional system role %q cannot be applied (not authorized)", requestedRole)
}
return nil
}
// AssertSystemRole is used by agents to prove that they have a given system role when their credentials
// originate from multiple separate join tokens so that they can be issued an instance certificate that
// encompasses all of their capabilities. This method will be deprecated once we have a more comprehensive
// model for join token joining/replacement.
func (a *ServerWithRoles) AssertSystemRole(ctx context.Context, req proto.SystemRoleAssertion) error {
role, ok := a.context.Identity.(authz.BuiltinRole)
if !ok || !role.IsServer() {
return trace.AccessDenied("system role assertions can only be executed by a teleport built-in server")
}
if req.ServerID != role.GetServerID() {
return trace.AccessDenied("system role assertions do not support impersonation (%q -> %q)", role.GetServerID(), req.ServerID)
}
if !a.hasBuiltinRole(req.SystemRole) {
return trace.AccessDenied("cannot assert unheld system role %q", req.SystemRole)
}
if !req.SystemRole.IsLocalService() {
return trace.AccessDenied("cannot assert non-service system role %q", req.SystemRole)
}
return a.authServer.AssertSystemRole(ctx, req)
}
// RegisterInventoryControlStream handles the upstream half of the control stream handshake, then passes the control stream to
// the auth server's main control logic. We also return the post-auth hello message back up to the grpcserver layer in order to
// use it for metrics purposes.
func (a *ServerWithRoles) RegisterInventoryControlStream(ics client.UpstreamInventoryControlStream) (proto.UpstreamInventoryHello, error) {
// this value gets set further down
var hello proto.UpstreamInventoryHello
// Ensure that caller is a teleport server
role, ok := a.context.Identity.(authz.BuiltinRole)
if !ok || !role.IsServer() {
return hello, trace.AccessDenied("inventory control streams can only be created by a teleport built-in server")
}
// wait for upstream hello
select {
case msg := <-ics.Recv():
switch m := msg.(type) {
case proto.UpstreamInventoryHello:
hello = m
default:
return hello, trace.BadParameter("expected upstream hello, got: %T", m)
}
case <-ics.Done():
return hello, trace.Wrap(ics.Error())
case <-a.CloseContext().Done():
return hello, trace.Errorf("auth server shutdown")
}
// verify that server is creating stream on behalf of itself.
if hello.ServerID != role.GetServerID() {
return hello, trace.AccessDenied("control streams do not support impersonation (%q -> %q)", role.GetServerID(), hello.ServerID)
}
// in order to reduce sensitivity to downgrades/misconfigurations, we simply filter out
// services that are unrecognized or unauthorized, rather than rejecting hellos that claim them.
var filteredServices []types.SystemRole
for _, service := range hello.Services {
if !a.hasBuiltinRole(service) {
log.Warnf("Omitting service %q for control stream of instance %q (unknown or unauthorized).", service, role.GetServerID())
continue
}
filteredServices = append(filteredServices, service)
}
hello.Services = filteredServices
return hello, a.authServer.RegisterInventoryControlStream(ics, hello)
}
func (a *ServerWithRoles) GetInventoryStatus(ctx context.Context, req proto.InventoryStatusRequest) (proto.InventoryStatusSummary, error) {
if err := a.action(types.KindInstance, types.VerbList, types.VerbRead); err != nil {
return proto.InventoryStatusSummary{}, trace.Wrap(err)
}
if req.Connected {
if !a.hasBuiltinRole(types.RoleAdmin) {
return proto.InventoryStatusSummary{}, trace.AccessDenied("requires local tctl, try using 'tctl inventory ls' instead")
}
}
return a.authServer.GetInventoryStatus(ctx, req)
}
// GetInventoryConnectedServiceCounts returns the counts of each connected service seen in the inventory.
func (a *ServerWithRoles) GetInventoryConnectedServiceCounts() (proto.InventoryConnectedServiceCounts, error) {
// TODO(fspmarshall): switch this to being scoped to instance:read once we have a sane remote version of
// this method. for now we're leaving it as requiring local admin because the returned value is basically
// nonsense if you aren't connected locally.
if !a.hasBuiltinRole(types.RoleAdmin) {
return proto.InventoryConnectedServiceCounts{}, trace.AccessDenied("requires builtin admin role")
}
return a.authServer.GetInventoryConnectedServiceCounts(), nil
}
func (a *ServerWithRoles) PingInventory(ctx context.Context, req proto.InventoryPingRequest) (proto.InventoryPingResponse, error) {
// this is scoped to admin-only not because we don't have appropriate rbac, but because this method doesn't function
// as expected if you aren't connected locally.
if !a.hasBuiltinRole(types.RoleAdmin) {
return proto.InventoryPingResponse{}, trace.AccessDenied("requires builtin admin role")
}
return a.authServer.PingInventory(ctx, req)
}
func (a *ServerWithRoles) GetInstances(ctx context.Context, filter types.InstanceFilter) stream.Stream[types.Instance] {
if err := a.action(types.KindInstance, types.VerbList, types.VerbRead); err != nil {
return stream.Fail[types.Instance](trace.Wrap(err))
}
return a.authServer.GetInstances(ctx, filter)
}
func (a *ServerWithRoles) GetClusterAlerts(ctx context.Context, query types.GetClusterAlertsRequest) ([]types.ClusterAlert, error) {
// unauthenticated clients can never check for alerts. we don't normally explicitly
// check for this kind of thing, but since alerts use an unusual access-control
// pattern, explicitly rejecting the nop role makes things easier.
if a.hasBuiltinRole(types.RoleNop) {
return nil, trace.AccessDenied("alerts not available to unauthenticated clients")
}
alerts, err := a.authServer.GetClusterAlerts(ctx, query)
if err != nil {
return nil, trace.Wrap(err)
}
var acks []types.AlertAcknowledgement
if !query.WithAcknowledged {
// load acks so that we can filter out acknowledged alerts
acks, err = a.authServer.GetAlertAcks(ctx)
if err != nil {
// we don't fail here since users are allowed to see acknowledged alerts, acks
// are intended only as a tool for reducing noise.
log.Warnf("Failed to load alert acks: %v", err)
}
}
// by default we only show alerts whose labels specify that a given user should see them, but users
// with permissions to view all resources of kind 'cluster_alert' can opt into viewing all alerts
// regardless of labels for management/debug purposes.
var resourceLevelPermit bool
if query.WithUntargeted && a.action(types.KindClusterAlert, types.VerbRead, types.VerbList) == nil {
resourceLevelPermit = true
}
// filter alerts by acks and teleport.internal 'permit' labels to determine whether the alert
// was intended to be visible to the calling user.
filtered := alerts[:0]
Outer:
for _, alert := range alerts {
// skip acknowledged alerts
for _, ack := range acks {
if ack.AlertID == alert.Metadata.Name {
continue Outer
}
}
// remaining checks in this loop are evaluating per-alert access, so short-circuit
// if we are going off of resource-level permissions for this query.
if resourceLevelPermit {
filtered = append(filtered, alert)
continue Outer
}
if alert.Metadata.Labels[types.AlertPermitAll] == "yes" {
// alert may be shown to all authenticated users
filtered = append(filtered, alert)
continue Outer
}
// the verb-permit label permits users to view an alert if they hold
// one of the specified <resource>:<verb> pairs (e.g. `node:list|token:create`
// would be satisfied by either a user that can list nodes *or* create tokens).
Verbs:
for _, s := range strings.Split(alert.Metadata.Labels[types.AlertVerbPermit], "|") {
rv := strings.Split(s, ":")
if len(rv) != 2 {
continue Verbs
}
if a.action(rv[0], rv[1]) == nil {
// user holds at least one of the resource:verb pairs specified by
// the verb-permit label.
filtered = append(filtered, alert)
continue Outer
}
}
}
alerts = filtered
if !query.WithSuperseded {
// aggregate supersede directives and filter. we do this as a separate filter
// step since we only obey supersede relationships within the set of
// visible alerts (i.e. an alert that isn't visible cannot supersede an alert
// that is visible).
sups := make(map[string]types.AlertSeverity)
for _, alert := range alerts {
for _, id := range strings.Split(alert.Metadata.Labels[types.AlertSupersedes], ",") {
if sups[id] < alert.Spec.Severity {
sups[id] = alert.Spec.Severity
}
}
}
filtered = alerts[:0]
for _, alert := range alerts {
if sups[alert.Metadata.Name] > alert.Spec.Severity {
continue
}
filtered = append(filtered, alert)
}
alerts = filtered
}
return alerts, nil
}
func (a *ServerWithRoles) UpsertClusterAlert(ctx context.Context, alert types.ClusterAlert) error {
if err := a.action(types.KindClusterAlert, types.VerbCreate, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.UpsertClusterAlert(ctx, alert)
}
func (a *ServerWithRoles) CreateAlertAck(ctx context.Context, ack types.AlertAcknowledgement) error {
// we treat alert acks as an extension of the cluster alert resource rather than its own resource
if err := a.action(types.KindClusterAlert, types.VerbCreate, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.CreateAlertAck(ctx, ack)
}
func (a *ServerWithRoles) GetAlertAcks(ctx context.Context) ([]types.AlertAcknowledgement, error) {
// we treat alert acks as an extension of the cluster alert resource rather than its own resource.
if err := a.action(types.KindClusterAlert, types.VerbRead, types.VerbList); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.GetAlertAcks(ctx)
}
func (a *ServerWithRoles) ClearAlertAcks(ctx context.Context, req proto.ClearAlertAcksRequest) error {
// we treat alert acks as an extension of the cluster alert resource rather than its own resource
if err := a.action(types.KindClusterAlert, types.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.authServer.ClearAlertAcks(ctx, req)
}
func (a *ServerWithRoles) UpsertNode(ctx context.Context, s types.Server) (*types.KeepAlive, error) {
// Note: UpsertNode doesn't allow any namespaces but "default".
if err := a.action(types.KindNode, types.VerbCreate, types.VerbUpdate); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.UpsertNode(ctx, s)
}
// KeepAliveServer updates expiry time of a server resource.
func (a *ServerWithRoles) KeepAliveServer(ctx context.Context, handle types.KeepAlive) error {
clusterName, err := a.GetDomainName(ctx)
if err != nil {
return trace.Wrap(err)
}
serverName, err := ExtractHostID(a.context.User.GetName(), clusterName)
if err != nil {