forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
abac.go
273 lines (237 loc) · 7.11 KB
/
abac.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
/*
Copyright 2014 The Kubernetes Authors.
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 abac
// Policy authorizes Kubernetes API actions using an Attribute-based access
// control scheme.
import (
"bufio"
"fmt"
"os"
"strings"
"k8s.io/klog"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/authorization/authorizer"
"k8s.io/kubernetes/pkg/apis/abac"
_ "k8s.io/kubernetes/pkg/apis/abac/latest"
"k8s.io/kubernetes/pkg/apis/abac/v0"
)
type policyLoadError struct {
path string
line int
data []byte
err error
}
func (p policyLoadError) Error() string {
if p.line >= 0 {
return fmt.Sprintf("error reading policy file %s, line %d: %s: %v", p.path, p.line, string(p.data), p.err)
}
return fmt.Sprintf("error reading policy file %s: %v", p.path, p.err)
}
type policyList []*abac.Policy
// TODO: Have policies be created via an API call and stored in REST storage.
func NewFromFile(path string) (policyList, error) {
// File format is one map per line. This allows easy concatenation of files,
// comments in files, and identification of errors by line number.
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
pl := make(policyList, 0)
decoder := abac.Codecs.UniversalDecoder()
i := 0
unversionedLines := 0
for scanner.Scan() {
i++
p := &abac.Policy{}
b := scanner.Bytes()
// skip comment lines and blank lines
trimmed := strings.TrimSpace(string(b))
if len(trimmed) == 0 || strings.HasPrefix(trimmed, "#") {
continue
}
decodedObj, _, err := decoder.Decode(b, nil, nil)
if err != nil {
if !(runtime.IsMissingVersion(err) || runtime.IsMissingKind(err) || runtime.IsNotRegisteredError(err)) {
return nil, policyLoadError{path, i, b, err}
}
unversionedLines++
// Migrate unversioned policy object
oldPolicy := &v0.Policy{}
if err := runtime.DecodeInto(decoder, b, oldPolicy); err != nil {
return nil, policyLoadError{path, i, b, err}
}
if err := abac.Scheme.Convert(oldPolicy, p, nil); err != nil {
return nil, policyLoadError{path, i, b, err}
}
pl = append(pl, p)
continue
}
decodedPolicy, ok := decodedObj.(*abac.Policy)
if !ok {
return nil, policyLoadError{path, i, b, fmt.Errorf("unrecognized object: %#v", decodedObj)}
}
pl = append(pl, decodedPolicy)
}
if unversionedLines > 0 {
klog.Warningf("Policy file %s contained unversioned rules. See docs/admin/authorization.md#abac-mode for ABAC file format details.", path)
}
if err := scanner.Err(); err != nil {
return nil, policyLoadError{path, -1, nil, err}
}
return pl, nil
}
func matches(p abac.Policy, a authorizer.Attributes) bool {
if subjectMatches(p, a.GetUser()) {
if verbMatches(p, a) {
// Resource and non-resource requests are mutually exclusive, at most one will match a policy
if resourceMatches(p, a) {
return true
}
if nonResourceMatches(p, a) {
return true
}
}
}
return false
}
// subjectMatches returns true if specified user and group properties in the policy match the attributes
func subjectMatches(p abac.Policy, user user.Info) bool {
matched := false
if user == nil {
return false
}
username := user.GetName()
groups := user.GetGroups()
// If the policy specified a user, ensure it matches
if len(p.Spec.User) > 0 {
if p.Spec.User == "*" {
matched = true
} else {
matched = p.Spec.User == username
if !matched {
return false
}
}
}
// If the policy specified a group, ensure it matches
if len(p.Spec.Group) > 0 {
if p.Spec.Group == "*" {
matched = true
} else {
matched = false
for _, group := range groups {
if p.Spec.Group == group {
matched = true
}
}
if !matched {
return false
}
}
}
return matched
}
func verbMatches(p abac.Policy, a authorizer.Attributes) bool {
// TODO: match on verb
// All policies allow read only requests
if a.IsReadOnly() {
return true
}
// Allow if policy is not readonly
if !p.Spec.Readonly {
return true
}
return false
}
func nonResourceMatches(p abac.Policy, a authorizer.Attributes) bool {
// A non-resource policy cannot match a resource request
if !a.IsResourceRequest() {
// Allow wildcard match
if p.Spec.NonResourcePath == "*" {
return true
}
// Allow exact match
if p.Spec.NonResourcePath == a.GetPath() {
return true
}
// Allow a trailing * subpath match
if strings.HasSuffix(p.Spec.NonResourcePath, "*") && strings.HasPrefix(a.GetPath(), strings.TrimRight(p.Spec.NonResourcePath, "*")) {
return true
}
}
return false
}
func resourceMatches(p abac.Policy, a authorizer.Attributes) bool {
// A resource policy cannot match a non-resource request
if a.IsResourceRequest() {
if p.Spec.Namespace == "*" || p.Spec.Namespace == a.GetNamespace() {
if p.Spec.Resource == "*" || p.Spec.Resource == a.GetResource() {
if p.Spec.APIGroup == "*" || p.Spec.APIGroup == a.GetAPIGroup() {
return true
}
}
}
}
return false
}
// Authorizer implements authorizer.Authorize
func (pl policyList) Authorize(a authorizer.Attributes) (authorizer.Decision, string, error) {
for _, p := range pl {
if matches(*p, a) {
return authorizer.DecisionAllow, "", nil
}
}
return authorizer.DecisionNoOpinion, "No policy matched.", nil
// TODO: Benchmark how much time policy matching takes with a medium size
// policy file, compared to other steps such as encoding/decoding.
// Then, add Caching only if needed.
}
func (pl policyList) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error) {
var (
resourceRules []authorizer.ResourceRuleInfo
nonResourceRules []authorizer.NonResourceRuleInfo
)
for _, p := range pl {
if subjectMatches(*p, user) {
if p.Spec.Namespace == "*" || p.Spec.Namespace == namespace {
if len(p.Spec.Resource) > 0 {
r := authorizer.DefaultResourceRuleInfo{
Verbs: getVerbs(p.Spec.Readonly),
APIGroups: []string{p.Spec.APIGroup},
Resources: []string{p.Spec.Resource},
}
var resourceRule authorizer.ResourceRuleInfo = &r
resourceRules = append(resourceRules, resourceRule)
}
if len(p.Spec.NonResourcePath) > 0 {
r := authorizer.DefaultNonResourceRuleInfo{
Verbs: getVerbs(p.Spec.Readonly),
NonResourceURLs: []string{p.Spec.NonResourcePath},
}
var nonResourceRule authorizer.NonResourceRuleInfo = &r
nonResourceRules = append(nonResourceRules, nonResourceRule)
}
}
}
}
return resourceRules, nonResourceRules, false, nil
}
func getVerbs(isReadOnly bool) []string {
if isReadOnly {
return []string{"get", "list", "watch"}
}
return []string{"*"}
}