/
image.go
332 lines (314 loc) · 10.6 KB
/
image.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
//
// Copyright 2020 IBM Corporation
//
// 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 shield
import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
common "github.com/IBM/integrity-enforcer/shield/pkg/common"
"github.com/IBM/integrity-enforcer/shield/pkg/util/kubeutil"
logger "github.com/IBM/integrity-enforcer/shield/pkg/util/logger"
appsv1 "k8s.io/api/apps/v1"
appsv1beta1 "k8s.io/api/apps/v1beta1"
appsv1beta2 "k8s.io/api/apps/v1beta2"
batchv1 "k8s.io/api/batch/v1"
batchv1beta1 "k8s.io/api/batch/v1beta1"
corev1 "k8s.io/api/core/v1"
extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
)
type SigCheckImages struct {
ImagesToVerify []ImageToVerify `json:"imagesToVefiry"`
}
type ImageToVerify struct {
Image string `json:"image"`
Profile ImageCheckProfile `json:"profile"`
Result ImageVerifyResult `json:"result"`
ProfileCheckResult bool `json:"profileCheckResult"`
}
type ImageVerifyResult struct {
Error error `json:"error"`
Allowed bool `json:"allowed"`
Reason string `json:"reason"`
Digest string `json:"digest"`
CommonNames []string `json:"commonNames"`
}
type ImageCheckProfile struct {
Key string `json:"key"`
KeyNamespace string `json:"keyNamespace"`
CommonName string `json:"commonName"`
Image string `json:"image"`
CosignExperimental bool `json:"cosignExperimental"`
}
func requestCheckForImageCheck(resc *common.ResourceContext) (bool, *SigCheckImages, string) {
// return needsigcheck, image, msg
// scope check
inscope := filterByKind(resc.Kind)
if !inscope {
// no image referenced
logger.Trace("no image referenced")
return false, nil, "no image referenced"
}
// get images
podspec, err := getPodSpec(resc.RawObject, resc.ApiGroup, resc.ApiVersion, resc.Kind)
if err != nil {
// "no image referenced: fail to get podspec"
logger.Trace("no image referenced: fail to get podspec")
return false, nil, "no image referenced: fail to get podspec"
}
images := getImages(podspec.Containers)
imagesToVerify, msg := getImageProfile(resc.Namespace, images)
if len(imagesToVerify) == 0 {
return false, nil, msg
}
sigCheckImages := &SigCheckImages{
ImagesToVerify: imagesToVerify,
}
return true, sigCheckImages, ""
}
func (sci *SigCheckImages) imageVerifiedResultCheckByProfile() {
for i, img := range sci.ImagesToVerify {
if contains(img.Result.CommonNames, img.Profile.CommonName) {
img.ProfileCheckResult = true
sci.ImagesToVerify[i] = img
}
}
}
func makeImageCheckResult(images *SigCheckImages) *DecisionResult {
res := &DecisionResult{}
for _, img := range images.ImagesToVerify {
if img.Result.Error != nil {
res.Type = common.DecisionError
res.Verified = true
res.ReasonCode = common.REASON_ERROR
res.Message = img.Result.Error.Error()
return res
}
if !img.Result.Allowed {
res.Type = common.DecisionDeny
res.Verified = true
res.ReasonCode = common.REASON_INVALID_SIG_IMAGE
res.Message = img.Result.Reason
return res
}
if !img.ProfileCheckResult {
res.Type = common.DecisionDeny
res.Verified = true
res.ReasonCode = common.REASON_NO_MATCH_IMAGE_PROFILE
res.Message = "no image profile matches with this commonName:" + strings.Join(img.Result.CommonNames, ",")
return res
}
}
res.Verified = true
res.ReasonCode = common.REASON_VALID_SIG_IMAGE
res.Type = common.DecisionAllow
res.Message = fmt.Sprintf("this image is signed by a valid signer; image digest: %s, signer: %s", images.ImagesToVerify[0].Result.Digest, images.ImagesToVerify[0].Profile.CommonName)
return res
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func getImageProfile(namespace string, images []string) ([]ImageToVerify, string) {
var imagesToVerify []ImageToVerify
// load image profile
ip, err := getConfigmapProfile(namespace, "image-profile-cm")
if err != nil {
return imagesToVerify, "fail to load image profile"
}
// check if there are policies for the given image
for _, img := range images {
if isMatchImage(ip.Image, img) {
var imageToVerify ImageToVerify
imageToVerify.Image = img
imageToVerify.Profile.CommonName = ip.CommonName
imageToVerify.Profile.CosignExperimental = ip.CosignExperimental
imageToVerify.Profile.Image = ip.Image
imagesToVerify = append(imagesToVerify, imageToVerify)
}
}
if len(imagesToVerify) == 0 {
return imagesToVerify, "No matching profile"
}
return imagesToVerify, ""
}
func isMatchImage(pattern, value string) bool {
// profileImage, givenImage
pattern = strings.TrimSpace(pattern)
if pattern == "" {
return true
} else if pattern == "*" {
return true
} else if pattern == "-" && value == "" {
return true
} else if strings.HasSuffix(pattern, "*") {
return strings.HasPrefix(value, strings.TrimRight(pattern, "*"))
} else if pattern == value {
return true
} else {
return false
}
}
func filterByKind(resource string) bool {
if resource == "Pod" || resource == "Deployment" || resource == "Replicaset" || resource == "Daemonset" || resource == "Statefulset" || resource == "Job" || resource == "Cronjob" {
return true
}
return false
}
func getImages(containers []corev1.Container) []string {
var images []string
for _, c := range containers {
images = append(images, c.Image)
}
return images
}
func getConfigmapProfile(namespace, profileName string) (*ImageCheckProfile, error) {
// Retrieve secret
config, _ := kubeutil.GetKubeConfig()
c, _ := corev1client.NewForConfig(config)
cm, err := c.ConfigMaps(namespace).Get(context.Background(), profileName, metav1.GetOptions{})
if err != nil {
return nil, err
}
// Obtain the key data
var imageProfile ImageCheckProfile
if transparencyLog, ok := cm.Data["transparencyLog"]; ok {
tlog, _ := strconv.ParseBool(transparencyLog)
imageProfile.CosignExperimental = tlog
}
if cn, ok := cm.Data["commonName"]; ok {
imageProfile.CommonName = cn
}
if key, ok := cm.Data["keySecret"]; ok {
imageProfile.Key = key
}
if keySecretNamespace, ok := cm.Data["keySecretNamespace"]; ok {
imageProfile.KeyNamespace = keySecretNamespace
}
if image, ok := cm.Data["image"]; ok {
imageProfile.Image = image
return &imageProfile, nil
}
return nil, fmt.Errorf("no image is defined in image profile configmap", namespace)
}
func getPodSpec(rawObj []byte, group, version, kind string) (*corev1.PodSpec, error) {
ps := corev1.PodSpec{}
if kind == "Pod" && version == "v1" {
pod := corev1.Pod{}
if err := json.Unmarshal(rawObj, &pod); err != nil {
return nil, err
}
ps = pod.Spec
} else if kind == "Deployment" && version == "v1" && group == "apps" {
deployment := appsv1.Deployment{}
if err := json.Unmarshal(rawObj, &deployment); err != nil {
return nil, err
}
ps = deployment.Spec.Template.Spec
} else if kind == "Deployment" && version == "v1beta1" && group == "apps" {
deployment := appsv1beta1.Deployment{}
if err := json.Unmarshal(rawObj, &deployment); err != nil {
return nil, err
}
ps = deployment.Spec.Template.Spec
} else if kind == "Deployment" && version == "v1beta2" && group == "apps" {
deployment := appsv1beta2.Deployment{}
if err := json.Unmarshal(rawObj, &deployment); err != nil {
return nil, err
}
ps = deployment.Spec.Template.Spec
} else if kind == "Deployment" && version == "v1beta1" && group == "extensions" {
deployment := extensionsv1beta1.Deployment{}
if err := json.Unmarshal(rawObj, &deployment); err != nil {
return nil, err
}
ps = deployment.Spec.Template.Spec
} else if kind == "Replicaset" && version == "v1" && group == "apps" {
replicaset := appsv1.ReplicaSet{}
if err := json.Unmarshal(rawObj, &replicaset); err != nil {
return nil, err
}
ps = replicaset.Spec.Template.Spec
} else if kind == "Replicaset" && version == "v1beta1" && group == "extensions" {
replicaset := extensionsv1beta1.ReplicaSet{}
if err := json.Unmarshal(rawObj, &replicaset); err != nil {
return nil, err
}
ps = replicaset.Spec.Template.Spec
} else if kind == "Replicaset" && version == "v1beta2" && group == "apps" {
replicaset := appsv1beta2.ReplicaSet{}
if err := json.Unmarshal(rawObj, &replicaset); err != nil {
return nil, err
}
ps = replicaset.Spec.Template.Spec
} else if kind == "DaemonSet" && version == "v1" && group == "apps" {
daemonset := appsv1.DaemonSet{}
if err := json.Unmarshal(rawObj, &daemonset); err != nil {
return nil, err
}
ps = daemonset.Spec.Template.Spec
} else if kind == "DaemonSet" && version == "v1beta2" && group == "apps" {
daemonset := appsv1beta2.DaemonSet{}
if err := json.Unmarshal(rawObj, &daemonset); err != nil {
return nil, err
}
ps = daemonset.Spec.Template.Spec
} else if kind == "DaemonSet" && version == "v1beta1" && group == "extensions" {
daemonset := extensionsv1beta1.DaemonSet{}
if err := json.Unmarshal(rawObj, &daemonset); err != nil {
return nil, err
}
ps = daemonset.Spec.Template.Spec
} else if kind == "StatefulSet" && version == "v1" && group == "apps" {
statefulset := appsv1.StatefulSet{}
if err := json.Unmarshal(rawObj, &statefulset); err != nil {
return nil, err
}
ps = statefulset.Spec.Template.Spec
} else if kind == "StatefulSet" && version == "v1beta2" && group == "apps" {
statefulset := appsv1beta2.StatefulSet{}
if err := json.Unmarshal(rawObj, &statefulset); err != nil {
return nil, err
}
ps = statefulset.Spec.Template.Spec
} else if kind == "StatefulSet" && version == "v1beta1" && group == "apps" {
statefulset := appsv1beta1.StatefulSet{}
if err := json.Unmarshal(rawObj, &statefulset); err != nil {
return nil, err
}
ps = statefulset.Spec.Template.Spec
} else if kind == "Job" && version == "v1" && group == "batch" {
job := batchv1.Job{}
if err := json.Unmarshal(rawObj, &job); err != nil {
return nil, err
}
ps = job.Spec.Template.Spec
} else if kind == "CronJob" && version == "v1beta1" && group == "batch" {
cronjob := batchv1beta1.CronJob{}
if err := json.Unmarshal(rawObj, &cronjob); err != nil {
return nil, err
}
ps = cronjob.Spec.JobTemplate.Spec.Template.Spec
}
return &ps, nil
}