/
k8s_pod.go
701 lines (580 loc) · 17.5 KB
/
k8s_pod.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
package analyzer
import (
"context"
"fmt"
"regexp"
"strings"
"time"
"github.com/kvesta/vesta/config"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func (ks *KScanner) podAnalyze(podSpec v1.PodSpec, rv RBACVuln, ns, podName string) []*threat {
vList := []*threat{}
for _, nswList := range namespaceWhileList {
if ns == nswList {
pruned, err := ks.prunePod(ns, podName)
if err != nil {
break
}
if pruned {
return vList
}
pod, err := ks.KClient.
CoreV1().
Pods(ns).
Get(context.TODO(), podName, metav1.GetOptions{})
if err != nil {
break
}
age := time.Since(pod.CreationTimestamp.Time)
if age.Hours() < 168 {
th := &threat{
Param: "replaced time",
Value: pod.CreationTimestamp.Time.Format("02/01/2006"),
Type: "Pod modify",
Describe: fmt.Sprintf("Pod has been modified %.2f hours ageo "+
"in crucial namespace: %s", age.Hours(), ns),
Severity: "medium",
}
vList = append(vList, th)
}
break
}
}
// Check the potential trampoline attack
if ok, tlist := ks.checkPodNodeSelector(podSpec); ok {
vList = append(vList, tlist...)
}
if podSpec.HostPID {
th := &threat{
Param: "Pod hostPID",
Value: "true",
Type: "hostPID",
Describe: "Pod is running with `hostPID`, " +
"which attackers can see all the processes in physical machine.",
Severity: "medium",
}
vList = append(vList, th)
}
if podSpec.HostNetwork {
th := &threat{
Param: "Pod hostNetwork",
Value: "true",
Type: "hostNetwork",
Describe: "Pod is running with `hostNetwork`, " +
"which will expose the network of physical machine.",
Severity: "medium",
}
vList = append(vList, th)
}
if podSpec.HostIPC {
th := &threat{
Param: "Pod hostIPC",
Value: "true",
Type: "hostIPC",
Describe: "Pod is running with `hostIPC`, " +
"which will expose all the data in shared memory segments.",
Severity: "medium",
}
vList = append(vList, th)
}
for _, v := range podSpec.Volumes {
if ok, tlist := checkPodVolume(v); ok {
vList = append(vList, tlist...)
}
}
for _, sp := range podSpec.Containers {
// Skip some sidecars
if sp.Name == "istio-proxy" {
// Try to check the istio header `X-Envoy-Peer-Metadata`
// reference: https://github.com/istio/istio/issues/17635
if ok, tlist := ks.checkIstioHeader(podName, ns, podSpec.Containers[0].Name); ok {
vList = append(vList, tlist...)
}
continue
}
if ok, tlist := checkPodPrivileged(sp); ok {
vList = append(vList, tlist...)
}
if ok, tlist := checkPodAccountService(sp, rv); ok {
vList = append(vList, tlist...)
}
if ok, tlist := checkResourcesLimits(sp, podSpec.Volumes); ok {
vList = append(vList, tlist...)
}
if ok, tlist := ks.checkSidecarEnv(sp, ns); ok {
vList = append(vList, tlist...)
}
if ok, tlist := ks.checkPodCommand(sp, ns); ok {
vList = append(vList, tlist...)
}
// Check CVE-2024-21626
if cveRuncRegex.MatchString(sp.WorkingDir) {
th := &threat{
Param: "Pod WorkDIR",
Value: fmt.Sprintf("WORKDIR: %s", sp.WorkingDir),
Type: "Suspect malicious pod",
Describe: fmt.Sprintf("Pod has malicious configuration, it's WORKDIR is '%s',"+
" which has a potential container escape, refer to CVE-2024-21626.", sp.WorkingDir),
Reference: "https://github.com/opencontainers/runc/security/advisories/GHSA-xr7r-f8xq-vfvv",
Severity: "high",
}
vList = append(vList, th)
}
}
return vList
}
func checkPodVolume(container v1.Volume) (bool, []*threat) {
tlist := []*threat{}
var vuln = false
hostPath := container.HostPath
if hostPath != nil {
//volumePath := filepath.Dir(hostPath.Path)
volumePath := hostPath.Path
if isVuln := checkMountPath(volumePath); isVuln {
th := &threat{
Param: fmt.Sprintf("volumes name: %s", container.Name),
Value: volumePath,
Type: string(*hostPath.Type),
Describe: fmt.Sprintf("Mounting '%s' is suffer vulnerable of "+
"container escape.", volumePath),
Severity: "critical",
}
tlist = append(tlist, th)
vuln = true
}
}
return vuln, tlist
}
func checkPodPrivileged(container v1.Container) (bool, []*threat) {
tlist := []*threat{}
var vuln = false
if container.SecurityContext != nil {
// check capabilities of pod
// Ignore the checking of cap_drop refer to:
// https://stackoverflow.com/questions/63162665/docker-compose-order-of-cap-drop-and-cap-add
capList, highestSeverity := "", "medium"
if container.SecurityContext.Capabilities != nil {
adds := container.SecurityContext.Capabilities.Add
for _, ad := range adds {
if ad == "ALL" {
capList = "ALL"
highestSeverity = "critical"
vuln = true
break
}
for c, s := range dangerCaps {
if string(ad) == c {
capList += c + " "
if config.SeverityMap[s] > config.SeverityMap[highestSeverity] {
highestSeverity = s
}
vuln = true
}
}
}
if vuln {
th := &threat{
Param: fmt.Sprintf("sidecar name: %s | "+
"capabilities", container.Name),
Value: capList,
Type: "capabilities.add",
Describe: "There has a potential container escape in dangerous capabilities.",
Severity: highestSeverity,
}
tlist = append(tlist, th)
}
}
if container.SecurityContext.Privileged != nil && *container.SecurityContext.Privileged {
th := &threat{
Param: fmt.Sprintf("sidecar name: %s | "+
"Privileged", container.Name),
Value: "true",
Type: "Sidecar Privileged",
Describe: "There has a potential container escape in privileged module.",
Severity: "critical",
}
tlist = append(tlist, th)
vuln = true
}
if container.SecurityContext.AllowPrivilegeEscalation != nil && *container.SecurityContext.AllowPrivilegeEscalation {
th := &threat{
Param: fmt.Sprintf("sidecar name: %s | "+
"AllowPrivilegeEscalation", container.Name),
Value: "true",
Type: "Sidecar Privileged",
Describe: "There has a potential container escape in privileged module.",
Severity: "critical",
}
tlist = append(tlist, th)
vuln = true
}
}
return vuln, tlist
}
func (ks *KScanner) checkSidecarEnv(container v1.Container, ns string) (bool, []*threat) {
var vuln = false
tlist := []*threat{}
// Check Pod Env
for _, env := range container.Env {
needCheck := false
if env.ValueFrom != nil {
switch {
case env.ValueFrom.SecretKeyRef != nil:
secretRef := env.ValueFrom.SecretKeyRef
if ok, th := ks.checkSecretFromName(ns, secretRef.Key, secretRef.Name, env.Name); ok {
th.Param = fmt.Sprintf("sidecar name: %s | env", container.Name)
tlist = append(tlist, th)
vuln = true
}
continue
case env.ValueFrom.ConfigMapKeyRef != nil:
configRef := env.ValueFrom.ConfigMapKeyRef
if ok, th := ks.checkConfigFromName(ns, configRef.Name, configRef.Key, env.Name); ok {
th.Param = fmt.Sprintf("sidecar name: %s | env", container.Name)
tlist = append(tlist, th)
vuln = true
}
continue
}
}
for _, p := range passKey {
if p.MatchString(env.Name) && env.ValueFrom == nil {
needCheck = true
break
}
}
if needCheck {
switch checkWeakPassword(env.Value) {
case "Weak":
th := &threat{
Param: fmt.Sprintf("sidecar name: %s | env", container.Name),
Value: fmt.Sprintf("%s: %s", env.Name, env.Value),
Type: "Sidecar Env",
Describe: fmt.Sprintf("Container '%s' has found weak password: '%s'.", container.Name, env.Value),
Severity: "high",
}
tlist = append(tlist, th)
vuln = true
case "Medium":
th := &threat{
Param: fmt.Sprintf("sidecar name: %s | env", container.Name),
Value: fmt.Sprintf("%s: %s", env.Name, env.Value),
Type: "Sidecar Env",
Describe: fmt.Sprintf("Container '%s' has found password '%s' "+
"need to be reinforeced.", container.Name, env.Value),
Severity: "medium",
}
tlist = append(tlist, th)
vuln = true
}
}
detect := maliciousContentCheck(env.Value)
th := &threat{
Param: fmt.Sprintf("sidecar name: %s | env", container.Name),
Value: fmt.Sprintf("%s: %s", env.Name, detect.Plain),
Type: "Sidecar Env",
}
switch detect.Types {
case Confusion:
th.Describe = fmt.Sprintf("Container '%s' finds high risk content(score: %.2f bigger than 0.75), "+
"which is a suspect command backdoor. ", container.Name, detect.Score)
th.Severity = "high"
tlist = append(tlist, th)
vuln = true
case Executable:
th.Describe = fmt.Sprintf("An executable format of content is detected in Container '%s', "+
"which is a potential backdoor and scanning the vulnerability is highly recommended.", container.Name)
th.Severity = "critical"
tlist = append(tlist, th)
vuln = true
default:
// ignore
}
}
// Check pod envFrom
for _, envFrom := range container.EnvFrom {
switch {
case envFrom.ConfigMapRef != nil:
configRef := envFrom.ConfigMapRef
configReg := regexp.MustCompile(`ConfigMap Name: (.*)? Namespace: (.*)`)
if ok, th := ks.checkConfigVulnType(ns, configRef.Name, "ConfigMap", configReg); ok {
th.Param = fmt.Sprintf("sidecar name: %s | env", container.Name)
tlist = append(tlist, th)
vuln = true
}
case envFrom.SecretRef != nil:
configRef := envFrom.SecretRef
configReg := regexp.MustCompile(`Secret Name: (.*)? Namespace: (.*)`)
if ok, th := ks.checkConfigVulnType(ns, configRef.Name, "Secret", configReg); ok {
th.Param = fmt.Sprintf("sidecar name: %s | env", container.Name)
tlist = append(tlist, th)
vuln = true
}
default:
//ignore
}
}
return vuln, tlist
}
func checkResourcesLimits(container v1.Container, volumes []v1.Volume) (bool, []*threat) {
var vuln = false
tlist := []*threat{}
if len(container.Resources.Limits) < 1 {
th := &threat{
Param: fmt.Sprintf("sidecar name: %s | "+
"Resource", container.Name),
Value: "memory, cpu, ephemeral-storage",
Type: "Sidecar Resource",
Describe: "None of resources is be limited.",
Reference: "https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/",
Severity: "low",
}
tlist = append(tlist, th)
vuln = true
return vuln, tlist
}
if container.Resources.Limits.Memory().String() == "0" {
th := &threat{
Param: fmt.Sprintf("sidecar name: %s | "+
"Resource", container.Name),
Value: "memory",
Type: "Sidecar Resource",
Describe: "Memory usage is not limited.",
Reference: "https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/",
Severity: "low",
}
tlist = append(tlist, th)
vuln = true
}
if container.Resources.Limits.Cpu().String() == "0" {
th := &threat{
Param: fmt.Sprintf("sidecar name: %s | "+
"Resource", container.Name),
Value: "cpu",
Type: "Sidecar Resource",
Describe: "CPU usage is not limited.",
Reference: "https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/",
Severity: "low",
}
tlist = append(tlist, th)
vuln = true
}
// Checking the correction of storage limit usage
if container.Resources.Limits.StorageEphemeral().String() != "0" {
podVolumes := container.VolumeMounts
for _, podV := range podVolumes {
for _, v := range volumes {
if v.HostPath != nil {
if podV.Name == v.Name {
th := &threat{
Param: fmt.Sprintf("sidecar name: %s | "+
"Resource", container.Name),
Value: "ephemeral-storage",
Type: "Sidecar Resource",
Describe: fmt.Sprintf("Ephemeral storage is used but in volumes '%s' with type hostpath, "+
"which limitation will not work.", v.Name),
Reference: "https://kubernetes.io/docs/concepts/storage/ephemeral-volumes/#types-of-ephemeral-volumes",
Severity: "low",
}
tlist = append(tlist, th)
vuln = true
break
}
}
}
}
}
return vuln, tlist
}
// checkPodAccountService check the default mount of service account
func checkPodAccountService(container v1.Container, rv RBACVuln) (bool, []*threat) {
var vuln = false
tlist := []*threat{}
for _, vc := range container.VolumeMounts {
if vc.MountPath == "/var/run/secrets/kubernetes.io/serviceaccount" {
th := &threat{
Param: fmt.Sprintf("sidecar name: %s | "+
"automountServiceAccountToken", container.Name),
Value: "true",
Type: vc.Name,
Describe: "Mount service account has a potential sensitive data leakage.",
Severity: "low",
}
switch rv.Severity {
case "high":
th.Severity = "critical"
th.Describe = fmt.Sprintf("Mount service account and key permission are given, "+
"which will cause a potential container escape. "+
"Reference clsuterRolebind: %s | roleBinding: %s",
rv.ClusterRoleBinding, rv.RoleBinding)
case "medium":
th.Severity = "high"
th.Describe = fmt.Sprintf("Mount service account and view permission are given, "+
"which will cause a sensitive data leakage. "+
"Reference clsuterRolebind: %s | roleBinding: %s",
rv.ClusterRoleBinding, rv.RoleBinding)
case "low":
th.Severity = "medium"
th.Describe = fmt.Sprintf("Mount service account and some permission are given, "+
"which will cause a potential data leakage. "+
"Reference clsuterRolebind: %s | roleBinding: %s",
rv.ClusterRoleBinding, rv.RoleBinding)
default:
//ignore
}
tlist = append(tlist, th)
vuln = true
}
}
return vuln, tlist
}
func checkPodAnnotation(ans map[string]string) (bool, []*threat) {
var vuln = false
tlist := []*threat{}
for k, v := range ans {
for n, t := range unsafeAnnotations {
if k == n {
if len(t.Values) > 0 {
for _, sv := range t.Values {
if strings.Contains(v, sv) {
th := &threat{
Param: fmt.Sprintf("pod annotation"),
Value: fmt.Sprintf("%s: %s", k, v),
Type: "Pod Annotation",
Describe: fmt.Sprintf("Pod Annotation has an unsafe config from %s"+
" and value is `%s`.", t.component, v),
Severity: t.level,
}
tlist = append(tlist, th)
vuln = true
break
}
}
} else {
th := &threat{
Param: fmt.Sprintf("pod annotation"),
Value: fmt.Sprintf("%s: %s", k, v),
Type: "Pod Annotation",
Describe: fmt.Sprintf("Pod Annotation detects unsafe annotation name from %s"+
" and value is `%s`, need to check.", t.component, v),
Severity: t.level,
}
tlist = append(tlist, th)
vuln = true
}
}
}
}
return vuln, tlist
}
func (ks *KScanner) checkPodCommand(container v1.Container, ns string) (bool, []*threat) {
var vuln = false
tlist := []*threat{}
comRex := regexp.MustCompile(`\$(\w+)`)
commands := strings.Join(container.Command, " ") + " "
commands += strings.Join(container.Args, " ")
comMatch := comRex.FindAllStringSubmatch(commands, -1)
if len(comMatch) > 1 {
for _, v := range comMatch[1:] {
val := ks.findEnvValue(container, v[1], ns)
detect := maliciousContentCheck(val)
switch detect.Types {
case Confusion:
th := &threat{
Param: "Pod command",
Value: fmt.Sprintf("command: %s", detect.Plain),
Type: "Pod Command",
Describe: fmt.Sprintf("Container command has found high risk environment in '%s'(score: %.2f bigger than 0.75), "+
"considering it as a backdoor.", v[0], detect.Score),
Severity: "high",
}
tlist = append(tlist, th)
vuln = true
return vuln, tlist
case Executable:
th := &threat{
Param: "Pod command",
Value: fmt.Sprintf("command: %s", detect.Plain),
Type: "Pod Command",
Describe: fmt.Sprintf("Container command has found executable risk environment in '%s', "+
"considering it as a backdoor.", v[0]),
Severity: "critical",
}
tlist = append(tlist, th)
vuln = true
return vuln, tlist
default:
// ignore
}
}
}
detect := maliciousContentCheck(commands)
switch detect.Types {
case Confusion:
th := &threat{
Param: "Pod command",
Value: fmt.Sprintf("command: %s", detect.Plain),
Type: "Pod Command",
Describe: fmt.Sprintf("Pod Command finds high risk content(score: %.2f bigger than 0.75), "+
"considering it as a backdoor.", detect.Score),
Severity: "high",
}
tlist = append(tlist, th)
vuln = true
case Executable:
th := &threat{
Param: "Pod command",
Value: fmt.Sprintf("command: %s", detect.Plain),
Type: "Pod Command",
Describe: "Container command is detected as a binary, " +
"considering it as a backdoor.",
Severity: "critical",
}
tlist = append(tlist, th)
vuln = true
default:
// ignore
}
return vuln, tlist
}
func (ks *KScanner) checkPodNodeSelector(podSpec v1.PodSpec) (bool, []*threat) {
var vuln = false
tlist := []*threat{}
if podSpec.NodeName != "" {
nodeName := podSpec.NodeName
if _, ok := ks.MasterNodes[nodeName]; ok {
if ks.MasterNodes[nodeName].IsMaster {
th := &threat{
Param: "Node Name",
Value: nodeName,
Type: "Pod Master NodeName",
Describe: "Pod is compulsively deployed in a master node.",
Severity: "low",
}
tlist = append(tlist, th)
vuln = true
}
}
}
for key, value := range podSpec.NodeSelector {
for _, node := range ks.MasterNodes {
if rv, ok := node.Role[key]; ok {
if value == rv && node.IsMaster {
th := &threat{
Param: fmt.Sprintf("nodeselector key: %s", key),
Value: value,
Type: "Pod NodeSelector",
Describe: "Pod is compulsively deployed in a master node.",
Severity: "low",
}
tlist = append(tlist, th)
vuln = true
break
}
}
}
}
return vuln, tlist
}