/
242451.go
238 lines (200 loc) · 7.98 KB
/
242451.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
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Gardener contributors
//
// SPDX-License-Identifier: Apache-2.0
package v1r11
import (
"cmp"
"context"
"fmt"
"slices"
"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"
sharedv1r11 "github.com/gardener/diki/pkg/shared/ruleset/disak8sstig/v1r11"
)
var _ rule.Rule = &Rule242451{}
type Rule242451 struct {
InstanceID string
Client client.Client
Namespace string
PodContext pod.PodContext
Options *option.FileOwnerOptions
Logger provider.Logger
}
func (r *Rule242451) ID() string {
return sharedv1r11.ID242451
}
func (r *Rule242451) Name() string {
return "The Kubernetes component PKI must be owned by root (MEDIUM 242451)"
}
func (r *Rule242451) Run(ctx context.Context) (rule.RuleResult, error) {
var (
checkResults []rule.CheckResult
options option.FileOwnerOptions
etcdMainSelector = labels.SelectorFromSet(labels.Set{"instance": "virtual-garden-etcd-main"})
etcdEventsSelector = labels.SelectorFromSet(labels.Set{"instance": "virtual-garden-etcd-events"})
deploymentNames = []string{"virtual-garden-kube-apiserver", "virtual-garden-kube-controller-manager"}
)
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"}
}
allPods, err := kubeutils.GetPods(ctx, r.Client, "", labels.NewSelector(), 300)
if err != nil {
return rule.SingleCheckResult(r, rule.ErroredCheckResult(err.Error(), rule.NewTarget("kind", "podList"))), nil
}
var (
checkPods []corev1.Pod
podSelectors = []labels.Selector{etcdMainSelector, etcdEventsSelector}
)
for _, podSelector := range podSelectors {
var 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!", rule.NewTarget("namespace", r.Namespace, "selector", podSelector.String())))
continue
}
checkPods = append(checkPods, pods...)
}
for _, deploymentName := range deploymentNames {
pods, err := kubeutils.GetDeploymentPods(ctx, r.Client, deploymentName, r.Namespace)
if err != nil {
checkResults = append(checkResults, rule.ErroredCheckResult(err.Error(), rule.NewTarget("kind", "podList")))
continue
}
if len(pods) == 0 {
checkResults = append(checkResults, rule.FailedCheckResult("Pods not found for deployment!", rule.NewTarget("name", deploymentName, "kind", "Deployment", "namespace", r.Namespace)))
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(), rule.NewTarget("kind", "nodeList"))), nil
}
nodesAllocatablePods := kubeutils.GetNodesAllocatablePodsNum(allPods, nodes)
groupedPods, checks := kubeutils.SelectPodOfReferenceGroup(checkPods, nodesAllocatablePods, rule.NewTarget())
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 {
checkResults = append(checkResults,
r.checkPods(ctx, pods, nodeName, image.String(), options)...)
}
return rule.RuleResult{
RuleID: r.ID(),
RuleName: r.Name(),
CheckResults: checkResults,
}, nil
}
func (r *Rule242451) checkPods(
ctx context.Context,
pods []corev1.Pod,
nodeName, imageName string,
options option.FileOwnerOptions,
) []rule.CheckResult {
var (
checkResults []rule.CheckResult
podName = fmt.Sprintf("diki-%s-%s", r.ID(), sharedv1r11.Generator.Generate(10))
execPodTarget = rule.NewTarget("name", podName, "namespace", "kube-system", "kind", "pod")
additionalLabels = map[string]string{pod.LabelInstanceID: r.InstanceID}
)
defer func() {
if err := r.PodContext.Delete(ctx, podName, "kube-system"); err != nil {
r.Logger.Error(err.Error())
}
}()
podExecutor, err := r.PodContext.Create(ctx, pod.NewPrivilegedPod(podName, "kube-system", imageName, nodeName, additionalLabels))
if err != nil {
return []rule.CheckResult{rule.ErroredCheckResult(err.Error(), execPodTarget)}
}
execPod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: podName,
Namespace: "kube-system",
},
}
if err := r.Client.Get(ctx, client.ObjectKeyFromObject(execPod), execPod); err != nil {
return []rule.CheckResult{rule.ErroredCheckResult(err.Error(), execPodTarget)}
}
var (
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)
)
slices.SortFunc(pods, func(a, b corev1.Pod) int {
return cmp.Compare(a.Name, b.Name)
})
for _, pod := range pods {
excludedSources := []string{"/lib/modules", "/usr/share/ca-certificates", "/var/log/journal", "/var/run/dbus/system_bus_socket"}
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 {
var (
delimiter = "\t"
pkiDirs = map[string]struct{}{}
containerTarget = rule.NewTarget("name", pod.Name, "namespace", pod.Namespace, "kind", "pod", "containerName", containerName)
)
// We iterate through a files matching certain suffixes and we check their permissions
// Directories that contain such files are saved so that they can be checked in the following for cycle
for _, fileStat := range fileStats {
if !strings.HasSuffix(fileStat.Path, ".key") && !strings.HasSuffix(fileStat.Path, ".pem") && !strings.HasSuffix(fileStat.Path, ".crt") {
continue
}
pkiDirs[fileStat.Dir()] = struct{}{}
checkResults = append(checkResults, intutils.MatchFileOwnersCases(fileStat, options.ExpectedFileOwner.Users, options.ExpectedFileOwner.Groups, containerTarget)...)
}
for dir := range pkiDirs {
dirStats, err := podExecutor.Execute(ctx, "/bin/sh", fmt.Sprintf(`stat -Lc "%%a%[1]s%%u%[1]s%%g%[1]s%%F%[1]s%%n" %s`, delimiter, dir))
if err != nil {
checkResults = append(checkResults, rule.ErroredCheckResult(err.Error(), execPodTarget))
continue
}
if len(dirStats) == 0 {
checkResults = append(checkResults, rule.ErroredCheckResult(fmt.Sprintf("could not find file %s", dir), execPodTarget))
continue
}
dirFilesStats := strings.Split(strings.TrimSpace(dirStats), "\n")
dirFileStats, err := intutils.NewFileStats(dirFilesStats[0], delimiter)
if err != nil {
checkResults = append(checkResults, rule.ErroredCheckResult(err.Error(), execPodTarget))
continue
}
checkResults = append(checkResults, intutils.MatchFileOwnersCases(dirFileStats, options.ExpectedFileOwner.Users, options.ExpectedFileOwner.Groups, containerTarget)...)
}
}
}
return checkResults
}