-
Notifications
You must be signed in to change notification settings - Fork 6
/
242445.go
172 lines (145 loc) · 5.68 KB
/
242445.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
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Gardener contributors
//
// SPDX-License-Identifier: Apache-2.0
package v1r11
import (
"context"
"fmt"
"strings"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/component-base/version"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/gardener/diki/imagevector"
intutils "github.com/gardener/diki/pkg/internal/utils"
"github.com/gardener/diki/pkg/kubernetes/pod"
kubeutils "github.com/gardener/diki/pkg/kubernetes/utils"
"github.com/gardener/diki/pkg/rule"
"github.com/gardener/diki/pkg/shared/images"
"github.com/gardener/diki/pkg/shared/provider"
"github.com/gardener/diki/pkg/shared/ruleset/disak8sstig/option"
)
var _ rule.Rule = &Rule242445{}
type Rule242445 struct {
InstanceID string
Client client.Client
Namespace string
PodContext pod.PodContext
ETCDMainSelector labels.Selector
ETCDEventsSelector labels.Selector
Options *option.FileOwnerOptions
Logger provider.Logger
}
func (r *Rule242445) ID() string {
return ID242445
}
func (r *Rule242445) Name() string {
return "The Kubernetes component etcd must be owned by etcd (MEDIUM 242445)"
}
func (r *Rule242445) Run(ctx context.Context) (rule.RuleResult, error) {
checkResults := []rule.CheckResult{}
etcdMainSelector := labels.SelectorFromSet(labels.Set{"instance": "etcd-main"})
etcdEventsSelector := labels.SelectorFromSet(labels.Set{"instance": "etcd-events"})
options := option.FileOwnerOptions{}
if r.Options != nil {
options = *r.Options
}
if len(options.ExpectedFileOwner.Users) == 0 {
options.ExpectedFileOwner.Users = []string{"0"}
}
if len(options.ExpectedFileOwner.Groups) == 0 {
options.ExpectedFileOwner.Groups = []string{"0"}
}
if r.ETCDMainSelector != nil {
etcdMainSelector = r.ETCDMainSelector
}
if r.ETCDEventsSelector != nil {
etcdEventsSelector = r.ETCDEventsSelector
}
target := rule.NewTarget()
allPods, err := kubeutils.GetPods(ctx, r.Client, "", labels.NewSelector(), 300)
if err != nil {
return rule.SingleCheckResult(r, rule.ErroredCheckResult(err.Error(), target.With("namespace", r.Namespace, "kind", "podList"))), nil
}
podSelectors := []labels.Selector{etcdMainSelector, etcdEventsSelector}
checkPods := []corev1.Pod{}
for _, podSelector := range podSelectors {
pods := []corev1.Pod{}
for _, p := range allPods {
if podSelector.Matches(labels.Set(p.Labels)) && p.Namespace == r.Namespace {
pods = append(pods, p)
}
}
if len(pods) == 0 {
checkResults = append(checkResults, rule.FailedCheckResult("Pods not found!", target.With("namespace", r.Namespace, "selector", podSelector.String())))
continue
}
checkPods = append(checkPods, pods...)
}
if len(checkPods) == 0 {
return rule.RuleResult{
RuleID: r.ID(),
RuleName: r.Name(),
CheckResults: checkResults,
}, nil
}
nodes, err := kubeutils.GetNodes(ctx, r.Client, 300)
if err != nil {
return rule.SingleCheckResult(r, rule.ErroredCheckResult(err.Error(), target.With("kind", "nodeList"))), nil
}
nodesAllocatablePods := kubeutils.GetNodesAllocatablePodsNum(allPods, nodes)
groupedPods, checks := kubeutils.SelectPodOfReferenceGroup(checkPods, nodesAllocatablePods, target)
checkResults = append(checkResults, checks...)
image, err := imagevector.ImageVector().FindImage(images.DikiOpsImageName)
if err != nil {
return rule.RuleResult{}, fmt.Errorf("failed to find image version for %s: %w", images.DikiOpsImageName, err)
}
image.WithOptionalTag(version.Get().GitVersion)
for nodeName, pods := range groupedPods {
podName := fmt.Sprintf("diki-%s-%s", r.ID(), Generator.Generate(10))
execPodTarget := target.With("name", podName, "namespace", "kube-system", "kind", "pod")
defer func() {
if err := r.PodContext.Delete(ctx, podName, "kube-system"); err != nil {
r.Logger.Error(err.Error())
}
}()
additionalLabels := map[string]string{pod.LabelInstanceID: r.InstanceID}
podExecutor, err := r.PodContext.Create(ctx, pod.NewPrivilegedPod(podName, "kube-system", image.String(), nodeName, additionalLabels))
if err != nil {
checkResults = append(checkResults, rule.ErroredCheckResult(err.Error(), execPodTarget))
continue
}
execPod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: podName,
Namespace: "kube-system",
},
}
if err := r.Client.Get(ctx, client.ObjectKeyFromObject(execPod), execPod); err != nil {
checkResults = append(checkResults, rule.ErroredCheckResult(err.Error(), execPodTarget))
continue
}
execContainerID := execPod.Status.ContainerStatuses[0].ContainerID
execBaseContainerID := strings.Split(execContainerID, "//")[1]
execContainerPath := fmt.Sprintf("/run/containerd/io.containerd.runtime.v2.task/k8s.io/%s/rootfs", execBaseContainerID)
for _, pod := range pods {
excludedSources := []string{"/lib/modules", "/usr/share/ca-certificates", "/var/log/journal"}
mappedFileStats, err := intutils.GetMountedFilesStats(ctx, execContainerPath, podExecutor, pod, excludedSources)
if err != nil {
checkResults = append(checkResults, rule.ErroredCheckResult(err.Error(), execPodTarget))
}
for containerName, fileStats := range mappedFileStats {
for _, fileStat := range fileStats {
containerTarget := rule.NewTarget("name", pod.Name, "namespace", pod.Namespace, "kind", "pod", "containerName", containerName)
checkResults = append(checkResults, intutils.MatchFileOwnersCases(fileStat, options.ExpectedFileOwner.Users, options.ExpectedFileOwner.Groups, containerTarget)...)
}
}
}
}
return rule.RuleResult{
RuleID: r.ID(),
RuleName: r.Name(),
CheckResults: checkResults,
}, nil
}