/
pod.go
319 lines (278 loc) Β· 7.66 KB
/
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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Popeye
package sanitize
import (
"context"
"sort"
"strings"
"github.com/rs/zerolog/log"
"k8s.io/apimachinery/pkg/labels"
"github.com/derailed/popeye/internal"
"github.com/derailed/popeye/internal/cache"
"github.com/derailed/popeye/internal/client"
"github.com/derailed/popeye/internal/issues"
v1 "k8s.io/api/core/v1"
policyv1 "k8s.io/api/policy/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
mv1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1"
)
const (
// SecNonRootUndefined denotes no root user set
SecNonRootUndefined NonRootUser = iota - 1
// SecNonRootUnset denotes root user
SecNonRootUnset = 0
// SecNonRootSet denotes non root user
SecNonRootSet = 1
)
// NonRootUser identifies if a security context for nonRootUser is set/unset or undefined.
type NonRootUser int
type (
// Pod represents a Pod linter.
Pod struct {
*issues.Collector
PodMXLister
}
// PdbLister list pdb matching a given selector
PdbLister interface {
ListPodDisruptionBudgets() map[string]*policyv1.PodDisruptionBudget
ForLabels(labels map[string]string) *policyv1.PodDisruptionBudget
}
// PodLister lists available pods.
PodLister interface {
ListPods() map[string]*v1.Pod
GetPod(ns string, sel map[string]string) *v1.Pod
}
// PodMXLister list available pods.
PodMXLister interface {
PodLimiter
PodMetricsLister
PodLister
PdbLister
ConfigLister
ListServiceAccounts() map[string]*v1.ServiceAccount
}
// PodMetric tracks node metrics available and current range.
PodMetric interface {
CurrentCPU() int64
CurrentMEM() int64
Empty() bool
}
)
// NewPod returns a new sanitizer.
func NewPod(co *issues.Collector, lister PodMXLister) *Pod {
return &Pod{
Collector: co,
PodMXLister: lister,
}
}
// Sanitize cleanse the resource..
func (p *Pod) Sanitize(ctx context.Context) error {
mx := p.ListPodsMetrics()
pdbs := p.ListPodDisruptionBudgets()
for fqn, po := range p.ListPods() {
p.InitOutcome(fqn)
ctx = internal.WithFQN(ctx, fqn)
p.checkStatus(ctx, po)
p.checkContainerStatus(ctx, po)
p.checkContainers(ctx, fqn, po)
p.checkOwnedByAnything(ctx, po.OwnerReferences)
if !ownedByDaemonSet(po) {
p.checkPdb(ctx, po.ObjectMeta.Labels)
}
p.checkForMultiplePdbMatches(ctx, po.Namespace, po.ObjectMeta.Labels, pdbs)
p.checkSecure(ctx, fqn, po.Spec)
pmx, cmx := mx[fqn], client.ContainerMetrics{}
containerMetrics(pmx, cmx)
p.checkUtilization(ctx, po, cmx)
if p.NoConcerns(fqn) && p.Config.ExcludeFQN(internal.MustExtractSectionGVR(ctx), fqn) {
p.ClearOutcome(fqn)
}
}
return nil
}
func ownedByDaemonSet(po *v1.Pod) bool {
for _, o := range po.OwnerReferences {
if o.Kind == "DaemonSet" {
return true
}
}
return false
}
func (p *Pod) checkOwnedByAnything(ctx context.Context, ownerRefs []metav1.OwnerReference) {
if len(ownerRefs) == 0 {
p.AddCode(ctx, 208)
return
}
controlled := false
for _, or := range ownerRefs {
if or.Controller != nil && *or.Controller {
controlled = true
break
}
}
if !controlled {
p.AddCode(ctx, 208)
}
}
func (p *Pod) checkPdb(ctx context.Context, labels map[string]string) {
if p.ForLabels(labels) == nil {
p.AddCode(ctx, 206)
}
}
func (p *Pod) checkUtilization(ctx context.Context, po *v1.Pod, cmx client.ContainerMetrics) {
if len(cmx) == 0 {
return
}
for _, co := range po.Spec.Containers {
cmx, ok := cmx[co.Name]
if !ok {
continue
}
NewContainer(internal.MustExtractFQN(ctx), p).checkUtilization(ctx, co, cmx)
}
}
func (p *Pod) checkSecure(ctx context.Context, fqn string, spec v1.PodSpec) {
ns, _ := namespaced(fqn)
if spec.ServiceAccountName == "default" {
p.AddCode(ctx, 300)
}
if p.PodMXLister != nil {
if sa, ok := p.ListServiceAccounts()[cache.FQN(ns, spec.ServiceAccountName)]; ok {
if spec.AutomountServiceAccountToken == nil {
if sa.AutomountServiceAccountToken == nil || *sa.AutomountServiceAccountToken {
p.AddCode(ctx, 301)
}
} else if *spec.AutomountServiceAccountToken {
p.AddCode(ctx, 301)
}
} else if spec.AutomountServiceAccountToken == nil || *spec.AutomountServiceAccountToken {
p.AddCode(ctx, 301)
}
}
if spec.SecurityContext == nil {
return
}
// If pod security ctx is present and we have
podSec := hasPodNonRootUser(spec.SecurityContext)
gvr := internal.MustExtractSectionGVR(ctx)
var victims int
for _, co := range spec.InitContainers {
if !p.Config.ExcludeContainer(gvr, fqn, co.Name) && !checkCOSecurityContext(co) && !podSec {
victims++
p.AddSubCode(internal.WithGroup(ctx, client.NewGVR("containers"), co.Name), 306)
}
}
for _, co := range spec.Containers {
if !p.Config.ExcludeContainer(gvr, fqn, co.Name) && !checkCOSecurityContext(co) && !podSec {
victims++
p.AddSubCode(internal.WithGroup(ctx, client.NewGVR("containers"), co.Name), 306)
}
}
if victims > 0 && !podSec {
p.AddCode(ctx, 302)
}
}
func checkCOSecurityContext(co v1.Container) bool {
return hasCoNonRootUser(co.SecurityContext)
}
func hasPodNonRootUser(sec *v1.PodSecurityContext) bool {
if sec == nil {
return false
}
if sec.RunAsNonRoot != nil {
return *sec.RunAsNonRoot
}
if sec.RunAsUser != nil {
return *sec.RunAsUser != 0
}
return false
}
func hasCoNonRootUser(sec *v1.SecurityContext) bool {
if sec == nil {
return false
}
if sec.RunAsNonRoot != nil {
return *sec.RunAsNonRoot
}
if sec.RunAsUser != nil {
return *sec.RunAsUser != 0
}
return false
}
func (p *Pod) checkContainers(ctx context.Context, fqn string, po *v1.Pod) {
co := NewContainer(internal.MustExtractFQN(ctx), p)
gvr := internal.MustExtractSectionGVR(ctx)
for _, c := range po.Spec.InitContainers {
if !p.Config.ExcludeContainer(gvr, fqn, c.Name) {
co.sanitize(ctx, c, false)
}
}
for _, c := range po.Spec.Containers {
if !p.Config.ExcludeContainer(gvr, fqn, c.Name) {
co.sanitize(ctx, c, !isPartOfJob(po))
}
}
}
func (p *Pod) checkContainerStatus(ctx context.Context, po *v1.Pod) {
limit := p.RestartsLimit()
for _, s := range po.Status.InitContainerStatuses {
cs := newContainerStatus(p, internal.MustExtractFQN(ctx), len(po.Status.InitContainerStatuses), true, limit)
cs.sanitize(ctx, s)
}
for _, s := range po.Status.ContainerStatuses {
cs := newContainerStatus(p, internal.MustExtractFQN(ctx), len(po.Status.ContainerStatuses), false, limit)
cs.sanitize(ctx, s)
}
}
func (p *Pod) checkStatus(ctx context.Context, po *v1.Pod) {
// nolint:exhaustive
switch po.Status.Phase {
case v1.PodRunning:
case v1.PodSucceeded:
default:
p.AddCode(ctx, 207, po.Status.Phase)
}
}
// ----------------------------------------------------------------------------
// Helpers...
func containerMetrics(pmx *mv1beta1.PodMetrics, mx client.ContainerMetrics) {
// No metrics -> Bail!
if pmx == nil {
return
}
for _, co := range pmx.Containers {
mx[co.Name] = client.Metrics{
CurrentCPU: *co.Usage.Cpu(),
CurrentMEM: *co.Usage.Memory(),
}
}
}
func isPartOfJob(po *v1.Pod) bool {
for _, o := range po.OwnerReferences {
if o.Kind == "Job" {
return true
}
}
return false
}
func (p *Pod) checkForMultiplePdbMatches(ctx context.Context, podNamespace string, podLabels map[string]string, pdbs map[string]*policyv1.PodDisruptionBudget) {
matchedPdbs := make([]string, 0, len(pdbs))
for _, pdb := range pdbs {
if podNamespace != pdb.Namespace {
continue
}
selector, err := metav1.LabelSelectorAsSelector(pdb.Spec.Selector)
if err != nil {
log.Error().Err(err).Msg("No selectors found")
return
}
if selector.Empty() || !selector.Matches(labels.Set(podLabels)) {
continue
}
matchedPdbs = append(matchedPdbs, pdb.Name)
}
if len(matchedPdbs) > 1 {
sort.Strings(matchedPdbs)
p.AddCode(ctx, 209, strings.Join(matchedPdbs, ", "))
}
}