/
rbacviz.go
510 lines (407 loc) · 14.7 KB
/
rbacviz.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
package visualize
import (
"encoding/json"
"fmt"
"regexp"
"sort"
"strings"
"github.com/emicklei/dot"
"github.com/fatih/color"
v1 "k8s.io/api/core/v1"
policy "k8s.io/api/policy/v1beta1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/klog"
"github.com/alcideio/rbac-tool/pkg/kube"
"github.com/alcideio/rbac-tool/pkg/rbac"
"github.com/alcideio/rbac-tool/pkg/utils"
)
func CreateRBACGraph(opts *Opts) error {
inNs, exNs := utils.GetNamespaceSets(opts.IncludedNamespaces, opts.ExcludedNamespaces)
rbacViz := RbacViz{
opts: opts,
includedNamespace: inNs,
excludedNamespace: exNs,
}
err := rbacViz.initialize(opts)
if err != nil {
return err
}
g := rbacViz.renderGraph()
legend := GraphLegend()
utils.ConsolePrinter(fmt.Sprintf("Generating Graph and Saving as '%v'", color.HiBlueString(opts.Outfile)))
return GenerateOutput(opts.Outfile, opts.Outformat, g, legend, opts)
}
type RbacViz struct {
opts *Opts
includedNamespace sets.String
excludedNamespace sets.String
permissions Permissions
includeSubjectsRegex *regexp.Regexp
}
func (r *RbacViz) initialize(opts *Opts) error {
if opts.Infile == "" {
//Connect to the cluster
var client *kube.KubeClient
var err error
utils.ConsolePrinter(fmt.Sprintf("Connecting to cluster '%v'", color.HiBlueString(opts.ClusterContext)))
client, err = kube.NewClient(opts.ClusterContext)
if err != nil {
return fmt.Errorf("Failed to create kubernetes client - %v", err)
}
perms, err := rbac.NewPermissionsFromCluster(client)
if err != nil {
return err
}
r.permissions.Permissions = *perms
r.permissions.Pods = make(map[string]map[string]v1.Pod)
r.permissions.ServiceAccountsUsed = sets.NewString()
if opts.ShowPodsOnly {
pods, err := client.ListPods(v1.NamespaceAll)
if err != nil {
return err
}
for _, pod := range pods {
if r.permissions.Pods[pod.Namespace] == nil {
r.permissions.Pods[pod.Namespace] = make(map[string]v1.Pod)
}
r.permissions.Pods[pod.Namespace][pod.Name] = pod
r.permissions.ServiceAccountsUsed.Insert(fmt.Sprintf("%s/%s", pod.Namespace, pod.Spec.ServiceAccountName))
klog.V(6).Infof("Pod %v/%v use ServiceAccount %v/%v", pod.Namespace, pod.Name, pod.Namespace, pod.Spec.ServiceAccountName)
}
}
} else {
utils.ConsolePrinter(fmt.Sprintf("Loading Resources from '%v'", color.HiBlueString(opts.Infile)))
// Load from file/stdin
objs, err := utils.ReadObjectsFromFile(opts.Infile)
if err != nil {
return err
}
klog.V(5).Infof("Loaded %v resources", len(objs))
perms, err := rbac.NewPermissionsFromResourceList(objs)
if err != nil {
return err
}
r.permissions.Permissions = *perms
r.permissions.Pods = make(map[string]map[string]v1.Pod)
r.permissions.ServiceAccountsUsed = sets.NewString()
}
var err error
r.includeSubjectsRegex, err = regexp.Compile(opts.IncludeSubjectsRegex)
if err != nil {
return err
}
return nil
}
func (r *RbacViz) isBindingUsed(binding rbacv1.RoleBinding) bool {
klog.V(5).Infof(">>> [process][ClusterRole/Role Binding %v/%v]", binding.Namespace, binding.Name)
for _, subject := range binding.Subjects {
if !utils.IsNamespaceIncluded(subject.Namespace, r.includedNamespace, r.excludedNamespace) {
klog.V(5).Infof("\t\t>>> [skip][ClusterRole/Role Binding %v/%v] ServiceAccount %v/%v - not in namespace inclusion list", binding.Namespace, binding.Name, subject.Namespace, subject.Name)
continue
}
if !r.includeSubjectsRegex.MatchString(subject.Name) {
klog.V(5).Infof("\t\t>>> [skip][Subject] ServiceAccount %v/%v - Subject '%v' does NOT match the regexp '%v'", binding.Namespace, binding.Name, subject.Name, r.includeSubjectsRegex.String())
continue
}
if !r.opts.ShowPodsOnly {
klog.V(5).Infof("\t\t>> [used][ClusterRole/Role Binding %v/%v] - used by %v/%v", binding.Namespace, binding.Name, binding.Namespace, subject.Name)
return true
}
if r.permissions.ServiceAccountsUsed.Has(fmt.Sprintf("%s/%s", subject.Namespace, subject.Name)) {
klog.V(5).Infof("\t\t>> [used][ClusterRole/Role Binding %v/%v] - used by %v/%v", binding.Namespace, binding.Name, subject.Namespace, subject.Name)
return true
}
klog.V(5).Infof("\t\t>>> [skip][ServiceAccount %v/%v] not used", subject.Namespace, subject.Name)
}
klog.V(5).Infof("<<< [skip][ClusterRole/Role Binding %v/%v]", binding.Namespace, binding.Name)
return false
}
func GraphLegend() *dot.Graph {
g := newGraph()
renderLegend(g)
return g
}
func (r *RbacViz) renderGraph() *dot.Graph {
g := newGraph()
if r.opts.ShowLegend {
renderLegend(g)
}
if r.opts.ShowPSP && r.opts.ShowRules {
klog.V(6).Infof("Adding PSP Nodes (%v)", len(r.permissions.PodSecurityPolicies))
for _, psp := range r.permissions.PodSecurityPolicies {
r.newPSPandRulesNodePair(g, psp.Name, false)
}
}
for _, bindings := range r.permissions.RoleBindings {
for _, binding := range bindings {
// Check that this a namespace we would like to visualize
// Binding with "" namespace are clusterrole bindings
if binding.Namespace != "" && !utils.IsNamespaceIncluded(binding.Namespace, r.includedNamespace, r.excludedNamespace) {
klog.V(5).Infof("Skiping %v/%v - namespace '%s' not included", binding.Namespace, binding.Name, binding.Namespace)
continue
}
//Lets skip bindings that do not point something active (TODO: add option to visualize this use case as well)
if !r.isBindingUsed(binding) {
klog.V(5).Infof("Binding %v/%v not used by any service account", binding.Namespace, binding.Name)
continue
}
//
// [Pod] --> [ServiceAccount]<----[Binding]--->[Role]
//
nsSubGraph := newNamespaceSubgraph(g, binding.Namespace)
bindingNode := r.newBindingNode(nsSubGraph, binding)
roleNode, rulesNode := r.newRoleAndRulesNodePair(nsSubGraph, binding.Namespace, binding.RoleRef)
newBindingToRoleEdge(bindingNode, roleNode)
saNodes := []dot.Node{}
for _, subject := range binding.Subjects {
if !r.includeSubjectsRegex.MatchString(subject.Name) {
klog.V(5).Infof("\t\t>>> [skip][Subject] ServiceAccount %v/%v - Subject '%v' does NOT match the regexp '%v'", binding.Namespace, binding.Name, subject.Name, r.includeSubjectsRegex.String())
continue
}
gns := newNamespaceSubgraph(g, subject.Namespace)
subjectNode := r.newSubjectNode(gns, subject.Kind, subject.Namespace, subject.Name)
saNodes = append(saNodes, subjectNode)
}
for _, saNode := range saNodes {
newSubjectToBindingEdge(saNode, bindingNode)
}
if r.opts.ShowPSP && r.opts.ShowRules {
r.connectPSPNodesIfNeeded(g, binding, rulesNode)
}
}
}
return g
}
func renderLegend(g *dot.Graph) {
legend := g.Subgraph("Legend", dot.ClusterOption{})
legend.Attr("style", "invis")
namespace := newNamespaceSubgraph(legend, "Namespace")
sa := newSubjectNode0(namespace, "Kind", "Subject", true, false)
missingSa := newSubjectNode0(namespace, "Kind", "Missing Subject", false, false)
role := newRoleNode(namespace, "ns", "Role", true, false)
clusterRoleBoundLocally := newClusterRoleNode(namespace, "ns", "ClusterRole", true, false) // bound by (namespaced!) RoleBinding
clusterrole := newClusterRoleNode(legend, "", "ClusterRole", true, false)
roleBinding := newRoleBindingNode(namespace, "RoleBinding", false)
newSubjectToBindingEdge(sa, roleBinding)
newSubjectToBindingEdge(missingSa, roleBinding)
newBindingToRoleEdge(roleBinding, role)
roleBinding2 := newRoleBindingNode(namespace, "RoleBinding-to-ClusterRole", false)
roleBinding2.Attr("label", "RoleBinding")
newSubjectToBindingEdge(sa, roleBinding2)
newBindingToRoleEdge(roleBinding2, clusterRoleBoundLocally)
clusterRoleBinding := newClusterRoleBindingNode(legend, "ClusterRoleBinding", false)
newSubjectToBindingEdge(sa, clusterRoleBinding)
newBindingToRoleEdge(clusterRoleBinding, clusterrole)
nsrules := newRulesNode0(namespace, "ns", "Role", "Namespace-scoped access rules", false)
newRoleToRulesEdge(role, nsrules)
nsrules2 := newRulesNode0(namespace, "ns", "ClusterRole", "Namespace-scoped access rules From ClusterRole", false)
//nsrules2.Attr("label", "Namespace-scoped\naccess rules")
newRoleToRulesEdge(clusterRoleBoundLocally, nsrules2)
clusterrules := newRulesNode0(legend, "", "ClusterRole", "Cluster-scoped access rules", false)
newRoleToRulesEdge(clusterrole, clusterrules)
pspNode := newPSPNode(legend, "", "PSP", true, false)
edge(nsrules2, pspNode)
pspRules := newRulesNode0(legend, "", "PSP Policy", "Pod Security Policy", false)
edge(pspNode, pspRules)
}
func (r *RbacViz) newBindingNode(gns *dot.Graph, binding rbacv1.RoleBinding) dot.Node {
if binding.Namespace == "" {
return newClusterRoleBindingNode(gns, binding.Name, false)
} else {
return newRoleBindingNode(gns, binding.Name, false)
}
}
func (r *RbacViz) newRoleAndRulesNodePair(gns *dot.Graph, bindingNamespace string, roleRef rbacv1.RoleRef) (dot.Node, *dot.Node) {
var roleNode dot.Node
var rulesNode *dot.Node
var roleNamespace string
if roleRef.Kind == "ClusterRole" {
roleNamespace = ""
roleNode = newClusterRoleNode(gns, bindingNamespace, roleRef.Name, r.roleExists("", roleRef.Name), false)
} else {
roleNamespace = bindingNamespace
roleNode = newRoleNode(gns, bindingNamespace, roleRef.Name, r.roleExists(bindingNamespace, roleRef.Name), false)
}
if r.opts.ShowRules {
rulesNode = r.newFormattedRulesNode(gns, roleNamespace, roleRef.Name, false)
if rulesNode != nil {
newRoleToRulesEdge(roleNode, *rulesNode)
}
}
return roleNode, rulesNode
}
func (r *RbacViz) roleExists(roleNamespace string, roleName string) bool {
if roles, nsExists := r.permissions.Roles[roleNamespace]; nsExists {
if _, roleExists := roles[roleName]; roleExists {
return true
}
}
return false
}
func (r *RbacViz) newSubjectNode(gns *dot.Graph, kind string, ns string, name string) dot.Node {
return newSubjectNode0(gns, kind, name, r.subjectExists(kind, ns, name), false)
}
func (r *RbacViz) subjectExists(kind string, ns string, name string) bool {
if strings.ToLower(kind) != strings.ToLower("ServiceAccount") {
klog.V(5).Infof("[Subject Exist] %v/%v (%v) exist", ns, name, kind)
return true // assume users and groups exist
}
if sas, nsExists := r.permissions.ServiceAccounts[ns]; nsExists {
if _, saExists := sas[name]; saExists {
return true
} else {
klog.V(5).Infof("[Subject Does Not Exist] %v/%v (%v) exist - Couldn't find service account in Namespace %v", ns, name, kind, ns)
}
} else {
klog.V(5).Infof("[Subject Does Not Exist] %v/%v (%v) exist - Couldn't find namespace '%v' with service accounts", ns, name, kind, ns)
}
return false
}
func (r *RbacViz) newFormattedRulesNode(g *dot.Graph, namespace, roleName string, highlight bool) *dot.Node {
var rulesText string
table := `
<table border="0" align="left">
<tr>
<td align="left" border="1" sides="b">ApiGroup</td>
<td align="left" border="1" sides="b">Kind</td>
<td align="left" border="1" sides="b">Names</td>
<td align="left" border="1" sides="b">Verbs</td>
<td align="left" border="1" sides="b">NonResourceURI</td>
</tr>
%s
</table>
`
if roles, found := r.permissions.Roles[namespace]; found {
if role, found := roles[roleName]; found {
for _, rule := range role.Rules {
rulesText += toRuleToTableRow(rule)
}
}
}
if rulesText == "" {
return nil
}
rulesText = fmt.Sprintf(table, rulesText)
node := newRulesNode0(g, namespace, roleName, rulesText, highlight)
return &node
}
func toRuleToTableRow(rule rbacv1.PolicyRule) string {
verbs := strings.Join(rule.Verbs, ",")
apiGroups := ""
resources := ""
resourcesNames := ""
nonResourceURLs := ""
if len(rule.Resources) > 0 {
resources += strings.Join(rule.Resources, ",")
}
if len(rule.ResourceNames) > 0 {
resourcesNames += strings.Join(rule.ResourceNames, ",")
} else {
resourcesNames = "*"
}
if len(rule.NonResourceURLs) > 0 {
nonResourceURLs += strings.Join(rule.NonResourceURLs, ",")
}
for i, apigroup := range rule.APIGroups {
if apigroup == "" {
apigroup = "core"
}
if i > 0 {
apiGroups = fmt.Sprint(apigroup, ",", apiGroups)
} else {
apiGroups = apigroup
}
}
tableRow := `
<tr>
<td align="left">%s</td>
<td align="left">%s</td>
<td align="left">%s</td>
<td align="left">%s</td>
<td align="left">%s</td>
</tr>
`
return fmt.Sprintf(tableRow, apiGroups, resources, resourcesNames, verbs, nonResourceURLs)
}
func formatPodSecurityPolicy(psp policy.PodSecurityPolicy) string {
var rulesText string
table := `
<table border="0" align="left">
<tr>
<td align="left" border="1" sides="b">Attribute</td>
<td align="left" border="1" sides="b">Expected Value(s)</td>
</tr>
%s
</table>
`
spec := utils.StructToMap(&psp.Spec)
keys := make([]string, 0, len(spec))
for k := range spec {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
rulesText = rulesText + fmt.Sprintf(`
<tr>
<td align="left">%s</td>
<td align="left">%v</td>
</tr>
`, k, spec[k])
}
return fmt.Sprintf(table, rulesText)
}
func (r *RbacViz) newPSPandRulesNodePair(g *dot.Graph, pspName string, highlight bool) *dot.Node {
var rulesText string
if psp, found := r.permissions.PodSecurityPolicies[pspName]; found {
data := formatPodSecurityPolicy(psp)
if data != "" {
rulesText = data
} else {
data, err := json.Marshal(psp.Spec)
if err != nil {
klog.V(5).Infof("Failed to marshal json - %v", psp.Spec)
return nil
}
rulesText = string(data)
}
}
klog.V(5).Infof("[PSP] Add %v", pspName)
pspNode := newPSPNode(g, "", pspName, true, highlight)
pspRulesNode := newPSPRulesNode(g, pspName, rulesText, false)
edge(pspNode, pspRulesNode)
return &pspNode
}
func (r *RbacViz) connectPSPNodesIfNeeded(g *dot.Graph, binding rbacv1.RoleBinding, rulesNode *dot.Node) {
var roleNamespace string
if rulesNode == nil {
return
}
if binding.RoleRef.Kind == "ClusterRole" {
roleNamespace = ""
} else {
roleNamespace = binding.Namespace
}
if roles, found := r.permissions.Roles[roleNamespace]; found {
if role, found := roles[binding.RoleRef.Name]; found {
for _, rule := range role.Rules {
verbs := sets.NewString(rule.Verbs...)
apigroups := sets.NewString(rule.APIGroups...)
resources := sets.NewString(rule.Resources...)
if resources.Has("podsecuritypolicies") && verbs.Has("use") && apigroups.Has("policy") {
for _, psp := range rule.ResourceNames {
if psp == "*" {
for pspName, _ := range r.permissions.PodSecurityPolicies {
klog.V(5).Infof("\t\t>>> [add][PSP] %v/%v -> %v", binding.Namespace, binding.RoleRef.Name, pspName)
edge(*rulesNode, g.Node(pspNodeId(pspName)))
}
} else {
klog.V(5).Infof("\t\t>>> [add][PSP] %v/%v -> %v", binding.Namespace, binding.RoleRef.Name, psp)
edge(*rulesNode, g.Node(pspNodeId(psp)))
}
}
}
}
}
}
}