forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
review.go
293 lines (256 loc) · 9.77 KB
/
review.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
package policy
import (
"fmt"
"io"
"strings"
"text/tabwriter"
"github.com/spf13/cobra"
appsv1 "k8s.io/api/apps/v1"
appsv1beta1 "k8s.io/api/apps/v1beta1"
appsv1beta2 "k8s.io/api/apps/v1beta2"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apiserver/pkg/authentication/serviceaccount"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/genericclioptions"
"k8s.io/kubernetes/pkg/kubectl/genericclioptions/printers"
"k8s.io/kubernetes/pkg/kubectl/genericclioptions/resource"
"k8s.io/kubernetes/pkg/kubectl/scheme"
securityv1 "github.com/openshift/api/security/v1"
securityv1typedclient "github.com/openshift/client-go/security/clientset/versioned/typed/security/v1"
ometa "github.com/openshift/origin/pkg/api/imagereferencemutators"
)
var (
reviewLong = templates.LongDesc(`Checks which Service Account can create a Pod.
The Pod is inferred from the PodTemplateSpec in the provided resource.
If no Service Account is provided the one specified in podTemplateSpec.spec.serviceAccountName is used,
unless it is empty, in which case "default" is used.
If Service Accounts are provided the podTemplateSpec.spec.serviceAccountName is ignored.
`)
reviewExamples = templates.Examples(`# Check whether Service Accounts sa1 and sa2 can admit a Pod with TemplatePodSpec specified in my_resource.yaml
# Service Account specified in myresource.yaml file is ignored
$ %[1]s -z sa1,sa2 -f my_resource.yaml
# Check whether Service Accounts system:serviceaccount:bob:default can admit a Pod with TemplatePodSpec specified in my_resource.yaml
$ %[1]s -z system:serviceaccount:bob:default -f my_resource.yaml
# Check whether Service Account specified in my_resource_with_sa.yaml can admit the Pod
$ %[1]s -f my_resource_with_sa.yaml
# Check whether default Service Account can admit the Pod, default is taken since no Service Account is defined in myresource_with_no_sa.yaml
$ %[1]s -f myresource_with_no_sa.yaml
`)
)
const (
ReviewRecommendedName = "scc-review"
tabWriterMinWidth = 0
tabWriterWidth = 7
tabWriterPadding = 3
tabWriterPadChar = ' '
tabWriterFlags = 0
)
type SCCReviewOptions struct {
PrintFlags *genericclioptions.PrintFlags
Printer *policyPrinter
client securityv1typedclient.PodSecurityPolicyReviewsGetter
namespace string
enforceNamespace bool
builder *resource.Builder
RESTClientFactory func(mapping *meta.RESTMapping) (resource.RESTClient, error)
FilenameOptions resource.FilenameOptions
serviceAccountNames []string // it contains user inputs it could be long sa name like system:serviceaccount:bob:default or short one
shortServiceAccountNames []string // it contains only short sa name for example 'bob'
genericclioptions.IOStreams
}
func NewSCCReviewOptions(streams genericclioptions.IOStreams) *SCCReviewOptions {
return &SCCReviewOptions{
PrintFlags: genericclioptions.NewPrintFlags("").WithTypeSetter(scheme.Scheme),
IOStreams: streams,
}
}
func NewCmdSccReview(name, fullName string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
o := NewSCCReviewOptions(streams)
cmd := &cobra.Command{
Use: name,
Short: "Checks which ServiceAccount can create a Pod",
Long: reviewLong,
Example: fmt.Sprintf(reviewExamples, fullName),
Run: func(cmd *cobra.Command, args []string) {
kcmdutil.CheckErr(o.Complete(f, args, cmd))
kcmdutil.CheckErr(o.Run(args))
},
}
cmd.Flags().StringSliceVarP(&o.serviceAccountNames, "serviceaccount", "z", o.serviceAccountNames, "service account in the current namespace to use as a user")
kcmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "Filename, directory, or URL to a file identifying the resource to get from a server.")
kcmdutil.AddNoHeadersFlags(cmd)
o.PrintFlags.AddFlags(cmd)
return cmd
}
type policyPrinter struct {
humanPrinting bool
humanPrintFunc func(*resource.Info, runtime.Object, *bool, io.Writer) error
noHeaders bool
printFlags *genericclioptions.PrintFlags
info *resource.Info
}
func (p *policyPrinter) WithInfo(info *resource.Info) *policyPrinter {
p.info = info
return p
}
func (p *policyPrinter) PrintObj(obj runtime.Object, out io.Writer) error {
if !p.humanPrinting {
printer, err := p.printFlags.ToPrinter()
if err != nil {
return err
}
return printer.PrintObj(obj, out)
}
return p.humanPrintFunc(p.info, obj, &p.noHeaders, out)
}
func (o *SCCReviewOptions) Complete(f kcmdutil.Factory, args []string, cmd *cobra.Command) error {
if len(args) == 0 && len(o.FilenameOptions.Filenames) == 0 {
return kcmdutil.UsageErrorf(cmd, "one or more resources must be specified")
}
for _, sa := range o.serviceAccountNames {
if strings.HasPrefix(sa, serviceaccount.ServiceAccountUsernamePrefix) {
_, user, err := serviceaccount.SplitUsername(sa)
if err != nil {
return err
}
o.shortServiceAccountNames = append(o.shortServiceAccountNames, user)
} else {
o.shortServiceAccountNames = append(o.shortServiceAccountNames, sa)
}
}
var err error
o.namespace, o.enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()
if err != nil {
return err
}
clientConfig, err := f.ToRESTConfig()
if err != nil {
return err
}
o.client, err = securityv1typedclient.NewForConfig(clientConfig)
if err != nil {
return fmt.Errorf("unable to obtain client: %v", err)
}
o.builder = f.NewBuilder()
o.RESTClientFactory = f.ClientForMapping
output := kcmdutil.GetFlagString(cmd, "output")
wide := len(output) > 0 && output == "wide"
o.Printer = &policyPrinter{
printFlags: o.PrintFlags,
humanPrinting: len(output) == 0 || wide,
humanPrintFunc: sccReviewHumanPrintFunc,
noHeaders: kcmdutil.GetFlagBool(cmd, "no-headers"),
}
return nil
}
func (o *SCCReviewOptions) Run(args []string) error {
r := o.builder.
WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
NamespaceParam(o.namespace).
FilenameParam(o.enforceNamespace, &o.FilenameOptions).
ResourceTypeOrNameArgs(true, args...).
ContinueOnError().
Flatten().
Do()
err := r.Err()
if err != nil {
return err
}
allErrs := []error{}
err = r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
objectName := info.Name
podTemplateSpec, err := GetPodTemplateForObject(info.Object)
if err != nil {
return fmt.Errorf(" %q cannot create pod: %v", objectName, err)
}
err = CheckStatefulSetWithWolumeClaimTemplates(info.Object)
if err != nil {
return err
}
review := &securityv1.PodSecurityPolicyReview{
Spec: securityv1.PodSecurityPolicyReviewSpec{
Template: *podTemplateSpec,
ServiceAccountNames: o.shortServiceAccountNames,
},
}
unversionedObj, err := o.client.PodSecurityPolicyReviews(o.namespace).Create(review)
if err != nil {
return fmt.Errorf("unable to compute Pod Security Policy Review for %q: %v", objectName, err)
}
if err = o.Printer.WithInfo(info).PrintObj(unversionedObj, o.Out); err != nil {
allErrs = append(allErrs, err)
}
return nil
})
allErrs = append(allErrs, err)
return utilerrors.NewAggregate(allErrs)
}
// CheckStatefulSetWithWolumeClaimTemplates checks whether a supplied object is a statefulSet with volumeClaimTemplates
// Currently scc-review and scc-subject-review commands cannot handle correctly this case since validation is not based
// only on podTemplateSpec.
func CheckStatefulSetWithWolumeClaimTemplates(obj runtime.Object) error {
// TODO remove this as soon upstream statefulSet validation for podSpec is fixed.
// Currently podTemplateSpec for a statefulSet is not fully validated
// spec.volumeClaimTemplates info should be propagated down to
// spec.template.spec validateContainers to validate volumeMounts
//https://github.com/openshift/origin/blob/master/vendor/k8s.io/kubernetes/pkg/apis/apps/validation/validation.go#L57
switch r := obj.(type) {
case *appsv1beta1.StatefulSet:
if len(r.Spec.VolumeClaimTemplates) > 0 {
return fmt.Errorf("StatefulSet %q with spec.volumeClaimTemplates currently not supported.", r.GetName())
}
case *appsv1beta2.StatefulSet:
if len(r.Spec.VolumeClaimTemplates) > 0 {
return fmt.Errorf("StatefulSet %q with spec.volumeClaimTemplates currently not supported.", r.GetName())
}
case *appsv1.StatefulSet:
if len(r.Spec.VolumeClaimTemplates) > 0 {
return fmt.Errorf("StatefulSet %q with spec.volumeClaimTemplates currently not supported.", r.GetName())
}
}
return nil
}
func GetPodTemplateForObject(obj runtime.Object) (*corev1.PodTemplateSpec, error) {
podSpec, _, err := ometa.GetPodSpecV1(obj)
if err != nil {
return nil, err
}
return &corev1.PodTemplateSpec{Spec: *podSpec}, nil
}
func sccReviewHumanPrintFunc(info *resource.Info, obj runtime.Object, noHeaders *bool, out io.Writer) error {
w := tabwriter.NewWriter(out, tabWriterMinWidth, tabWriterWidth, tabWriterPadding, tabWriterPadChar, tabWriterFlags)
defer w.Flush()
if info == nil {
return fmt.Errorf("expected non-nil resource info")
}
noHeadersVal := *noHeaders
if !noHeadersVal {
columns := []string{"RESOURCE", "SERVICE ACCOUNT", "ALLOWED BY"}
fmt.Fprintf(w, "%s\t\n", strings.Join(columns, "\t"))
// printed only the first time if requested
*noHeaders = true
}
pspreview, ok := obj.(*securityv1.PodSecurityPolicyReview)
if !ok {
return fmt.Errorf("unexpected object %T", obj)
}
gk := printers.GetObjectGroupKind(info.Object)
for _, allowedSA := range pspreview.Status.AllowedServiceAccounts {
allowedBy := "<none>"
if allowedSA.AllowedBy != nil {
allowedBy = allowedSA.AllowedBy.Name
}
_, err := fmt.Fprintf(w, "%s/%s\t%s\t%s\t\n", gk.Kind, info.Name, allowedSA.Name, allowedBy)
if err != nil {
return err
}
}
return nil
}