-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathauth_with_roles.go
4554 lines (4010 loc) · 171 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
/*
Copyright 2015-2021 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 auth
import (
"context"
"net/url"
"time"
"github.com/coreos/go-semver/semver"
"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"
"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/lib/backend"
"github.com/gravitational/teleport/lib/defaults"
"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/utils"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
)
// ServerWithRoles is a wrapper around auth service
// methods that focuses on authorizing every request
type ServerWithRoles struct {
authServer *Server
sessions session.Service
alog events.IAuditLog
// context holds authorization context
context Context
}
// CloseContext is closed when the auth server shuts down
func (a *ServerWithRoles) CloseContext() context.Context {
return a.authServer.closeCtx
}
func (a *ServerWithRoles) actionWithContext(ctx *services.Context, 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(ctx, namespace, resource, verb, false))
}
// Convert generic aggregate error to AccessDenied.
if err := trace.NewAggregate(errs...); err != nil {
return trace.AccessDenied(err.Error())
}
return nil
}
type actionConfig struct {
quiet bool
context Context
}
type actionOption func(*actionConfig)
func quietAction(quiet bool) actionOption {
return func(cfg *actionConfig) {
cfg.quiet = quiet
}
}
func (a *ServerWithRoles) withOptions(opts ...actionOption) actionConfig {
cfg := actionConfig{context: a.context}
for _, opt := range opts {
opt(&cfg)
}
return cfg
}
func (c actionConfig) action(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, c.context.Checker.CheckAccessToRule(&services.Context{User: c.context.User}, namespace, resource, verb, c.quiet))
}
// Convert generic aggregate error to AccessDenied.
if err := trace.NewAggregate(errs...); err != nil {
return trace.AccessDenied(err.Error())
}
return nil
}
func (a *ServerWithRoles) action(namespace, resource string, verbs ...string) error {
return a.withOptions().action(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 hasLocalUserRole(a.context.Checker) && username == a.context.User.GetName() {
return nil
}
return a.context.Checker.CheckAccessToRule(&services.Context{User: a.context.User},
apidefaults.Namespace, types.KindUser, types.VerbCreate, true)
}
// 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(namespace string, resource string, verb string) error {
if err := a.context.Checker.CheckAccessToRule(&services.Context{User: a.context.User}, namespace, resource, verb, true); err != nil {
if err := a.context.Checker.CheckAccessToRule(&services.Context{User: a.context.User}, namespace, types.KindAuthConnector, verb, false); err != nil {
return trace.Wrap(err)
}
}
return nil
}
// actionForListWithCondition extracts a restrictive filter condition to be
// added to a list query after a simple resource check fails.
func (a *ServerWithRoles) actionForListWithCondition(namespace, resource, identifier string) (*types.WhereExpr, error) {
origErr := a.withOptions(quietAction(true)).action(namespace, 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}, 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, 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(namespace, kind, verb string, extendContext func(*services.Context) error) error {
ruleCtx := &services.Context{User: a.context.User}
origErr := a.context.Checker.CheckAccessToRule(ruleCtx, namespace, kind, verb, true)
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, namespace, kind, verb, false))
}
// 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(namespace, verb string, sid session.ID) error {
extendContext := func(ctx *services.Context) error {
sessionEnd, err := a.findSessionEndEvent(namespace, sid)
ctx.Session = sessionEnd
return trace.Wrap(err)
}
return trace.Wrap(a.actionWithExtendedContext(namespace, types.KindSession, verb, extendContext))
}
// actionForKindSSHSession is a special checker that grants access to active SSH
// sessions. It can allow access to a specific session based on the `where`
// section of the user's access rule for kind `ssh_session`.
func (a *ServerWithRoles) actionForKindSSHSession(namespace, verb string, sid session.ID) error {
extendContext := func(ctx *services.Context) error {
session, err := a.sessions.GetSession(namespace, sid)
ctx.SSHSession = session
return trace.Wrap(err)
}
return trace.Wrap(a.actionWithExtendedContext(namespace, types.KindSSHSession, verb, extendContext))
}
// serverAction returns an access denied error if the role is not one of the builtin server roles.
func (a *ServerWithRoles) serverAction() error {
role, ok := a.context.Identity.(BuiltinRole)
if !ok || !role.IsServer() {
return trace.AccessDenied("this request can be only executed by a teleport built-in server")
}
return nil
}
// hasBuiltinRole checks that the attached checker is a BuiltinRoleSet
// and whether any of the given roles match the role set.
func (a *ServerWithRoles) hasBuiltinRole(roles ...types.SystemRole) bool {
for _, role := range roles {
if HasBuiltinRole(a.context.Checker, string(role)) {
return true
}
}
return false
}
// HasBuiltinRole checks the type of the role set returned and the name.
// Returns true if role set is builtin and the name matches.
func HasBuiltinRole(checker services.AccessChecker, name string) bool {
if _, ok := checker.(BuiltinRoleSet); !ok {
return false
}
if !checker.HasRole(name) {
return false
}
return true
}
// HasRemoteBuiltinRole checks the type of the role set returned and the name.
// Returns true if role set is remote builtin and the name matches.
func HasRemoteBuiltinRole(checker services.AccessChecker, name string) bool {
if _, ok := checker.(RemoteBuiltinRoleSet); !ok {
return false
}
if !checker.HasRole(name) {
return false
}
return true
}
// hasRemoteBuiltinRole checks the type of the role set returned and the name.
// Returns true if role set is remote builtin and the name matches.
func (a *ServerWithRoles) hasRemoteBuiltinRole(name string) bool {
return HasRemoteBuiltinRole(a.context.Checker, name)
}
// hasRemoteUserRole checks if the type of the role set is a remote user or
// not.
func hasRemoteUserRole(checker services.AccessChecker) bool {
_, ok := checker.(RemoteUserRoleSet)
return ok
}
// hasLocalUserRole checks if the type of the role set is a local user or not.
func hasLocalUserRole(checker services.AccessChecker) bool {
_, ok := checker.(LocalUserRoleSet)
return ok
}
// 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.serverAction(); 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
}
// 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) {
if err := a.serverAction(); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.GetSessionTracker(ctx, sessionID)
}
// 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)
}
var filteredSessions []types.SessionTracker
for _, sess := range sessions {
evaluator := NewSessionAccessEvaluator(sess.GetHostPolicySets(), sess.GetSessionKind())
joinerRoles, err := a.authServer.GetRoles(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
modes, err := evaluator.CanJoin(SessionAccessContext{Roles: joinerRoles})
if err == nil || len(modes) > 0 {
// 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 sess.GetKind() == types.KindSSHSession {
ruleCtx := &services.Context{User: a.context.User}
ruleCtx.SSHSession = &session.Session{
ID: session.ID(sess.GetSessionID()),
Namespace: apidefaults.Namespace,
Login: sess.GetLogin(),
Created: sess.GetCreated(),
LastActive: a.authServer.GetClock().Now(),
ServerID: sess.GetAddress(),
ServerAddr: sess.GetAddress(),
ServerHostname: sess.GetHostname(),
ClusterName: sess.GetClusterName(),
}
for _, participant := range sess.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, types.VerbList, true /* silent */); err != nil {
continue
}
}
filteredSessions = append(filteredSessions, sess)
} else {
log.Warnf("Session %v is not allowed to join: %v", sess.GetSessionID(), err)
}
}
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.serverAction(); 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.serverAction(); 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(req AuthenticateUserRequest) (types.WebSession, error) {
// authentication request has it's 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(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(req AuthenticateSSHRequest) (*SSHLoginResponse, error) {
// authentication request has it's 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(req)
}
func (a *ServerWithRoles) GetSessions(namespace string) ([]session.Session, error) {
cond, err := a.actionForListWithCondition(namespace, types.KindSSHSession, services.SSHSessionIdentifier)
if err != nil {
return nil, trace.Wrap(err)
}
sessions, err := a.sessions.GetSessions(namespace)
if err != nil {
return nil, trace.Wrap(err)
}
if cond == nil {
return sessions, nil
}
// Filter sessions according to cond.
filteredSessions := make([]session.Session, 0, len(sessions))
ruleCtx := &services.Context{User: a.context.User}
for _, s := range sessions {
ruleCtx.SSHSession = &s
if err := a.context.Checker.CheckAccessToRule(ruleCtx, namespace, types.KindSSHSession, types.VerbList, true /* silent */); err != nil {
continue
}
filteredSessions = append(filteredSessions, s)
}
return filteredSessions, nil
}
func (a *ServerWithRoles) GetSession(namespace string, id session.ID) (*session.Session, error) {
if err := a.actionForKindSSHSession(namespace, types.VerbRead, id); err != nil {
return nil, trace.Wrap(err)
}
return a.sessions.GetSession(namespace, id)
}
func (a *ServerWithRoles) CreateSession(s session.Session) error {
if err := a.action(s.Namespace, types.KindSSHSession, types.VerbCreate); err != nil {
return trace.Wrap(err)
}
return a.sessions.CreateSession(s)
}
func (a *ServerWithRoles) UpdateSession(req session.UpdateRequest) error {
if err := a.actionForKindSSHSession(req.Namespace, types.VerbUpdate, req.ID); err != nil {
return trace.Wrap(err)
}
return a.sessions.UpdateSession(req)
}
// DeleteSession removes an active session from the backend.
func (a *ServerWithRoles) DeleteSession(namespace string, id session.ID) error {
if err := a.actionForKindSSHSession(namespace, types.VerbDelete, id); err != nil {
return trace.Wrap(err)
}
return a.sessions.DeleteSession(namespace, id)
}
// CreateCertAuthority not implemented: can only be called locally.
func (a *ServerWithRoles) CreateCertAuthority(ca types.CertAuthority) error {
return trace.NotImplemented(notImplementedMessage)
}
// RotateCertAuthority starts or restarts certificate authority rotation process.
func (a *ServerWithRoles) RotateCertAuthority(ctx context.Context, req RotateRequest) error {
if err := req.CheckAndSetDefaults(a.authServer.clock); err != nil {
return trace.Wrap(err)
}
if err := a.action(apidefaults.Namespace, types.KindCertAuthority, types.VerbCreate, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.RotateCertAuthority(ctx, req)
}
// RotateExternalCertAuthority rotates external certificate authority,
// this method is called by a remote trusted cluster and is used to update
// only public keys and certificates of the certificate authority.
func (a *ServerWithRoles) RotateExternalCertAuthority(ctx context.Context, ca types.CertAuthority) error {
if ca == nil {
return trace.BadParameter("missing certificate authority")
}
sctx := &services.Context{User: a.context.User, Resource: ca}
if err := a.actionWithContext(sctx, apidefaults.Namespace, types.KindCertAuthority, types.VerbRotate); err != nil {
return trace.Wrap(err)
}
return a.authServer.RotateExternalCertAuthority(ctx, ca)
}
// UpsertCertAuthority updates existing cert authority or updates the existing one.
func (a *ServerWithRoles) UpsertCertAuthority(ca types.CertAuthority) error {
if ca == nil {
return trace.BadParameter("missing certificate authority")
}
ctx := &services.Context{User: a.context.User, Resource: ca}
if err := a.actionWithContext(ctx, apidefaults.Namespace, types.KindCertAuthority, types.VerbCreate, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.UpsertCertAuthority(ca)
}
// 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(apidefaults.Namespace, types.KindCertAuthority, types.VerbCreate, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.CompareAndSwapCertAuthority(new, existing)
}
func (a *ServerWithRoles) GetCertAuthorities(ctx context.Context, caType types.CertAuthType, loadKeys bool, opts ...services.MarshalOption) ([]types.CertAuthority, error) {
if err := a.action(apidefaults.Namespace, types.KindCertAuthority, types.VerbList, types.VerbReadNoSecrets); err != nil {
return nil, trace.Wrap(err)
}
if loadKeys {
if err := a.action(apidefaults.Namespace, types.KindCertAuthority, types.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
}
return a.authServer.GetCertAuthorities(ctx, caType, loadKeys, opts...)
}
func (a *ServerWithRoles) GetCertAuthority(ctx context.Context, id types.CertAuthID, loadKeys bool, opts ...services.MarshalOption) (types.CertAuthority, error) {
if err := a.action(apidefaults.Namespace, types.KindCertAuthority, types.VerbReadNoSecrets); err != nil {
return nil, trace.Wrap(err)
}
if loadKeys {
if err := a.action(apidefaults.Namespace, types.KindCertAuthority, types.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
}
return a.authServer.GetCertAuthority(ctx, id, loadKeys, opts...)
}
func (a *ServerWithRoles) GetDomainName() (string, error) {
// anyone can read it, no harm in that
return a.authServer.GetDomainName()
}
func (a *ServerWithRoles) GetLocalClusterName() (string, error) {
// anyone can read it, no harm in that
return a.authServer.GetLocalClusterName()
}
// 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() (*LocalCAResponse, error) {
// Allow all roles to get the CA certs.
return a.authServer.GetClusterCACert()
}
func (a *ServerWithRoles) UpsertLocalClusterName(clusterName string) error {
if err := a.action(apidefaults.Namespace, types.KindAuthServer, types.VerbCreate, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.UpsertLocalClusterName(clusterName)
}
func (a *ServerWithRoles) DeleteCertAuthority(id types.CertAuthID) error {
if err := a.action(apidefaults.Namespace, types.KindCertAuthority, types.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.authServer.DeleteCertAuthority(id)
}
// ActivateCertAuthority not implemented: can only be called locally.
func (a *ServerWithRoles) ActivateCertAuthority(id types.CertAuthID) error {
return trace.NotImplemented(notImplementedMessage)
}
// DeactivateCertAuthority not implemented: can only be called locally.
func (a *ServerWithRoles) DeactivateCertAuthority(id types.CertAuthID) error {
return trace.NotImplemented(notImplementedMessage)
}
// GenerateToken generates multi-purpose authentication token.
func (a *ServerWithRoles) GenerateToken(ctx context.Context, req GenerateTokenRequest) (string, error) {
if err := a.action(apidefaults.Namespace, types.KindToken, types.VerbCreate); err != nil {
return "", trace.Wrap(err)
}
return a.authServer.GenerateToken(ctx, req)
}
func (a *ServerWithRoles) RegisterUsingToken(ctx context.Context, req *types.RegisterUsingTokenRequest) (*proto.Certs, error) {
// tokens have authz mechanism on their own, no need to check
return a.authServer.RegisterUsingToken(ctx, req)
}
func (a *ServerWithRoles) RegisterNewAuthServer(ctx context.Context, token string) error {
// tokens have authz mechanism on their own, no need to check
return a.authServer.RegisterNewAuthServer(ctx, token)
}
// RegisterUsingIAMMethod registers the caller using the IAM join method and
// returns signed certs to join the cluster.
//
// See (*Server).RegisterUsingIAMMethod for further documentation.
//
// This wrapper does not do any extra authz checks, as the register method has
// its own authz mechanism.
func (a *ServerWithRoles) RegisterUsingIAMMethod(ctx context.Context, challengeResponse client.RegisterChallengeResponseFunc) (*proto.Certs, error) {
certs, err := a.authServer.RegisterUsingIAMMethod(ctx, challengeResponse)
return certs, trace.Wrap(err)
}
// 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() != HostFQDN(req.HostID, clusterName) {
return nil, trace.AccessDenied("username mismatch %q and %q", a.context.User.GetName(), HostFQDN(req.HostID, clusterName))
}
existingRoles, err := types.NewTeleportRoles(a.context.User.GetRoles())
if err != nil {
return nil, trace.Wrap(err)
}
// prohibit privilege escalations through role changes
if !existingRoles.Equals(types.SystemRoles{req.Role}) {
return nil, trace.AccessDenied("roles do not match: %v and %v", existingRoles, req.Role)
}
return a.authServer.GenerateHostCerts(ctx, req)
}
// UpsertNodes bulk upserts nodes into the backend.
func (a *ServerWithRoles) UpsertNodes(namespace string, servers []types.Server) error {
if err := a.action(namespace, types.KindNode, types.VerbCreate, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.UpsertNodes(namespace, servers)
}
func (a *ServerWithRoles) UpsertNode(ctx context.Context, s types.Server) (*types.KeepAlive, error) {
if err := a.action(s.GetNamespace(), types.KindNode, types.VerbCreate, types.VerbUpdate); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.UpsertNode(ctx, s)
}
// DELETE IN: 5.1.0
//
// This logic has moved to KeepAliveServer.
func (a *ServerWithRoles) KeepAliveNode(ctx context.Context, handle types.KeepAlive) error {
if !a.hasBuiltinRole(types.RoleNode) {
return trace.AccessDenied("[10] access denied")
}
clusterName, err := a.GetDomainName()
if err != nil {
return trace.Wrap(err)
}
serverName, err := ExtractHostID(a.context.User.GetName(), clusterName)
if err != nil {
return trace.AccessDenied("[10] access denied")
}
if serverName != handle.Name {
return trace.AccessDenied("[10] access denied")
}
if err := a.action(apidefaults.Namespace, types.KindNode, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.KeepAliveNode(ctx, handle)
}
// KeepAliveServer updates expiry time of a server resource.
func (a *ServerWithRoles) KeepAliveServer(ctx context.Context, handle types.KeepAlive) error {
clusterName, err := a.GetDomainName()
if err != nil {
return trace.Wrap(err)
}
serverName, err := ExtractHostID(a.context.User.GetName(), clusterName)
if err != nil {
return trace.AccessDenied("access denied")
}
switch handle.GetType() {
case constants.KeepAliveNode:
if serverName != handle.Name {
return trace.AccessDenied("access denied")
}
if !a.hasBuiltinRole(types.RoleNode) {
return trace.AccessDenied("access denied")
}
if err := a.action(apidefaults.Namespace, types.KindNode, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
case constants.KeepAliveApp:
if handle.HostID != "" {
if serverName != handle.HostID {
return trace.AccessDenied("access denied")
}
} else { // DELETE IN 9.0. Legacy app server is heartbeating back.
if serverName != handle.Name {
return trace.AccessDenied("access denied")
}
}
if !a.hasBuiltinRole(types.RoleApp) {
return trace.AccessDenied("access denied")
}
if err := a.action(apidefaults.Namespace, types.KindAppServer, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
case constants.KeepAliveDatabase:
// There can be multiple database servers per host so they send their
// host ID in a separate field because unlike SSH nodes the resource
// name cannot be the host ID.
if serverName != handle.HostID {
return trace.AccessDenied("access denied")
}
if !a.hasBuiltinRole(types.RoleDatabase) {
return trace.AccessDenied("access denied")
}
if err := a.action(apidefaults.Namespace, types.KindDatabaseServer, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
case constants.KeepAliveWindowsDesktopService:
if serverName != handle.Name {
return trace.AccessDenied("access denied")
}
if !a.hasBuiltinRole(types.RoleWindowsDesktop) {
return trace.AccessDenied("access denied")
}
if err := a.action(apidefaults.Namespace, types.KindWindowsDesktopService, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
case constants.KeepAliveKube:
if serverName != handle.Name || !a.hasBuiltinRole(types.RoleKube) {
return trace.AccessDenied("access denied")
}
if err := a.action(apidefaults.Namespace, types.KindKubeService, types.VerbUpdate); err != nil {
return trace.Wrap(err)
}
default:
return trace.BadParameter("unknown keep alive type %q", handle.Type)
}
return a.authServer.KeepAliveServer(ctx, handle)
}
// NewWatcher returns a new event watcher
func (a *ServerWithRoles) NewWatcher(ctx context.Context, watch types.Watch) (types.Watcher, error) {
if len(watch.Kinds) == 0 {
return nil, trace.AccessDenied("can't setup global watch")
}
for _, kind := range watch.Kinds {
// Check the permissions for data of each kind. For watching, most
// kinds of data just need a Read permission, but some have more
// complicated logic.
switch kind.Kind {
case types.KindCertAuthority:
verb := types.VerbReadNoSecrets
if kind.LoadSecrets {
verb = types.VerbRead
}
if err := a.action(apidefaults.Namespace, types.KindCertAuthority, verb); err != nil {
return nil, trace.Wrap(err)
}
case types.KindAccessRequest:
var filter types.AccessRequestFilter
if err := filter.FromMap(kind.Filter); err != nil {
return nil, trace.Wrap(err)
}
if filter.User == "" || a.currentUserAction(filter.User) != nil {
if err := a.action(apidefaults.Namespace, types.KindAccessRequest, types.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
}
case types.KindAppServer:
if err := a.action(apidefaults.Namespace, types.KindAppServer, types.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case types.KindWebSession:
var filter types.WebSessionFilter
if err := filter.FromMap(kind.Filter); err != nil {
return nil, trace.Wrap(err)
}
if filter.User == "" || a.currentUserAction(filter.User) != nil {
if err := a.action(apidefaults.Namespace, types.KindWebSession, types.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
}
case types.KindWebToken:
if err := a.action(apidefaults.Namespace, types.KindWebToken, types.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case types.KindRemoteCluster:
if err := a.action(apidefaults.Namespace, types.KindRemoteCluster, types.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case types.KindDatabaseServer:
if err := a.action(apidefaults.Namespace, types.KindDatabaseServer, types.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case types.KindKubeService:
if err := a.action(apidefaults.Namespace, types.KindKubeService, types.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case types.KindWindowsDesktopService:
if err := a.action(apidefaults.Namespace, types.KindWindowsDesktopService, types.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
default:
if err := a.action(apidefaults.Namespace, kind.Kind, types.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
}
}
switch {
case a.hasBuiltinRole(types.RoleProxy):
watch.QueueSize = defaults.ProxyQueueSize
case a.hasBuiltinRole(types.RoleNode):
watch.QueueSize = defaults.NodeQueueSize
}
return a.authServer.NewWatcher(ctx, watch)
}
// filterNodes filters nodes based off the role of the logged in user.
func (a *ServerWithRoles) filterNodes(checker *nodeChecker, nodes []types.Server) ([]types.Server, error) {
// Loop over all nodes and check if the caller has access.
var filteredNodes []types.Server
for _, node := range nodes {
err := checker.CanAccess(node)
if err != nil {
if trace.IsAccessDenied(err) {
continue
}
return nil, trace.Wrap(err)
}
filteredNodes = append(filteredNodes, node)
}
return filteredNodes, nil
}
// DeleteAllNodes deletes all nodes in a given namespace
func (a *ServerWithRoles) DeleteAllNodes(ctx context.Context, namespace string) error {
if err := a.action(namespace, types.KindNode, types.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.authServer.DeleteAllNodes(ctx, namespace)
}
// DeleteNode deletes node in the namespace
func (a *ServerWithRoles) DeleteNode(ctx context.Context, namespace, node string) error {
if err := a.action(namespace, types.KindNode, types.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.authServer.DeleteNode(ctx, namespace, node)
}
// GetNode gets a node by name and namespace.
func (a *ServerWithRoles) GetNode(ctx context.Context, namespace, name string) (types.Server, error) {
if err := a.action(namespace, types.KindNode, types.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
node, err := a.authServer.GetCache().GetNode(ctx, namespace, name)
if err != nil {
return nil, trace.Wrap(err)
}
checker, err := newNodeChecker(a.context.Checker, a.context.User, a.authServer)
if err != nil {
return nil, trace.Wrap(err)
}
// Run node through filter to check if it's for the connected identity.
if filteredNodes, err := a.filterNodes(checker, []types.Server{node}); err != nil {
return nil, trace.Wrap(err)
} else if len(filteredNodes) == 0 {
return nil, trace.NotFound("not found")
}
return node, nil
}
func (a *ServerWithRoles) GetNodes(ctx context.Context, namespace string, opts ...services.MarshalOption) ([]types.Server, error) {
if err := a.action(namespace, types.KindNode, types.VerbList); err != nil {
return nil, trace.Wrap(err)
}
// Fetch full list of nodes in the backend.
startFetch := time.Now()
nodes, err := a.authServer.GetNodes(ctx, namespace, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
elapsedFetch := time.Since(startFetch)
checker, err := newNodeChecker(a.context.Checker, a.context.User, a.authServer)
if err != nil {
return nil, trace.Wrap(err)
}
// Filter nodes to return the ones for the connected identity.
startFilter := time.Now()
filteredNodes, err := a.filterNodes(checker, nodes)
if err != nil {
return nil, trace.Wrap(err)
}
elapsedFilter := time.Since(startFilter)
log.WithFields(logrus.Fields{
"user": a.context.User.GetName(),
"elapsed_fetch": elapsedFetch,
"elapsed_filter": elapsedFilter,
}).Debugf(
"GetServers(%v->%v) in %v.",
len(nodes), len(filteredNodes), elapsedFetch+elapsedFilter)
return filteredNodes, nil
}
// ListResources returns a paginated list of resources filtered by user access.
func (a *ServerWithRoles) ListResources(ctx context.Context, req proto.ListResourcesRequest) (*types.ListResourcesResponse, error) {
if req.UseSearchAsRoles {
// For search-based access requests, replace the current roles with all
// roles the user is allowed to search with.
if err := a.context.UseSearchAsRoles(services.RoleGetter(a.authServer)); err != nil {
return nil, trace.Wrap(err)
}
a.authServer.emitter.EmitAuditEvent(a.authServer.closeCtx, &apievents.AccessRequestResourceSearch{
Metadata: apievents.Metadata{
Type: events.AccessRequestResourceSearch,
Code: events.AccessRequestResourceSearchCode,
},
UserMetadata: ClientUserMetadata(ctx),
SearchAsRoles: a.context.Checker.RoleNames(),
ResourceType: req.ResourceType,
Namespace: req.Namespace,
Labels: req.Labels,
PredicateExpression: req.PredicateExpression,
SearchKeywords: req.SearchKeywords,
})
}
// ListResources request coming through this auth layer gets request filters
// stripped off and saved to be applied later after items go through rbac checks.
// The list that gets returned from the backend comes back unfiltered and as
// we apply request filters, we might make multiple trips to get more subsets to
// reach our limit, which is fine b/c we can start query with our next key.
//
// But since sorting and counting totals requires us to work with entire list upfront,
// special handling is needed in this layer b/c if we try to mimic the "subset" here,
// we will be making unnecessary trips and doing needless work of deserializing every
// item for every subset.
if req.RequiresFakePagination() {
resp, err := a.listResourcesWithSort(ctx, req)
if err != nil {
return nil, trace.Wrap(err)
}
return resp, nil
}
// Start real pagination.
if err := req.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
limit := int(req.Limit)
actionVerbs := []string{types.VerbList, types.VerbRead}
switch req.ResourceType {
case types.KindNode:
// We are checking list only for Nodes to keep backwards compatibility.
// The read verb got added to GetNodes initially in:
// https://github.com/gravitational/teleport/pull/1209
// but got removed shortly afterwards in:
// https://github.com/gravitational/teleport/pull/1224
actionVerbs = []string{types.VerbList}
case types.KindDatabaseServer, types.KindAppServer, types.KindKubeService, types.KindWindowsDesktop:
default:
return nil, trace.NotImplemented("resource type %s does not support pagination", req.ResourceType)
}
if err := a.action(req.Namespace, req.ResourceType, actionVerbs...); err != nil {
return nil, trace.Wrap(err)
}
// Perform the label/search/expr filtering here (instead of at the backend
// `ListResources`) to ensure that it will be applied only to resources
// the user has access to.
filter := services.MatchResourceFilter{
ResourceKind: req.ResourceType,
Labels: req.Labels,
SearchKeywords: req.SearchKeywords,
PredicateExpression: req.PredicateExpression,
}
req.Labels = nil
req.SearchKeywords = nil
req.PredicateExpression = ""
var resources []types.ResourceWithLabels
resourceChecker, err := a.newResourceAccessChecker(req.ResourceType)
if err != nil {
return nil, trace.Wrap(err)
}
resp, err := a.authServer.IterateResourcePages(ctx, req, func(nextPage []types.ResourceWithLabels) (bool, error) {
for _, resource := range nextPage {
if len(resources) == limit {
break
}
if err := resourceChecker.CanAccess(resource); err != nil {
if trace.IsAccessDenied(err) {
continue
}
return false, trace.Wrap(err)
}
switch match, err := services.MatchResourceByFilters(resource, filter); {