-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
role.go
2159 lines (1904 loc) · 61.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 2016 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 (
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/modules"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/utils/parse"
"github.com/gravitational/configure/cstrings"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
log "github.com/sirupsen/logrus"
"github.com/vulcand/predicate"
)
// AdminUserRules provides access to the default set of rules assigned to
// all users.
var AdminUserRules = []Rule{
NewRule(KindRole, RW()),
NewRule(KindAuthConnector, RW()),
NewRule(KindSession, RO()),
NewRule(KindTrustedCluster, RW()),
}
// DefaultImplicitRules provides access to the default set of implicit rules
// assigned to all roles.
var DefaultImplicitRules = []Rule{
NewRule(KindNode, RO()),
NewRule(KindAuthServer, RO()),
NewRule(KindReverseTunnel, RO()),
NewRule(KindCertAuthority, RO()),
NewRule(KindClusterAuthPreference, RO()),
NewRule(KindClusterName, RO()),
NewRule(KindSSHSession, 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, RO()),
}
// 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 (Enterprise only).
func NewAdminRole() Role {
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),
},
Allow: RoleConditions{
Namespaces: []string{defaults.Namespace},
NodeLabels: Labels{Wildcard: []string{Wildcard}},
Rules: CopyRulesSlice(AdminUserRules),
},
},
}
role.SetLogins(Allow, modules.GetModules().DefaultAllowedLogins())
role.SetKubeGroups(Allow, modules.GetModules().DefaultKubeGroups())
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(),
},
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),
},
Allow: RoleConditions{
Namespaces: []string{defaults.Namespace},
NodeLabels: Labels{Wildcard: []string{Wildcard}},
Rules: CopyRulesSlice(AdminUserRules),
},
},
}
}
// 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}},
Rules: CopyRulesSlice(DefaultCertAuthorityRules),
},
},
}
}
// ConvertV1CertAuthority converts V1 cert authority for new CA and Role
func ConvertV1CertAuthority(v1 *CertAuthorityV1) (CertAuthority, Role) {
ca := v1.V2()
role := RoleForCertAuthority(ca)
role.SetLogins(Allow, v1.AllowedLogins)
ca.AddRole(role.GetName())
return ca, role
}
// Access service manages roles and permissions
type Access interface {
// GetRoles returns a list of roles
GetRoles() ([]Role, error)
// CreateRole creates a role
CreateRole(role Role, ttl time.Duration) error
// UpsertRole creates or updates role
UpsertRole(role Role, ttl time.Duration) error
// DeleteAllRoles deletes all roles
DeleteAllRoles() error
// GetRole returns role by name
GetRole(name string) (Role, error)
// DeleteRole deletes role by name
DeleteRole(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
)
// RoleConditionType specifies if it's an allow rule (true) or deny rule (false).
type RoleConditionType bool
// Role contains a set of permissions or settings
type Role interface {
// Resource provides common resource methods.
Resource
// CheckAndSetDefaults checks and set default values for any missing fields.
CheckAndSetDefaults() error
// Equals returns true if the roles are equal. Roles are equal if options and
// conditions match.
Equals(other Role) bool
// ApplyTraits applies the passed in traits to any variables within the role
// and returns itself.
ApplyTraits(map[string][]string) Role
// GetRawObject returns the raw object stored in the backend without any
// conversions applied, used in migrations.
GetRawObject() interface{}
// GetOptions gets role options.
GetOptions() RoleOptions
// SetOptions sets role options
SetOptions(opt RoleOptions)
// GetLogins gets *nix system logins for allow or deny condition.
GetLogins(RoleConditionType) []string
// SetLogins sets *nix system logins for allow or deny condition.
SetLogins(RoleConditionType, []string)
// GetNamespaces gets a list of namespaces this role is allowed or denied access to.
GetNamespaces(RoleConditionType) []string
// GetNamespaces sets a list of namespaces this role is allowed or denied access to.
SetNamespaces(RoleConditionType, []string)
// GetNodeLabels gets the map of node labels this role is allowed or denied access to.
GetNodeLabels(RoleConditionType) Labels
// SetNodeLabels sets the map of node labels this role is allowed or denied access to.
SetNodeLabels(RoleConditionType, Labels)
// GetRules gets all allow or deny rules.
GetRules(rct RoleConditionType) []Rule
// SetRules sets an allow or deny rule.
SetRules(rct RoleConditionType, rules []Rule)
// GetKubeGroups returns kubernetes groups
GetKubeGroups(RoleConditionType) []string
// SetKubeGroups sets kubernetes groups for allow or deny condition.
SetKubeGroups(RoleConditionType, []string)
}
// 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))
inLabels := r.GetNodeLabels(condition)
// to avoid unnecessary allocations
if inLabels != nil {
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)
}
r.SetNodeLabels(condition, outLabels)
}
}
return r
}
// 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 variablePrefix and variableName from the role variable.
variablePrefix, variableName, err := parse.IsRoleVariable(val)
if err != nil {
if !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
return []string{val}, nil
}
// For internal traits, only internal.logins and internal.kubernetes_groups is supported at the moment.
if variablePrefix == teleport.TraitInternalPrefix {
if variableName != teleport.TraitLogins && variableName != teleport.TraitKubeGroups {
return nil, trace.BadParameter("unsupported variable %q", variableName)
}
}
// If the variable is not found in the traits, skip it.
variableValues, ok := traits[variableName]
if !ok || len(variableValues) == 0 {
return nil, trace.NotFound("variable %q not found in traits", variableName)
}
return append([]string{}, variableValues...), nil
}
// RoleV3 represents role resource specification
type RoleV3 struct {
// Kind is the type of resource.
Kind string `json:"kind"`
// Version is the resource version.
Version string `json:"version"`
// Metadata is resource metadata.
Metadata Metadata `json:"metadata"`
// Spec contains resource specification.
Spec RoleSpecV3 `json:"spec"`
// rawObject is the raw object stored in the backend without any
// conversions applied, used in migrations.
rawObject interface{}
}
// Equals returns true if the roles are equal. Roles are equal if options,
// namespaces, logins, labels, and conditions match.
func (r *RoleV3) Equals(other Role) bool {
if !r.GetOptions().Equals(other.GetOptions()) {
return false
}
for _, condition := range []RoleConditionType{Allow, Deny} {
if !utils.StringSlicesEqual(r.GetLogins(condition), other.GetLogins(condition)) {
return false
}
if !utils.StringSlicesEqual(r.GetNamespaces(condition), other.GetNamespaces(condition)) {
return false
}
if !r.GetNodeLabels(condition).Equals(other.GetNodeLabels(condition)) {
return false
}
if !RuleSlicesEqual(r.GetRules(condition), other.GetRules(condition)) {
return false
}
}
return true
}
// ApplyTraits applies the passed in traits to any variables within the role
// and returns itself.
func (r *RoleV3) ApplyTraits(traits map[string][]string) Role {
return ApplyTraits(r, traits)
}
// SetRawObject sets raw object as it was stored in the database
// used for migrations and should not be modifed
func (r *RoleV3) SetRawObject(raw interface{}) {
r.rawObject = raw
}
// GetRawObject returns the raw object stored in the backend without any
// conversions applied, used in migrations.
func (r *RoleV3) GetRawObject() interface{} {
return r.rawObject
}
// SetExpiry sets expiry time for the object.
func (r *RoleV3) SetExpiry(expires time.Time) {
r.Metadata.SetExpiry(expires)
}
// Expiry returns the expiry time for the object.
func (r *RoleV3) Expiry() time.Time {
return r.Metadata.Expiry()
}
// SetTTL sets TTL header using realtime clock.
func (r *RoleV3) SetTTL(clock clockwork.Clock, ttl time.Duration) {
r.Metadata.SetTTL(clock, ttl)
}
// SetName sets the role name and is a shortcut for SetMetadata().Name.
func (r *RoleV3) SetName(s string) {
r.Metadata.Name = s
}
// GetName gets the role name and is a shortcut for GetMetadata().Name.
func (r *RoleV3) GetName() string {
return r.Metadata.Name
}
// GetMetadata returns role metadata.
func (r *RoleV3) GetMetadata() Metadata {
return r.Metadata
}
// GetOptions gets role options.
func (r *RoleV3) GetOptions() RoleOptions {
return r.Spec.Options
}
// SetOptions sets role options.
func (r *RoleV3) SetOptions(options RoleOptions) {
r.Spec.Options = options
}
// GetLogins gets system logins for allow or deny condition.
func (r *RoleV3) GetLogins(rct RoleConditionType) []string {
if rct == Allow {
return r.Spec.Allow.Logins
}
return r.Spec.Deny.Logins
}
// SetLogins sets system logins for allow or deny condition.
func (r *RoleV3) SetLogins(rct RoleConditionType, logins []string) {
lcopy := utils.CopyStrings(logins)
if rct == Allow {
r.Spec.Allow.Logins = lcopy
} else {
r.Spec.Deny.Logins = lcopy
}
}
// GetKubeGroups returns kubernetes groups
func (r *RoleV3) GetKubeGroups(rct RoleConditionType) []string {
if rct == Allow {
return r.Spec.Allow.KubeGroups
}
return r.Spec.Deny.KubeGroups
}
// SetKubeGroups sets kubernetes groups for allow or deny condition.
func (r *RoleV3) SetKubeGroups(rct RoleConditionType, groups []string) {
lcopy := utils.CopyStrings(groups)
if rct == Allow {
r.Spec.Allow.KubeGroups = lcopy
} else {
r.Spec.Deny.KubeGroups = lcopy
}
}
// GetNamespaces gets a list of namespaces this role is allowed or denied access to.
func (r *RoleV3) GetNamespaces(rct RoleConditionType) []string {
if rct == Allow {
return r.Spec.Allow.Namespaces
}
return r.Spec.Deny.Namespaces
}
// GetNamespaces sets a list of namespaces this role is allowed or denied access to.
func (r *RoleV3) SetNamespaces(rct RoleConditionType, namespaces []string) {
ncopy := utils.CopyStrings(namespaces)
if rct == Allow {
r.Spec.Allow.Namespaces = ncopy
} else {
r.Spec.Deny.Namespaces = ncopy
}
}
// GetNodeLabels gets the map of node labels this role is allowed or denied access to.
func (r *RoleV3) GetNodeLabels(rct RoleConditionType) Labels {
if rct == Allow {
return r.Spec.Allow.NodeLabels
}
return r.Spec.Deny.NodeLabels
}
// SetNodeLabels sets the map of node labels this role is allowed or denied access to.
func (r *RoleV3) SetNodeLabels(rct RoleConditionType, labels Labels) {
if rct == Allow {
r.Spec.Allow.NodeLabels = labels.Clone()
} else {
r.Spec.Deny.NodeLabels = labels.Clone()
}
}
// GetRules gets all allow or deny rules.
func (r *RoleV3) GetRules(rct RoleConditionType) []Rule {
if rct == Allow {
return r.Spec.Allow.Rules
}
return r.Spec.Deny.Rules
}
// SetRules sets an allow or deny rule.
func (r *RoleV3) SetRules(rct RoleConditionType, in []Rule) {
rcopy := CopyRulesSlice(in)
if rct == Allow {
r.Spec.Allow.Rules = rcopy
} else {
r.Spec.Deny.Rules = rcopy
}
}
// Check checks validity of all parameters and sets defaults
func (r *RoleV3) CheckAndSetDefaults() error {
err := r.Metadata.CheckAndSetDefaults()
if err != nil {
return trace.Wrap(err)
}
// make sure we have defaults for all fields
if r.Spec.Options.CertificateFormat == "" {
r.Spec.Options.CertificateFormat = teleport.CertificateFormatStandard
}
if r.Spec.Options.MaxSessionTTL.Value() == 0 {
r.Spec.Options.MaxSessionTTL = NewDuration(defaults.MaxCertDuration)
}
if r.Spec.Options.PortForwarding == nil {
r.Spec.Options.PortForwarding = NewBoolOption(true)
}
if r.Spec.Allow.Namespaces == nil {
r.Spec.Allow.Namespaces = []string{defaults.Namespace}
}
if r.Spec.Allow.NodeLabels == nil {
r.Spec.Allow.NodeLabels = Labels{Wildcard: []string{Wildcard}}
}
if r.Spec.Deny.Namespaces == nil {
r.Spec.Deny.Namespaces = []string{defaults.Namespace}
}
// 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.IsRoleVariable(login)
if err != nil {
return trace.BadParameter("invalid login found: %v", login)
}
}
}
}
// check and correct the session ttl
if r.Spec.Options.MaxSessionTTL.Value() <= 0 {
r.Spec.Options.MaxSessionTTL = NewDuration(defaults.MaxCertDuration)
}
// restrict wildcards
for _, login := range r.Spec.Allow.Logins {
if login == Wildcard {
return trace.BadParameter("wildcard matcher is not allowed in logins")
}
}
for key, val := range r.Spec.Allow.NodeLabels {
if key == Wildcard && !(len(val) == 1 && val[0] == Wildcard) {
return trace.BadParameter("selector *:<val> is not supported")
}
}
for i := range r.Spec.Allow.Rules {
err := r.Spec.Allow.Rules[i].CheckAndSetDefaults()
if err != nil {
return trace.BadParameter("failed to process 'allow' rule %v: %v", i, err)
}
}
for i := range r.Spec.Deny.Rules {
err := r.Spec.Deny.Rules[i].CheckAndSetDefaults()
if err != nil {
return trace.BadParameter("failed to process 'deny' rule %v: %v", i, err)
}
}
return nil
}
// String returns the human readable representation of a role.
func (r *RoleV3) String() string {
return fmt.Sprintf("Role(Name=%v,Options=%v,Allow=%+v,Deny=%+v)",
r.GetName(), r.Spec.Options, r.Spec.Allow, r.Spec.Deny)
}
// RoleSpecV3 is role specification for RoleV3.
type RoleSpecV3 struct {
// Options is for OpenSSH options like agent forwarding.
Options RoleOptions `json:"options,omitempty"`
// Allow is the set of conditions evaluated to grant access.
Allow RoleConditions `json:"allow,omitempty"`
// Deny is the set of conditions evaluated to deny access. Deny takes priority over allow.
Deny RoleConditions `json:"deny,omitempty"`
}
// RoleOptions is a set of role options
type RoleOptions struct {
// ForwardAgent is SSH agent forwarding.
ForwardAgent Bool `json:"forward_agent"`
// MaxSessionTTL defines how long a SSH session can last for.
MaxSessionTTL Duration `json:"max_session_ttl"`
// PortForwarding defines if the certificate will have "permit-port-forwarding"
// in the certificate. PortForwarding is "yes" if not set,
// that's why this is a pointer
PortForwarding *Bool `json:"port_forwarding,omitempty"`
// CertificateFormat defines the format of the user certificate to allow
// compatibility with older versions of OpenSSH.
CertificateFormat string `json:"cert_format"`
// ClientIdleTimeout sets disconnect clients on idle timeout behavior,
// if set to 0 means do not disconnect, otherwise is set to the idle
// duration.
ClientIdleTimeout Duration `json:"client_idle_timeout"`
// DisconnectExpiredCert sets disconnect clients on expired certificates.
DisconnectExpiredCert Bool `json:"disconnect_expired_cert"`
}
// Equals checks if all the key/values in the RoleOptions map match.
func (o RoleOptions) Equals(other RoleOptions) bool {
return (o.ForwardAgent.Value() == other.ForwardAgent.Value() &&
o.MaxSessionTTL.Value() == other.MaxSessionTTL.Value() &&
BoolOption(o.PortForwarding).Value() == BoolOption(other.PortForwarding).Value() &&
o.CertificateFormat == other.CertificateFormat &&
o.ClientIdleTimeout.Value() == other.ClientIdleTimeout.Value() &&
o.DisconnectExpiredCert.Value() == other.DisconnectExpiredCert.Value())
}
// RoleConditions is a set of conditions that must all match to be allowed or
// denied access.
type RoleConditions struct {
// Logins is a list of *nix system logins.
Logins []string `json:"logins,omitempty"`
// Namespaces is a list of namespaces (used to partition a cluster). The
// field should be called "namespaces" when it returns in Teleport 2.4.
Namespaces []string `json:"-"`
// NodeLabels is a map of node labels (used to dynamically grant access to nodes).
NodeLabels Labels `json:"node_labels,omitempty"`
// Rules is a list of rules and their access levels. Rules are a high level
// construct used for access control.
Rules []Rule `json:"rules,omitempty"`
// KubeGroups is a list of kubernetes groups
KubeGroups []string `json:"kubernetes_groups,omitempty"`
}
// Equals returns true if the role conditions (logins, namespaces, labels,
// and rules) are equal and false if they are not.
func (r *RoleConditions) Equals(o RoleConditions) bool {
if !utils.StringSlicesEqual(r.Logins, o.Logins) {
return false
}
if !utils.StringSlicesEqual(r.Namespaces, o.Namespaces) {
return false
}
if !r.NodeLabels.Equals(o.NodeLabels) {
return false
}
if len(r.Rules) != len(o.Rules) {
return false
}
for i := range r.Rules {
if !r.Rules[i].Equals(o.Rules[i]) {
return false
}
}
return true
}
// NewRule creates a rule based on a resource name and a list of verbs
func NewRule(resource string, verbs []string) Rule {
return Rule{
Resources: []string{resource},
Verbs: verbs,
}
}
// Rule represents allow or deny rule that is executed to check
// if user or service have access to resource
type Rule struct {
// Resources is a list of resources
Resources []string `json:"resources"`
// Verbs is a list of verbs
Verbs []string `json:"verbs"`
// Where specifies optional advanced matcher
Where string `json:"where,omitempty"`
// Actions specifies optional actions taken when this rule matches
Actions []string `json:"actions,omitempty"`
}
// CheckAndSetDefaults checks and sets defaults for this rule
func (r *Rule) CheckAndSetDefaults() error {
if len(r.Resources) == 0 {
return trace.BadParameter("missing resources to match")
}
if len(r.Verbs) == 0 {
return trace.BadParameter("missing verbs")
}
if len(r.Where) != 0 {
parser, err := GetWhereParserFn()(&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 := GetActionsParserFn()(&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
}
// score is a sorting score of the rule, the more the score, the more
// specific the rule is
func (r *Rule) score() int {
score := 0
// wilcard 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 wilcard 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
}
// IsMoreSpecificThan returns true if the 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 (r *Rule) IsMoreSpecificThan(o Rule) bool {
return r.score() > o.score()
}
// MatchesWhere returns true if Where rule matches
// Empty Where block always matches
func (r *Rule) MatchesWhere(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("unsupported type: %T", ifn)
}
return fn(), nil
}
// ProcessActions processes actions specified for this rule
func (r *Rule) ProcessActions(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("unsupported type: %T", ifn)
}
fn()
}
return nil
}
// HasVerb returns true if the rule has verb,
// this method also matches wildcard
func (r *Rule) HasVerb(verb string) bool {
for _, v := range r.Verbs {
// readnosecrets can be satisfied by having readnosecrets or read
if verb == VerbReadNoSecrets {
if v == VerbReadNoSecrets || v == VerbRead {
return true
}
continue
}
if v == verb {
return true
}
}
return false
}
// Equals returns true if the rule equals to another
func (r *Rule) Equals(other Rule) bool {
if !utils.StringSlicesEqual(r.Resources, other.Resources) {
return false
}
if !utils.StringSlicesEqual(r.Verbs, other.Verbs) {
return false
}
if !utils.StringSlicesEqual(r.Actions, other.Actions) {
return false
}
if r.Where != other.Where {
return false
}
return true
}
// RuleSet maps resource to a set of rules defined for it
type RuleSet map[string][]Rule
// MatchRule 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 := rule.MatchesWhere(whereParser)
if err != nil {
return false, trace.Wrap(err)
}
if match && (rule.HasVerb(Wildcard) || rule.HasVerb(verb)) {
if err := rule.ProcessActions(actionsParser); err != nil {
return true, trace.Wrap(err)
}
return true, nil
}
}
// check for wildcard resource matcher
for _, rule := range set[Wildcard] {
match, err := rule.MatchesWhere(whereParser)
if err != nil {
return false, trace.Wrap(err)
}
if match && (rule.HasVerb(Wildcard) || rule.HasVerb(verb)) {
if err := rule.ProcessActions(actionsParser); err != nil {
return true, trace.Wrap(err)
}
return true, nil
}
}
return false, 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
}
// MakeRuleSet converts slice of rules to the set of rules
func MakeRuleSet(rules []Rule) RuleSet {
set := make(RuleSet)
for _, rule := range rules {
for _, resource := range rule.Resources {
rules, ok := set[resource]
if !ok {
set[resource] = []Rule{rule}
} else {
rules = append(rules, rule)
set[resource] = rules
}
}
}
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 rules[i].IsMoreSpecificThan(rules[j])
})
set[resource] = rules
}
return set
}
// CopyRulesSlice copies input slice of Rules and returns the copy
func CopyRulesSlice(in []Rule) []Rule {
out := make([]Rule, len(in))
copy(out, in)
return out
}
// RuleSlicesEqual returns true if two rule slices are equal
func RuleSlicesEqual(a, b []Rule) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if !a[i].Equals(b[i]) {
return false
}
}