-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
subject_review.go
285 lines (259 loc) · 9.9 KB
/
subject_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
package policy
import (
"fmt"
"io"
"strings"
"text/tabwriter"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apiserver/pkg/authentication/serviceaccount"
kapi "k8s.io/kubernetes/pkg/api"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/resource"
kprinters "k8s.io/kubernetes/pkg/printers"
"github.com/openshift/origin/pkg/client"
"github.com/openshift/origin/pkg/cmd/templates"
"github.com/openshift/origin/pkg/cmd/util/clientcmd"
securityapi "github.com/openshift/origin/pkg/security/api"
securityapiv1 "github.com/openshift/origin/pkg/security/api/v1"
)
var (
subjectReviewLong = templates.LongDesc(`Check whether a User, Service Account or a Group can create a Pod.
It returns a list of Security Context Constraints that will admit the resource.
If User is specified but not Groups, it is interpreted as "What if User is not a member of any groups".
If User and Groups are empty, then the check is performed using the current user
`)
subjectReviewExamples = templates.Examples(`# Check whether user bob can create a pod specified in myresource.yaml
$ %[1]s -u bob -f myresource.yaml
# Check whether user bob who belongs to projectAdmin group can create a pod specified in myresource.yaml
$ %[1]s -u bob -g projectAdmin -f myresource.yaml
# Check whether ServiceAccount specified in podTemplateSpec in myresourcewithsa.yaml can create the Pod
$ %[1]s -f myresourcewithsa.yaml `)
)
const SubjectReviewRecommendedName = "scc-subject-review"
type sccSubjectReviewOptions struct {
sccSubjectReviewClient client.PodSecurityPolicySubjectReviewsNamespacer
sccSelfSubjectReviewClient client.PodSecurityPolicySelfSubjectReviewsNamespacer
namespace string
enforceNamespace bool
out io.Writer
mapper meta.RESTMapper
typer runtime.ObjectTyper
RESTClientFactory func(mapping *meta.RESTMapping) (resource.RESTClient, error)
printer sccSubjectReviewPrinter
FilenameOptions resource.FilenameOptions
User string
Groups []string
serviceAccount string
}
func NewCmdSccSubjectReview(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
o := &sccSubjectReviewOptions{}
cmd := &cobra.Command{
Use: name,
Long: subjectReviewLong,
Short: "Check whether a user or a ServiceAccount can create a Pod.",
Example: fmt.Sprintf(subjectReviewExamples, fullName, fullName),
Run: func(cmd *cobra.Command, args []string) {
kcmdutil.CheckErr(o.Complete(f, args, cmd, out))
kcmdutil.CheckErr(o.Run(args))
},
}
cmd.Flags().StringVarP(&o.User, "user", "u", o.User, "Review will be performed on behalf of this user")
cmd.Flags().StringSliceVarP(&o.Groups, "groups", "g", o.Groups, "Comma separated, list of groups. Review will be performed on behalf of these groups")
cmd.Flags().StringVarP(&o.serviceAccount, "serviceaccount", "z", o.serviceAccount, "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.AddPrinterFlags(cmd)
return cmd
}
func (o *sccSubjectReviewOptions) Complete(f *clientcmd.Factory, args []string, cmd *cobra.Command, out io.Writer) error {
if len(args) == 0 && len(o.FilenameOptions.Filenames) == 0 {
return kcmdutil.UsageError(cmd, cmd.Use)
}
if len(o.User) > 0 && len(o.serviceAccount) > 0 {
return fmt.Errorf("--user and --serviceaccount are mutually exclusive")
}
if len(o.serviceAccount) > 0 { // check whether user supplied a list of SA
if len(strings.Split(o.serviceAccount, ",")) > 1 {
return fmt.Errorf("only one Service Account is supported")
}
if strings.HasPrefix(o.serviceAccount, serviceaccount.ServiceAccountUsernamePrefix) {
_, user, err := serviceaccount.SplitUsername(o.serviceAccount)
if err != nil {
return err
}
o.serviceAccount = user
}
}
var err error
o.namespace, o.enforceNamespace, err = f.DefaultNamespace()
if err != nil {
return err
}
oclient, _, err := f.Clients()
if err != nil {
return fmt.Errorf("unable to obtain client: %v", err)
}
o.sccSubjectReviewClient = oclient
o.sccSelfSubjectReviewClient = oclient
o.mapper, o.typer = f.Object()
o.RESTClientFactory = f.ClientForMapping
if len(kcmdutil.GetFlagString(cmd, "output")) != 0 {
printer, _, err := f.PrinterForCommand(cmd)
if err != nil {
return err
}
o.printer = &sccSubjectReviewOutputPrinter{printer}
} else {
o.printer = &sccSubjectReviewHumanReadablePrinter{noHeaders: kcmdutil.GetFlagBool(cmd, "no-headers")}
}
o.out = out
return nil
}
func (o *sccSubjectReviewOptions) Run(args []string) error {
userOrSA := o.User
if len(o.serviceAccount) > 0 {
userOrSA = o.serviceAccount
}
r := resource.NewBuilder(o.mapper, o.typer, resource.ClientMapperFunc(o.RESTClientFactory), kapi.Codecs.UniversalDecoder()).
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
}
var response runtime.Object
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
}
if len(userOrSA) > 0 || len(o.Groups) > 0 {
unversionedObj, err := o.pspSubjectReview(userOrSA, podTemplateSpec)
if err != nil {
return fmt.Errorf("unable to compute Pod Security Policy Subject Review for %q: %v", objectName, err)
}
versionedObj := &securityapiv1.PodSecurityPolicySubjectReview{}
if err := kapi.Scheme.Convert(unversionedObj, versionedObj, nil); err != nil {
return err
}
response = versionedObj
} else {
unversionedObj, err := o.pspSelfSubjectReview(podTemplateSpec)
if err != nil {
return fmt.Errorf("unable to compute Pod Security Policy Subject Review for %q: %v", objectName, err)
}
versionedObj := &securityapiv1.PodSecurityPolicySelfSubjectReview{}
if err := kapi.Scheme.Convert(unversionedObj, versionedObj, nil); err != nil {
return err
}
response = versionedObj
}
if err := o.printer.print(info, response, o.out); err != nil {
allErrs = append(allErrs, err)
}
return nil
})
allErrs = append(allErrs, err)
return utilerrors.NewAggregate(allErrs)
}
func (o *sccSubjectReviewOptions) pspSubjectReview(userOrSA string, podTemplateSpec *kapi.PodTemplateSpec) (*securityapi.PodSecurityPolicySubjectReview, error) {
podSecurityPolicySubjectReview := &securityapi.PodSecurityPolicySubjectReview{
Spec: securityapi.PodSecurityPolicySubjectReviewSpec{
Template: *podTemplateSpec,
User: userOrSA,
Groups: o.Groups,
},
}
return o.sccSubjectReviewClient.PodSecurityPolicySubjectReviews(o.namespace).Create(podSecurityPolicySubjectReview)
}
func (o *sccSubjectReviewOptions) pspSelfSubjectReview(podTemplateSpec *kapi.PodTemplateSpec) (*securityapi.PodSecurityPolicySelfSubjectReview, error) {
podSecurityPolicySelfSubjectReview := &securityapi.PodSecurityPolicySelfSubjectReview{
Spec: securityapi.PodSecurityPolicySelfSubjectReviewSpec{
Template: *podTemplateSpec,
},
}
return o.sccSelfSubjectReviewClient.PodSecurityPolicySelfSubjectReviews(o.namespace).Create(podSecurityPolicySelfSubjectReview)
}
type sccSubjectReviewPrinter interface {
print(*resource.Info, runtime.Object, io.Writer) error
}
type sccSubjectReviewOutputPrinter struct {
kprinters.ResourcePrinter
}
var _ sccSubjectReviewPrinter = &sccSubjectReviewOutputPrinter{}
func (s *sccSubjectReviewOutputPrinter) print(unused *resource.Info, obj runtime.Object, out io.Writer) error {
return s.ResourcePrinter.PrintObj(obj, out)
}
type sccSubjectReviewHumanReadablePrinter struct {
noHeaders bool
}
var _ sccSubjectReviewPrinter = &sccSubjectReviewHumanReadablePrinter{}
const (
sccSubjectReviewTabWriterMinWidth = 0
sccSubjectReviewTabWriterWidth = 7
sccSubjectReviewTabWriterPadding = 3
sccSubjectReviewTabWriterPadChar = ' '
sccSubjectReviewTabWriterFlags = 0
)
func (s *sccSubjectReviewHumanReadablePrinter) print(info *resource.Info, obj runtime.Object, out io.Writer) error {
w := tabwriter.NewWriter(out, sccSubjectReviewTabWriterMinWidth, sccSubjectReviewTabWriterWidth, sccSubjectReviewTabWriterPadding, sccSubjectReviewTabWriterPadChar, sccSubjectReviewTabWriterFlags)
defer w.Flush()
if s.noHeaders == false {
columns := []string{"RESOURCE", "ALLOWED BY"}
fmt.Fprintf(w, "%s\t\n", strings.Join(columns, "\t"))
s.noHeaders = true // printed only the first time if requested
}
gvk, _, err := kapi.Scheme.ObjectKind(info.Object)
if err != nil {
return err
}
kind := gvk.Kind
allowedBy, err := getAllowedBy(obj)
if err != nil {
return err
}
_, err = fmt.Fprintf(w, "%s/%s\t%s\t\n", kind, info.Name, allowedBy)
if err != nil {
return err
}
return nil
}
func getAllowedBy(obj runtime.Object) (string, error) {
value := "<none>"
switch review := obj.(type) {
case *securityapi.PodSecurityPolicySelfSubjectReview:
if review.Status.AllowedBy != nil {
value = review.Status.AllowedBy.Name
}
case *securityapi.PodSecurityPolicySubjectReview:
if review.Status.AllowedBy != nil {
value = review.Status.AllowedBy.Name
}
case *securityapiv1.PodSecurityPolicySelfSubjectReview:
if review.Status.AllowedBy != nil {
value = review.Status.AllowedBy.Name
}
case *securityapiv1.PodSecurityPolicySubjectReview:
if review.Status.AllowedBy != nil {
value = review.Status.AllowedBy.Name
}
default:
return value, fmt.Errorf("unexpected object %T", obj)
}
return value, nil
}