forked from gravitational/teleport
/
role.go
3210 lines (2861 loc) · 104 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
/*
* Teleport
* Copyright (C) 2023 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package services
import (
"context"
"encoding/json"
"errors"
"fmt"
"path"
"regexp"
"slices"
"sort"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/google/uuid"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"
"github.com/vulcand/predicate"
"golang.org/x/crypto/ssh"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/constants"
"github.com/gravitational/teleport/api/defaults"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/api/types/wrappers"
apiutils "github.com/gravitational/teleport/api/utils"
"github.com/gravitational/teleport/api/utils/keys"
dtauthz "github.com/gravitational/teleport/lib/devicetrust/authz"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
awsutils "github.com/gravitational/teleport/lib/utils/aws"
"github.com/gravitational/teleport/lib/utils/parse"
)
// DefaultImplicitRules provides access to the default set of implicit rules
// assigned to all roles.
var DefaultImplicitRules = []types.Rule{
types.NewRule(types.KindNode, RO()),
types.NewRule(types.KindProxy, RO()),
types.NewRule(types.KindAuthServer, RO()),
types.NewRule(types.KindReverseTunnel, RO()),
types.NewRule(types.KindCertAuthority, ReadNoSecrets()),
types.NewRule(types.KindClusterAuthPreference, RO()),
types.NewRule(types.KindClusterName, RO()),
types.NewRule(types.KindSSHSession, RO()),
types.NewRule(types.KindAppServer, RO()),
types.NewRule(types.KindRemoteCluster, RO()),
types.NewRule(types.KindKubeServer, RO()),
types.NewRule(types.KindDatabaseServer, RO()),
types.NewRule(types.KindDatabase, RO()),
types.NewRule(types.KindApp, RO()),
types.NewRule(types.KindWindowsDesktopService, RO()),
types.NewRule(types.KindWindowsDesktop, RO()),
types.NewRule(types.KindKubernetesCluster, RO()),
types.NewRule(types.KindUsageEvent, []string{types.VerbCreate}),
}
// DefaultCertAuthorityRules provides access the minimal set of resources
// needed for a certificate authority to function.
var DefaultCertAuthorityRules = []types.Rule{
types.NewRule(types.KindSession, RO()),
types.NewRule(types.KindNode, RO()),
types.NewRule(types.KindAuthServer, RO()),
types.NewRule(types.KindReverseTunnel, RO()),
types.NewRule(types.KindCertAuthority, ReadNoSecrets()),
}
// ErrTrustedDeviceRequired is returned by AccessChecker when access to a
// resource requires a trusted device.
// It's an alias to [dtauthz.ErrTrustedDeviceRequired].
var ErrTrustedDeviceRequired = dtauthz.ErrTrustedDeviceRequired
// ErrSessionMFARequired is returned by AccessChecker when access to a resource
// requires an MFA check.
var ErrSessionMFARequired = &trace.AccessDeniedError{
Message: "access to resource requires MFA",
}
// ErrSessionMFANotRequired indicates that per session mfa will not grant
// access to a resource.
var ErrSessionMFANotRequired = &trace.AccessDeniedError{
Message: "MFA is not required to access resource",
}
// 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
}
// NewImplicitRole is the default implicit role that gets added to all
// RoleSets.
func NewImplicitRole() types.Role {
return &types.RoleV6{
Kind: types.KindRole,
Version: types.V3,
Metadata: types.Metadata{
Name: constants.DefaultImplicitRole,
Namespace: defaults.Namespace,
},
Spec: types.RoleSpecV6{
Options: types.RoleOptions{
MaxSessionTTL: types.MaxDuration(),
// Explicitly disable options that default to true, otherwise the option
// will always be enabled, as this implicit role is part of every role set.
PortForwarding: types.NewBoolOption(false),
RecordSession: &types.RecordSession{
Desktop: types.NewBoolOption(false),
},
},
Allow: types.RoleConditions{
Namespaces: []string{defaults.Namespace},
Rules: types.CopyRulesSlice(DefaultImplicitRules),
},
},
}
}
// RoleForUser creates an admin role for a services.User.
//
// Used in tests only.
func RoleForUser(u types.User) types.Role {
role, _ := types.NewRole(RoleNameForUser(u.GetName()), types.RoleSpecV6{
Options: types.RoleOptions{
CertificateFormat: constants.CertificateFormatStandard,
MaxSessionTTL: types.NewDuration(defaults.MaxCertDuration),
PortForwarding: types.NewBoolOption(true),
ForwardAgent: types.NewBool(true),
BPF: defaults.EnhancedEvents(),
},
Allow: types.RoleConditions{
Namespaces: []string{defaults.Namespace},
NodeLabels: types.Labels{types.Wildcard: []string{types.Wildcard}},
AppLabels: types.Labels{types.Wildcard: []string{types.Wildcard}},
GroupLabels: types.Labels{types.Wildcard: []string{types.Wildcard}},
KubernetesLabels: types.Labels{types.Wildcard: []string{types.Wildcard}},
DatabaseServiceLabels: types.Labels{types.Wildcard: []string{types.Wildcard}},
DatabaseLabels: types.Labels{types.Wildcard: []string{types.Wildcard}},
Rules: []types.Rule{
types.NewRule(types.KindRole, RW()),
types.NewRule(types.KindAuthConnector, RW()),
types.NewRule(types.KindSession, RO()),
types.NewRule(types.KindTrustedCluster, RW()),
types.NewRule(types.KindEvent, RO()),
types.NewRule(types.KindClusterAuthPreference, RW()),
types.NewRule(types.KindClusterNetworkingConfig, RW()),
types.NewRule(types.KindSessionRecordingConfig, RW()),
types.NewRule(types.KindUIConfig, RW()),
types.NewRule(types.KindApp, RW()),
types.NewRule(types.KindDatabase, RW()),
types.NewRule(types.KindLock, RW()),
types.NewRule(types.KindToken, RW()),
types.NewRule(types.KindConnectionDiagnostic, RW()),
types.NewRule(types.KindKubernetesCluster, RW()),
types.NewRule(types.KindSessionTracker, RO()),
types.NewRule(types.KindUserGroup, RW()),
types.NewRule(types.KindSAMLIdPServiceProvider, RW()),
},
JoinSessions: []*types.SessionJoinPolicy{
{
Name: "foo",
Roles: []string{"*"},
Kinds: []string{string(types.SSHSessionKind)},
Modes: []string{string(types.SessionPeerMode)},
},
},
},
})
return role
}
// RoleForCertAuthority creates role using types.CertAuthority.
func RoleForCertAuthority(ca types.CertAuthority) types.Role {
role, _ := types.NewRole(RoleNameForCertAuthority(ca.GetClusterName()), types.RoleSpecV6{
Options: types.RoleOptions{
MaxSessionTTL: types.NewDuration(defaults.MaxCertDuration),
},
Allow: types.RoleConditions{
Namespaces: []string{defaults.Namespace},
NodeLabels: types.Labels{types.Wildcard: []string{types.Wildcard}},
AppLabels: types.Labels{types.Wildcard: []string{types.Wildcard}},
KubernetesLabels: types.Labels{types.Wildcard: []string{types.Wildcard}},
DatabaseLabels: types.Labels{types.Wildcard: []string{types.Wildcard}},
Rules: types.CopyRulesSlice(DefaultCertAuthorityRules),
},
})
return role
}
// ValidateRoleName checks that the role name is allowed to be created.
func ValidateRoleName(role types.Role) error {
// System role names are not allowed.
systemRoles := types.SystemRoles([]types.SystemRole{
types.SystemRole(role.GetMetadata().Name),
})
if err := systemRoles.Check(); err == nil {
return trace.BadParameter("reserved role: %s", role.GetMetadata().Name)
}
return nil
}
type validateRoleOptions struct {
warningReporter func(error)
}
func defaultValidateRoleOptions() validateRoleOptions {
return validateRoleOptions{
warningReporter: func(error) {},
}
}
type validateRoleOption func(*validateRoleOptions)
// withWarningReporter is meant for tests to assert the presence of expected
// warnings.
func withWarningReporter(f func(error)) validateRoleOption {
return func(opts *validateRoleOptions) {
opts.warningReporter = f
}
}
// ValidateRole parses validates the role, and sets default values.
func ValidateRole(r types.Role, opts ...validateRoleOption) error {
options := defaultValidateRoleOptions()
for _, opt := range opts {
opt(&options)
}
if err := CheckAndSetDefaults(r); err != nil {
return trace.Wrap(err)
}
// Expression parsers in new versions sometimes get smarter/more strict and
// catch more syntax or type errors that previously would only be caught
// when they were evaluated. To avoid any possibility of bricking a cluster
// by making all roles invalid due to a buggy expression that may not even
// be used, only log expression parse errors as a warning.
if err := validateRoleExpressions(r); err != nil {
options.warningReporter(err)
log.Warnf("Detected invalid role %q: %v", r.GetName(), err)
}
return nil
}
func validateRoleExpressions(r types.Role) error {
var errs []error
for _, condition := range []struct {
name string
condition types.RoleConditionType
}{
{"allow", types.Allow},
{"deny", types.Deny},
} {
for _, rule := range r.GetRules(condition.condition) {
if err := validateRule(rule); err != nil {
err = trace.BadParameter("parsing %s rule: %v", condition.name, err)
errs = append(errs, err)
}
}
for _, values := range []struct {
name string
values []string
}{
{"logins", r.GetLogins(condition.condition)},
{"windows_desktop_logins", r.GetWindowsLogins(condition.condition)},
{"aws_role_arns", r.GetAWSRoleARNs(condition.condition)},
{"azure_identities", r.GetAzureIdentities(condition.condition)},
{"gcp_service_accounts", r.GetGCPServiceAccounts(condition.condition)},
{"kubernetes_groups", r.GetKubeGroups(condition.condition)},
{"kubernetes_users", r.GetKubeUsers(condition.condition)},
{"db_names", r.GetDatabaseNames(condition.condition)},
{"db_users", r.GetDatabaseUsers(condition.condition)},
{"host_groups", r.GetHostGroups(condition.condition)},
{"host_sudeoers", r.GetHostSudoers(condition.condition)},
{"desktop_groups", r.GetDesktopGroups(condition.condition)},
{"impersonate.users", r.GetImpersonateConditions(condition.condition).Users},
{"impersonate.roles", r.GetImpersonateConditions(condition.condition).Roles},
} {
for _, value := range values.values {
_, err := parse.NewTraitsTemplateExpression(value)
if err != nil {
err = trace.BadParameter("parsing %s.%s expression: %v", condition.name, values.name, err)
errs = append(errs, err)
}
}
}
for _, labels := range []struct {
name string
kind string
}{
{"cluster_labels", types.KindRemoteCluster},
{"node_labels", types.KindNode},
{"kubernetes_labels", types.KindKubernetesCluster},
{"app_labels", types.KindApp},
{"db_labels", types.KindDatabase},
{"db_service_labels", types.KindDatabaseService},
{"windows_desktop_labels", types.KindWindowsDesktop},
{"group_labels", types.KindUserGroup},
} {
labelMatchers, err := r.GetLabelMatchers(condition.condition, labels.kind)
if err != nil {
return trace.Wrap(err)
}
for _, labelValues := range labelMatchers.Labels {
for _, label := range labelValues {
_, err := parse.NewTraitsTemplateExpression(label)
if err != nil {
err = trace.BadParameter("parsing %s.%s template expression: %v", condition.name, labels.name, err)
errs = append(errs, err)
}
}
}
if len(labelMatchers.Expression) > 0 {
if _, err := parseLabelExpression(labelMatchers.Expression); err != nil {
err = trace.BadParameter("parsing %s.%s_expression: %v", condition.name, labels.name, err)
errs = append(errs, err)
}
}
}
}
return trace.NewAggregate(errs...)
}
// validateRule parses the where and action fields to validate the rule.
func validateRule(r types.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
}
func filterInvalidUnixLogins(candidates []string) []string {
var output []string
for _, candidate := range candidates {
if utils.IsValidUnixUser(candidate) {
// A valid variable was found in the traits, append it to the list of logins.
output = append(output, candidate)
continue
}
// Log any invalid logins which were added by a user but ignore any
// Teleport internal logins which are known to be invalid.
if candidate != teleport.SSHSessionJoinPrincipal && !strings.HasPrefix(candidate, "no-login-") {
log.Debugf("Skipping login %v, not a valid Unix login.", candidate)
}
}
return output
}
func filterInvalidWindowsLogins(candidates []string) []string {
var output []string
// https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-2000-server/bb726984(v=technet.10)
const invalidChars = `"/\[]:;|=,+*?<>`
for _, candidate := range candidates {
if strings.ContainsAny(candidate, invalidChars) {
log.Debugf("Skipping Windows login %v, not a valid Windows login.", candidate)
continue
}
output = append(output, candidate)
}
return output
}
func warnInvalidAzureIdentities(candidates []string) {
for _, candidate := range candidates {
if !MatchValidAzureIdentity(candidate) {
log.Warningf("Invalid format of Azure identity %q", candidate)
}
}
}
// ParseResourceID from Azure SDK is too lenient; we use a strict regexp instead.
var azureIdentityPattern = regexp.MustCompile(`(?i)^/subscriptions/([a-fA-F0-9-]+)/resourceGroups/([0-9a-zA-Z-_]+)/providers/Microsoft\.ManagedIdentity/userAssignedIdentities/([0-9a-zA-Z-_]+)$`)
func MatchValidAzureIdentity(identity string) bool {
if identity == types.Wildcard {
return true
}
return azureIdentityPattern.MatchString(identity)
}
// ApplyTraits applies the passed in traits to any variables within the role
// and returns itself.
func ApplyTraits(r types.Role, traits map[string][]string) (types.Role, error) {
for _, condition := range []types.RoleConditionType{types.Allow, types.Deny} {
inLogins := r.GetLogins(condition)
outLogins := applyValueTraitsSlice(inLogins, traits, "login")
outLogins = filterInvalidUnixLogins(outLogins)
r.SetLogins(condition, apiutils.Deduplicate(outLogins))
inWindowsLogins := r.GetWindowsLogins(condition)
outWindowsLogins := applyValueTraitsSlice(inWindowsLogins, traits, "windows_login")
outWindowsLogins = filterInvalidWindowsLogins(outWindowsLogins)
r.SetWindowsLogins(condition, apiutils.Deduplicate(outWindowsLogins))
inRoleARNs := r.GetAWSRoleARNs(condition)
outRoleARNs := applyValueTraitsSlice(inRoleARNs, traits, "AWS role ARN")
r.SetAWSRoleARNs(condition, apiutils.Deduplicate(outRoleARNs))
inAzureIdentities := r.GetAzureIdentities(condition)
outAzureIdentities := applyValueTraitsSlice(inAzureIdentities, traits, "Azure identity")
warnInvalidAzureIdentities(outAzureIdentities)
r.SetAzureIdentities(condition, apiutils.Deduplicate(outAzureIdentities))
inGCPAccounts := r.GetGCPServiceAccounts(condition)
outGCPAccounts := applyValueTraitsSlice(inGCPAccounts, traits, "GCP service account")
r.SetGCPServiceAccounts(condition, apiutils.Deduplicate(outGCPAccounts))
// apply templates to kubernetes groups
inKubeGroups := r.GetKubeGroups(condition)
outKubeGroups := applyValueTraitsSlice(inKubeGroups, traits, "kube group")
r.SetKubeGroups(condition, apiutils.Deduplicate(outKubeGroups))
// apply templates to kubernetes users
inKubeUsers := r.GetKubeUsers(condition)
outKubeUsers := applyValueTraitsSlice(inKubeUsers, traits, "kube user")
r.SetKubeUsers(condition, apiutils.Deduplicate(outKubeUsers))
// apply templates to database names
inDbNames := r.GetDatabaseNames(condition)
outDbNames := applyValueTraitsSlice(inDbNames, traits, "database name")
r.SetDatabaseNames(condition, apiutils.Deduplicate(outDbNames))
// apply templates to database users
inDbUsers := r.GetDatabaseUsers(condition)
outDbUsers := applyValueTraitsSlice(inDbUsers, traits, "database user")
r.SetDatabaseUsers(condition, apiutils.Deduplicate(outDbUsers))
// apply templates to database roles
inDbRoles := r.GetDatabaseRoles(condition)
outDbRoles := applyValueTraitsSlice(inDbRoles, traits, "database role")
r.SetDatabaseRoles(condition, apiutils.Deduplicate(outDbRoles))
for _, kind := range []string{
types.KindRemoteCluster,
types.KindNode,
types.KindKubernetesCluster,
types.KindApp,
types.KindDatabase,
types.KindDatabaseService,
types.KindWindowsDesktop,
types.KindUserGroup,
} {
labelMatchers, err := r.GetLabelMatchers(condition, kind)
if err != nil {
return nil, trace.Wrap(err)
}
// Only labelMatchers.Labels is templated, if empty we can skip
// these label matchers. labelMatchers.Expression can reference user
// traits later during the access check through the expression
// environment, they are not templated in here.
if len(labelMatchers.Labels) == 0 {
continue
}
labelMatchers.Labels = applyLabelsTraits(labelMatchers.Labels, traits)
if err := r.SetLabelMatchers(condition, kind, labelMatchers); err != nil {
return nil, trace.Wrap(err)
}
}
r.SetHostGroups(condition,
applyValueTraitsSlice(r.GetHostGroups(condition), traits, "host_groups"))
r.SetHostSudoers(condition,
applyValueTraitsSlice(r.GetHostSudoers(condition), traits, "host_sudoers"))
r.SetDesktopGroups(condition,
applyValueTraitsSlice(r.GetDesktopGroups(condition), traits, "desktop_groups"))
options := r.GetOptions()
for i, ext := range options.CertExtensions {
vals, err := ApplyValueTraits(ext.Value, traits)
if err != nil && !trace.IsNotFound(err) {
log.Warnf("Did not apply trait to cert_extensions.value: %v", err)
continue
}
if len(vals) != 0 {
options.CertExtensions[i].Value = vals[0]
}
}
// apply templates to impersonation conditions
inCond := r.GetImpersonateConditions(condition)
var outCond types.ImpersonateConditions
outCond.Users = applyValueTraitsSlice(inCond.Users, traits, "impersonate user")
outCond.Roles = applyValueTraitsSlice(inCond.Roles, traits, "impersonate role")
outCond.Users = apiutils.Deduplicate(outCond.Users)
outCond.Roles = apiutils.Deduplicate(outCond.Roles)
outCond.Where = inCond.Where
r.SetImpersonateConditions(condition, outCond)
}
return r, nil
}
// applyValueTraitsSlice iterates over a slice of input strings, calling
// ApplyValueTraits on each.
func applyValueTraitsSlice(inputs []string, traits map[string][]string, fieldName string) []string {
var output []string
for _, value := range inputs {
outputs, err := ApplyValueTraits(value, traits)
if err != nil {
if !trace.IsNotFound(err) {
log.WithError(err).Debugf("Skipping %s %q.", fieldName, value)
}
continue
}
output = append(output, outputs...)
}
return output
}
// 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 types.Labels, traits map[string][]string) types.Labels {
outLabels := make(types.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]] = apiutils.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.
expr, err := parse.NewTraitsTemplateExpression(val)
if err != nil {
return nil, trace.Wrap(err)
}
varValidation := func(namespace string, name string) error {
// verify that internal traits match the supported variables
if namespace == teleport.TraitInternalPrefix {
switch name {
case constants.TraitLogins, constants.TraitWindowsLogins,
constants.TraitKubeGroups, constants.TraitKubeUsers,
constants.TraitDBNames, constants.TraitDBUsers, constants.TraitDBRoles,
constants.TraitAWSRoleARNs, constants.TraitAzureIdentities,
constants.TraitGCPServiceAccounts, teleport.TraitJWT:
default:
return trace.BadParameter("unsupported variable %q", name)
}
}
// TODO: return a not found error if the variable namespace is not
// the namespace of `traits`.
// If e.g. the `traits` belong to the "internal" namespace (as the
// validation above suggests), and "foo" is a key in `traits`, then
// "external.foo" will return the value of "internal.foo". This is
// incorrect, and a not found error should be returned instead.
// This would be similar to the var validation done in getPAMConfig
// (lib/srv/ctx.go).
return nil
}
interpolated, err := expr.Interpolate(varValidation, traits)
if err != nil {
return nil, trace.Wrap(err)
}
if len(interpolated) == 0 {
return nil, trace.NotFound("variable interpolation result is empty")
}
return interpolated, nil
}
// ruleScore is a sorting score of the rule, the larger the score, the more
// specific the rule is
func ruleScore(r *types.Rule) int {
score := 0
// wildcard rules are less specific
if slices.Contains(r.Resources, types.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 slices.Contains(r.Verbs, types.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 *types.Rule, o *types.Rule) bool {
return ruleScore(r) > ruleScore(o)
}
// RuleSet maps resource to a set of rules defined for it
type RuleSet map[string][]types.Rule
// MakeRuleSet creates a new rule set from a list
func MakeRuleSet(rules []types.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(types.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[types.Wildcard] {
match, err := matchesWhere(&rule, whereParser)
if err != nil {
return false, trace.Wrap(err)
}
if match && (rule.HasVerb(types.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 *types.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 *types.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() []types.Rule {
var out []types.Rule
for _, rules := range set {
out = append(out, rules...)
}
return out
}
// RoleFromSpec returns new Role created from spec
func RoleFromSpec(name string, spec types.RoleSpecV6) (types.Role, error) {
role, err := types.NewRole(name, spec)
return role, trace.Wrap(err)
}
// RoleSetFromSpec returns a new RoleSet from spec
func RoleSetFromSpec(name string, spec types.RoleSpecV6) (RoleSet, error) {
role, err := RoleFromSpec(name, spec)
if err != nil {
return nil, trace.Wrap(err)
}
return NewRoleSet(role), nil
}
// RW is a shortcut that returns all CRUD verbs.
func RW() []string {
return []string{types.VerbList, types.VerbCreate, types.VerbRead, types.VerbUpdate, types.VerbDelete}
}
// RO is a shortcut that returns read only verbs that provide access to secrets.
func RO() []string {
return []string{types.VerbList, types.VerbRead}
}
// ReadNoSecrets is a shortcut that returns read only verbs that do not
// provide access to secrets.
func ReadNoSecrets() []string {
return []string{types.VerbList, types.VerbReadNoSecrets}
}
// RoleGetter is an interface that defines GetRole method
type RoleGetter interface {
// GetRole returns role by name
GetRole(ctx context.Context, name string) (types.Role, error)
}
// ExtractFromCertificate will extract roles and traits from a *ssh.Certificate.
func ExtractFromCertificate(cert *ssh.Certificate) ([]string, wrappers.Traits, error) {
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(ctx context.Context, access UserGetter, identity tlsca.Identity) ([]string, wrappers.Traits, error) {
// Legacy certs are not encoded with roles or traits,
// so we fallback to the traits and roles in the backend.
// empty traits are a valid use case in standard certs,
// so we only check for whether roles are empty.
if len(identity.Groups) == 0 {
u, err := access.GetUser(ctx, identity.Username, false)
if err != nil {
return nil, nil, trace.Wrap(err)
}
log.Warnf("Failed to find roles 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 []types.Role
for _, roleName := range roleNames {
role, err := access.GetRole(context.TODO(), roleName)
if err != nil {
return nil, trace.Wrap(err)
}
role, err = ApplyTraits(role, traits)
if err != nil {
return nil, trace.Wrap(err)
}
roles = append(roles, role)
}
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
}
// 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)
}
// ExtractTraitsFromCert extracts traits from the certificate extensions.
func ExtractTraitsFromCert(cert *ssh.Certificate) (wrappers.Traits, error) {
rawTraits, ok := cert.Extensions[teleport.CertExtensionTeleportTraits]
if !ok {
return nil, trace.NotFound("no traits found")
}
var traits wrappers.Traits
err := wrappers.UnmarshalTraits([]byte(rawTraits), &traits)
if err != nil {
return nil, trace.Wrap(err)
}
return traits, nil
}
func ExtractAllowedResourcesFromCert(cert *ssh.Certificate) ([]types.ResourceID, error) {
allowedResourcesStr, ok := cert.Extensions[teleport.CertExtensionAllowedResources]
if !ok {
// if not present in the cert, there are no resource-based restrictions
return nil, nil
}
allowedResources, err := types.ResourceIDsFromString(allowedResourcesStr)
return allowedResources, trace.Wrap(err)
}
// NewRoleSet returns new RoleSet based on the roles
func NewRoleSet(roles ...types.Role) RoleSet {
// unauthenticated Nop role should not have any privileges
// by default, otherwise it is too permissive
if len(roles) == 1 && roles[0].GetName() == string(types.RoleNop) {
return roles
}
return append(roles, NewImplicitRole())
}
// RoleSet is a set of roles that implements access control functionality
type RoleSet []types.Role
// EnumerationResult is a result of enumerating a role set against some property, e.g. allowed names or logins.
type EnumerationResult struct {
allowedDeniedMap map[string]bool
wildcardAllowed bool
wildcardDenied bool
}
func (result *EnumerationResult) filtered(value bool) []string {
var filtered []string
for entity, allow := range result.allowedDeniedMap {
if allow == value {
filtered = append(filtered, entity)
}
}
sort.Strings(filtered)
return filtered
}
// Denied returns all explicitly denied entities.
func (result *EnumerationResult) Denied() []string {
return result.filtered(false)
}
// Allowed returns all known allowed entities.
func (result *EnumerationResult) Allowed() []string {
if result.WildcardDenied() {
return nil
}
return result.filtered(true)
}
// WildcardAllowed is true if the * entity is allowed for a given rule set.
func (result *EnumerationResult) WildcardAllowed() bool {
return result.wildcardAllowed && !result.wildcardDenied
}
// WildcardDenied is true if the * entity is denied for a given rule set.
func (result *EnumerationResult) WildcardDenied() bool {
return result.wildcardDenied
}