/
dpi.go
504 lines (464 loc) · 16.7 KB
/
dpi.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
// Copyright (c) 2021-2023 Tigera, Inc. All rights reserved.
// 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 dpi
import (
"fmt"
relasticsearch "github.com/tigera/operator/pkg/render/common/elasticsearch"
"github.com/tigera/operator/pkg/tls/certificatemanagement"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"sigs.k8s.io/controller-runtime/pkg/client"
v3 "github.com/tigera/api/pkg/apis/projectcalico/v3"
operatorv1 "github.com/tigera/operator/api/v1"
"github.com/tigera/operator/pkg/common"
"github.com/tigera/operator/pkg/components"
"github.com/tigera/operator/pkg/render"
"github.com/tigera/operator/pkg/render/common/meta"
"github.com/tigera/operator/pkg/render/common/networkpolicy"
"github.com/tigera/operator/pkg/render/common/secret"
"github.com/tigera/operator/pkg/render/common/securitycontext"
)
const (
DeepPacketInspectionNamespace = "tigera-dpi"
DeepPacketInspectionName = "tigera-dpi"
DeepPacketInspectionPolicyName = networkpolicy.TigeraComponentPolicyPrefix + DeepPacketInspectionName
DefaultMemoryLimit = "1Gi"
DefaultMemoryRequest = "100Mi"
DefaultCPULimit = "1"
DefaultCPURequest = "100m"
DeepPacketInspectionLinseedRBACName = "tigera-dpi-linseed-permissions"
)
type DPIConfig struct {
IntrusionDetection *operatorv1.IntrusionDetection
Installation *operatorv1.InstallationSpec
TyphaNodeTLS *render.TyphaNodeTLS
PullSecrets []*corev1.Secret
Openshift bool
ManagedCluster bool
ManagementCluster bool
HasNoLicense bool
HasNoDPIResource bool
ClusterDomain string
DPICertSecret certificatemanagement.KeyPairInterface
}
func DPI(cfg *DPIConfig) render.Component {
return &dpiComponent{cfg: cfg}
}
type dpiComponent struct {
cfg *DPIConfig
dpiImage string
}
func (d *dpiComponent) ResolveImages(is *operatorv1.ImageSet) error {
var err error
d.dpiImage, err = components.GetReference(
components.ComponentDeepPacketInspection,
d.cfg.Installation.Registry,
d.cfg.Installation.ImagePath,
d.cfg.Installation.ImagePrefix,
is)
if err != nil {
return err
}
return nil
}
func (d *dpiComponent) Objects() (objsToCreate, objsToDelete []client.Object) {
var toCreate, toDelete []client.Object
if d.cfg.HasNoLicense {
toDelete = append(toDelete, render.CreateNamespace(DeepPacketInspectionNamespace, d.cfg.Installation.KubernetesProvider, render.PSSPrivileged))
} else {
toCreate = append(toCreate, render.CreateNamespace(DeepPacketInspectionNamespace, d.cfg.Installation.KubernetesProvider, render.PSSPrivileged))
}
// This secret is deprecated in this namespace and should be removed in upgrade scenarios
toDelete = append(toDelete, &corev1.Secret{
TypeMeta: metav1.TypeMeta{Kind: "Secret", APIVersion: "v1"},
ObjectMeta: metav1.ObjectMeta{Name: relasticsearch.PublicCertSecret, Namespace: DeepPacketInspectionNamespace},
})
if d.cfg.HasNoDPIResource || d.cfg.HasNoLicense {
toDelete = append(toDelete, d.dpiAllowTigeraPolicy())
toDelete = append(toDelete, secret.ToRuntimeObjects(secret.CopyToNamespace(DeepPacketInspectionNamespace, d.cfg.PullSecrets...)...)...)
toDelete = append(toDelete,
d.dpiServiceAccount(),
d.dpiClusterRole(),
d.dpiClusterRoleBinding(),
d.dpiDaemonset(),
)
} else {
toCreate = append(toCreate, d.dpiAllowTigeraPolicy())
toCreate = append(toCreate, secret.ToRuntimeObjects(secret.CopyToNamespace(DeepPacketInspectionNamespace)...)...)
toCreate = append(toCreate, secret.ToRuntimeObjects(secret.CopyToNamespace(DeepPacketInspectionNamespace, d.cfg.PullSecrets...)...)...)
toCreate = append(toCreate,
d.dpiServiceAccount(),
d.dpiClusterRole(),
d.dpiClusterRoleBinding(),
d.dpiDaemonset(),
)
}
if d.cfg.ManagementCluster {
// We always want to create these permissions when a management
// cluster is configured, to allow any DPI running inside a
// managed cluster to write data
toCreate = append(toCreate, d.dpiLinseedAccessClusterRole())
toCreate = append(toCreate, d.dpiLinseedAccessClusterRoleBinding())
} else if !d.cfg.ManagedCluster && !d.cfg.HasNoDPIResource && !d.cfg.HasNoLicense {
// We want to create these permissions when a standalone
// cluster is configured to run DPI
toCreate = append(toCreate, d.dpiLinseedAccessClusterRole())
toCreate = append(toCreate, d.dpiLinseedAccessClusterRoleBinding())
} else {
// We want to remove these permissions when a standalone
// cluster is no longer configured, to run DPI or for managed clusters
toDelete = append(toDelete,
d.dpiLinseedAccessClusterRole(),
d.dpiLinseedAccessClusterRoleBinding(),
)
}
if d.cfg.ManagedCluster {
// For managed clusters, we must create a role binding to allow Linseed to
// manage access token secrets in our namespace.
toCreate = append(toCreate, d.externalLinseedRoleBinding())
} else {
// We can delete the role binding for management and standalone clusters, since
// for these cluster types normal serviceaccount tokens are used.
toDelete = append(toDelete, d.externalLinseedRoleBinding())
}
return toCreate, toDelete
}
func (d *dpiComponent) Ready() bool {
return true
}
func (d *dpiComponent) SupportedOSType() meta.OSType {
return meta.OSTypeLinux
}
func (d *dpiComponent) dpiDaemonset() *appsv1.DaemonSet {
var terminationGracePeriod int64 = 0
var initContainers []corev1.Container
if d.cfg.TyphaNodeTLS.NodeSecret.UseCertificateManagement() {
initContainers = append(initContainers, d.cfg.TyphaNodeTLS.NodeSecret.InitContainer(DeepPacketInspectionNamespace))
}
podTemplate := &corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Annotations: d.dpiAnnotations(),
},
Spec: corev1.PodSpec{
Tolerations: meta.TolerateAll,
ImagePullSecrets: secret.GetReferenceList(d.cfg.PullSecrets),
ServiceAccountName: DeepPacketInspectionName,
TerminationGracePeriodSeconds: &terminationGracePeriod,
HostNetwork: true,
// Adjust DNS policy so we can access in-cluster services.
DNSPolicy: corev1.DNSClusterFirstWithHostNet,
InitContainers: initContainers,
Containers: []corev1.Container{d.dpiContainer()},
Volumes: d.dpiVolumes(),
},
}
return &appsv1.DaemonSet{
TypeMeta: metav1.TypeMeta{Kind: "DaemonSet", APIVersion: "apps/v1"},
ObjectMeta: metav1.ObjectMeta{
Name: DeepPacketInspectionName,
Namespace: DeepPacketInspectionNamespace,
},
Spec: appsv1.DaemonSetSpec{
Template: *podTemplate,
},
}
}
func (d *dpiComponent) dpiContainer() corev1.Container {
sc := securitycontext.NewRootContext(d.cfg.Openshift)
sc.Capabilities.Add = []corev1.Capability{
"NET_ADMIN",
"NET_RAW",
}
dpiContainer := corev1.Container{
Name: DeepPacketInspectionName,
Image: d.dpiImage,
ImagePullPolicy: render.ImagePullPolicy(),
Resources: *d.cfg.IntrusionDetection.Spec.ComponentResources[0].ResourceRequirements,
Env: d.dpiEnvVars(),
VolumeMounts: d.dpiVolumeMounts(),
// On OpenShift Snort needs privileged access to access host network
SecurityContext: sc,
ReadinessProbe: d.dpiReadinessProbes(),
}
return dpiContainer
}
func (d *dpiComponent) dpiVolumes() []corev1.Volume {
dirOrCreate := corev1.HostPathDirectoryOrCreate
volumes := []corev1.Volume{
d.cfg.DPICertSecret.Volume(),
d.cfg.TyphaNodeTLS.TrustedBundle.Volume(),
d.cfg.TyphaNodeTLS.NodeSecret.Volume(),
{
Name: "log-snort-alters",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/var/log/calico/snort-alerts",
Type: &dirOrCreate,
},
},
},
}
if d.cfg.ManagedCluster {
volumes = append(volumes,
corev1.Volume{
Name: render.LinseedTokenVolumeName,
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: fmt.Sprintf(render.LinseedTokenSecret, DeepPacketInspectionName),
Items: []corev1.KeyToPath{{Key: render.LinseedTokenKey, Path: render.LinseedTokenSubPath}},
},
},
})
}
return volumes
}
func (d *dpiComponent) dpiEnvVars() []corev1.EnvVar {
env := []corev1.EnvVar{
{
Name: "DPI_NODENAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{FieldPath: "spec.nodeName"},
},
},
{Name: "DPI_TYPHAK8SNAMESPACE", Value: common.CalicoNamespace},
{Name: "DPI_TYPHAK8SSERVICENAME", Value: render.TyphaServiceName},
{Name: "DPI_TYPHACAFILE", Value: d.cfg.TyphaNodeTLS.TrustedBundle.MountPath()},
{Name: "DPI_TYPHACERTFILE", Value: d.cfg.TyphaNodeTLS.NodeSecret.VolumeMountCertificateFilePath()},
{Name: "DPI_TYPHAKEYFILE", Value: d.cfg.TyphaNodeTLS.NodeSecret.VolumeMountKeyFilePath()},
{Name: "LINSEED_CLIENT_CERT", Value: d.cfg.DPICertSecret.VolumeMountCertificateFilePath()},
{Name: "LINSEED_CLIENT_KEY", Value: d.cfg.DPICertSecret.VolumeMountKeyFilePath()},
{Name: "LINSEED_TOKEN", Value: render.GetLinseedTokenPath(d.cfg.ManagedCluster)},
{Name: "FIPS_MODE_ENABLED", Value: operatorv1.IsFIPSModeEnabledString(d.cfg.Installation.FIPSMode)},
}
// We need at least the CN or URISAN set, we depend on the validation
// done by the core_controller that the Secret will have one.
if d.cfg.TyphaNodeTLS.TyphaCommonName != "" {
env = append(env, corev1.EnvVar{Name: "DPI_TYPHACN", Value: d.cfg.TyphaNodeTLS.TyphaCommonName})
}
if d.cfg.TyphaNodeTLS.TyphaURISAN != "" {
env = append(env, corev1.EnvVar{Name: "DPI_TYPHAURISAN", Value: d.cfg.TyphaNodeTLS.TyphaURISAN})
}
return env
}
func (d *dpiComponent) dpiVolumeMounts() []corev1.VolumeMount {
volumeMounts := append(
d.cfg.TyphaNodeTLS.TrustedBundle.VolumeMounts(d.SupportedOSType()),
d.cfg.TyphaNodeTLS.NodeSecret.VolumeMount(d.SupportedOSType()),
corev1.VolumeMount{MountPath: "/var/log/calico/snort-alerts", Name: "log-snort-alters"},
d.cfg.DPICertSecret.VolumeMount(d.SupportedOSType()),
)
if d.cfg.ManagedCluster {
volumeMounts = append(volumeMounts,
corev1.VolumeMount{
Name: render.LinseedTokenVolumeName,
MountPath: render.LinseedVolumeMountPath,
})
}
return volumeMounts
}
func (d *dpiComponent) dpiReadinessProbes() *corev1.Probe {
return &corev1.Probe{
ProbeHandler: corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Host: "localhost",
Path: "/readiness",
Port: intstr.FromInt(9097),
Scheme: corev1.URISchemeHTTP,
},
},
TimeoutSeconds: 10,
InitialDelaySeconds: 90,
}
}
func (d *dpiComponent) dpiServiceAccount() *corev1.ServiceAccount {
return &corev1.ServiceAccount{
TypeMeta: metav1.TypeMeta{Kind: "ServiceAccount", APIVersion: "v1"},
ObjectMeta: metav1.ObjectMeta{
Name: DeepPacketInspectionName,
Namespace: DeepPacketInspectionNamespace,
},
}
}
func (d *dpiComponent) dpiClusterRoleBinding() *rbacv1.ClusterRoleBinding {
return &rbacv1.ClusterRoleBinding{
TypeMeta: metav1.TypeMeta{Kind: "ClusterRoleBinding", APIVersion: "rbac.authorization.k8s.io/v1"},
ObjectMeta: metav1.ObjectMeta{
Name: DeepPacketInspectionName,
Labels: map[string]string{},
},
RoleRef: rbacv1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: DeepPacketInspectionName,
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: DeepPacketInspectionName,
Namespace: DeepPacketInspectionNamespace,
},
},
}
}
func (d *dpiComponent) dpiLinseedAccessClusterRoleBinding() *rbacv1.ClusterRoleBinding {
return &rbacv1.ClusterRoleBinding{
TypeMeta: metav1.TypeMeta{Kind: "ClusterRoleBinding", APIVersion: "rbac.authorization.k8s.io/v1"},
ObjectMeta: metav1.ObjectMeta{
Name: DeepPacketInspectionLinseedRBACName,
Labels: map[string]string{},
},
RoleRef: rbacv1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: DeepPacketInspectionLinseedRBACName,
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: DeepPacketInspectionName,
Namespace: DeepPacketInspectionNamespace,
},
},
}
}
func (d *dpiComponent) dpiClusterRole() *rbacv1.ClusterRole {
role := &rbacv1.ClusterRole{
TypeMeta: metav1.TypeMeta{Kind: "ClusterRole", APIVersion: "rbac.authorization.k8s.io/v1"},
ObjectMeta: metav1.ObjectMeta{
Name: DeepPacketInspectionName,
},
Rules: []rbacv1.PolicyRule{
{
APIGroups: []string{"crd.projectcalico.org"},
Resources: []string{
"deeppacketinspections",
},
Verbs: []string{"get", "list", "watch"},
},
{
// Used to update the DPI resource status
APIGroups: []string{"crd.projectcalico.org"},
Resources: []string{
"deeppacketinspections/status",
},
Verbs: []string{"update"},
},
{
// Used to discover Typha endpoints and service IPs for advertisement.
APIGroups: []string{""},
Resources: []string{"endpoints", "services"},
Verbs: []string{"watch", "list", "get"},
},
},
}
if d.cfg.Installation.KubernetesProvider != operatorv1.ProviderOpenShift {
// Allow access to the pod security policy in case this is enforced on the cluster
role.Rules = append(role.Rules, rbacv1.PolicyRule{
APIGroups: []string{"policy"},
Resources: []string{"podsecuritypolicies"},
Verbs: []string{"use"},
ResourceNames: []string{DeepPacketInspectionName},
})
}
return role
}
func (d *dpiComponent) dpiLinseedAccessClusterRole() *rbacv1.ClusterRole {
return &rbacv1.ClusterRole{
TypeMeta: metav1.TypeMeta{Kind: "ClusterRole", APIVersion: "rbac.authorization.k8s.io/v1"},
ObjectMeta: metav1.ObjectMeta{
Name: DeepPacketInspectionLinseedRBACName,
},
Rules: []rbacv1.PolicyRule{
{
// Add write access to Linseed APIs.
APIGroups: []string{"linseed.tigera.io"},
Resources: []string{"events"},
Verbs: []string{"create"},
},
},
}
}
func (d *dpiComponent) dpiAnnotations() map[string]string {
if d.cfg.HasNoDPIResource || d.cfg.HasNoLicense {
return nil
}
annotations := d.cfg.TyphaNodeTLS.TrustedBundle.HashAnnotations()
annotations[d.cfg.TyphaNodeTLS.NodeSecret.HashAnnotationKey()] = d.cfg.TyphaNodeTLS.NodeSecret.HashAnnotationValue()
annotations[d.cfg.DPICertSecret.HashAnnotationKey()] = d.cfg.DPICertSecret.HashAnnotationValue()
return annotations
}
func (c *dpiComponent) externalLinseedRoleBinding() *rbacv1.RoleBinding {
// For managed clusters, we must create a role binding to allow Linseed to manage access token secrets
// in our namespace.
linseed := "tigera-linseed"
return &rbacv1.RoleBinding{
TypeMeta: metav1.TypeMeta{Kind: "RoleBinding", APIVersion: "rbac.authorization.k8s.io/v1"},
ObjectMeta: metav1.ObjectMeta{
Name: linseed,
Namespace: DeepPacketInspectionNamespace,
},
RoleRef: rbacv1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: render.TigeraLinseedSecretsClusterRole,
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: linseed,
Namespace: render.ElasticsearchNamespace,
},
},
}
}
// This policy uses service selectors.
func (d *dpiComponent) dpiAllowTigeraPolicy() *v3.NetworkPolicy {
egressRules := []v3.Rule{
{
Action: v3.Allow,
Protocol: &networkpolicy.TCPProtocol,
Destination: networkpolicy.KubeAPIServerServiceSelectorEntityRule,
},
}
egressRules = networkpolicy.AppendServiceSelectorDNSEgressRules(egressRules, d.cfg.Openshift)
if d.cfg.ManagedCluster {
egressRules = append(egressRules, v3.Rule{
Action: v3.Allow,
Protocol: &networkpolicy.TCPProtocol,
Destination: render.GuardianServiceSelectorEntityRule,
})
} else {
egressRules = append(egressRules, v3.Rule{
Action: v3.Allow,
Protocol: &networkpolicy.TCPProtocol,
Destination: networkpolicy.Helper(false, render.ElasticsearchNamespace).LinseedServiceSelectorEntityRule(),
})
}
return &v3.NetworkPolicy{
TypeMeta: metav1.TypeMeta{Kind: "NetworkPolicy", APIVersion: "projectcalico.org/v3"},
ObjectMeta: metav1.ObjectMeta{
Name: DeepPacketInspectionPolicyName,
Namespace: DeepPacketInspectionNamespace,
},
Spec: v3.NetworkPolicySpec{
Order: &networkpolicy.HighPrecedenceOrder,
Tier: networkpolicy.TigeraComponentTierName,
Selector: networkpolicy.KubernetesAppSelector(DeepPacketInspectionName),
Types: []v3.PolicyType{v3.PolicyTypeEgress},
Egress: egressRules,
},
}
}