forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth_with_roles.go
1642 lines (1447 loc) · 60.2 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-2018 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/gravitational/teleport"
"github.com/gravitational/teleport/lib/auth/proto"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/wrappers"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
"github.com/tstranex/u2f"
)
// AuthWithRoles is a wrapper around auth service
// methods that focuses on authorizing every request
type AuthWithRoles struct {
authServer *AuthServer
checker services.AccessChecker
user services.User
sessions session.Service
alog events.IAuditLog
identity tlsca.Identity
}
func (a *AuthWithRoles) actionWithContext(ctx *services.Context, namespace string, resource string, action string) error {
return a.checker.CheckAccessToRule(ctx, namespace, resource, action, false)
}
func (a *AuthWithRoles) action(namespace string, resource string, action string) error {
return a.checker.CheckAccessToRule(&services.Context{User: a.user}, namespace, resource, action, false)
}
// 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 *AuthWithRoles) currentUserAction(username string) error {
if a.hasLocalUserRole(a.checker) && username == a.user.GetName() {
return nil
}
return a.checker.CheckAccessToRule(&services.Context{User: a.user},
defaults.Namespace, services.KindUser, services.VerbCreate, false)
}
// 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 *AuthWithRoles) authConnectorAction(namespace string, resource string, verb string) error {
if err := a.checker.CheckAccessToRule(&services.Context{User: a.user}, namespace, resource, verb, false); err != nil {
if err := a.checker.CheckAccessToRule(&services.Context{User: a.user}, namespace, services.KindAuthConnector, verb, false); err != nil {
return trace.Wrap(err)
}
}
return nil
}
// hasBuiltinRole checks the type of the role set returned and the name.
// Returns true if role set is builtin and the name matches.
func (a *AuthWithRoles) hasBuiltinRole(name string) bool {
return hasBuiltinRole(a.checker, name)
}
// 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 (a *AuthWithRoles) hasRemoteBuiltinRole(name string) bool {
if _, ok := a.checker.(RemoteBuiltinRoleSet); !ok {
return false
}
if !a.checker.HasRole(name) {
return false
}
return true
}
// hasLocalUserRole checks if the type of the role set is a local user or not.
func (a *AuthWithRoles) hasLocalUserRole(checker services.AccessChecker) bool {
if _, ok := checker.(LocalUserRoleSet); !ok {
return false
}
return true
}
// AuthenticateWebUser authenticates web user, creates and returns web session
// in case if authentication is successful
func (a *AuthWithRoles) AuthenticateWebUser(req AuthenticateUserRequest) (services.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(string(teleport.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 *AuthWithRoles) 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(string(teleport.RoleProxy)) {
return nil, trace.AccessDenied("this request can be only executed by a proxy")
}
return a.authServer.AuthenticateSSHUser(req)
}
func (a *AuthWithRoles) GetSessions(namespace string) ([]session.Session, error) {
if err := a.action(namespace, services.KindSSHSession, services.VerbList); err != nil {
return nil, trace.Wrap(err)
}
return a.sessions.GetSessions(namespace)
}
func (a *AuthWithRoles) GetSession(namespace string, id session.ID) (*session.Session, error) {
if err := a.action(namespace, services.KindSSHSession, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
return a.sessions.GetSession(namespace, id)
}
func (a *AuthWithRoles) CreateSession(s session.Session) error {
if err := a.action(s.Namespace, services.KindSSHSession, services.VerbCreate); err != nil {
return trace.Wrap(err)
}
return a.sessions.CreateSession(s)
}
func (a *AuthWithRoles) UpdateSession(req session.UpdateRequest) error {
if err := a.action(req.Namespace, services.KindSSHSession, services.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.sessions.UpdateSession(req)
}
// DeleteSession removes an active session from the backend.
func (a *AuthWithRoles) DeleteSession(namespace string, id session.ID) error {
if err := a.action(namespace, services.KindSSHSession, services.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.sessions.DeleteSession(namespace, id)
}
func (a *AuthWithRoles) CreateCertAuthority(ca services.CertAuthority) error {
return trace.NotImplemented("not implemented")
}
// RotateCertAuthority starts or restarts certificate authority rotation process.
func (a *AuthWithRoles) RotateCertAuthority(req RotateRequest) error {
if err := req.CheckAndSetDefaults(a.authServer.clock); err != nil {
return trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbCreate); err != nil {
return trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.RotateCertAuthority(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 *AuthWithRoles) RotateExternalCertAuthority(ca services.CertAuthority) error {
if ca == nil {
return trace.BadParameter("missing certificate authority")
}
ctx := &services.Context{User: a.user, Resource: ca}
if err := a.actionWithContext(ctx, defaults.Namespace, services.KindCertAuthority, services.VerbRotate); err != nil {
return trace.Wrap(err)
}
return a.authServer.RotateExternalCertAuthority(ca)
}
// UpsertCertAuthority updates existing cert authority or updates the existing one.
func (a *AuthWithRoles) UpsertCertAuthority(ca services.CertAuthority) error {
if ca == nil {
return trace.BadParameter("missing certificate authority")
}
ctx := &services.Context{User: a.user, Resource: ca}
if err := a.actionWithContext(ctx, defaults.Namespace, services.KindCertAuthority, services.VerbCreate); err != nil {
return trace.Wrap(err)
}
if err := a.actionWithContext(ctx, defaults.Namespace, services.KindCertAuthority, services.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 *AuthWithRoles) CompareAndSwapCertAuthority(new, existing services.CertAuthority) error {
if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbCreate); err != nil {
return trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.CompareAndSwapCertAuthority(new, existing)
}
func (a *AuthWithRoles) GetCertAuthorities(caType services.CertAuthType, loadKeys bool, opts ...services.MarshalOption) ([]services.CertAuthority, error) {
if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbList); err != nil {
return nil, trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbReadNoSecrets); err != nil {
return nil, trace.Wrap(err)
}
if loadKeys {
if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
}
return a.authServer.GetCertAuthorities(caType, loadKeys, opts...)
}
func (a *AuthWithRoles) GetCertAuthority(id services.CertAuthID, loadKeys bool, opts ...services.MarshalOption) (services.CertAuthority, error) {
if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbReadNoSecrets); err != nil {
return nil, trace.Wrap(err)
}
if loadKeys {
if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
}
return a.authServer.GetCertAuthority(id, loadKeys, opts...)
}
func (a *AuthWithRoles) GetDomainName() (string, error) {
// anyone can read it, no harm in that
return a.authServer.GetDomainName()
}
func (a *AuthWithRoles) GetLocalClusterName() (string, error) {
// anyone can read it, no harm in that
return a.authServer.GetLocalClusterName()
}
// GetClusterCACert returns the CAs for the local cluster without signing keys.
func (a *AuthWithRoles) GetClusterCACert() (*LocalCAResponse, error) {
// Allow all roles to get the local CA.
return a.authServer.GetClusterCACert()
}
func (a *AuthWithRoles) UpsertLocalClusterName(clusterName string) error {
if err := a.action(defaults.Namespace, services.KindAuthServer, services.VerbCreate); err != nil {
return trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindAuthServer, services.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.UpsertLocalClusterName(clusterName)
}
func (a *AuthWithRoles) DeleteCertAuthority(id services.CertAuthID) error {
if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.authServer.DeleteCertAuthority(id)
}
func (a *AuthWithRoles) ActivateCertAuthority(id services.CertAuthID) error {
return trace.NotImplemented("not implemented")
}
func (a *AuthWithRoles) DeactivateCertAuthority(id services.CertAuthID) error {
return trace.NotImplemented("not implemented")
}
func (a *AuthWithRoles) GenerateToken(req GenerateTokenRequest) (string, error) {
if err := a.action(defaults.Namespace, services.KindToken, services.VerbCreate); err != nil {
return "", trace.Wrap(err)
}
return a.authServer.GenerateToken(req)
}
func (a *AuthWithRoles) RegisterUsingToken(req RegisterUsingTokenRequest) (*PackedKeys, error) {
// tokens have authz mechanism on their own, no need to check
return a.authServer.RegisterUsingToken(req)
}
func (a *AuthWithRoles) RegisterNewAuthServer(token string) error {
// tokens have authz mechanism on their own, no need to check
return a.authServer.RegisterNewAuthServer(token)
}
// GenerateServerKeys generates new host private keys and certificates (signed
// by the host certificate authority) for a node.
func (a *AuthWithRoles) GenerateServerKeys(req GenerateServerKeysRequest) (*PackedKeys, 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.user.GetName() != HostFQDN(req.HostID, clusterName) {
return nil, trace.AccessDenied("username mismatch %q and %q", a.user.GetName(), HostFQDN(req.HostID, clusterName))
}
existingRoles, err := teleport.NewRoles(a.user.GetRoles())
if err != nil {
return nil, trace.Wrap(err)
}
// prohibit privilege escalations through role changes
if !existingRoles.Equals(req.Roles) {
return nil, trace.AccessDenied("roles do not match: %v and %v", existingRoles, req.Roles)
}
return a.authServer.GenerateServerKeys(req)
}
// UpsertNodes bulk upserts nodes into the backend.
func (a *AuthWithRoles) UpsertNodes(namespace string, servers []services.Server) error {
if err := a.action(namespace, services.KindNode, services.VerbCreate); err != nil {
return trace.Wrap(err)
}
if err := a.action(namespace, services.KindNode, services.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.UpsertNodes(namespace, servers)
}
func (a *AuthWithRoles) UpsertNode(s services.Server) (*services.KeepAlive, error) {
if err := a.action(s.GetNamespace(), services.KindNode, services.VerbCreate); err != nil {
return nil, trace.Wrap(err)
}
if err := a.action(s.GetNamespace(), services.KindNode, services.VerbUpdate); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.UpsertNode(s)
}
func (a *AuthWithRoles) KeepAliveNode(ctx context.Context, handle services.KeepAlive) error {
if !a.hasBuiltinRole(string(teleport.RoleNode)) {
return trace.AccessDenied("[10] access denied")
}
clusterName, err := a.GetDomainName()
if err != nil {
return trace.Wrap(err)
}
serverName, err := ExtractHostID(a.user.GetName(), clusterName)
if err != nil {
return trace.AccessDenied("[10] access denied")
}
if serverName != handle.ServerName {
return trace.AccessDenied("[10] access denied")
}
if err := a.action(defaults.Namespace, services.KindNode, services.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.KeepAliveNode(ctx, handle)
}
// NewWatcher returns a new event watcher
func (a *AuthWithRoles) NewWatcher(ctx context.Context, watch services.Watch) (services.Watcher, error) {
if len(watch.Kinds) == 0 {
return nil, trace.AccessDenied("can't setup global watch")
}
for _, kind := range watch.Kinds {
switch kind.Kind {
case services.KindNamespace:
if err := a.action(defaults.Namespace, services.KindNamespace, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case services.KindUser:
if err := a.action(defaults.Namespace, services.KindUser, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case services.KindRole:
if err := a.action(defaults.Namespace, services.KindRole, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case services.KindNode:
if err := a.action(defaults.Namespace, services.KindNode, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case services.KindProxy:
if err := a.action(defaults.Namespace, services.KindProxy, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case services.KindAuthServer:
if err := a.action(defaults.Namespace, services.KindAuthServer, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case services.KindTunnelConnection:
if err := a.action(defaults.Namespace, services.KindTunnelConnection, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case services.KindReverseTunnel:
if err := a.action(defaults.Namespace, services.KindReverseTunnel, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case services.KindClusterConfig:
if err := a.action(defaults.Namespace, services.KindClusterConfig, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case services.KindClusterName:
if err := a.action(defaults.Namespace, services.KindClusterName, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case services.KindToken:
if err := a.action(defaults.Namespace, services.KindToken, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case services.KindStaticTokens:
if err := a.action(defaults.Namespace, services.KindStaticTokens, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
case services.KindCertAuthority:
if kind.LoadSecrets {
if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
} else {
if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbReadNoSecrets); err != nil {
return nil, trace.Wrap(err)
}
}
default:
return nil, trace.AccessDenied("not authorized to watch %v events", kind.Kind)
}
}
switch {
case a.hasBuiltinRole(string(teleport.RoleProxy)):
watch.QueueSize = defaults.ProxyQueueSize
case a.hasBuiltinRole(string(teleport.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 *AuthWithRoles) filterNodes(nodes []services.Server) ([]services.Server, error) {
// For certain built-in roles, continue to allow full access and return
// the full set of nodes to not break existing clusters during migration.
//
// In addition, allow proxy (and remote proxy) to access all nodes for it's
// smart resolution address resolution. Once the smart resolution logic is
// moved to the auth server, this logic can be removed.
if a.hasBuiltinRole(string(teleport.RoleAdmin)) ||
a.hasBuiltinRole(string(teleport.RoleProxy)) ||
a.hasRemoteBuiltinRole(string(teleport.RoleRemoteProxy)) {
return nodes, nil
}
// Fetch services.RoleSet for the identity of the logged in user.
roles, traits, err := services.ExtractFromIdentity(a.authServer, &a.identity)
if err != nil {
return nil, trace.Wrap(err)
}
roleset, err := services.FetchRoles(roles, a.authServer, traits)
if err != nil {
return nil, trace.Wrap(err)
}
// Extract all unique allowed logins across all roles.
allowedLogins := make(map[string]bool)
for _, role := range roleset {
for _, login := range role.GetLogins(services.Allow) {
allowedLogins[login] = true
}
}
// Loop over all nodes and check if the caller has access.
filteredNodes := make([]services.Server, 0, len(nodes))
NextNode:
for _, node := range nodes {
for login, _ := range allowedLogins {
err := roleset.CheckAccessToServer(login, node)
if err == nil {
filteredNodes = append(filteredNodes, node)
continue NextNode
}
}
}
return filteredNodes, nil
}
// DeleteAllNodes deletes all nodes in a given namespace
func (a *AuthWithRoles) DeleteAllNodes(namespace string) error {
if err := a.action(namespace, services.KindNode, services.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.authServer.DeleteAllNodes(namespace)
}
// DeleteNode deletes node in the namespace
func (a *AuthWithRoles) DeleteNode(namespace, node string) error {
if err := a.action(namespace, services.KindNode, services.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.authServer.DeleteNode(namespace, node)
}
func (a *AuthWithRoles) GetNodes(namespace string, opts ...services.MarshalOption) ([]services.Server, error) {
if err := a.action(namespace, services.KindNode, services.VerbList); err != nil {
return nil, trace.Wrap(err)
}
// Fetch full list of nodes in the backend.
startFetch := time.Now()
nodes, err := a.authServer.GetNodes(namespace, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
elapsedFetch := time.Since(startFetch)
// Filter nodes to return the ones for the connected identity.
startFilter := time.Now()
filteredNodes, err := a.filterNodes(nodes)
if err != nil {
return nil, trace.Wrap(err)
}
elapsedFilter := time.Since(startFilter)
log.WithFields(logrus.Fields{
"user": a.user.GetName(),
"elapsed_fetch": elapsedFetch,
"elapsed_filter": elapsedFilter,
}).Debugf(
"GetServers(%v->%v) in %v.",
len(nodes), len(filteredNodes), elapsedFetch+elapsedFilter)
return filteredNodes, nil
}
func (a *AuthWithRoles) UpsertAuthServer(s services.Server) error {
if err := a.action(defaults.Namespace, services.KindAuthServer, services.VerbCreate); err != nil {
return trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindAuthServer, services.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.UpsertAuthServer(s)
}
func (a *AuthWithRoles) GetAuthServers() ([]services.Server, error) {
if err := a.action(defaults.Namespace, services.KindAuthServer, services.VerbList); err != nil {
return nil, trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindAuthServer, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.GetAuthServers()
}
// DeleteAllAuthServers deletes all auth servers
func (a *AuthWithRoles) DeleteAllAuthServers() error {
if err := a.action(defaults.Namespace, services.KindAuthServer, services.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.authServer.DeleteAllAuthServers()
}
// DeleteAuthServer deletes auth server by name
func (a *AuthWithRoles) DeleteAuthServer(name string) error {
if err := a.action(defaults.Namespace, services.KindAuthServer, services.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.authServer.DeleteAuthServer(name)
}
func (a *AuthWithRoles) UpsertProxy(s services.Server) error {
if err := a.action(defaults.Namespace, services.KindProxy, services.VerbCreate); err != nil {
return trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindProxy, services.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.UpsertProxy(s)
}
func (a *AuthWithRoles) GetProxies() ([]services.Server, error) {
if err := a.action(defaults.Namespace, services.KindProxy, services.VerbList); err != nil {
return nil, trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindProxy, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.GetProxies()
}
// DeleteAllProxies deletes all proxies
func (a *AuthWithRoles) DeleteAllProxies() error {
if err := a.action(defaults.Namespace, services.KindProxy, services.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.authServer.DeleteAllProxies()
}
// DeleteProxy deletes proxy by name
func (a *AuthWithRoles) DeleteProxy(name string) error {
if err := a.action(defaults.Namespace, services.KindProxy, services.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.authServer.DeleteProxy(name)
}
func (a *AuthWithRoles) UpsertReverseTunnel(r services.ReverseTunnel) error {
if err := a.action(defaults.Namespace, services.KindReverseTunnel, services.VerbCreate); err != nil {
return trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindReverseTunnel, services.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.UpsertReverseTunnel(r)
}
func (a *AuthWithRoles) GetReverseTunnel(name string, opts ...services.MarshalOption) (services.ReverseTunnel, error) {
if err := a.action(defaults.Namespace, services.KindReverseTunnel, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.GetReverseTunnel(name, opts...)
}
func (a *AuthWithRoles) GetReverseTunnels(opts ...services.MarshalOption) ([]services.ReverseTunnel, error) {
if err := a.action(defaults.Namespace, services.KindReverseTunnel, services.VerbList); err != nil {
return nil, trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindReverseTunnel, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.GetReverseTunnels(opts...)
}
func (a *AuthWithRoles) DeleteReverseTunnel(domainName string) error {
if err := a.action(defaults.Namespace, services.KindReverseTunnel, services.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.authServer.DeleteReverseTunnel(domainName)
}
func (a *AuthWithRoles) DeleteToken(token string) error {
if err := a.action(defaults.Namespace, services.KindToken, services.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.authServer.DeleteToken(token)
}
func (a *AuthWithRoles) GetTokens(opts ...services.MarshalOption) ([]services.ProvisionToken, error) {
if err := a.action(defaults.Namespace, services.KindToken, services.VerbList); err != nil {
return nil, trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindToken, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.GetTokens(opts...)
}
func (a *AuthWithRoles) GetToken(token string) (services.ProvisionToken, error) {
if err := a.action(defaults.Namespace, services.KindToken, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.GetToken(token)
}
func (a *AuthWithRoles) UpsertToken(token services.ProvisionToken) error {
if err := a.action(defaults.Namespace, services.KindToken, services.VerbCreate); err != nil {
return trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindToken, services.VerbUpdate); err != nil {
return trace.Wrap(err)
}
return a.authServer.UpsertToken(token)
}
func (a *AuthWithRoles) UpsertPassword(user string, password []byte) error {
if err := a.currentUserAction(user); err != nil {
return trace.Wrap(err)
}
return a.authServer.UpsertPassword(user, password)
}
func (a *AuthWithRoles) ChangePassword(req services.ChangePasswordReq) error {
if err := a.currentUserAction(req.User); err != nil {
return trace.Wrap(err)
}
return a.authServer.ChangePassword(req)
}
func (a *AuthWithRoles) CheckPassword(user string, password []byte, otpToken string) error {
if err := a.currentUserAction(user); err != nil {
return trace.Wrap(err)
}
return a.authServer.CheckPassword(user, password, otpToken)
}
func (a *AuthWithRoles) UpsertTOTP(user string, otpSecret string) error {
if err := a.currentUserAction(user); err != nil {
return trace.Wrap(err)
}
return a.authServer.UpsertTOTP(user, otpSecret)
}
func (a *AuthWithRoles) GetOTPData(user string) (string, []byte, error) {
if err := a.currentUserAction(user); err != nil {
return "", nil, trace.Wrap(err)
}
return a.authServer.GetOTPData(user)
}
func (a *AuthWithRoles) PreAuthenticatedSignIn(user string) (services.WebSession, error) {
if err := a.currentUserAction(user); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.PreAuthenticatedSignIn(user, &a.identity)
}
func (a *AuthWithRoles) GetU2FSignRequest(user string, password []byte) (*u2f.SignRequest, error) {
// we are already checking password here, no need to extra permission check
// anyone who has user's password can generate sign request
return a.authServer.U2FSignRequest(user, password)
}
func (a *AuthWithRoles) CreateWebSession(user string) (services.WebSession, error) {
if err := a.currentUserAction(user); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.CreateWebSession(user, &a.identity)
}
func (a *AuthWithRoles) ExtendWebSession(user, prevSessionID string) (services.WebSession, error) {
if err := a.currentUserAction(user); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.ExtendWebSession(user, prevSessionID, &a.identity)
}
func (a *AuthWithRoles) GetWebSessionInfo(user string, sid string) (services.WebSession, error) {
if err := a.currentUserAction(user); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.GetWebSessionInfo(user, sid)
}
func (a *AuthWithRoles) DeleteWebSession(user string, sid string) error {
if err := a.currentUserAction(user); err != nil {
return trace.Wrap(err)
}
return a.authServer.DeleteWebSession(user, sid)
}
func (a *AuthWithRoles) GetUsers(withSecrets bool) ([]services.User, error) {
if withSecrets {
// TODO(fspmarshall): replace admin requirement with VerbReadWithSecrets once we've
// migrated to that model.
if !a.hasBuiltinRole(string(teleport.RoleAdmin)) {
err := trace.AccessDenied("user %q requested access to all users with secrets", a.user.GetName())
log.Warning(err)
a.authServer.EmitAuditEvent(events.UserLocalLoginFailure, events.EventFields{
events.LoginMethod: events.LoginMethodClientCert,
events.AuthAttemptSuccess: false,
// log the original internal error in audit log
events.AuthAttemptErr: trace.Unwrap(err).Error(),
})
return nil, trace.AccessDenied("this request can be only executed by an admin")
}
} else {
if err := a.action(defaults.Namespace, services.KindUser, services.VerbList); err != nil {
return nil, trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindUser, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
}
return a.authServer.GetUsers(withSecrets)
}
func (a *AuthWithRoles) GetUser(name string, withSecrets bool) (services.User, error) {
if withSecrets {
// TODO(fspmarshall): replace admin requirement with VerbReadWithSecrets once we've
// migrated to that model.
if !a.hasBuiltinRole(string(teleport.RoleAdmin)) {
err := trace.AccessDenied("user %q requested access to user %q with secrets", a.user.GetName(), name)
log.Warning(err)
a.authServer.EmitAuditEvent(events.UserLocalLoginFailure, events.EventFields{
events.LoginMethod: events.LoginMethodClientCert,
events.AuthAttemptSuccess: false,
// log the original internal error in audit log
events.AuthAttemptErr: trace.Unwrap(err).Error(),
})
return nil, trace.AccessDenied("this request can be only executed by an admin")
}
} else {
// if secrets are not being accessed, let users always read
// their own info.
if err := a.currentUserAction(name); err != nil {
// not current user, perform normal permission check.
if err := a.action(defaults.Namespace, services.KindUser, services.VerbRead); err != nil {
return nil, trace.Wrap(err)
}
}
}
return a.authServer.Identity.GetUser(name, withSecrets)
}
func (a *AuthWithRoles) DeleteUser(user string) error {
if err := a.action(defaults.Namespace, services.KindUser, services.VerbDelete); err != nil {
return trace.Wrap(err)
}
return a.authServer.DeleteUser(user)
}
func (a *AuthWithRoles) GenerateKeyPair(pass string) ([]byte, []byte, error) {
if err := a.action(defaults.Namespace, services.KindKeyPair, services.VerbCreate); err != nil {
return nil, nil, trace.Wrap(err)
}
return a.authServer.GenerateKeyPair(pass)
}
func (a *AuthWithRoles) GenerateHostCert(
key []byte, hostID, nodeName string, principals []string, clusterName string, roles teleport.Roles, ttl time.Duration) ([]byte, error) {
if err := a.action(defaults.Namespace, services.KindHostCert, services.VerbCreate); err != nil {
return nil, trace.Wrap(err)
}
return a.authServer.GenerateHostCert(key, hostID, nodeName, principals, clusterName, roles, ttl)
}
// NewKeepAliver returns a new instance of keep aliver
func (a *AuthWithRoles) NewKeepAliver(ctx context.Context) (services.KeepAliver, error) {
return nil, trace.NotImplemented("not implemented")
}
// GenerateUserCerts generates users certificates
func (a *AuthWithRoles) GenerateUserCerts(ctx context.Context, req proto.UserCertsRequest) (*proto.Certs, error) {
var err error
var roles []string
var traits wrappers.Traits
switch {
case a.hasBuiltinRole(string(teleport.RoleAdmin)):
// If it's an admin generating the certificate, the roles and traits for
// the user have to be fetched from the backend. This should be safe since
// this is typically done against a local user.
user, err := a.GetUser(req.Username, false)
if err != nil {
return nil, trace.Wrap(err)
}
roles = user.GetRoles()
traits = user.GetTraits()
case req.Username == a.user.GetName():
// user is requesting TTL for themselves,
// limit the TTL to the duration of the session, to prevent
// users renewing their certificates forever
if a.identity.Expires.IsZero() {
log.Warningf("Encountered identity with no expiry: %v and denied request. Must be internal logic error.", a.identity)
return nil, trace.AccessDenied("access denied")
}
req.Expires = a.identity.Expires
if req.Expires.Before(a.authServer.GetClock().Now()) {
return nil, trace.AccessDenied("access denied: client credentials have expired, please relogin.")
}
// If the user is generating a certificate, the roles and traits come from
// the logged in identity.
roles, traits, err = services.ExtractFromIdentity(a.authServer, &a.identity)
if err != nil {
return nil, trace.Wrap(err)
}
default:
err := trace.AccessDenied("user %q has requested to generate certs for %q.", a.user.GetName(), req.Username)
log.Warning(err)
a.authServer.EmitAuditEvent(events.UserLocalLoginFailure, events.EventFields{
events.LoginMethod: events.LoginMethodClientCert,
events.AuthAttemptSuccess: false,
// log the original internal error in audit log
events.AuthAttemptErr: trace.Unwrap(err).Error(),
})
// this error is vague on purpose, it should not happen unless someone is trying something out of loop
return nil, trace.AccessDenied("this request can be only executed by an admin")
}
// Extract the user and role set for whom the certificate will be generated.
user, err := a.GetUser(req.Username, false)
if err != nil {
return nil, trace.Wrap(err)
}
checker, err := services.FetchRoles(roles, a.authServer, traits)
if err != nil {
return nil, trace.Wrap(err)
}
// Generate certificate, note that the roles TTL will be ignored because
// the request is coming from "tctl auth sign" itself.
certs, err := a.authServer.generateUserCert(certRequest{
user: user,
ttl: req.Expires.Sub(a.authServer.GetClock().Now()),
compatibility: req.Format,
publicKey: req.PublicKey,
overrideRoleTTL: a.hasBuiltinRole(string(teleport.RoleAdmin)),
routeToCluster: req.RouteToCluster,
checker: checker,
traits: traits,
})
if err != nil {
return nil, trace.Wrap(err)
}
return &proto.Certs{
SSH: certs.ssh,
TLS: certs.tls,
}, nil
}
func (a *AuthWithRoles) CreateSignupToken(user services.UserV1, ttl time.Duration) (token string, e error) {
if err := a.action(defaults.Namespace, services.KindUser, services.VerbCreate); err != nil {
return "", trace.Wrap(err)
}
return a.authServer.CreateSignupToken(user, ttl)
}
func (a *AuthWithRoles) GetSignupTokenData(token string) (user string, otpQRCode []byte, err error) {
// signup token are their own authz resource
return a.authServer.GetSignupTokenData(token)
}
func (a *AuthWithRoles) GetSignupToken(token string) (*services.SignupToken, error) {
// signup token are their own authz resource
return a.authServer.GetSignupToken(token)
}
func (a *AuthWithRoles) GetSignupU2FRegisterRequest(token string) (u2fRegisterRequest *u2f.RegisterRequest, e error) {
// signup token are their own authz resource
return a.authServer.CreateSignupU2FRegisterRequest(token)
}
func (a *AuthWithRoles) CreateUserWithOTP(token, password, otpToken string) (services.WebSession, error) {
// tokens are their own authz mechanism, no need to double check
return a.authServer.CreateUserWithOTP(token, password, otpToken)
}
func (a *AuthWithRoles) CreateUserWithoutOTP(token string, password string) (services.WebSession, error) {
// tokens are their own authz mechanism, no need to double check
return a.authServer.CreateUserWithoutOTP(token, password)
}
func (a *AuthWithRoles) CreateUserWithU2FToken(token string, password string, u2fRegisterResponse u2f.RegisterResponse) (services.WebSession, error) {
// signup tokens are their own authz resource
return a.authServer.CreateUserWithU2FToken(token, password, u2fRegisterResponse)
}
func (a *AuthWithRoles) UpsertUser(u services.User) error {
if err := a.action(defaults.Namespace, services.KindUser, services.VerbCreate); err != nil {
return trace.Wrap(err)
}
if err := a.action(defaults.Namespace, services.KindUser, services.VerbUpdate); err != nil {
return trace.Wrap(err)
}
createdBy := u.GetCreatedBy()
if createdBy.IsEmpty() {
u.SetCreatedBy(services.CreatedBy{
User: services.UserRef{Name: a.user.GetName()},
})
}
return a.authServer.UpsertUser(u)
}
func (a *AuthWithRoles) UpsertOIDCConnector(connector services.OIDCConnector) error {
if err := a.authConnectorAction(defaults.Namespace, services.KindOIDC, services.VerbCreate); err != nil {
return trace.Wrap(err)
}