-
Notifications
You must be signed in to change notification settings - Fork 81
/
list.go
474 lines (392 loc) · 13.8 KB
/
list.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
package cmd
import (
"context"
"errors"
"flag"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
core "k8s.io/api/core/v1"
rbac "k8s.io/api/rbac/v1"
apimeta "k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
clioptions "k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/kubernetes"
clientcore "k8s.io/client-go/kubernetes/typed/core/v1"
clientrbac "k8s.io/client-go/kubernetes/typed/rbac/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/klog/v2"
)
const (
whoCanUsage = `kubectl who-can VERB (TYPE | TYPE/NAME | NONRESOURCEURL)`
whoCanLong = `Shows which users, groups and service accounts can perform a given verb on a given resource type.
VERB is a logical Kubernetes API verb like 'get', 'list', 'watch', 'delete', etc.
TYPE is a Kubernetes resource. Shortcuts and API groups will be resolved, e.g. 'po' or 'pods.metrics.k8s.io'.
NAME is the name of a particular Kubernetes resource.
NONRESOURCEURL is a partial URL that starts with "/".`
whoCanExample = ` # List who can get pods from any of the available namespaces
kubectl who-can get pods --all-namespaces
# List who can create pods in the current namespace
kubectl who-can create pods
# List who can get pods specifying the API group
kubectl who-can get pods.metrics.k8s.io
# List who can create services in namespace "foo"
kubectl who-can create services -n foo
# List who can get the service named "mongodb" in namespace "bar"
kubectl who-can get svc/mongodb --namespace bar
# List who can do everything with pods in the current namespace
kubectl who-can '*' pods
# List who can list every resource in the namespace "baz"
kubectl who-can list '*' -n baz
# List who can read pod logs
kubectl who-can get pods --subresource=log
# List who can access the URL /logs/
kubectl who-can get /logs`
)
const (
// RoleKind is the RoleRef's Kind referencing a Role.
RoleKind = "Role"
// ClusterRoleKind is the RoleRef's Kind referencing a ClusterRole.
ClusterRoleKind = "ClusterRole"
)
const (
subResourceFlag = "subresource"
allNamespacesFlag = "all-namespaces"
namespaceFlag = "namespace"
outputFlag = "output"
outputWide = "wide"
outputJson = "json"
)
// Action represents an action a subject can be given permission to.
type Action struct {
Verb string
Resource string
ResourceName string
SubResource string
NonResourceURL string
Namespace string
AllNamespaces bool
}
type resolvedAction struct {
Action
gr schema.GroupResource
}
// roles is a set of Role names matching the specified Action.
type roles map[string]struct{}
// clusterRoles is a set of ClusterRole names matching the specified Action.
type clusterRoles map[string]struct{}
type WhoCan struct {
clientNamespace clientcore.NamespaceInterface
clientRBAC clientrbac.RbacV1Interface
namespaceValidator NamespaceValidator
resourceResolver ResourceResolver
accessChecker AccessChecker
policyRuleMatcher PolicyRuleMatcher
}
// NewWhoCan constructs a new WhoCan checker with the specified rest.Config and RESTMapper.
func NewWhoCan(restConfig *rest.Config, mapper apimeta.RESTMapper) (*WhoCan, error) {
client, err := kubernetes.NewForConfig(restConfig)
if err != nil {
return nil, err
}
clientNamespace := client.CoreV1().Namespaces()
return &WhoCan{
clientNamespace: clientNamespace,
clientRBAC: client.RbacV1(),
namespaceValidator: NewNamespaceValidator(clientNamespace),
resourceResolver: NewResourceResolver(client.Discovery(), mapper),
accessChecker: NewAccessChecker(client.AuthorizationV1().SelfSubjectAccessReviews()),
policyRuleMatcher: NewPolicyRuleMatcher(),
}, nil
}
// NewWhoCanCommand constructs the WhoCan command with the specified IOStreams.
func NewWhoCanCommand(streams clioptions.IOStreams) (*cobra.Command, error) {
var configFlags *clioptions.ConfigFlags
cmd := &cobra.Command{
Use: whoCanUsage,
Long: whoCanLong,
Example: whoCanExample,
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
clientConfig := configFlags.ToRawKubeConfigLoader()
restConfig, err := clientConfig.ClientConfig()
if err != nil {
return fmt.Errorf("getting rest config: %v", err)
}
mapper, err := configFlags.ToRESTMapper()
if err != nil {
return fmt.Errorf("getting mapper: %v", err)
}
action, err := ActionFrom(clientConfig, cmd.Flags(), args)
if err != nil {
return err
}
o, err := NewWhoCan(restConfig, mapper)
if err != nil {
return err
}
warnings, err := o.CheckAPIAccess(action)
if err != nil {
return err
}
output, err := cmd.Flags().GetString(outputFlag)
if err != nil {
return err
}
printer := NewPrinter(streams.Out, output == outputWide)
// Output warnings
printer.PrintWarnings(warnings)
roleBindings, clusterRoleBindings, err := o.Check(action)
if err != nil {
return err
}
// Output check results
output = strings.ToLower(output)
if output == outputJson {
printer.ExportData(action, roleBindings, clusterRoleBindings)
} else if output == outputWide || output == "" {
printer.PrintChecks(action, roleBindings, clusterRoleBindings)
} else {
return fmt.Errorf("invalid output format: %v", output)
}
return nil
},
}
cmd.Flags().String(subResourceFlag, "", "SubResource such as pod/log or deployment/scale")
cmd.Flags().BoolP(allNamespacesFlag, "A", false, "If true, check for users that can do the specified action in any of the available namespaces")
cmd.Flags().StringP(outputFlag, "o", "", "Output format. Currently the only supported output format is wide or JSON.")
flag.CommandLine.VisitAll(func(gf *flag.Flag) {
cmd.Flags().AddGoFlag(gf)
})
configFlags = clioptions.NewConfigFlags(true)
configFlags.AddFlags(cmd.Flags())
return cmd, nil
}
// ActionFrom sets all information required to check who can perform the specified action.
func ActionFrom(clientConfig clientcmd.ClientConfig, flags *pflag.FlagSet, args []string) (action Action, err error) {
if len(args) < 2 {
err = errors.New("you must specify two or three arguments: verb, resource, and optional resourceName")
return
}
action.Verb = args[0]
if strings.HasPrefix(args[1], "/") {
action.NonResourceURL = args[1]
klog.V(3).Infof("Resolved nonResourceURL `%s`", action.NonResourceURL)
} else {
resourceTokens := strings.SplitN(args[1], "/", 2)
action.Resource = resourceTokens[0]
if len(resourceTokens) > 1 {
action.ResourceName = resourceTokens[1]
klog.V(3).Infof("Resolved resourceName `%s`", action.ResourceName)
}
}
action.SubResource, err = flags.GetString(subResourceFlag)
if err != nil {
return
}
action.AllNamespaces, err = flags.GetBool(allNamespacesFlag)
if err != nil {
return
}
if action.AllNamespaces {
action.Namespace = core.NamespaceAll
klog.V(3).Infof("Resolved namespace `%s` from --all-namespaces flag", action.Namespace)
return
}
action.Namespace, err = flags.GetString(namespaceFlag)
if err != nil {
return
}
if action.Namespace != "" {
klog.V(3).Infof("Resolved namespace `%s` from --namespace flag", action.Namespace)
return
}
// Neither --all-namespaces nor --namespace flag was specified
action.Namespace, _, err = clientConfig.Namespace()
if err != nil {
err = fmt.Errorf("getting namespace from current context: %v", err)
}
klog.V(3).Infof("Resolved namespace `%s` from current context", action.Namespace)
return
}
// Validate makes sure that the specified action is valid.
func (w *WhoCan) validate(action Action) error {
if action.NonResourceURL != "" && action.SubResource != "" {
return fmt.Errorf("--subresource cannot be used with NONRESOURCEURL")
}
err := w.namespaceValidator.Validate(action.Namespace)
if err != nil {
return fmt.Errorf("validating namespace: %v", err)
}
return nil
}
// Check checks who can perform the action specified by WhoCanOptions and returns the role bindings that allows the
// action to be performed.
func (w *WhoCan) Check(action Action) (roleBindings []rbac.RoleBinding, clusterRoleBindings []rbac.ClusterRoleBinding, err error) {
err = w.validate(action)
if err != nil {
err = fmt.Errorf("validation: %v", err)
return
}
resolvedAction := resolvedAction{Action: action}
if action.Resource != "" {
resolvedAction.gr, err = w.resourceResolver.Resolve(action.Verb, action.Resource, action.SubResource)
if err != nil {
err = fmt.Errorf("resolving resource: %v", err)
return
}
klog.V(3).Infof("Resolved resource `%s`", resolvedAction.gr.String())
}
// Get the Roles that relate to the Verbs and Resources we are interested in
roleNames, err := w.getRolesFor(resolvedAction)
if err != nil {
return []rbac.RoleBinding{}, []rbac.ClusterRoleBinding{}, fmt.Errorf("getting Roles: %v", err)
}
// Get the ClusterRoles that relate to the verbs and resources we are interested in
clusterRoleNames, err := w.getClusterRolesFor(resolvedAction)
if err != nil {
return []rbac.RoleBinding{}, []rbac.ClusterRoleBinding{}, fmt.Errorf("getting ClusterRoles: %v", err)
}
// Get the RoleBindings that relate to this set of Roles or ClusterRoles
roleBindings, err = w.getRoleBindings(resolvedAction, roleNames, clusterRoleNames)
if err != nil {
err = fmt.Errorf("getting RoleBindings: %v", err)
return
}
// Get the ClusterRoleBindings that relate to this set of ClusterRoles
clusterRoleBindings, err = w.getClusterRoleBindings(clusterRoleNames)
if err != nil {
err = fmt.Errorf("getting ClusterRoleBindings: %v", err)
return
}
return
}
// CheckAPIAccess checks whether the subject in the current context has enough privileges to query Kubernetes API
// server to perform Check.
func (w *WhoCan) CheckAPIAccess(action Action) ([]string, error) {
type check struct {
verb string
resource string
namespace string
}
var checks []check
var warnings []string
ctx := context.Background()
// Determine which checks need to be executed.
if action.Namespace == "" {
checks = append(checks, check{"list", "namespaces", ""})
nsList, err := w.clientNamespace.List(ctx, metav1.ListOptions{})
if err != nil {
return nil, fmt.Errorf("listing namespaces: %v", err)
}
for _, ns := range nsList.Items {
checks = append(checks, check{"list", "roles", ns.Name})
checks = append(checks, check{"list", "rolebindings", ns.Name})
}
} else {
checks = append(checks, check{"list", "roles", action.Namespace})
checks = append(checks, check{"list", "rolebindings", action.Namespace})
}
// Actually run the checks and collect warnings.
for _, check := range checks {
allowed, err := w.accessChecker.IsAllowedTo(check.verb, check.resource, check.namespace)
if err != nil {
return nil, err
}
if !allowed {
var msg string
if check.namespace == "" {
msg = fmt.Sprintf("The user is not allowed to %s %s", check.verb, check.resource)
} else {
msg = fmt.Sprintf("The user is not allowed to %s %s in the %s namespace", check.verb, check.resource, check.namespace)
}
warnings = append(warnings, msg)
}
}
return warnings, nil
}
// GetRolesFor returns a set of names of Roles matching the specified Action.
func (w *WhoCan) getRolesFor(action resolvedAction) (roles, error) {
ctx := context.Background()
rl, err := w.clientRBAC.Roles(action.Namespace).List(ctx, metav1.ListOptions{})
if err != nil {
return nil, err
}
roleNames := make(map[string]struct{}, 10)
for _, item := range rl.Items {
if w.policyRuleMatcher.MatchesRole(item, action) {
if _, ok := roleNames[item.Name]; !ok {
roleNames[item.Name] = struct{}{}
}
}
}
return roleNames, nil
}
// GetClusterRolesFor returns a set of names of ClusterRoles matching the specified Action.
func (w *WhoCan) getClusterRolesFor(action resolvedAction) (clusterRoles, error) {
ctx := context.Background()
crl, err := w.clientRBAC.ClusterRoles().List(ctx, metav1.ListOptions{})
if err != nil {
return nil, err
}
cr := make(map[string]struct{}, 10)
for _, item := range crl.Items {
if w.policyRuleMatcher.MatchesClusterRole(item, action) {
if _, ok := cr[item.Name]; !ok {
cr[item.Name] = struct{}{}
}
}
}
return cr, nil
}
// GetRoleBindings returns the RoleBindings that refer to the given set of Role names or ClusterRole names.
func (w *WhoCan) getRoleBindings(action resolvedAction, roleNames roles, clusterRoleNames clusterRoles) (roleBindings []rbac.RoleBinding, err error) {
// TODO I'm wondering if GetRoleBindings should be invoked at all when the --all-namespaces flag is specified?
if action.Namespace == core.NamespaceAll {
return
}
ctx := context.Background()
list, err := w.clientRBAC.RoleBindings(action.Namespace).List(ctx, metav1.ListOptions{})
if err != nil {
return
}
for _, roleBinding := range list.Items {
if roleBinding.RoleRef.Kind == RoleKind {
if _, ok := roleNames[roleBinding.RoleRef.Name]; ok {
roleBindings = append(roleBindings, roleBinding)
}
} else if roleBinding.RoleRef.Kind == ClusterRoleKind {
if _, ok := clusterRoleNames[roleBinding.RoleRef.Name]; ok {
roleBindings = append(roleBindings, roleBinding)
}
}
}
return
}
// GetClusterRoleBindings returns the ClusterRoleBindings that refer to the given sef of ClusterRole names.
func (w *WhoCan) getClusterRoleBindings(clusterRoleNames clusterRoles) (clusterRoleBindings []rbac.ClusterRoleBinding, err error) {
ctx := context.Background()
list, err := w.clientRBAC.ClusterRoleBindings().List(ctx, metav1.ListOptions{})
if err != nil {
return
}
for _, roleBinding := range list.Items {
if _, ok := clusterRoleNames[roleBinding.RoleRef.Name]; ok {
clusterRoleBindings = append(clusterRoleBindings, roleBinding)
}
}
return
}
func (w Action) String() string {
if w.NonResourceURL != "" {
return fmt.Sprintf("%s %s", w.Verb, w.NonResourceURL)
}
name := w.ResourceName
if name != "" {
name = "/" + name
}
return fmt.Sprintf("%s %s%s", w.Verb, w.Resource, name)
}