-
Notifications
You must be signed in to change notification settings - Fork 66
/
whocan_cmd.go
224 lines (180 loc) · 5.28 KB
/
whocan_cmd.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
package cmd
import (
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"github.com/alcideio/rbac-tool/pkg/kube"
"github.com/alcideio/rbac-tool/pkg/rbac"
"github.com/antonmedv/expr"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"k8s.io/klog"
"sigs.k8s.io/yaml"
)
type whoCanQuery struct {
Verb string
APIGroup string
Kind string
Name string
NonResourceUrl string
Rules []rbac.SubjectPolicyList
}
func NewCommandWhoCan() *cobra.Command {
clusterContext := ""
output := "table"
// Support overrides
cmd := &cobra.Command{
Use: "who-can",
Aliases: []string{"who", "whocan"},
Args: cobra.ExactArgs(2),
SilenceUsage: true,
SilenceErrors: true,
Example: "rbac-tool who-can delete deployments.apps",
Short: "Shows which subjects have RBAC permissions to perform an action",
Long: `
Shows which subjects have RBAC permissions to perform an action denoted by VERB on an object denoted as ( KIND | KIND/NAME | NON-RESOURCE-URL)
* VERB is a logical Kubernetes API verb like 'get', 'list', 'watch', 'delete', etc.
* KIND is a Kubernetes resource kind. Shortcuts and API groups will be resolved, e.g. 'po' or 'deploy'.
* NAME is the name of a particular Kubernetes resource.
* NON-RESOURCE-URL is a URL that starts with "/".
Shows which subjects have RBAC permissions to <VERB> ( KIND> | KIND/NAME | NON-RESOURCE-URL)
Examples:
# Who can read ConfigMap resources
rbac-tool who-can get cm
# Who can watch Deployments
rbac-tool who-can watch deployments.apps
# Who can read the Kubernetes API endpoint /apis
rbac-tool who-can get /apis
# Who can read a secret resource by the name some-secret
rbac-tool who-can get secret/some-secret
`,
Hidden: false,
RunE: func(c *cobra.Command, args []string) error {
var err error
kind := ""
queryEnv := whoCanQuery{
Verb: args[0],
APIGroup: "core",
Kind: "*",
Name: "*",
NonResourceUrl: "",
Rules: nil,
}
if len(args) == 2 {
kind = args[1]
}
query := `
filter(
Rules,
{any(
.AllowedTo,
{ .Verb in [Verb, "*"] and
.Resource in [Kind, "*"] and
.APIGroup in [APIGroup, "*"] and
(Name == "*" or len(.ResourceNames) == 0 or Name in .ResourceNames)
}
)}
)`
if strings.HasPrefix(kind, "/") {
queryEnv.NonResourceUrl = kind
query = `
filter(
Rules,
{any(
.AllowedTo,
{ .Verb in [Verb, "*"] and
(NonResourceUrl in .NonResourceURLs or (len(.NonResourceURLs) == 1 and .NonResourceURLs[0] == "*"))
}
)}
)`
} else if strings.Contains(kind, "/") {
parts := strings.Split(kind, "/")
queryEnv.Kind = parts[0]
queryEnv.Name = parts[1]
} else {
queryEnv.Kind = kind
}
client, err := kube.NewClient(clusterContext)
if err != nil {
return fmt.Errorf("Failed to create kubernetes client - %v", err)
}
if queryEnv.NonResourceUrl == "" {
gr, err := client.Resolve(queryEnv.Verb, queryEnv.Kind, "")
if err != nil {
return err
}
queryEnv.Kind = gr.Resource
if gr.Group != "" {
queryEnv.APIGroup = gr.Group
}
}
klog.V(8).Infof("query\n%v\n%#v\n", query, queryEnv)
program, err := expr.Compile(query)
if err != nil {
return err
}
perms, err := rbac.NewPermissionsFromCluster(client)
if err != nil {
return err
}
permsPerSubject := rbac.NewSubjectPermissions(perms)
policies := rbac.NewSubjectPermissionsList(permsPerSubject)
queryEnv.Rules = policies
out, err := expr.Run(program, queryEnv)
if err != nil {
return fmt.Errorf("Failed to run program - %v", err)
}
filteredPolicies := out.([]interface{})
switch output {
case "table":
rows := [][]string{}
for _, e := range filteredPolicies {
p := e.(rbac.SubjectPolicyList)
row := []string{
p.Kind,
p.Name,
p.Namespace,
}
rows = append(rows, row)
}
sort.Slice(rows, func(i, j int) bool {
if strings.Compare(rows[i][0], rows[j][0]) == 0 {
return (strings.Compare(rows[i][1], rows[j][1]) < 0)
}
return (strings.Compare(rows[i][0], rows[j][0]) < 0)
})
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"TYPE", "SUBJECT", "NAMESPACE"})
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
table.SetBorder(false)
table.SetAlignment(tablewriter.ALIGN_LEFT)
//table.SetAutoMergeCells(true)
table.AppendBulk(rows)
table.Render()
return nil
case "yaml":
data, err := yaml.Marshal(&filteredPolicies)
if err != nil {
return fmt.Errorf("Processing error - %v", err)
}
fmt.Fprintln(os.Stdout, string(data))
return nil
case "json":
data, err := json.Marshal(&filteredPolicies)
if err != nil {
return fmt.Errorf("Processing error - %v", err)
}
fmt.Fprintln(os.Stdout, string(data))
return nil
default:
return fmt.Errorf("Unsupported output format")
}
},
}
flags := cmd.Flags()
flags.StringVar(&clusterContext, "cluster-context", "", "Cluster Context .use 'kubectl config get-contexts' to list available contexts")
flags.StringVarP(&output, "output", "o", "table", "Output type: table | json | yaml")
return cmd
}