forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
admission.go
280 lines (242 loc) · 11.1 KB
/
admission.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
package sccadmission
import (
"fmt"
"io"
"sort"
"strings"
"github.com/golang/glog"
apiequality "k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/apiserver/pkg/admission/initializer"
"k8s.io/apiserver/pkg/authorization/authorizer"
kapihelper "k8s.io/kubernetes/pkg/apis/core/helper"
rbacregistry "k8s.io/kubernetes/pkg/registry/rbac"
oadmission "github.com/openshift/origin/pkg/cmd/server/admission"
allocator "github.com/openshift/origin/pkg/security"
scc "github.com/openshift/origin/pkg/security/apiserver/securitycontextconstraints"
securityinformer "github.com/openshift/origin/pkg/security/generated/informers/internalversion"
securitylisters "github.com/openshift/origin/pkg/security/generated/listers/security/internalversion"
admission "k8s.io/apiserver/pkg/admission"
kapi "k8s.io/kubernetes/pkg/apis/core"
kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
kadmission "k8s.io/kubernetes/pkg/kubeapiserver/admission"
"k8s.io/kubernetes/pkg/serviceaccount"
)
const PluginName = "SecurityContextConstraint"
func Register(plugins *admission.Plugins) {
plugins.Register(PluginName,
func(config io.Reader) (admission.Interface, error) {
return NewConstraint(), nil
})
}
type constraint struct {
*admission.Handler
client kclientset.Interface
sccLister securitylisters.SecurityContextConstraintsLister
authorizer authorizer.Authorizer
}
var (
_ = admission.Interface(&constraint{})
_ = initializer.WantsAuthorizer(&constraint{})
_ = oadmission.WantsSecurityInformer(&constraint{})
_ = kadmission.WantsInternalKubeClientSet(&constraint{})
)
// NewConstraint creates a new SCC constraint admission plugin.
func NewConstraint() *constraint {
return &constraint{
Handler: admission.NewHandler(admission.Create, admission.Update),
}
}
// Admit determines if the pod should be admitted based on the requested security context
// and the available SCCs.
//
// 1. Find SCCs for the user.
// 2. Find SCCs for the SA. If there is an error retrieving SA SCCs it is not fatal.
// 3. Remove duplicates between the user/SA SCCs.
// 4. Create the providers, includes setting pre-allocated values if necessary.
// 5. Try to generate and validate an SCC with providers. If we find one then admit the pod
// with the validated SCC. If we don't find any reject the pod and give all errors from the
// failed attempts.
// On updates, the BeforeUpdate of the pod strategy only zeroes out the status. That means that
// any change that claims the pod is no longer privileged will be removed. That should hold until
// we get a true old/new set of objects in.
func (c *constraint) Admit(a admission.Attributes) error {
if ignore, err := shouldIgnore(a); err != nil {
return err
} else if ignore {
return nil
}
pod := a.GetObject().(*kapi.Pod)
// TODO(liggitt): allow spec mutation during initializing updates?
specMutationAllowed := a.GetOperation() == admission.Create
allowedPod, sccName, validationErrs, err := c.computeSecurityContext(a, pod, specMutationAllowed, "")
if err != nil {
return admission.NewForbidden(a, err)
}
if allowedPod != nil {
*pod = *allowedPod
// annotate and accept the pod
glog.V(4).Infof("pod %s (generate: %s) validated against provider %s", pod.Name, pod.GenerateName, sccName)
if pod.ObjectMeta.Annotations == nil {
pod.ObjectMeta.Annotations = map[string]string{}
}
pod.ObjectMeta.Annotations[allocator.ValidatedSCCAnnotation] = sccName
return nil
}
// we didn't validate against any security context constraint provider, reject the pod and give the errors for each attempt
glog.V(4).Infof("unable to validate pod %s (generate: %s) against any security context constraint: %v", pod.Name, pod.GenerateName, validationErrs)
return admission.NewForbidden(a, fmt.Errorf("unable to validate against any security context constraint: %v", validationErrs))
}
func (c *constraint) Validate(a admission.Attributes) error {
if ignore, err := shouldIgnore(a); err != nil {
return err
} else if ignore {
return nil
}
pod := a.GetObject().(*kapi.Pod)
// compute the context. Mutation is not allowed. ValidatedSCCAnnotation is used as a hint to gain same speed-up.
allowedPod, _, validationErrs, err := c.computeSecurityContext(a, pod, false, pod.ObjectMeta.Annotations[allocator.ValidatedSCCAnnotation])
if err != nil {
return admission.NewForbidden(a, err)
}
if allowedPod != nil && apiequality.Semantic.DeepEqual(pod, allowedPod) {
return nil
}
// we didn't validate against any provider, reject the pod and give the errors for each attempt
glog.V(4).Infof("unable to validate pod %s (generate: %s) in namespace %s against any pod security policy: %v", pod.Name, pod.GenerateName, a.GetNamespace(), validationErrs)
return admission.NewForbidden(a, fmt.Errorf("unable to validate against any pod security policy: %v", validationErrs))
}
func (c *constraint) computeSecurityContext(a admission.Attributes, pod *kapi.Pod, specMutationAllowed bool, validatedSCCHint string) (*kapi.Pod, string, field.ErrorList, error) {
// get all constraints that are usable by the user
glog.V(4).Infof("getting security context constraints for pod %s (generate: %s) in namespace %s with user info %v", pod.Name, pod.GenerateName, a.GetNamespace(), a.GetUserInfo())
sccMatcher := scc.NewDefaultSCCMatcher(c.sccLister, c.authorizer)
matchedConstraints, err := sccMatcher.FindApplicableSCCs(a.GetUserInfo(), a.GetNamespace())
if err != nil {
return nil, "", nil, admission.NewForbidden(a, err)
}
// get all constraints that are usable by the SA
if len(pod.Spec.ServiceAccountName) > 0 {
userInfo := serviceaccount.UserInfo(a.GetNamespace(), pod.Spec.ServiceAccountName, "")
glog.V(4).Infof("getting security context constraints for pod %s (generate: %s) with service account info %v", pod.Name, pod.GenerateName, userInfo)
saConstraints, err := sccMatcher.FindApplicableSCCs(userInfo, a.GetNamespace())
if err != nil {
return nil, "", nil, admission.NewForbidden(a, err)
}
matchedConstraints = append(matchedConstraints, saConstraints...)
}
// remove duplicate constraints and sort
matchedConstraints = scc.DeduplicateSecurityContextConstraints(matchedConstraints)
sort.Sort(scc.ByPriority(matchedConstraints))
// If mutation is not allowed and validatedSCCHint is provided, check the validated policy first.
// Keep the other the same for everything else
sort.SliceStable(matchedConstraints, func(i, j int) bool {
if !specMutationAllowed {
if matchedConstraints[i].Name == validatedSCCHint {
return true
}
if matchedConstraints[j].Name == validatedSCCHint {
return false
}
}
return i < j
})
providers, errs := scc.CreateProvidersFromConstraints(a.GetNamespace(), matchedConstraints, c.client)
logProviders(pod, providers, errs)
if len(providers) == 0 {
return nil, "", nil, admission.NewForbidden(a, fmt.Errorf("no providers available to validate pod request"))
}
// all containers in a single pod must validate under a single provider or we will reject the request
validationErrs := field.ErrorList{}
var (
allowedPod *kapi.Pod
allowingProvider scc.SecurityContextConstraintsProvider
)
loop:
for _, provider := range providers {
podCopy := pod.DeepCopy()
if errs := scc.AssignSecurityContext(provider, podCopy, field.NewPath(fmt.Sprintf("provider %s: ", provider.GetSCCName()))); len(errs) > 0 {
validationErrs = append(validationErrs, errs...)
continue
}
// the entire pod validated
switch {
case specMutationAllowed:
// if mutation is allowed, use the first found SCC that allows the pod.
// This behavior is different from Kubernetes which tries to search a non-mutating provider
// even on creating. We prefer most restrictive SCC in this case even if it mutates a pod.
allowedPod = podCopy
allowingProvider = provider
glog.V(5).Infof("pod %s (generate: %s) validated against provider %s with mutation", pod.Name, pod.GenerateName, provider.GetSCCName())
break loop
case apiequality.Semantic.DeepEqual(pod, podCopy):
// if we don't allow mutation, only use the validated pod if it didn't require any spec changes
allowedPod = podCopy
allowingProvider = provider
glog.V(5).Infof("pod %s (generate: %s) validated against provider %s without mutation", pod.Name, pod.GenerateName, provider.GetSCCName())
break loop
default:
glog.V(5).Infof("pod %s (generate: %s) validated against provider %s, but required mutation, skipping", pod.Name, pod.GenerateName, provider.GetSCCName())
}
}
if allowedPod == nil || allowingProvider == nil {
return nil, "", validationErrs, nil
}
return allowedPod, allowingProvider.GetSCCName(), validationErrs, nil
}
func shouldIgnore(a admission.Attributes) (bool, error) {
if a.GetResource().GroupResource() != kapi.Resource("pods") {
return true, nil
}
if len(a.GetSubresource()) != 0 {
return true, nil
}
_, ok := a.GetObject().(*kapi.Pod)
// if we can't convert then fail closed since we've already checked that this is supposed to be a pod object.
// this shouldn't normally happen during admission but could happen if an integrator passes a versioned
// pod object rather than an internal object.
if !ok {
return false, admission.NewForbidden(a, fmt.Errorf("object was marked as kind pod but was unable to be converted: %v", a.GetObject()))
}
// if this is an update, see if we are only updating the ownerRef. Garbage collection does this
// and we should allow it in general, since you had the power to update and the power to delete.
// The worst that happens is that you delete something, but you aren't controlling the privileged object itself
if a.GetOperation() == admission.Update && rbacregistry.IsOnlyMutatingGCFields(a.GetObject(), a.GetOldObject(), kapihelper.Semantic) {
return true, nil
}
return false, nil
}
// SetSecurityInformers implements WantsSecurityInformer interface for constraint.
func (c *constraint) SetSecurityInformers(informers securityinformer.SharedInformerFactory) {
c.sccLister = informers.Security().InternalVersion().SecurityContextConstraints().Lister()
}
func (c *constraint) SetInternalKubeClientSet(client kclientset.Interface) {
c.client = client
}
func (c *constraint) SetAuthorizer(authorizer authorizer.Authorizer) {
c.authorizer = authorizer
}
// ValidateInitialization implements InitializationValidator interface for constraint.
func (c *constraint) ValidateInitialization() error {
if c.sccLister == nil {
return fmt.Errorf("%s requires an sccLister", PluginName)
}
if c.client == nil {
return fmt.Errorf("%s requires a client", PluginName)
}
if c.authorizer == nil {
return fmt.Errorf("%s requires an authorizer", PluginName)
}
return nil
}
// logProviders logs what providers were found for the pod as well as any errors that were encountered
// while creating providers.
func logProviders(pod *kapi.Pod, providers []scc.SecurityContextConstraintsProvider, providerCreationErrs []error) {
names := make([]string, len(providers))
for i, p := range providers {
names[i] = p.GetSCCName()
}
glog.V(4).Infof("validating pod %s (generate: %s) against providers %s", pod.Name, pod.GenerateName, strings.Join(names, ","))
for _, err := range providerCreationErrs {
glog.V(4).Infof("provider creation error: %v", err)
}
}