-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathrole.go
2370 lines (2142 loc) · 74.3 KB
/
role.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 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 services
import (
"context"
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"golang.org/x/crypto/ssh"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/api/types/wrappers"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/modules"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/utils/parse"
"github.com/gravitational/configure/cstrings"
"github.com/gravitational/trace"
"github.com/pborman/uuid"
log "github.com/sirupsen/logrus"
"github.com/vulcand/predicate"
)
// getExtendedAdminUserRules provides access to the default set of rules assigned to
// all users.
func getExtendedAdminUserRules(features modules.Features) []Rule {
rules := []Rule{
NewRule(KindRole, RW()),
NewRule(KindAuthConnector, RW()),
NewRule(KindSession, RO()),
NewRule(KindTrustedCluster, RW()),
NewRule(KindEvent, RO()),
NewRule(KindUser, RW()),
NewRule(KindToken, RW()),
}
if features.Cloud {
rules = append(rules, NewRule(KindBilling, RW()))
}
return rules
}
// DefaultImplicitRules provides access to the default set of implicit rules
// assigned to all roles.
var DefaultImplicitRules = []Rule{
NewRule(KindNode, RO()),
NewRule(KindProxy, RO()),
NewRule(KindAuthServer, RO()),
NewRule(KindReverseTunnel, RO()),
NewRule(KindCertAuthority, ReadNoSecrets()),
NewRule(KindClusterAuthPreference, RO()),
NewRule(KindClusterName, RO()),
NewRule(KindSSHSession, RO()),
NewRule(KindAppServer, RO()),
NewRule(KindRemoteCluster, RO()),
NewRule(KindKubeService, RO()),
NewRule(types.KindDatabaseServer, RO()),
}
// DefaultCertAuthorityRules provides access the minimal set of resources
// needed for a certificate authority to function.
var DefaultCertAuthorityRules = []Rule{
NewRule(KindSession, RO()),
NewRule(KindNode, RO()),
NewRule(KindAuthServer, RO()),
NewRule(KindReverseTunnel, RO()),
NewRule(KindCertAuthority, ReadNoSecrets()),
}
// ErrSessionMFARequired is returned by AccessChecker when access to a resource
// requires an MFA check.
var ErrSessionMFARequired = trace.AccessDenied("access to resource requires MFA")
// RoleNameForUser returns role name associated with a user.
func RoleNameForUser(name string) string {
return "user:" + name
}
// RoleNameForCertAuthority returns role name associated with a certificate
// authority.
func RoleNameForCertAuthority(name string) string {
return "ca:" + name
}
// NewAdminRole is the default admin role for all local users if another role
// is not explicitly assigned (this role applies to all users in OSS version).
func NewAdminRole() Role {
adminRules := getExtendedAdminUserRules(modules.GetModules().Features())
role := &RoleV3{
Kind: KindRole,
Version: V3,
Metadata: Metadata{
Name: teleport.AdminRoleName,
Namespace: defaults.Namespace,
},
Spec: RoleSpecV3{
Options: RoleOptions{
CertificateFormat: teleport.CertificateFormatStandard,
MaxSessionTTL: NewDuration(defaults.MaxCertDuration),
PortForwarding: NewBoolOption(true),
ForwardAgent: NewBool(true),
BPF: defaults.EnhancedEvents(),
},
Allow: RoleConditions{
Namespaces: []string{defaults.Namespace},
NodeLabels: Labels{Wildcard: []string{Wildcard}},
AppLabels: Labels{Wildcard: []string{Wildcard}},
KubernetesLabels: Labels{Wildcard: []string{Wildcard}},
DatabaseLabels: Labels{Wildcard: []string{Wildcard}},
DatabaseNames: []string{teleport.TraitInternalDBNamesVariable},
DatabaseUsers: []string{teleport.TraitInternalDBUsersVariable},
Rules: adminRules,
},
},
}
role.SetLogins(Allow, []string{teleport.TraitInternalLoginsVariable, teleport.Root})
role.SetKubeUsers(Allow, []string{teleport.TraitInternalKubeUsersVariable})
role.SetKubeGroups(Allow, []string{teleport.TraitInternalKubeGroupsVariable})
return role
}
// NewImplicitRole is the default implicit role that gets added to all
// RoleSets.
func NewImplicitRole() Role {
return &RoleV3{
Kind: KindRole,
Version: V3,
Metadata: Metadata{
Name: teleport.DefaultImplicitRole,
Namespace: defaults.Namespace,
},
Spec: RoleSpecV3{
Options: RoleOptions{
MaxSessionTTL: MaxDuration(),
// PortForwarding has to be set to false in the default-implicit-role
// otherwise all roles will be allowed to forward ports (since we default
// to true in the check).
PortForwarding: NewBoolOption(false),
},
Allow: RoleConditions{
Namespaces: []string{defaults.Namespace},
Rules: CopyRulesSlice(DefaultImplicitRules),
},
},
}
}
// RoleForUser creates an admin role for a services.User.
func RoleForUser(u User) Role {
return &RoleV3{
Kind: KindRole,
Version: V3,
Metadata: Metadata{
Name: RoleNameForUser(u.GetName()),
Namespace: defaults.Namespace,
},
Spec: RoleSpecV3{
Options: RoleOptions{
CertificateFormat: teleport.CertificateFormatStandard,
MaxSessionTTL: NewDuration(defaults.MaxCertDuration),
PortForwarding: NewBoolOption(true),
ForwardAgent: NewBool(true),
BPF: defaults.EnhancedEvents(),
},
Allow: RoleConditions{
Namespaces: []string{defaults.Namespace},
NodeLabels: Labels{Wildcard: []string{Wildcard}},
AppLabels: Labels{Wildcard: []string{Wildcard}},
KubernetesLabels: Labels{Wildcard: []string{Wildcard}},
DatabaseLabels: Labels{Wildcard: []string{Wildcard}},
Rules: []Rule{
NewRule(KindRole, RW()),
NewRule(KindAuthConnector, RW()),
NewRule(KindSession, RO()),
NewRule(KindTrustedCluster, RW()),
NewRule(KindEvent, RO()),
},
},
},
}
}
// NewDowngradedOSSAdminRole is a role for enabling RBAC for open source users.
// This role overrides built in OSS "admin" role to have less privileges.
// DELETE IN (7.x)
func NewDowngradedOSSAdminRole() Role {
role := &RoleV3{
Kind: KindRole,
Version: V3,
Metadata: Metadata{
Name: teleport.AdminRoleName,
Namespace: defaults.Namespace,
Labels: map[string]string{teleport.OSSMigratedV6: types.True},
},
Spec: RoleSpecV3{
Options: RoleOptions{
CertificateFormat: teleport.CertificateFormatStandard,
MaxSessionTTL: NewDuration(defaults.MaxCertDuration),
PortForwarding: NewBoolOption(true),
ForwardAgent: NewBool(true),
BPF: defaults.EnhancedEvents(),
},
Allow: RoleConditions{
Namespaces: []string{defaults.Namespace},
NodeLabels: Labels{Wildcard: []string{Wildcard}},
AppLabels: Labels{Wildcard: []string{Wildcard}},
KubernetesLabels: Labels{Wildcard: []string{Wildcard}},
DatabaseLabels: Labels{Wildcard: []string{Wildcard}},
DatabaseNames: []string{teleport.TraitInternalDBNamesVariable},
DatabaseUsers: []string{teleport.TraitInternalDBUsersVariable},
Rules: []Rule{
NewRule(KindEvent, RO()),
NewRule(KindSession, RO()),
},
},
},
}
role.SetLogins(Allow, []string{teleport.TraitInternalLoginsVariable})
role.SetKubeUsers(Allow, []string{teleport.TraitInternalKubeUsersVariable})
role.SetKubeGroups(Allow, []string{teleport.TraitInternalKubeGroupsVariable})
return role
}
// NewOSSGithubRole creates a role for enabling RBAC for open source Github users
func NewOSSGithubRole(logins []string, kubeUsers []string, kubeGroups []string) Role {
role := &RoleV3{
Kind: KindRole,
Version: V3,
Metadata: Metadata{
Name: "github-" + uuid.New(),
Namespace: defaults.Namespace,
},
Spec: RoleSpecV3{
Options: RoleOptions{
CertificateFormat: teleport.CertificateFormatStandard,
MaxSessionTTL: NewDuration(defaults.MaxCertDuration),
PortForwarding: NewBoolOption(true),
ForwardAgent: NewBool(true),
BPF: defaults.EnhancedEvents(),
},
Allow: RoleConditions{
Namespaces: []string{defaults.Namespace},
NodeLabels: Labels{Wildcard: []string{Wildcard}},
AppLabels: Labels{Wildcard: []string{Wildcard}},
KubernetesLabels: Labels{Wildcard: []string{Wildcard}},
DatabaseLabels: Labels{Wildcard: []string{Wildcard}},
DatabaseNames: []string{teleport.TraitInternalDBNamesVariable},
DatabaseUsers: []string{teleport.TraitInternalDBUsersVariable},
Rules: []Rule{
NewRule(KindEvent, RO()),
},
},
},
}
role.SetLogins(Allow, logins)
role.SetKubeUsers(Allow, kubeUsers)
role.SetKubeGroups(Allow, kubeGroups)
return role
}
// RoleForCertAuthority creates role using services.CertAuthority.
func RoleForCertAuthority(ca CertAuthority) Role {
return &RoleV3{
Kind: KindRole,
Version: V3,
Metadata: Metadata{
Name: RoleNameForCertAuthority(ca.GetClusterName()),
Namespace: defaults.Namespace,
},
Spec: RoleSpecV3{
Options: RoleOptions{
MaxSessionTTL: NewDuration(defaults.MaxCertDuration),
},
Allow: RoleConditions{
Namespaces: []string{defaults.Namespace},
NodeLabels: Labels{Wildcard: []string{Wildcard}},
AppLabels: Labels{Wildcard: []string{Wildcard}},
KubernetesLabels: Labels{Wildcard: []string{Wildcard}},
DatabaseLabels: Labels{Wildcard: []string{Wildcard}},
Rules: CopyRulesSlice(DefaultCertAuthorityRules),
},
},
}
}
// Access service manages roles and permissions
type Access interface {
// GetRoles returns a list of roles
GetRoles(ctx context.Context) ([]Role, error)
// CreateRole creates a role
CreateRole(role Role) error
// UpsertRole creates or updates role
UpsertRole(ctx context.Context, role Role) error
// DeleteAllRoles deletes all roles
DeleteAllRoles() error
// GetRole returns role by name
GetRole(ctx context.Context, name string) (Role, error)
// DeleteRole deletes role by name
DeleteRole(ctx context.Context, name string) error
}
const (
// Allow is the set of conditions that allow access.
Allow RoleConditionType = true
// Deny is the set of conditions that prevent access.
Deny RoleConditionType = false
)
// ValidateRole parses validates the role, and sets default values.
func ValidateRole(r Role) error {
if err := r.CheckAndSetDefaults(); err != nil {
return err
}
// if we find {{ or }} but the syntax is invalid, the role is invalid
for _, condition := range []RoleConditionType{Allow, Deny} {
for _, login := range r.GetLogins(condition) {
if strings.Contains(login, "{{") || strings.Contains(login, "}}") {
_, err := parse.NewExpression(login)
if err != nil {
return trace.BadParameter("invalid login found: %v", login)
}
}
}
}
rules := append(r.GetRules(types.Allow), r.GetRules(types.Deny)...)
for _, rule := range rules {
if err := validateRule(rule); err != nil {
return trace.Wrap(err)
}
}
return nil
}
// validateRule parses the where and action fields to validate the rule.
func validateRule(r Rule) error {
if len(r.Where) != 0 {
parser, err := NewWhereParser(&Context{})
if err != nil {
return trace.Wrap(err)
}
_, err = parser.Parse(r.Where)
if err != nil {
return trace.BadParameter("could not parse 'where' rule: %q, error: %v", r.Where, err)
}
}
if len(r.Actions) != 0 {
parser, err := NewActionsParser(&Context{})
if err != nil {
return trace.Wrap(err)
}
for i, action := range r.Actions {
_, err = parser.Parse(action)
if err != nil {
return trace.BadParameter("could not parse action %v %q, error: %v", i, action, err)
}
}
}
return nil
}
// ApplyTraits applies the passed in traits to any variables within the role
// and returns itself.
func ApplyTraits(r Role, traits map[string][]string) Role {
for _, condition := range []RoleConditionType{Allow, Deny} {
inLogins := r.GetLogins(condition)
var outLogins []string
for _, login := range inLogins {
variableValues, err := applyValueTraits(login, traits)
if err != nil {
if !trace.IsNotFound(err) {
log.Debugf("Skipping login %v: %v.", login, err)
}
continue
}
// Filter out logins that come from variables that are not valid Unix logins.
for _, variableValue := range variableValues {
if !cstrings.IsValidUnixUser(variableValue) {
log.Debugf("Skipping login %v, not a valid Unix login.", variableValue)
continue
}
// A valid variable was found in the traits, append it to the list of logins.
outLogins = append(outLogins, variableValue)
}
}
r.SetLogins(condition, utils.Deduplicate(outLogins))
// apply templates to kubernetes groups
inKubeGroups := r.GetKubeGroups(condition)
var outKubeGroups []string
for _, group := range inKubeGroups {
variableValues, err := applyValueTraits(group, traits)
if err != nil {
if !trace.IsNotFound(err) {
log.Debugf("Skipping kube group %v: %v.", group, err)
}
continue
}
outKubeGroups = append(outKubeGroups, variableValues...)
}
r.SetKubeGroups(condition, utils.Deduplicate(outKubeGroups))
// apply templates to kubernetes users
inKubeUsers := r.GetKubeUsers(condition)
var outKubeUsers []string
for _, user := range inKubeUsers {
variableValues, err := applyValueTraits(user, traits)
if err != nil {
if !trace.IsNotFound(err) {
log.Debugf("Skipping kube user %v: %v.", user, err)
}
continue
}
outKubeUsers = append(outKubeUsers, variableValues...)
}
r.SetKubeUsers(condition, utils.Deduplicate(outKubeUsers))
// apply templates to database names
inDbNames := r.GetDatabaseNames(condition)
var outDbNames []string
for _, name := range inDbNames {
variableValues, err := applyValueTraits(name, traits)
if err != nil {
if !trace.IsNotFound(err) {
log.Debugf("Skipping database name %q: %v.", name, err)
}
continue
}
outDbNames = append(outDbNames, variableValues...)
}
r.SetDatabaseNames(condition, utils.Deduplicate(outDbNames))
// apply templates to database users
inDbUsers := r.GetDatabaseUsers(condition)
var outDbUsers []string
for _, user := range inDbUsers {
variableValues, err := applyValueTraits(user, traits)
if err != nil {
if !trace.IsNotFound(err) {
log.Debugf("Skipping database user %q: %v.", user, err)
}
continue
}
outDbUsers = append(outDbUsers, variableValues...)
}
r.SetDatabaseUsers(condition, utils.Deduplicate(outDbUsers))
// apply templates to node labels
inLabels := r.GetNodeLabels(condition)
if inLabels != nil {
r.SetNodeLabels(condition, applyLabelsTraits(inLabels, traits))
}
// apply templates to cluster labels
inLabels = r.GetClusterLabels(condition)
if inLabels != nil {
r.SetClusterLabels(condition, applyLabelsTraits(inLabels, traits))
}
// apply templates to kube labels
inLabels = r.GetKubernetesLabels(condition)
if inLabels != nil {
r.SetKubernetesLabels(condition, applyLabelsTraits(inLabels, traits))
}
// apply templates to app labels
inLabels = r.GetAppLabels(condition)
if inLabels != nil {
r.SetAppLabels(condition, applyLabelsTraits(inLabels, traits))
}
// apply templates to database labels
inLabels = r.GetDatabaseLabels(condition)
if inLabels != nil {
r.SetDatabaseLabels(condition, applyLabelsTraits(inLabels, traits))
}
// apply templates to impersonation conditions
inCond := r.GetImpersonateConditions(condition)
var outCond types.ImpersonateConditions
for _, user := range inCond.Users {
variableValues, err := applyValueTraits(user, traits)
if err != nil {
if !trace.IsNotFound(err) {
log.WithError(err).Debugf("Skipping impersonate user %q.", user)
}
continue
}
outCond.Users = append(outCond.Users, variableValues...)
}
for _, role := range inCond.Roles {
variableValues, err := applyValueTraits(role, traits)
if err != nil {
if !trace.IsNotFound(err) {
log.WithError(err).Debugf("Skipping impersonate role %q.", role)
}
continue
}
outCond.Roles = append(outCond.Roles, variableValues...)
}
outCond.Users = utils.Deduplicate(outCond.Users)
outCond.Roles = utils.Deduplicate(outCond.Roles)
outCond.Where = inCond.Where
r.SetImpersonateConditions(condition, outCond)
}
return r
}
// applyLabelsTraits interpolates variables based on the templates
// and traits from identity provider. For example:
//
// cluster_labels:
// env: ['{{external.groups}}']
//
// and groups: ['admins', 'devs']
//
// will be interpolated to:
//
// cluster_labels:
// env: ['admins', 'devs']
//
func applyLabelsTraits(inLabels Labels, traits map[string][]string) Labels {
outLabels := make(Labels, len(inLabels))
// every key will be mapped to the first value
for key, vals := range inLabels {
keyVars, err := applyValueTraits(key, traits)
if err != nil {
// empty key will not match anything
log.Debugf("Setting empty node label pair %q -> %q: %v", key, vals, err)
keyVars = []string{""}
}
var values []string
for _, val := range vals {
valVars, err := applyValueTraits(val, traits)
if err != nil {
log.Debugf("Setting empty node label value %q -> %q: %v", key, val, err)
// empty value will not match anything
valVars = []string{""}
}
values = append(values, valVars...)
}
outLabels[keyVars[0]] = utils.Deduplicate(values)
}
return outLabels
}
// applyValueTraits applies the passed in traits to the variable,
// returns BadParameter in case if referenced variable is unsupported,
// returns NotFound in case if referenced trait is missing,
// mapped list of values otherwise, the function guarantees to return
// at least one value in case if return value is nil
func applyValueTraits(val string, traits map[string][]string) ([]string, error) {
// Extract the variable from the role variable.
variable, err := parse.NewExpression(val)
if err != nil {
return nil, trace.Wrap(err)
}
// For internal traits, only internal.logins, internal.kubernetes_users and
// internal.kubernetes_groups are supported at the moment.
if variable.Namespace() == teleport.TraitInternalPrefix {
switch variable.Name() {
case teleport.TraitLogins, teleport.TraitKubeGroups, teleport.TraitKubeUsers, teleport.TraitDBNames, teleport.TraitDBUsers:
default:
return nil, trace.BadParameter("unsupported variable %q", variable.Name())
}
}
// If the variable is not found in the traits, skip it.
interpolated, err := variable.Interpolate(traits)
if trace.IsNotFound(err) || len(interpolated) == 0 {
return nil, trace.NotFound("variable %q not found in traits", variable.Name())
}
if err != nil {
return nil, trace.Wrap(err)
}
return interpolated, nil
}
// ruleScore is a sorting score of the rule, the larger the score, the more
// specific the rule is
func ruleScore(r *Rule) int {
score := 0
// wildcard rules are less specific
if utils.SliceContainsStr(r.Resources, Wildcard) {
score -= 4
} else if len(r.Resources) == 1 {
// rules that match specific resource are more specific than
// fields that match several resources
score += 2
}
// rules that have wildcard verbs are less specific
if utils.SliceContainsStr(r.Verbs, Wildcard) {
score -= 2
}
// rules that supply 'where' or 'actions' are more specific
// having 'where' or 'actions' is more important than
// whether the rules are wildcard or not, so here we have +8 vs
// -4 and -2 score penalty for wildcards in resources and verbs
if len(r.Where) > 0 {
score += 8
}
// rules featuring actions are more specific
if len(r.Actions) > 0 {
score += 8
}
return score
}
// CompareRuleScore returns true if the first rule is more specific than the other.
//
// * nRule matching wildcard resource is less specific
// than same rule matching specific resource.
// * Rule that has wildcard verbs is less specific
// than the same rules matching specific verb.
// * Rule that has where section is more specific
// than the same rule without where section.
// * Rule that has actions list is more specific than
// rule without actions list.
func CompareRuleScore(r *Rule, o *Rule) bool {
return ruleScore(r) > ruleScore(o)
}
// RuleSet maps resource to a set of rules defined for it
type RuleSet map[string][]Rule
// MakeRuleSet creates a new rule set from a list
func MakeRuleSet(rules []Rule) RuleSet {
set := make(RuleSet)
for _, rule := range rules {
for _, resource := range rule.Resources {
set[resource] = append(set[resource], rule)
}
}
for resource := range set {
rules := set[resource]
// sort rules by most specific rule, the rule that has actions
// is more specific than the one that has no actions
sort.Slice(rules, func(i, j int) bool {
return CompareRuleScore(&rules[i], &rules[j])
})
set[resource] = rules
}
return set
}
// Match tests if the resource name and verb are in a given list of rules.
// More specific rules will be matched first. See Rule.IsMoreSpecificThan
// for exact specs on whether the rule is more or less specific.
//
// Specifying order solves the problem on having multiple rules, e.g. one wildcard
// rule can override more specific rules with 'where' sections that can have
// 'actions' lists with side effects that will not be triggered otherwise.
//
func (set RuleSet) Match(whereParser predicate.Parser, actionsParser predicate.Parser, resource string, verb string) (bool, error) {
// empty set matches nothing
if len(set) == 0 {
return false, nil
}
// check for matching resource by name
// the most specific rule should win
rules := set[resource]
for _, rule := range rules {
match, err := matchesWhere(&rule, whereParser)
if err != nil {
return false, trace.Wrap(err)
}
if match && (rule.HasVerb(Wildcard) || rule.HasVerb(verb)) {
if err := processActions(&rule, actionsParser); err != nil {
return true, trace.Wrap(err)
}
return true, nil
}
}
// check for wildcard resource matcher
for _, rule := range set[Wildcard] {
match, err := matchesWhere(&rule, whereParser)
if err != nil {
return false, trace.Wrap(err)
}
if match && (rule.HasVerb(Wildcard) || rule.HasVerb(verb)) {
if err := processActions(&rule, actionsParser); err != nil {
return true, trace.Wrap(err)
}
return true, nil
}
}
return false, nil
}
// matchesWhere returns true if Where rule matches.
// Empty Where block always matches.
func matchesWhere(r *Rule, parser predicate.Parser) (bool, error) {
if r.Where == "" {
return true, nil
}
ifn, err := parser.Parse(r.Where)
if err != nil {
return false, trace.Wrap(err)
}
fn, ok := ifn.(predicate.BoolPredicate)
if !ok {
return false, trace.BadParameter("invalid predicate type for where expression: %v", r.Where)
}
return fn(), nil
}
// processActions processes actions specified for this rule
func processActions(r *Rule, parser predicate.Parser) error {
for _, action := range r.Actions {
ifn, err := parser.Parse(action)
if err != nil {
return trace.Wrap(err)
}
fn, ok := ifn.(predicate.BoolPredicate)
if !ok {
return trace.BadParameter("invalid predicate type for action expression: %v", action)
}
fn()
}
return nil
}
// Slice returns slice from a set
func (set RuleSet) Slice() []Rule {
var out []Rule
for _, rules := range set {
out = append(out, rules...)
}
return out
}
// AccessChecker interface implements access checks for given role or role set
type AccessChecker interface {
// HasRole checks if the checker includes the role
HasRole(role string) bool
// RoleNames returns a list of role names
RoleNames() []string
// CheckAccessToServer checks access to server.
CheckAccessToServer(login string, server Server, mfa AccessMFAParams) error
// CheckAccessToRemoteCluster checks access to remote cluster
CheckAccessToRemoteCluster(cluster RemoteCluster) error
// CheckAccessToRule checks access to a rule within a namespace.
CheckAccessToRule(context RuleContext, namespace string, rule string, verb string, silent bool) error
// CheckLoginDuration checks if role set can login up to given duration and
// returns a combined list of allowed logins.
CheckLoginDuration(ttl time.Duration) ([]string, error)
// CheckKubeGroupsAndUsers check if role can login into kubernetes
// and returns two lists of combined allowed groups and users
CheckKubeGroupsAndUsers(ttl time.Duration, overrideTTL bool) (groups []string, users []string, err error)
// AdjustSessionTTL will reduce the requested ttl to lowest max allowed TTL
// for this role set, otherwise it returns ttl unchanged
AdjustSessionTTL(ttl time.Duration) time.Duration
// AdjustClientIdleTimeout adjusts requested idle timeout
// to the lowest max allowed timeout, the most restrictive
// option will be picked
AdjustClientIdleTimeout(ttl time.Duration) time.Duration
// AdjustDisconnectExpiredCert adjusts the value based on the role set
// the most restrictive option will be picked
AdjustDisconnectExpiredCert(disconnect bool) bool
// CheckAgentForward checks if the role can request agent forward for this
// user.
CheckAgentForward(login string) error
// CanForwardAgents returns true if this role set offers capability to forward
// agents.
CanForwardAgents() bool
// CanPortForward returns true if this RoleSet can forward ports.
CanPortForward() bool
// MaybeCanReviewRequests attempts to guess if this RoleSet belongs
// to a user who should be submitting access reviews. Because not all rolesets
// are derived from statically assigned roles, this may return false positives.
MaybeCanReviewRequests() bool
// PermitX11Forwarding returns true if this RoleSet allows X11 Forwarding.
PermitX11Forwarding() bool
// CertificateFormat returns the most permissive certificate format in a
// RoleSet.
CertificateFormat() string
// EnhancedRecordingSet returns a set of events that will be recorded
// for enhanced session recording.
EnhancedRecordingSet() map[string]bool
// CheckAccessToApp checks access to an application.
CheckAccessToApp(login string, app *App, mfa AccessMFAParams) error
// CheckAccessToKubernetes checks access to a kubernetes cluster.
CheckAccessToKubernetes(login string, app *KubernetesCluster, mfa AccessMFAParams) error
// CheckDatabaseNamesAndUsers returns database names and users this role
// is allowed to use.
CheckDatabaseNamesAndUsers(ttl time.Duration, overrideTTL bool) (names []string, users []string, err error)
// CheckAccessToDatabase checks whether a user has access to the provided
// database server.
CheckAccessToDatabase(server types.DatabaseServer, mfa AccessMFAParams, matchers ...RoleMatcher) error
// CheckImpersonate checks whether current user is allowed to impersonate
// users and roles
CheckImpersonate(currentUser, impersonateUser types.User, impersonateRoles []types.Role) error
// CanImpersonateSomeone returns true if this checker has any impersonation rules
CanImpersonateSomeone() bool
}
// FromSpec returns new RoleSet created from spec
func FromSpec(name string, spec RoleSpecV3) (RoleSet, error) {
role, err := NewRole(name, spec)
if err != nil {
return nil, trace.Wrap(err)
}
return NewRoleSet(role), nil
}
// RW is a shortcut that returns all verbs.
func RW() []string {
return []string{VerbList, VerbCreate, VerbRead, VerbUpdate, VerbDelete}
}
// RO is a shortcut that returns read only verbs that provide access to secrets.
func RO() []string {
return []string{VerbList, VerbRead}
}
// ReadNoSecrets is a shortcut that returns read only verbs that do not
// provide access to secrets.
func ReadNoSecrets() []string {
return []string{VerbList, VerbReadNoSecrets}
}
// RoleGetter is an interface that defines GetRole method
type RoleGetter interface {
// GetRole returns role by name
GetRole(ctx context.Context, name string) (Role, error)
}
// ExtractFromCertificate will extract roles and traits from a *ssh.Certificate
// or from the backend if they do not exist in the certificate.
func ExtractFromCertificate(access UserGetter, cert *ssh.Certificate) ([]string, wrappers.Traits, error) {
// For legacy certificates, fetch roles and traits from the services.User
// object in the backend.
if isFormatOld(cert) {
u, err := access.GetUser(cert.KeyId, false)
if err != nil {
return nil, nil, trace.Wrap(err)
}
log.Warnf("User %v using old style SSH certificate, fetching roles and traits "+
"from backend. If the identity provider allows username changes, this can "+
"potentially allow an attacker to change the role of the existing user. "+
"It's recommended to upgrade to standard SSH certificates.", cert.KeyId)
return u.GetRoles(), u.GetTraits(), nil
}
// Standard certificates have the roles and traits embedded in them.
roles, err := extractRolesFromCert(cert)
if err != nil {
return nil, nil, trace.Wrap(err)
}
traits, err := extractTraitsFromCert(cert)
if err != nil {
return nil, nil, trace.Wrap(err)
}
return roles, traits, nil
}
// ExtractFromIdentity will extract roles and traits from the *x509.Certificate
// which Teleport passes along as a *tlsca.Identity. If roles and traits do not
// exist in the certificates, they are extracted from the backend.
func ExtractFromIdentity(access UserGetter, identity tlsca.Identity) ([]string, wrappers.Traits, error) {
// For legacy certificates, fetch roles and traits from the services.User
// object in the backend.
if missingIdentity(identity) {
u, err := access.GetUser(identity.Username, false)
if err != nil {
return nil, nil, trace.Wrap(err)
}
log.Warnf("Failed to find roles or traits in x509 identity for %v. Fetching "+
"from backend. If the identity provider allows username changes, this can "+
"potentially allow an attacker to change the role of the existing user.",
identity.Username)
return u.GetRoles(), u.GetTraits(), nil
}
return identity.Groups, identity.Traits, nil
}
// FetchRoleList fetches roles by their names, applies the traits to role
// variables, and returns the list
func FetchRoleList(roleNames []string, access RoleGetter, traits map[string][]string) (RoleSet, error) {
var roles []Role
for _, roleName := range roleNames {
role, err := access.GetRole(context.TODO(), roleName)
if err != nil {
return nil, trace.Wrap(err)
}
roles = append(roles, ApplyTraits(role, traits))
}
return roles, nil
}
// FetchRoles fetches roles by their names, applies the traits to role
// variables, and returns the RoleSet. Adds runtime roles like the default
// implicit role to RoleSet.
func FetchRoles(roleNames []string, access RoleGetter, traits map[string][]string) (RoleSet, error) {
roles, err := FetchRoleList(roleNames, access, traits)
if err != nil {
return nil, trace.Wrap(err)
}
return NewRoleSet(roles...), nil
}
// isFormatOld returns true if roles and traits were not found in the
// *ssh.Certificate.
func isFormatOld(cert *ssh.Certificate) bool {
_, hasRoles := cert.Extensions[teleport.CertExtensionTeleportRoles]
_, hasTraits := cert.Extensions[teleport.CertExtensionTeleportTraits]
if hasRoles || hasTraits {
return false
}
return true
}
// missingIdentity returns true if the identity is missing or the identity
// has no roles or traits.
func missingIdentity(identity tlsca.Identity) bool {
if len(identity.Groups) == 0 || len(identity.Traits) == 0 {
return true
}
return false
}
// extractRolesFromCert extracts roles from certificate metadata extensions.
func extractRolesFromCert(cert *ssh.Certificate) ([]string, error) {
data, ok := cert.Extensions[teleport.CertExtensionTeleportRoles]
if !ok {
return nil, trace.NotFound("no roles found")
}
return UnmarshalCertRoles(data)
}