• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

noironetworks / aci-containers / 10544

09 Apr 2025 03:01PM UTC coverage: 69.055% (+0.01%) from 69.045%
10544

push

travis-pro

web-flow
Merge pull request #1509 from noironetworks/cni_version_fix

Added fix to support CNI version 1.0.0 from OCP 4.16

13320 of 19289 relevant lines covered (69.05%)

0.79 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

79.86
/pkg/controller/network_policy.go
1
// Copyright 2017 Cisco Systems, Inc.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15
// Handlers for network policy updates.  Generate ACI security groups
16
// based on Kubernetes network policies.
17

18
package controller
19

20
import (
21
        "bytes"
22
        "context"
23
        "fmt"
24
        "net"
25
        "os"
26
        "reflect"
27
        "slices"
28
        "sort"
29
        "strconv"
30
        "strings"
31

32
        "github.com/sirupsen/logrus"
33
        "github.com/yl2chen/cidranger"
34

35
        v1 "k8s.io/api/core/v1"
36
        v1net "k8s.io/api/networking/v1"
37
        "k8s.io/apimachinery/pkg/api/errors"
38
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
39
        "k8s.io/apimachinery/pkg/fields"
40
        "k8s.io/apimachinery/pkg/labels"
41
        "k8s.io/apimachinery/pkg/util/intstr"
42
        "k8s.io/client-go/kubernetes"
43
        "k8s.io/client-go/tools/cache"
44
        k8util "k8s.io/kubectl/pkg/util"
45

46
        "github.com/noironetworks/aci-containers/pkg/apicapi"
47
        hppv1 "github.com/noironetworks/aci-containers/pkg/hpp/apis/aci.hpp/v1"
48
        hppclset "github.com/noironetworks/aci-containers/pkg/hpp/clientset/versioned"
49
        "github.com/noironetworks/aci-containers/pkg/index"
50
        "github.com/noironetworks/aci-containers/pkg/ipam"
51
        "github.com/noironetworks/aci-containers/pkg/util"
52
        discovery "k8s.io/api/discovery/v1"
53
)
54

55
func (cont *AciController) initNetworkPolicyInformerFromClient(
56
        kubeClient kubernetes.Interface) {
×
57
        cont.initNetworkPolicyInformerBase(
×
58
                cache.NewListWatchFromClient(
×
59
                        kubeClient.NetworkingV1().RESTClient(), "networkpolicies",
×
60
                        metav1.NamespaceAll, fields.Everything()))
×
61
}
×
62

63
func (cont *AciController) initNetworkPolicyInformerBase(listWatch *cache.ListWatch) {
1✔
64
        cont.networkPolicyIndexer, cont.networkPolicyInformer =
1✔
65
                cache.NewIndexerInformer(
1✔
66
                        listWatch, &v1net.NetworkPolicy{}, 0,
1✔
67
                        cache.ResourceEventHandlerFuncs{
1✔
68
                                AddFunc: func(obj interface{}) {
2✔
69
                                        cont.networkPolicyAdded(obj)
1✔
70
                                },
1✔
71
                                UpdateFunc: func(oldobj interface{}, newobj interface{}) {
×
72
                                        cont.networkPolicyChanged(oldobj, newobj)
×
73
                                },
×
74
                                DeleteFunc: func(obj interface{}) {
1✔
75
                                        cont.networkPolicyDeleted(obj)
1✔
76
                                },
1✔
77
                        },
78
                        cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
79
                )
80
}
81

82
func (cont *AciController) peerPodSelector(np *v1net.NetworkPolicy,
83
        peers []v1net.NetworkPolicyPeer) []index.PodSelector {
1✔
84
        var ret []index.PodSelector
1✔
85
        for _, peer := range peers {
2✔
86
                podselector, err :=
1✔
87
                        metav1.LabelSelectorAsSelector(peer.PodSelector)
1✔
88
                if err != nil {
1✔
89
                        networkPolicyLogger(cont.log, np).
×
90
                                Error("Could not create selector: ", err)
×
91
                        continue
×
92
                }
93
                nsselector, err := metav1.
1✔
94
                        LabelSelectorAsSelector(peer.NamespaceSelector)
1✔
95
                if err != nil {
1✔
96
                        networkPolicyLogger(cont.log, np).
×
97
                                Error("Could not create selector: ", err)
×
98
                        continue
×
99
                }
100

101
                switch {
1✔
102
                case peer.PodSelector != nil && peer.NamespaceSelector != nil:
1✔
103
                        ret = append(ret, index.PodSelector{
1✔
104
                                NsSelector:  nsselector,
1✔
105
                                PodSelector: podselector,
1✔
106
                        })
1✔
107
                case peer.PodSelector != nil:
1✔
108
                        ret = append(ret, index.PodSelector{
1✔
109
                                Namespace:   &np.ObjectMeta.Namespace,
1✔
110
                                PodSelector: podselector,
1✔
111
                        })
1✔
112
                case peer.NamespaceSelector != nil:
1✔
113
                        ret = append(ret, index.PodSelector{
1✔
114
                                NsSelector:  nsselector,
1✔
115
                                PodSelector: labels.Everything(),
1✔
116
                        })
1✔
117
                }
118
        }
119
        return ret
1✔
120
}
121

122
func (cont *AciController) egressPodSelector(np *v1net.NetworkPolicy) []index.PodSelector {
1✔
123
        var ret []index.PodSelector
1✔
124

1✔
125
        for _, egress := range np.Spec.Egress {
2✔
126
                ret = append(ret, cont.peerPodSelector(np, egress.To)...)
1✔
127
        }
1✔
128

129
        return ret
1✔
130
}
131

132
func (cont *AciController) ingressPodSelector(np *v1net.NetworkPolicy) []index.PodSelector {
1✔
133
        var ret []index.PodSelector
1✔
134

1✔
135
        for _, ingress := range np.Spec.Ingress {
2✔
136
                ret = append(ret, cont.peerPodSelector(np, ingress.From)...)
1✔
137
        }
1✔
138

139
        return ret
1✔
140
}
141

142
func (cont *AciController) initNetPolPodIndex() {
1✔
143
        cont.netPolPods = index.NewPodSelectorIndex(
1✔
144
                cont.log,
1✔
145
                cont.podIndexer, cont.namespaceIndexer, cont.networkPolicyIndexer,
1✔
146
                cache.MetaNamespaceKeyFunc,
1✔
147
                func(obj interface{}) []index.PodSelector {
2✔
148
                        np := obj.(*v1net.NetworkPolicy)
1✔
149
                        return index.PodSelectorFromNsAndSelector(np.ObjectMeta.Namespace,
1✔
150
                                &np.Spec.PodSelector)
1✔
151
                },
1✔
152
        )
153
        cont.netPolPods.SetPodUpdateCallback(func(podkey string) {
2✔
154
                podobj, exists, err := cont.podIndexer.GetByKey(podkey)
1✔
155
                if exists && err == nil {
2✔
156
                        cont.queuePodUpdate(podobj.(*v1.Pod))
1✔
157
                }
1✔
158
        })
159

160
        cont.netPolIngressPods = index.NewPodSelectorIndex(
1✔
161
                cont.log,
1✔
162
                cont.podIndexer, cont.namespaceIndexer, cont.networkPolicyIndexer,
1✔
163
                cache.MetaNamespaceKeyFunc,
1✔
164
                func(obj interface{}) []index.PodSelector {
2✔
165
                        return cont.ingressPodSelector(obj.(*v1net.NetworkPolicy))
1✔
166
                },
1✔
167
        )
168
        cont.netPolEgressPods = index.NewPodSelectorIndex(
1✔
169
                cont.log,
1✔
170
                cont.podIndexer, cont.namespaceIndexer, cont.networkPolicyIndexer,
1✔
171
                cache.MetaNamespaceKeyFunc,
1✔
172
                func(obj interface{}) []index.PodSelector {
2✔
173
                        return cont.egressPodSelector(obj.(*v1net.NetworkPolicy))
1✔
174
                },
1✔
175
        )
176
        npupdate := func(npkey string) {
2✔
177
                npobj, exists, err := cont.networkPolicyIndexer.GetByKey(npkey)
1✔
178
                if exists && err == nil {
2✔
179
                        cont.queueNetPolUpdate(npobj.(*v1net.NetworkPolicy))
1✔
180
                }
1✔
181
        }
182
        nphash := func(pod *v1.Pod) string {
2✔
183
                return pod.Status.PodIP
1✔
184
        }
1✔
185

186
        remipupdate := func(pod *v1.Pod, deleted bool) {
2✔
187
                cont.queueRemoteIpConUpdate(pod, deleted)
1✔
188
        }
1✔
189

190
        cont.netPolIngressPods.SetObjUpdateCallback(npupdate)
1✔
191
        cont.netPolIngressPods.SetRemIpUpdateCallback(remipupdate)
1✔
192
        cont.netPolIngressPods.SetPodHashFunc(nphash)
1✔
193
        cont.netPolEgressPods.SetObjUpdateCallback(npupdate)
1✔
194
        cont.netPolEgressPods.SetRemIpUpdateCallback(remipupdate)
1✔
195
        cont.netPolEgressPods.SetPodHashFunc(nphash)
1✔
196
}
197

198
func (cont *AciController) staticNetPolObjs() apicapi.ApicSlice {
1✔
199
        hppIngress :=
1✔
200
                apicapi.NewHostprotPol(cont.config.AciPolicyTenant,
1✔
201
                        cont.aciNameForKey("np", "static-ingress"))
1✔
202
        {
2✔
203
                ingressSubj := apicapi.NewHostprotSubj(hppIngress.GetDn(), "ingress")
1✔
204
                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
205
                        outbound := apicapi.NewHostprotRule(ingressSubj.GetDn(),
1✔
206
                                "allow-all-reflexive-v6")
1✔
207
                        outbound.SetAttr("direction", "ingress")
1✔
208
                        outbound.SetAttr("ethertype", "ipv6")
1✔
209
                        ingressSubj.AddChild(outbound)
1✔
210
                }
1✔
211
                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
212
                        outbound := apicapi.NewHostprotRule(ingressSubj.GetDn(),
1✔
213
                                "allow-all-reflexive")
1✔
214
                        outbound.SetAttr("direction", "ingress")
1✔
215
                        outbound.SetAttr("ethertype", "ipv4")
1✔
216
                        ingressSubj.AddChild(outbound)
1✔
217
                }
1✔
218
                hppIngress.AddChild(ingressSubj)
1✔
219
        }
220

221
        hppEgress :=
1✔
222
                apicapi.NewHostprotPol(cont.config.AciPolicyTenant,
1✔
223
                        cont.aciNameForKey("np", "static-egress"))
1✔
224
        {
2✔
225
                egressSubj := apicapi.NewHostprotSubj(hppEgress.GetDn(), "egress")
1✔
226
                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
227
                        outbound := apicapi.NewHostprotRule(egressSubj.GetDn(),
1✔
228
                                "allow-all-reflexive-v6")
1✔
229
                        outbound.SetAttr("direction", "egress")
1✔
230
                        outbound.SetAttr("ethertype", "ipv6")
1✔
231
                        egressSubj.AddChild(outbound)
1✔
232
                }
1✔
233
                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
234
                        outbound := apicapi.NewHostprotRule(egressSubj.GetDn(),
1✔
235
                                "allow-all-reflexive")
1✔
236
                        outbound.SetAttr("direction", "egress")
1✔
237
                        outbound.SetAttr("ethertype", "ipv4")
1✔
238
                        egressSubj.AddChild(outbound)
1✔
239
                }
1✔
240
                hppEgress.AddChild(egressSubj)
1✔
241
        }
242

243
        hppDiscovery :=
1✔
244
                apicapi.NewHostprotPol(cont.config.AciPolicyTenant,
1✔
245
                        cont.aciNameForKey("np", "static-discovery"))
1✔
246
        {
2✔
247
                discSubj := apicapi.NewHostprotSubj(hppDiscovery.GetDn(), "discovery")
1✔
248
                discDn := discSubj.GetDn()
1✔
249
                {
2✔
250
                        arpin := apicapi.NewHostprotRule(discDn, "arp-ingress")
1✔
251
                        arpin.SetAttr("direction", "ingress")
1✔
252
                        arpin.SetAttr("ethertype", "arp")
1✔
253
                        arpin.SetAttr("connTrack", "normal")
1✔
254
                        discSubj.AddChild(arpin)
1✔
255
                }
1✔
256
                {
1✔
257
                        arpout := apicapi.NewHostprotRule(discDn, "arp-egress")
1✔
258
                        arpout.SetAttr("direction", "egress")
1✔
259
                        arpout.SetAttr("ethertype", "arp")
1✔
260
                        arpout.SetAttr("connTrack", "normal")
1✔
261
                        discSubj.AddChild(arpout)
1✔
262
                }
1✔
263
                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
264
                        icmpin := apicapi.NewHostprotRule(discDn, "icmp-ingress")
1✔
265
                        icmpin.SetAttr("direction", "ingress")
1✔
266
                        icmpin.SetAttr("ethertype", "ipv4")
1✔
267
                        icmpin.SetAttr("protocol", "icmp")
1✔
268
                        icmpin.SetAttr("connTrack", "normal")
1✔
269
                        discSubj.AddChild(icmpin)
1✔
270
                }
1✔
271

272
                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
273
                        icmpin := apicapi.NewHostprotRule(discDn, "icmpv6-ingress")
1✔
274
                        icmpin.SetAttr("direction", "ingress")
1✔
275
                        icmpin.SetAttr("ethertype", "ipv6")
1✔
276
                        icmpin.SetAttr("protocol", "icmpv6")
1✔
277
                        icmpin.SetAttr("connTrack", "normal")
1✔
278
                        discSubj.AddChild(icmpin)
1✔
279
                }
1✔
280
                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
281
                        icmpout := apicapi.NewHostprotRule(discDn, "icmp-egress")
1✔
282
                        icmpout.SetAttr("direction", "egress")
1✔
283
                        icmpout.SetAttr("ethertype", "ipv4")
1✔
284
                        icmpout.SetAttr("protocol", "icmp")
1✔
285
                        icmpout.SetAttr("connTrack", "normal")
1✔
286
                        discSubj.AddChild(icmpout)
1✔
287
                }
1✔
288

289
                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
290
                        icmpout := apicapi.NewHostprotRule(discDn, "icmpv6-egress")
1✔
291
                        icmpout.SetAttr("direction", "egress")
1✔
292
                        icmpout.SetAttr("ethertype", "ipv6")
1✔
293
                        icmpout.SetAttr("protocol", "icmpv6")
1✔
294
                        icmpout.SetAttr("connTrack", "normal")
1✔
295
                        discSubj.AddChild(icmpout)
1✔
296
                }
1✔
297

298
                hppDiscovery.AddChild(discSubj)
1✔
299
        }
300

301
        return apicapi.ApicSlice{hppIngress, hppEgress, hppDiscovery}
1✔
302
}
303

304
func (cont *AciController) getHppClient() (hppclset.Interface, bool) {
1✔
305
        env := cont.env.(*K8sEnvironment)
1✔
306
        hppcl := env.hppClient
1✔
307
        if hppcl == nil {
2✔
308
                cont.log.Error("hpp client not found")
1✔
309
                return nil, false
1✔
310
        }
1✔
311
        return hppcl, true
1✔
312
}
313

314
func (cont *AciController) validateHppCr(hpp *hppv1.HostprotPol) bool {
1✔
315
        allowedProtocols := map[string]bool{
1✔
316
                "tcp":         true,
1✔
317
                "udp":         true,
1✔
318
                "icmp":        true,
1✔
319
                "icmpv6":      true,
1✔
320
                "unspecified": true,
1✔
321
        }
1✔
322

1✔
323
        for _, subj := range hpp.Spec.HostprotSubj {
2✔
324
                for _, rule := range subj.HostprotRule {
2✔
325
                        if rule.Protocol != "" {
2✔
326
                                if !allowedProtocols[rule.Protocol] {
1✔
327
                                        cont.log.Error("unknown protocol value: ", rule.Protocol, ", hostprotPol CR: ", hpp)
×
328
                                        return false
×
329
                                }
×
330
                        }
331
                }
332
        }
333
        return true
1✔
334
}
335

336
func (cont *AciController) createHostprotPol(hpp *hppv1.HostprotPol, ns string) bool {
1✔
337
        if !cont.validateHppCr(hpp) {
1✔
338
                return false
×
339
        }
×
340
        hppcl, ok := cont.getHppClient()
1✔
341
        if !ok {
2✔
342
                return false
1✔
343
        }
1✔
344

345
        cont.log.Debug("Creating HPP CR: ", hpp)
1✔
346
        _, err := hppcl.AciV1().HostprotPols(ns).Create(context.TODO(), hpp, metav1.CreateOptions{})
1✔
347
        if err != nil {
1✔
348
                cont.log.Error("Error creating HPP CR: ", err)
×
349
                return false
×
350
        }
×
351

352
        return true
1✔
353
}
354

355
func (cont *AciController) updateHostprotPol(hpp *hppv1.HostprotPol, ns string) bool {
1✔
356
        if !cont.validateHppCr(hpp) {
1✔
357
                cont.deleteHostprotPol(hpp.Name, hpp.Namespace)
×
358
                return false
×
359
        }
×
360
        hppcl, ok := cont.getHppClient()
1✔
361
        if !ok {
2✔
362
                return false
1✔
363
        }
1✔
364

365
        cont.log.Debug("Updating HPP CR: ", hpp)
1✔
366
        _, err := hppcl.AciV1().HostprotPols(ns).Update(context.TODO(), hpp, metav1.UpdateOptions{})
1✔
367
        if err != nil {
1✔
368
                cont.log.Error("Error updating HPP CR: ", err)
×
369
                return false
×
370
        }
×
371

372
        return true
1✔
373
}
374

375
func (cont *AciController) deleteAllHostprotPol() error {
1✔
376
        sysNs := os.Getenv("SYSTEM_NAMESPACE")
1✔
377
        hppcl, ok := cont.getHppClient()
1✔
378
        if !ok {
1✔
379
                cont.log.Error("Failed to delete HostprotPol CRs")
×
380
                return fmt.Errorf("HppClient not initialized")
×
381
        }
×
382

383
        cont.log.Debug("Deleting all HostprotPol CRs")
1✔
384
        err := hppcl.AciV1().HostprotPols(sysNs).DeleteCollection(context.TODO(), metav1.DeleteOptions{}, metav1.ListOptions{})
1✔
385
        if err != nil {
1✔
386
                cont.log.Error("Failed to delete HostprotPol CRs: ", err)
×
387
        }
×
388
        return err
1✔
389
}
390

391
func (cont *AciController) deleteHostprotPol(hppName string, ns string) bool {
1✔
392
        hppcl, ok := cont.getHppClient()
1✔
393
        if !ok {
2✔
394
                return false
1✔
395
        }
1✔
396

397
        cont.log.Debug("Deleting HPP CR: ", hppName)
1✔
398
        err := hppcl.AciV1().HostprotPols(ns).Delete(context.TODO(), hppName, metav1.DeleteOptions{})
1✔
399
        if err != nil {
1✔
400
                cont.log.Error("Error deleting HPP CR: ", err)
×
401
                return false
×
402
        }
×
403

404
        return true
1✔
405
}
406

407
func (cont *AciController) getHostprotPol(hppName string, ns string) (*hppv1.HostprotPol, error) {
1✔
408
        hppcl, ok := cont.getHppClient()
1✔
409
        if !ok {
2✔
410
                return nil, fmt.Errorf("hpp client not found")
1✔
411
        }
1✔
412

413
        hpp, err := hppcl.AciV1().HostprotPols(ns).Get(context.TODO(), hppName, metav1.GetOptions{})
1✔
414
        if err != nil {
2✔
415
                return nil, err
1✔
416
        }
1✔
417
        cont.log.Debug("HPP CR found: ", hpp)
1✔
418
        return hpp, nil
1✔
419
}
420

421
func (cont *AciController) getHostprotRemoteIpContainer(name, ns string) (*hppv1.HostprotRemoteIpContainer, error) {
1✔
422
        hppcl, ok := cont.getHppClient()
1✔
423
        if !ok {
2✔
424
                return nil, fmt.Errorf("hpp client not found")
1✔
425
        }
1✔
426

427
        hpp, err := hppcl.AciV1().HostprotRemoteIpContainers(ns).Get(context.TODO(), name, metav1.GetOptions{})
1✔
428
        if err != nil {
2✔
429
                cont.log.Error("Error getting HostprotRemoteIpContainers CR: ", err)
1✔
430
                return nil, err
1✔
431
        }
1✔
432
        cont.log.Debug("HostprotRemoteIpContainers CR found: ", hpp)
1✔
433
        return hpp, nil
1✔
434
}
435

436
func (cont *AciController) createHostprotRemoteIpContainer(hppIpCont *hppv1.HostprotRemoteIpContainer, ns string) bool {
1✔
437
        hppcl, ok := cont.getHppClient()
1✔
438
        if !ok {
2✔
439
                return false
1✔
440
        }
1✔
441

442
        cont.log.Debug("Creating HostprotRemoteIpContainer CR: ", hppIpCont)
1✔
443
        _, err := hppcl.AciV1().HostprotRemoteIpContainers(ns).Create(context.TODO(), hppIpCont, metav1.CreateOptions{})
1✔
444
        if err != nil {
1✔
445
                cont.log.Error("Error creating HostprotRemoteIpContainer CR: ", err)
×
446
                return false
×
447
        }
×
448

449
        return true
1✔
450
}
451

452
func (cont *AciController) updateHostprotRemoteIpContainer(hppIpCont *hppv1.HostprotRemoteIpContainer, ns string) bool {
1✔
453
        hppcl, ok := cont.getHppClient()
1✔
454
        if !ok {
2✔
455
                return false
1✔
456
        }
1✔
457

458
        cont.log.Debug("Updating HostprotRemoteIpContainer CR: ", hppIpCont)
1✔
459
        _, err := hppcl.AciV1().HostprotRemoteIpContainers(ns).Update(context.TODO(), hppIpCont, metav1.UpdateOptions{})
1✔
460
        if err != nil {
1✔
461
                cont.log.Error("Error updating HostprotRemoteIpContainer CR: ", err)
×
462
                return false
×
463
        }
×
464

465
        return true
1✔
466
}
467

468
func (cont *AciController) deleteAllHostprotRemoteIpContainers() error {
1✔
469
        sysNs := os.Getenv("SYSTEM_NAMESPACE")
1✔
470
        hppcl, ok := cont.getHppClient()
1✔
471
        if !ok {
1✔
472
                cont.log.Error("Failed to delete HostprotRemoteIpContainer CRs")
×
473
                return fmt.Errorf("HppClient not initialized")
×
474
        }
×
475

476
        cont.log.Debug("Deleting all HostprotRemoteIpContainer CRs")
1✔
477
        err := hppcl.AciV1().HostprotRemoteIpContainers(sysNs).DeleteCollection(context.TODO(), metav1.DeleteOptions{}, metav1.ListOptions{})
1✔
478
        if err != nil {
1✔
479
                cont.log.Error("Failed to delete HostprotRemoteIpContainer CRs: ", err)
×
480
        }
×
481
        return err
1✔
482
}
483

484
func (cont *AciController) deleteHostprotRemoteIpContainer(hppIpContName string, ns string) bool {
1✔
485
        hppcl, ok := cont.getHppClient()
1✔
486
        if !ok {
2✔
487
                return false
1✔
488
        }
1✔
489

490
        cont.log.Debug("Deleting HostprotRemoteIpContainer CR: ", hppIpContName)
1✔
491
        err := hppcl.AciV1().HostprotRemoteIpContainers(ns).Delete(context.TODO(), hppIpContName, metav1.DeleteOptions{})
1✔
492
        if err != nil {
1✔
493
                cont.log.Error("Error deleting HostprotRemoteIpContainer CR: ", err)
×
494
                return false
×
495
        }
×
496

497
        return true
1✔
498
}
499

500
func (cont *AciController) listHostprotPol(ns string) (*hppv1.HostprotPolList, error) {
1✔
501
        hppcl, ok := cont.getHppClient()
1✔
502
        if !ok {
1✔
503
                return nil, fmt.Errorf("hpp client not found")
×
504
        }
×
505

506
        hpps, err := hppcl.AciV1().HostprotPols(ns).List(context.TODO(), metav1.ListOptions{})
1✔
507
        if err != nil {
2✔
508
                cont.log.Error("Error listing HPP CR: ", err)
1✔
509
                return nil, err
1✔
510
        }
1✔
511
        return hpps, nil
×
512
}
513

514
func (cont *AciController) listHostprotRemoteIpContainers(ns string) (*hppv1.HostprotRemoteIpContainerList, error) {
1✔
515
        hppcl, ok := cont.getHppClient()
1✔
516
        if !ok {
1✔
517
                return nil, fmt.Errorf("hpp client not found")
×
518
        }
×
519

520
        hpRemoteIpConts, err := hppcl.AciV1().HostprotRemoteIpContainers(ns).List(context.TODO(), metav1.ListOptions{})
1✔
521
        if err != nil {
2✔
522
                cont.log.Error("Error getting HostprotRemoteIpContainers CRs: ", err)
1✔
523
                return nil, err
1✔
524
        }
1✔
525
        return hpRemoteIpConts, nil
×
526
}
527

528
func (cont *AciController) createStaticNetPolCrs() bool {
1✔
529
        ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
530

1✔
531
        createPol := func(labelKey, subjName, direction string, rules []hppv1.HostprotRule) bool {
2✔
532
                hppName := strings.ReplaceAll(labelKey, "_", "-")
1✔
533
                if _, err := cont.getHostprotPol(hppName, ns); errors.IsNotFound(err) {
2✔
534
                        hpp := &hppv1.HostprotPol{
1✔
535
                                ObjectMeta: metav1.ObjectMeta{
1✔
536
                                        Name:      hppName,
1✔
537
                                        Namespace: ns,
1✔
538
                                },
1✔
539
                                Spec: hppv1.HostprotPolSpec{
1✔
540
                                        Name:            labelKey,
1✔
541
                                        NetworkPolicies: []string{labelKey},
1✔
542
                                        HostprotSubj: []hppv1.HostprotSubj{
1✔
543
                                                {
1✔
544
                                                        Name:         subjName,
1✔
545
                                                        HostprotRule: rules,
1✔
546
                                                },
1✔
547
                                        },
1✔
548
                                },
1✔
549
                        }
1✔
550
                        if !cont.createHostprotPol(hpp, ns) {
1✔
551
                                return false
×
552
                        }
×
553
                }
554
                return true
1✔
555
        }
556

557
        if !createPol(cont.aciNameForKey("np", "static-ingress"), "ingress", "ingress", cont.getHostprotRules("ingress")) {
1✔
558
                return false
×
559
        }
×
560
        if !createPol(cont.aciNameForKey("np", "static-egress"), "egress", "egress", cont.getHostprotRules("egress")) {
1✔
561
                return false
×
562
        }
×
563
        if !createPol(cont.aciNameForKey("np", "static-discovery"), "discovery", "discovery", cont.getDiscoveryRules()) {
1✔
564
                return false
×
565
        }
×
566

567
        return true
1✔
568
}
569

570
func (cont *AciController) getHostprotRules(direction string) []hppv1.HostprotRule {
1✔
571
        var rules []hppv1.HostprotRule
1✔
572
        outbound := hppv1.HostprotRule{
1✔
573
                ConnTrack: "reflexive",
1✔
574
                Protocol:  "unspecified",
1✔
575
                FromPort:  "unspecified",
1✔
576
                ToPort:    "unspecified",
1✔
577
                Direction: direction,
1✔
578
        }
1✔
579

1✔
580
        if !cont.configuredPodNetworkIps.V6.Empty() {
1✔
581
                outbound.Name = "allow-all-reflexive-v6"
×
582
                outbound.Ethertype = "ipv6"
×
583
                rules = append(rules, outbound)
×
584
        }
×
585
        if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
586
                outbound.Name = "allow-all-reflexive"
1✔
587
                outbound.Ethertype = "ipv4"
1✔
588
                rules = append(rules, outbound)
1✔
589
        }
1✔
590

591
        return rules
1✔
592
}
593

594
func (cont *AciController) getDiscoveryRules() []hppv1.HostprotRule {
1✔
595
        rules := []hppv1.HostprotRule{
1✔
596
                {
1✔
597
                        Name:      "arp-ingress",
1✔
598
                        Direction: "ingress",
1✔
599
                        Ethertype: "arp",
1✔
600
                        ConnTrack: "normal",
1✔
601
                },
1✔
602
                {
1✔
603
                        Name:      "arp-egress",
1✔
604
                        Direction: "egress",
1✔
605
                        Ethertype: "arp",
1✔
606
                        ConnTrack: "normal",
1✔
607
                },
1✔
608
        }
1✔
609

1✔
610
        if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
611
                rules = append(rules,
1✔
612
                        hppv1.HostprotRule{
1✔
613
                                Name:      "icmp-ingress",
1✔
614
                                Direction: "ingress",
1✔
615
                                Ethertype: "ipv4",
1✔
616
                                Protocol:  "icmp",
1✔
617
                                ConnTrack: "normal",
1✔
618
                        },
1✔
619
                        hppv1.HostprotRule{
1✔
620
                                Name:      "icmp-egress",
1✔
621
                                Direction: "egress",
1✔
622
                                Ethertype: "ipv4",
1✔
623
                                Protocol:  "icmp",
1✔
624
                                ConnTrack: "normal",
1✔
625
                        },
1✔
626
                )
1✔
627
        }
1✔
628

629
        if !cont.configuredPodNetworkIps.V6.Empty() {
1✔
630
                rules = append(rules,
×
631
                        hppv1.HostprotRule{
×
632
                                Name:      "icmpv6-ingress",
×
633
                                Direction: "ingress",
×
634
                                Ethertype: "ipv6",
×
635
                                Protocol:  "icmpv6",
×
636
                                ConnTrack: "normal",
×
637
                        },
×
638
                        hppv1.HostprotRule{
×
639
                                Name:      "icmpv6-egress",
×
640
                                Direction: "egress",
×
641
                                Ethertype: "ipv6",
×
642
                                Protocol:  "icmpv6",
×
643
                                ConnTrack: "normal",
×
644
                        },
×
645
                )
×
646
        }
×
647

648
        return rules
1✔
649
}
650

651
func (cont *AciController) cleanStaleHppCrs() {
1✔
652
        sysNs := os.Getenv("SYSTEM_NAMESPACE")
1✔
653
        npNames := make(map[string]struct{})
1✔
654

1✔
655
        namespaces, err := cont.listNamespaces()
1✔
656
        if err != nil {
1✔
657
                cont.log.Error("Error listing namespaces: ", err)
×
658
                return
×
659
        }
×
660

661
        for _, ns := range namespaces.Items {
1✔
662
                netpols, err := cont.listNetworkPolicies(ns.Name)
×
663
                if err != nil {
×
664
                        cont.log.Error("Error listing network policies in namespace ", ns.Name, ": ", err)
×
665
                        continue
×
666
                }
667
                for _, np := range netpols.Items {
×
668
                        nsName := np.ObjectMeta.Namespace + "/" + np.ObjectMeta.Name
×
669
                        npNames[nsName] = struct{}{}
×
670
                }
×
671
        }
672

673
        hpps, err := cont.listHostprotPol(sysNs)
1✔
674
        if err != nil {
2✔
675
                cont.log.Error("Error listing HostprotPols: ", err)
1✔
676
                return
1✔
677
        }
1✔
678

679
        for _, hpp := range hpps.Items {
×
680
                for _, npName := range hpp.Spec.NetworkPolicies {
×
681
                        if _, exists := npNames[npName]; !exists {
×
682
                                if !cont.deleteHostprotPol(hpp.ObjectMeta.Name, sysNs) {
×
683
                                        cont.log.Error("Error deleting stale HostprotPol: ", hpp.ObjectMeta.Name)
×
684
                                }
×
685
                        }
686
                }
687
        }
688
}
689

690
func (cont *AciController) cleanStaleHostprotRemoteIpContainers() {
1✔
691
        sysNs := os.Getenv("SYSTEM_NAMESPACE")
1✔
692
        nsNames := make(map[string]struct{})
1✔
693

1✔
694
        namespaces, err := cont.listNamespaces()
1✔
695
        if err != nil {
1✔
696
                cont.log.Error("Error listing namespaces: ", err)
×
697
                return
×
698
        }
×
699

700
        for _, ns := range namespaces.Items {
1✔
701
                nsNames[ns.Name] = struct{}{}
×
702
        }
×
703

704
        hpRemIpConts, err := cont.listHostprotRemoteIpContainers(sysNs)
1✔
705
        if err != nil {
2✔
706
                cont.log.Error("Error listing HostprotRemoteIpContainers: ", err)
1✔
707
                return
1✔
708
        }
1✔
709

710
        for _, hpRemIpCont := range hpRemIpConts.Items {
×
711
                if _, exists := nsNames[hpRemIpCont.ObjectMeta.Name]; !exists {
×
712
                        if !cont.deleteHostprotRemoteIpContainer(hpRemIpCont.ObjectMeta.Name, sysNs) {
×
713
                                cont.log.Error("Error deleting stale HostprotRemoteIpContainer: ", hpRemIpCont.ObjectMeta.Name)
×
714
                        }
×
715
                }
716
        }
717
}
718

719
func (cont *AciController) initStaticNetPolObjs() {
1✔
720
        if cont.config.EnableHppDirect {
2✔
721
                cont.cleanStaleHostprotRemoteIpContainers()
1✔
722
                cont.cleanStaleHppCrs()
1✔
723

1✔
724
                if !cont.createStaticNetPolCrs() {
1✔
725
                        cont.log.Error("Error creating static HPP CRs")
×
726
                }
×
727
                return
1✔
728
        } else {
1✔
729
                cont.deleteAllHostprotPol()
1✔
730
                cont.deleteAllHostprotRemoteIpContainers()
1✔
731
        }
1✔
732

733
        cont.apicConn.WriteApicObjects(cont.config.AciPrefix+"_np_static", cont.staticNetPolObjs())
1✔
734
}
735

736
func networkPolicyLogger(log *logrus.Logger,
737
        np *v1net.NetworkPolicy) *logrus.Entry {
1✔
738
        return log.WithFields(logrus.Fields{
1✔
739
                "namespace": np.ObjectMeta.Namespace,
1✔
740
                "name":      np.ObjectMeta.Name,
1✔
741
        })
1✔
742
}
1✔
743

744
func (cont *AciController) queueNetPolUpdateByKey(key string) {
1✔
745
        cont.netPolQueue.Add(key)
1✔
746
}
1✔
747

748
func (cont *AciController) queueRemoteIpConUpdate(pod *v1.Pod, deleted bool) {
1✔
749
        cont.hppMutex.Lock()
1✔
750
        update := cont.updateNsRemoteIpCont(pod, deleted)
1✔
751
        if update {
2✔
752
                podns := pod.ObjectMeta.Namespace
1✔
753
                cont.remIpContQueue.Add(podns)
1✔
754
        }
1✔
755
        cont.hppMutex.Unlock()
1✔
756
}
757

758
func (cont *AciController) queueNetPolUpdate(netpol *v1net.NetworkPolicy) {
1✔
759
        key, err := cache.MetaNamespaceKeyFunc(netpol)
1✔
760
        if err != nil {
1✔
761
                networkPolicyLogger(cont.log, netpol).
×
762
                        Error("Could not create network policy key: ", err)
×
763
                return
×
764
        }
×
765
        cont.netPolQueue.Add(key)
1✔
766
}
767

768
func (cont *AciController) peerMatchesPod(npNs string,
769
        peer *v1net.NetworkPolicyPeer, pod *v1.Pod, podNs *v1.Namespace) bool {
1✔
770
        if peer.PodSelector != nil && npNs == pod.ObjectMeta.Namespace {
2✔
771
                selector, err :=
1✔
772
                        metav1.LabelSelectorAsSelector(peer.PodSelector)
1✔
773
                if err != nil {
1✔
774
                        cont.log.Error("Could not parse pod selector: ", err)
×
775
                } else {
1✔
776
                        return selector.Matches(labels.Set(pod.ObjectMeta.Labels))
1✔
777
                }
1✔
778
        }
779
        if peer.NamespaceSelector != nil {
2✔
780
                selector, err :=
1✔
781
                        metav1.LabelSelectorAsSelector(peer.NamespaceSelector)
1✔
782
                if err != nil {
1✔
783
                        cont.log.Error("Could not parse namespace selector: ", err)
×
784
                } else {
1✔
785
                        match := selector.Matches(labels.Set(podNs.ObjectMeta.Labels))
1✔
786
                        if match && peer.PodSelector != nil {
2✔
787
                                podSelector, err :=
1✔
788
                                        metav1.LabelSelectorAsSelector(peer.PodSelector)
1✔
789
                                if err != nil {
1✔
790
                                        cont.log.Error("Could not parse pod selector: ", err)
×
791
                                } else {
1✔
792
                                        return podSelector.Matches(labels.Set(pod.ObjectMeta.Labels))
1✔
793
                                }
1✔
794
                        }
795
                        return match
1✔
796
                }
797
        }
798
        return false
×
799
}
800

801
func ipsForPod(pod *v1.Pod) []string {
1✔
802
        var ips []string
1✔
803
        podIPsField := reflect.ValueOf(pod.Status).FieldByName("PodIPs")
1✔
804
        if podIPsField.IsValid() {
2✔
805
                if len(pod.Status.PodIPs) > 0 {
1✔
806
                        for _, ip := range pod.Status.PodIPs {
×
807
                                ips = append(ips, ip.IP)
×
808
                        }
×
809
                        return ips
×
810
                }
811
        }
812
        if pod.Status.PodIP != "" {
2✔
813
                return []string{pod.Status.PodIP}
1✔
814
        }
1✔
815
        return nil
1✔
816
}
817

818
func ipBlockToSubnets(ipblock *v1net.IPBlock) ([]string, error) {
1✔
819
        _, nw, err := net.ParseCIDR(ipblock.CIDR)
1✔
820
        if err != nil {
1✔
821
                return nil, err
×
822
        }
×
823
        ips := ipam.New()
1✔
824
        ips.AddSubnet(nw)
1✔
825
        for _, except := range ipblock.Except {
2✔
826
                _, nw, err = net.ParseCIDR(except)
1✔
827
                if err != nil {
1✔
828
                        return nil, err
×
829
                }
×
830
                ips.RemoveSubnet(nw)
1✔
831
        }
832
        var subnets []string
1✔
833
        for _, r := range ips.FreeList {
2✔
834
                ipnets := ipam.Range2Cidr(r.Start, r.End)
1✔
835
                for _, n := range ipnets {
2✔
836
                        subnets = append(subnets, n.String())
1✔
837
                }
1✔
838
        }
839
        return subnets, nil
1✔
840
}
841

842
func parseCIDR(sub string) *net.IPNet {
1✔
843
        _, netw, err := net.ParseCIDR(sub)
1✔
844
        if err == nil {
2✔
845
                return netw
1✔
846
        }
1✔
847
        ip := net.ParseIP(sub)
1✔
848
        if ip == nil {
1✔
849
                return nil
×
850
        }
×
851
        var mask net.IPMask
1✔
852
        if ip.To4() != nil {
2✔
853
                mask = net.CIDRMask(32, 32)
1✔
854
        } else if ip.To16() != nil {
3✔
855
                mask = net.CIDRMask(128, 128)
1✔
856
        } else {
1✔
857
                return nil
×
858
        }
×
859
        return &net.IPNet{
1✔
860
                IP:   ip,
1✔
861
                Mask: mask,
1✔
862
        }
1✔
863
}
864

865
func netEqual(a, b net.IPNet) bool {
1✔
866
        return a.IP.Equal(b.IP) && bytes.Equal(a.Mask, b.Mask)
1✔
867
}
1✔
868

869
func (cont *AciController) updateIpIndexEntry(index cidranger.Ranger,
870
        subnetStr string, key string, add bool) bool {
1✔
871
        cidr := parseCIDR(subnetStr)
1✔
872
        if cidr == nil {
1✔
873
                cont.log.WithFields(logrus.Fields{
×
874
                        "subnet": subnetStr,
×
875
                        "netpol": key,
×
876
                }).Warning("Invalid subnet or IP")
×
877
                return false
×
878
        }
×
879

880
        entries, err := index.CoveredNetworks(*cidr)
1✔
881
        if err != nil {
1✔
882
                cont.log.Error("Corrupted subnet index: ", err)
×
883
                return false
×
884
        }
×
885
        if add {
2✔
886
                for _, entryObj := range entries {
2✔
887
                        if netEqual(entryObj.Network(), *cidr) {
2✔
888
                                entry := entryObj.(*ipIndexEntry)
1✔
889
                                existing := entry.keys[key]
1✔
890
                                entry.keys[key] = true
1✔
891
                                return !existing
1✔
892
                        }
1✔
893
                }
894

895
                entry := &ipIndexEntry{
1✔
896
                        ipNet: *cidr,
1✔
897
                        keys: map[string]bool{
1✔
898
                                key: true,
1✔
899
                        },
1✔
900
                }
1✔
901
                index.Insert(entry)
1✔
902
                return true
1✔
903
        } else {
1✔
904
                var existing bool
1✔
905
                for _, entryObj := range entries {
2✔
906
                        entry := entryObj.(*ipIndexEntry)
1✔
907
                        if entry.keys[key] {
2✔
908
                                existing = true
1✔
909
                                delete(entry.keys, key)
1✔
910
                        }
1✔
911
                        if len(entry.keys) == 0 {
2✔
912
                                index.Remove(entry.Network())
1✔
913
                        }
1✔
914
                }
915
                return existing
1✔
916
        }
917
}
918

919
func (cont *AciController) updateIpIndex(index cidranger.Ranger,
920
        oldSubnets map[string]bool, newSubnets map[string]bool, key string) {
1✔
921
        for subStr := range oldSubnets {
2✔
922
                if newSubnets[subStr] {
2✔
923
                        continue
1✔
924
                }
925
                cont.updateIpIndexEntry(index, subStr, key, false)
1✔
926
        }
927
        for subStr := range newSubnets {
2✔
928
                if oldSubnets[subStr] {
2✔
929
                        continue
1✔
930
                }
931
                cont.updateIpIndexEntry(index, subStr, key, true)
1✔
932
        }
933
}
934

935
func (cont *AciController) updateTargetPortIndex(service bool, key string,
936
        oldPorts map[string]targetPort, newPorts map[string]targetPort) {
1✔
937
        for portkey := range oldPorts {
2✔
938
                if _, ok := newPorts[portkey]; ok {
1✔
939
                        continue
×
940
                }
941

942
                entry, ok := cont.targetPortIndex[portkey]
1✔
943
                if !ok {
1✔
944
                        continue
×
945
                }
946

947
                if service {
1✔
948
                        delete(entry.serviceKeys, key)
×
949
                } else {
1✔
950
                        delete(entry.networkPolicyKeys, key)
1✔
951
                }
1✔
952
                if len(entry.serviceKeys) == 0 && len(entry.networkPolicyKeys) == 0 {
2✔
953
                        delete(cont.targetPortIndex, portkey)
1✔
954
                }
1✔
955
        }
956
        for portkey, port := range newPorts {
2✔
957
                if _, ok := oldPorts[portkey]; ok {
1✔
958
                        continue
×
959
                }
960
                entry := cont.targetPortIndex[portkey]
1✔
961
                if entry == nil {
2✔
962
                        entry = &portIndexEntry{
1✔
963
                                port:              port,
1✔
964
                                serviceKeys:       make(map[string]bool),
1✔
965
                                networkPolicyKeys: make(map[string]bool),
1✔
966
                        }
1✔
967
                        cont.targetPortIndex[portkey] = entry
1✔
968
                } else {
2✔
969
                        entry.port.ports = port.ports
1✔
970
                }
1✔
971

972
                if service {
2✔
973
                        entry.serviceKeys[key] = true
1✔
974
                } else {
2✔
975
                        entry.networkPolicyKeys[key] = true
1✔
976
                }
1✔
977
        }
978
}
979

980
func (cont *AciController) getPortNumsFromPortName(podKeys []string, portName string) []int {
1✔
981
        var ports []int
1✔
982
        portmap := make(map[int]bool)
1✔
983
        for _, podkey := range podKeys {
2✔
984
                podobj, exists, err := cont.podIndexer.GetByKey(podkey)
1✔
985
                if exists && err == nil {
2✔
986
                        pod := podobj.(*v1.Pod)
1✔
987
                        port, err := k8util.LookupContainerPortNumberByName(*pod, portName)
1✔
988
                        if err != nil {
1✔
989
                                continue
×
990
                        }
991
                        if _, ok := portmap[int(port)]; !ok {
2✔
992
                                ports = append(ports, int(port))
1✔
993
                                portmap[int(port)] = true
1✔
994
                        }
1✔
995
                }
996
        }
997
        if len(ports) == 0 {
2✔
998
                cont.log.Infof("No matching portnumbers for portname %s: ", portName)
1✔
999
        }
1✔
1000
        cont.log.Debug("PortName: ", portName, "Mapping port numbers: ", ports)
1✔
1001
        return ports
1✔
1002
}
1003

1004
// get a map of target ports for egress rules that have no "To" clause
1005
func (cont *AciController) getNetPolTargetPorts(np *v1net.NetworkPolicy) map[string]targetPort {
1✔
1006
        ports := make(map[string]targetPort)
1✔
1007
        for _, egress := range np.Spec.Egress {
2✔
1008
                if len(egress.To) != 0 && !isNamedPortPresenInNp(np) {
2✔
1009
                        continue
1✔
1010
                }
1011
                for _, port := range egress.Ports {
2✔
1012
                        if port.Port == nil {
1✔
1013
                                continue
×
1014
                        }
1015
                        proto := v1.ProtocolTCP
1✔
1016
                        if port.Protocol != nil {
2✔
1017
                                proto = *port.Protocol
1✔
1018
                        }
1✔
1019
                        npKey, _ := cache.MetaNamespaceKeyFunc(np)
1✔
1020
                        var key string
1✔
1021
                        var portnums []int
1✔
1022
                        if port.Port.Type == intstr.Int {
2✔
1023
                                key = portProto(&proto) + "-num-" + port.Port.String()
1✔
1024
                                portnums = append(portnums, port.Port.IntValue())
1✔
1025
                        } else {
2✔
1026
                                if len(egress.To) != 0 {
2✔
1027
                                        // TODO optimize this code instead going through all matching pods every time
1✔
1028
                                        podKeys := cont.netPolEgressPods.GetPodForObj(npKey)
1✔
1029
                                        portnums = cont.getPortNumsFromPortName(podKeys, port.Port.String())
1✔
1030
                                } else {
2✔
1031
                                        ctrNmpEntry, ok := cont.ctrPortNameCache[port.Port.String()]
1✔
1032
                                        if ok {
2✔
1033
                                                for key := range ctrNmpEntry.ctrNmpToPods {
2✔
1034
                                                        val := strings.Split(key, "-")
1✔
1035
                                                        if len(val) != 2 {
1✔
1036
                                                                continue
×
1037
                                                        }
1038
                                                        if val[0] == portProto(&proto) {
2✔
1039
                                                                port, _ := strconv.Atoi(val[1])
1✔
1040
                                                                portnums = append(portnums, port)
1✔
1041
                                                        }
1✔
1042
                                                }
1043
                                        }
1044
                                }
1045
                                if len(portnums) == 0 {
2✔
1046
                                        continue
1✔
1047
                                }
1048
                                key = portProto(&proto) + "-name-" + port.Port.String()
1✔
1049
                        }
1050
                        ports[key] = targetPort{
1✔
1051
                                proto: proto,
1✔
1052
                                ports: portnums,
1✔
1053
                        }
1✔
1054
                }
1055
        }
1056
        return ports
1✔
1057
}
1058

1059
type peerRemoteInfo struct {
1060
        remotePods   []*v1.Pod
1061
        podSelectors []*metav1.LabelSelector
1062
}
1063

1064
func (cont *AciController) getPeerRemoteSubnets(peers []v1net.NetworkPolicyPeer,
1065
        namespace string, peerPods []*v1.Pod, peerNs map[string]*v1.Namespace,
1066
        logger *logrus.Entry) ([]string, []string, peerRemoteInfo, map[string]bool, []string) {
1✔
1067
        var remoteSubnets []string
1✔
1068
        var peerremote peerRemoteInfo
1✔
1069
        subnetMap := make(map[string]bool)
1✔
1070
        var peerNsList []string
1✔
1071
        var ipBlockSubs []string
1✔
1072
        if len(peers) > 0 {
2✔
1073
                // only applies to matching pods
1✔
1074
                for _, pod := range peerPods {
2✔
1075
                        for peerIx, peer := range peers {
2✔
1076
                                if ns, ok := peerNs[pod.ObjectMeta.Namespace]; ok &&
1✔
1077
                                        cont.peerMatchesPod(namespace,
1✔
1078
                                                &peers[peerIx], pod, ns) {
2✔
1079
                                        podIps := ipsForPod(pod)
1✔
1080
                                        for _, ip := range podIps {
2✔
1081
                                                if _, exists := subnetMap[ip]; !exists {
2✔
1082
                                                        subnetMap[ip] = true
1✔
1083
                                                        if cont.config.EnableHppDirect {
2✔
1084
                                                                peerremote.remotePods = append(peerremote.remotePods, pod)
1✔
1085
                                                                if !slices.Contains(peerNsList, pod.ObjectMeta.Namespace) {
2✔
1086
                                                                        peerNsList = append(peerNsList, pod.ObjectMeta.Namespace)
1✔
1087
                                                                }
1✔
1088
                                                        }
1089
                                                        remoteSubnets = append(remoteSubnets, ip)
1✔
1090
                                                }
1091
                                        }
1092
                                }
1093
                                if cont.config.EnableHppDirect && peer.PodSelector != nil {
2✔
1094
                                        if !cont.isPodSelectorPresent(peerremote.podSelectors, peer.PodSelector) {
2✔
1095
                                                peerremote.podSelectors = append(peerremote.podSelectors, peer.PodSelector)
1✔
1096
                                        }
1✔
1097
                                }
1098
                        }
1099
                }
1100

1101
                for _, peer := range peers {
2✔
1102
                        if peer.IPBlock == nil {
2✔
1103
                                continue
1✔
1104
                        }
1105
                        subs, err := ipBlockToSubnets(peer.IPBlock)
1✔
1106
                        if err != nil {
1✔
1107
                                logger.Warning("Invalid IPBlock in network policy rule: ", err)
×
1108
                        } else {
1✔
1109
                                for _, subnet := range subs {
2✔
1110
                                        subnetMap[subnet] = true
1✔
1111
                                }
1✔
1112
                                remoteSubnets = append(remoteSubnets, subs...)
1✔
1113
                                ipBlockSubs = append(ipBlockSubs, subs...)
1✔
1114
                        }
1115
                }
1116
        }
1117
        sort.Strings(remoteSubnets)
1✔
1118
        return remoteSubnets, peerNsList, peerremote, subnetMap, ipBlockSubs
1✔
1119
}
1120

1121
func (cont *AciController) ipInPodSubnet(ip net.IP) bool {
×
1122
        for _, podsubnet := range cont.config.PodSubnet {
×
1123
                _, subnet, err := net.ParseCIDR(podsubnet)
×
1124
                if err == nil && subnet != nil {
×
1125
                        if subnet.Contains(ip) {
×
1126
                                return true
×
1127
                        }
×
1128
                }
1129
        }
1130
        return false
×
1131
}
1132

1133
func (cont *AciController) buildNetPolSubjRule(subj apicapi.ApicObject, ruleName,
1134
        direction, ethertype, proto, port string, remoteSubnets []string,
1135
        addPodSubnetAsRemIp bool) {
1✔
1136
        ruleNameWithEtherType := fmt.Sprintf("%s-%s", ruleName, ethertype)
1✔
1137
        rule := apicapi.NewHostprotRule(subj.GetDn(), ruleNameWithEtherType)
1✔
1138
        rule.SetAttr("direction", direction)
1✔
1139
        rule.SetAttr("ethertype", ethertype)
1✔
1140
        if proto != "" {
2✔
1141
                rule.SetAttr("protocol", proto)
1✔
1142
        }
1✔
1143

1144
        if addPodSubnetAsRemIp {
1✔
1145
                for _, podsubnet := range cont.config.PodSubnet {
×
1146
                        _, subnet, err := net.ParseCIDR(podsubnet)
×
1147
                        if err == nil && subnet != nil {
×
1148
                                if (ethertype == "ipv4" && subnet.IP.To4() != nil) || (ethertype == "ipv6" && subnet.IP.To4() == nil) {
×
1149
                                        rule.AddChild(apicapi.NewHostprotRemoteIp(rule.GetDn(), podsubnet))
×
1150
                                }
×
1151
                        }
1152
                }
1153
        }
1154
        for _, subnetStr := range remoteSubnets {
2✔
1155
                _, subnet, err := net.ParseCIDR(subnetStr)
1✔
1156
                if err == nil && subnet != nil {
2✔
1157
                        // subnetStr is a valid CIDR notation, check its IP version and add the subnet to the rule
1✔
1158
                        if (ethertype == "ipv4" && subnet.IP.To4() != nil) || (ethertype == "ipv6" && subnet.IP.To4() == nil) {
2✔
1159
                                rule.AddChild(apicapi.NewHostprotRemoteIp(rule.GetDn(), subnetStr))
1✔
1160
                        }
1✔
1161
                } else if ip := net.ParseIP(subnetStr); ip != nil {
2✔
1162
                        if addPodSubnetAsRemIp && cont.ipInPodSubnet(ip) {
1✔
1163
                                continue
×
1164
                        }
1165
                        if ethertype == "ipv6" && (ip.To16() != nil && ip.To4() == nil) || ethertype == "ipv4" && ip.To4() != nil {
2✔
1166
                                rule.AddChild(apicapi.NewHostprotRemoteIp(rule.GetDn(), subnetStr))
1✔
1167
                        }
1✔
1168
                }
1169
        }
1170
        if port != "" {
2✔
1171
                rule.SetAttr("toPort", port)
1✔
1172
        }
1✔
1173

1174
        subj.AddChild(rule)
1✔
1175
}
1176

1177
func (cont *AciController) isPodSelectorPresent(podSelectors []*metav1.LabelSelector,
1178
        podSelector *metav1.LabelSelector) bool {
1✔
1179

1✔
1180
        present := false
1✔
1181
        for _, selector := range podSelectors {
1✔
1182
                if reflect.DeepEqual(selector, podSelector) {
×
1183
                        present = true
×
1184
                        break
×
1185
                }
1186
        }
1187
        return present
1✔
1188
}
1189

1190
func (cont *AciController) buildLocalNetPolSubjRule(subj *hppv1.HostprotSubj, ruleName,
1191
        direction, ethertype, proto, port string, remoteNs []string,
1192
        podSelectors []*metav1.LabelSelector, remoteSubnets []string) {
1✔
1193
        rule := hppv1.HostprotRule{
1✔
1194
                ConnTrack: "reflexive",
1✔
1195
                Direction: "ingress",
1✔
1196
                Ethertype: "undefined",
1✔
1197
                Protocol:  "unspecified",
1✔
1198
                FromPort:  "unspecified",
1✔
1199
                ToPort:    "unspecified",
1✔
1200
        }
1✔
1201
        rule.Direction = direction
1✔
1202
        rule.Ethertype = ethertype
1✔
1203
        if proto != "" {
2✔
1204
                rule.Protocol = proto
1✔
1205
        }
1✔
1206
        rule.Name = ruleName
1✔
1207

1✔
1208
        rule.RsRemoteIpContainer = remoteNs
1✔
1209
        var remoteSubnetsCidr []hppv1.HostprotRemoteIp
1✔
1210
        for _, subnetStr := range remoteSubnets {
2✔
1211
                _, subnet, err := net.ParseCIDR(subnetStr)
1✔
1212
                if err == nil && subnet != nil {
2✔
1213
                        if (ethertype == "ipv4" && subnet.IP.To4() != nil) || (ethertype == "ipv6" && subnet.IP.To4() == nil) {
2✔
1214
                                remIpObj := hppv1.HostprotRemoteIp{
1✔
1215
                                        Addr: subnetStr,
1✔
1216
                                }
1✔
1217
                                remoteSubnetsCidr = append(remoteSubnetsCidr, remIpObj)
1✔
1218
                        }
1✔
1219
                }
1220
        }
1221
        if len(remoteSubnetsCidr) > 0 {
2✔
1222
                rule.HostprotRemoteIp = remoteSubnetsCidr
1✔
1223
        }
1✔
1224

1225
        var filterContainers []hppv1.HostprotFilterContainer
1✔
1226
        for _, podSelector := range podSelectors {
2✔
1227
                filterContainer := hppv1.HostprotFilterContainer{}
1✔
1228
                for key, val := range podSelector.MatchLabels {
2✔
1229
                        filter := hppv1.HostprotFilter{
1✔
1230
                                Key: key,
1✔
1231
                        }
1✔
1232
                        filter.Values = append(filter.Values, val)
1✔
1233
                        filter.Operator = "Equals"
1✔
1234
                        filterContainer.HostprotFilter = append(filterContainer.HostprotFilter, filter)
1✔
1235
                }
1✔
1236
                for _, expressions := range podSelector.MatchExpressions {
2✔
1237
                        filter := hppv1.HostprotFilter{
1✔
1238
                                Key:      expressions.Key,
1✔
1239
                                Values:   expressions.Values,
1✔
1240
                                Operator: string(expressions.Operator),
1✔
1241
                        }
1✔
1242
                        filterContainer.HostprotFilter = append(filterContainer.HostprotFilter, filter)
1✔
1243
                }
1✔
1244
                filterContainers = append(filterContainers, filterContainer)
1✔
1245
        }
1246

1247
        if len(filterContainers) > 0 {
2✔
1248
                rule.HostprotFilterContainer = filterContainers
1✔
1249
        }
1✔
1250

1251
        if port != "" {
2✔
1252
                rule.ToPort = port
1✔
1253
        }
1✔
1254

1255
        cont.log.Debug(direction)
1✔
1256
        if len(remoteSubnets) != 0 && direction == "egress" {
2✔
1257
                cont.log.Debug("HostprotServiceRemoteIps")
1✔
1258
                rule.HostprotServiceRemoteIps = remoteSubnets
1✔
1259
        }
1✔
1260

1261
        subj.HostprotRule = append(subj.HostprotRule, rule)
1✔
1262
}
1263

1264
func (cont *AciController) buildNetPolSubjRules(ruleName string,
1265
        subj apicapi.ApicObject, direction string, peers []v1net.NetworkPolicyPeer,
1266
        remoteSubnets []string, ports []v1net.NetworkPolicyPort,
1267
        logger *logrus.Entry, npKey string, np *v1net.NetworkPolicy,
1268
        addPodSubnetAsRemIp bool) {
1✔
1269
        if len(peers) > 0 && len(remoteSubnets) == 0 {
2✔
1270
                // nonempty From matches no pods or IPBlocks; don't
1✔
1271
                // create the rule
1✔
1272
                return
1✔
1273
        }
1✔
1274
        if len(ports) == 0 {
2✔
1275
                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
1276
                        cont.buildNetPolSubjRule(subj, ruleName, direction,
1✔
1277
                                "ipv4", "", "", remoteSubnets, addPodSubnetAsRemIp)
1✔
1278
                }
1✔
1279
                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
1280
                        cont.buildNetPolSubjRule(subj, ruleName, direction,
1✔
1281
                                "ipv6", "", "", remoteSubnets, addPodSubnetAsRemIp)
1✔
1282
                }
1✔
1283
        } else {
1✔
1284
                for j := range ports {
2✔
1285
                        proto := portProto(ports[j].Protocol)
1✔
1286
                        var portList []string
1✔
1287

1✔
1288
                        if ports[j].Port != nil {
2✔
1289
                                if ports[j].Port.Type == intstr.Int {
2✔
1290
                                        portList = append(portList, ports[j].Port.String())
1✔
1291
                                } else {
2✔
1292
                                        var portnums []int
1✔
1293
                                        if direction == "egress" {
2✔
1294
                                                portnums = append(portnums, cont.getPortNums(&ports[j])...)
1✔
1295
                                        } else {
2✔
1296
                                                // TODO need to handle empty Pod Selector
1✔
1297
                                                if reflect.DeepEqual(np.Spec.PodSelector, metav1.LabelSelector{}) {
1✔
1298
                                                        logger.Warning("Empty PodSelctor for NamedPort is not supported in ingress direction"+
×
1299
                                                                "port in network policy: ", ports[j].Port.String())
×
1300
                                                        continue
×
1301
                                                }
1302
                                                podKeys := cont.netPolPods.GetPodForObj(npKey)
1✔
1303
                                                portnums = cont.getPortNumsFromPortName(podKeys, ports[j].Port.String())
1✔
1304
                                        }
1305
                                        if len(portnums) == 0 {
2✔
1306
                                                logger.Warning("There is no matching  ports in ingress/egress direction "+
1✔
1307
                                                        "port in network policy: ", ports[j].Port.String())
1✔
1308
                                                continue
1✔
1309
                                        }
1310
                                        for _, portnum := range portnums {
2✔
1311
                                                portList = append(portList, strconv.Itoa(portnum))
1✔
1312
                                        }
1✔
1313
                                }
1314
                        }
1315
                        for i, port := range portList {
2✔
1316
                                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
1317
                                        cont.buildNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(i+j), direction,
1✔
1318
                                                "ipv4", proto, port, remoteSubnets, addPodSubnetAsRemIp)
1✔
1319
                                }
1✔
1320
                                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
1321
                                        cont.buildNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(i+j), direction,
1✔
1322
                                                "ipv6", proto, port, remoteSubnets, addPodSubnetAsRemIp)
1✔
1323
                                }
1✔
1324
                        }
1325
                        if len(portList) == 0 && proto != "" {
2✔
1326
                                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
1327
                                        cont.buildNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(j), direction,
1✔
1328
                                                "ipv4", proto, "", remoteSubnets, addPodSubnetAsRemIp)
1✔
1329
                                }
1✔
1330
                                if !cont.configuredPodNetworkIps.V6.Empty() {
1✔
1331
                                        cont.buildNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(j), direction,
×
1332
                                                "ipv6", proto, "", remoteSubnets, addPodSubnetAsRemIp)
×
1333
                                }
×
1334
                        }
1335
                }
1336
        }
1337
}
1338

1339
func (cont *AciController) buildLocalNetPolSubjRules(ruleName string,
1340
        subj *hppv1.HostprotSubj, direction string, peerNs []string,
1341
        podSelector []*metav1.LabelSelector, ports []v1net.NetworkPolicyPort,
1342
        logger *logrus.Entry, npKey string, np *v1net.NetworkPolicy, peerIpBlock []string) {
1✔
1343
        if len(ports) == 0 {
2✔
1344
                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
1345
                        cont.buildLocalNetPolSubjRule(subj, ruleName+"-ipv4", direction,
1✔
1346
                                "ipv4", "", "", peerNs, podSelector, peerIpBlock)
1✔
1347
                }
1✔
1348
                if !cont.configuredPodNetworkIps.V6.Empty() {
1✔
1349
                        cont.buildLocalNetPolSubjRule(subj, ruleName+"-ipv6", direction,
×
1350
                                "ipv6", "", "", peerNs, podSelector, peerIpBlock)
×
1351
                }
×
1352
        } else {
1✔
1353
                for j := range ports {
2✔
1354
                        proto := portProto(ports[j].Protocol)
1✔
1355
                        var portList []string
1✔
1356

1✔
1357
                        if ports[j].Port != nil {
2✔
1358
                                if ports[j].Port.Type == intstr.Int {
2✔
1359
                                        portList = append(portList, ports[j].Port.String())
1✔
1360
                                } else {
1✔
1361
                                        var portnums []int
×
1362
                                        if direction == "egress" {
×
1363
                                                portnums = append(portnums, cont.getPortNums(&ports[j])...)
×
1364
                                        } else {
×
1365
                                                // TODO need to handle empty Pod Selector
×
1366
                                                if reflect.DeepEqual(np.Spec.PodSelector, metav1.LabelSelector{}) {
×
1367
                                                        logger.Warning("Empty PodSelctor for NamedPort is not supported in ingress direction"+
×
1368
                                                                "port in network policy: ", ports[j].Port.String())
×
1369
                                                        continue
×
1370
                                                }
1371
                                                podKeys := cont.netPolPods.GetPodForObj(npKey)
×
1372
                                                portnums = cont.getPortNumsFromPortName(podKeys, ports[j].Port.String())
×
1373
                                        }
1374
                                        if len(portnums) == 0 {
×
1375
                                                logger.Warning("There is no matching  ports in ingress/egress direction "+
×
1376
                                                        "port in network policy: ", ports[j].Port.String())
×
1377
                                                continue
×
1378
                                        }
1379
                                        for _, portnum := range portnums {
×
1380
                                                portList = append(portList, strconv.Itoa(portnum))
×
1381
                                        }
×
1382
                                }
1383
                        }
1384
                        for i, port := range portList {
2✔
1385
                                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
1386
                                        cont.buildLocalNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(i+j)+"-ipv4", direction,
1✔
1387
                                                "ipv4", proto, port, peerNs, podSelector, peerIpBlock)
1✔
1388
                                }
1✔
1389
                                if !cont.configuredPodNetworkIps.V6.Empty() {
1✔
1390
                                        cont.buildLocalNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(i+j)+"-ipv6", direction,
×
1391
                                                "ipv6", proto, port, peerNs, podSelector, peerIpBlock)
×
1392
                                }
×
1393
                        }
1394
                        if len(portList) == 0 && proto != "" {
1✔
1395
                                if !cont.configuredPodNetworkIps.V4.Empty() {
×
1396
                                        cont.buildLocalNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(j)+"-ipv4", direction,
×
1397
                                                "ipv4", proto, "", peerNs, podSelector, peerIpBlock)
×
1398
                                }
×
1399
                                if !cont.configuredPodNetworkIps.V6.Empty() {
×
1400
                                        cont.buildLocalNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(j)+"-ipv6", direction,
×
1401
                                                "ipv6", proto, "", peerNs, podSelector, peerIpBlock)
×
1402
                                }
×
1403
                        }
1404
                }
1405
        }
1406
}
1407

1408
func (cont *AciController) getPortNums(port *v1net.NetworkPolicyPort) []int {
1✔
1409
        portkey := portKey(port)
1✔
1410
        cont.indexMutex.Lock()
1✔
1411
        defer cont.indexMutex.Unlock()
1✔
1412
        cont.log.Debug("PortKey1: ", portkey)
1✔
1413
        entry := cont.targetPortIndex[portkey]
1✔
1414
        var length int
1✔
1415
        if entry == nil || len(entry.port.ports) == 0 {
2✔
1416
                return []int{}
1✔
1417
        }
1✔
1418
        length = len(entry.port.ports)
1✔
1419
        ports := make([]int, length)
1✔
1420
        copy(ports, entry.port.ports)
1✔
1421
        return ports
1✔
1422
}
1423
func portProto(protocol *v1.Protocol) string {
1✔
1424
        proto := "tcp"
1✔
1425
        if protocol != nil && *protocol == v1.ProtocolUDP {
2✔
1426
                proto = "udp"
1✔
1427
        } else if protocol != nil && *protocol == v1.ProtocolSCTP {
3✔
1428
                proto = "sctp"
1✔
1429
        }
1✔
1430
        return proto
1✔
1431
}
1432

1433
func portKey(p *v1net.NetworkPolicyPort) string {
1✔
1434
        portType := ""
1✔
1435
        port := ""
1✔
1436
        if p != nil && p.Port != nil {
2✔
1437
                if p.Port.Type == intstr.Int {
2✔
1438
                        portType = "num"
1✔
1439
                } else {
2✔
1440
                        portType = "name"
1✔
1441
                }
1✔
1442
                port = p.Port.String()
1✔
1443
                return portProto(p.Protocol) + "-" + portType + "-" + port
1✔
1444
        }
1445
        return ""
1✔
1446
}
1447

1448
func checkEndpoints(subnetIndex cidranger.Ranger,
1449
        addresses []v1.EndpointAddress) bool {
1✔
1450
        for _, addr := range addresses {
2✔
1451
                ip := net.ParseIP(addr.IP)
1✔
1452
                if ip == nil {
1✔
1453
                        return false
×
1454
                }
×
1455
                contains, err := subnetIndex.Contains(ip)
1✔
1456
                if err != nil || !contains {
2✔
1457
                        return false
1✔
1458
                }
1✔
1459
        }
1460

1461
        return true
1✔
1462
}
1463
func checkEndpointslices(subnetIndex cidranger.Ranger,
1464
        addresses []string) bool {
1✔
1465
        for _, addr := range addresses {
2✔
1466
                ip := net.ParseIP(addr)
1✔
1467
                if ip == nil {
1✔
1468
                        return false
×
1469
                }
×
1470
                contains, err := subnetIndex.Contains(ip)
1✔
1471
                if err != nil || !contains {
2✔
1472
                        return false
1✔
1473
                }
1✔
1474
        }
1475
        return true
1✔
1476
}
1477

1478
type portRemoteSubnet struct {
1479
        port           *v1net.NetworkPolicyPort
1480
        subnetMap      map[string]bool
1481
        hasNamedTarget bool
1482
}
1483

1484
func updatePortRemoteSubnets(portRemoteSubs map[string]*portRemoteSubnet,
1485
        portkey string, port *v1net.NetworkPolicyPort, subnetMap map[string]bool,
1486
        hasNamedTarget bool) {
1✔
1487
        if prs, ok := portRemoteSubs[portkey]; ok {
1✔
1488
                for s := range subnetMap {
×
1489
                        prs.subnetMap[s] = true
×
1490
                }
×
1491
                prs.hasNamedTarget = hasNamedTarget || prs.hasNamedTarget
×
1492
        } else {
1✔
1493
                portRemoteSubs[portkey] = &portRemoteSubnet{
1✔
1494
                        port:           port,
1✔
1495
                        subnetMap:      subnetMap,
1✔
1496
                        hasNamedTarget: hasNamedTarget,
1✔
1497
                }
1✔
1498
        }
1✔
1499
}
1500

1501
func portServiceAugmentKey(proto, port string) string {
1✔
1502
        return proto + "-" + port
1✔
1503
}
1✔
1504

1505
type portServiceAugment struct {
1506
        proto string
1507
        port  string
1508
        ipMap map[string]bool
1509
}
1510

1511
func updateServiceAugment(portAugments map[string]*portServiceAugment, proto, port, ip string) {
1✔
1512
        key := portServiceAugmentKey(proto, port)
1✔
1513
        if psa, ok := portAugments[key]; ok {
1✔
1514
                psa.ipMap[ip] = true
×
1515
        } else {
1✔
1516
                portAugments[key] = &portServiceAugment{
1✔
1517
                        proto: proto,
1✔
1518
                        port:  port,
1✔
1519
                        ipMap: map[string]bool{ip: true},
1✔
1520
                }
1✔
1521
        }
1✔
1522
}
1523

1524
func updateServiceAugmentForService(portAugments map[string]*portServiceAugment,
1525
        proto, port string, service *v1.Service) {
1✔
1526
        if service.Spec.ClusterIP != "" {
2✔
1527
                updateServiceAugment(portAugments,
1✔
1528
                        proto, port, service.Spec.ClusterIP)
1✔
1529
        }
1✔
1530
        for _, ig := range service.Status.LoadBalancer.Ingress {
1✔
1531
                if ig.IP == "" {
×
1532
                        continue
×
1533
                }
1534
                updateServiceAugment(portAugments,
×
1535
                        proto, port, ig.IP)
×
1536
        }
1537
}
1538

1539
// build service augment by matching peers against the endpoints ip
1540
// index
1541
func (cont *AciController) getServiceAugmentBySubnet(
1542
        prs *portRemoteSubnet, portAugments map[string]*portServiceAugment,
1543
        logger *logrus.Entry) {
1✔
1544
        matchedServices := make(map[string]bool)
1✔
1545
        subnetIndex := cidranger.NewPCTrieRanger()
1✔
1546

1✔
1547
        // find candidate service endpoints objects that include
1✔
1548
        // endpoints selected by the egress rule
1✔
1549
        cont.indexMutex.Lock()
1✔
1550
        for sub := range prs.subnetMap {
2✔
1551
                cidr := parseCIDR(sub)
1✔
1552
                if cidr == nil {
1✔
1553
                        continue
×
1554
                }
1555
                subnetIndex.Insert(cidranger.NewBasicRangerEntry(*cidr))
1✔
1556

1✔
1557
                entries, err := cont.endpointsIpIndex.CoveredNetworks(*cidr)
1✔
1558
                if err != nil {
1✔
1559
                        logger.Error("endpointsIpIndex corrupted: ", err)
×
1560
                        continue
×
1561
                }
1562
                for _, entry := range entries {
2✔
1563
                        e := entry.(*ipIndexEntry)
1✔
1564
                        for servicekey := range e.keys {
2✔
1565
                                matchedServices[servicekey] = true
1✔
1566
                        }
1✔
1567
                }
1568
        }
1569
        cont.indexMutex.Unlock()
1✔
1570

1✔
1571
        // if all endpoints are selected by egress rule, allow egress
1✔
1572
        // to the service cluster IP as well as to the endpoints
1✔
1573
        // themselves
1✔
1574
        for servicekey := range matchedServices {
2✔
1575
                serviceobj, _, err := cont.serviceIndexer.GetByKey(servicekey)
1✔
1576
                if err != nil {
1✔
1577
                        logger.Error("Could not lookup service for "+
×
1578
                                servicekey+": ", err.Error())
×
1579
                        continue
×
1580
                }
1581
                if serviceobj == nil {
1✔
1582
                        continue
×
1583
                }
1584
                service := serviceobj.(*v1.Service)
1✔
1585
                cont.serviceEndPoints.SetNpServiceAugmentForService(servicekey, service,
1✔
1586
                        prs, portAugments, subnetIndex, logger)
1✔
1587
        }
1588
}
1589

1590
// build service augment by matching against services with a given
1591
// target port
1592
func (cont *AciController) getServiceAugmentByPort(
1593
        prs *portRemoteSubnet, portAugments map[string]*portServiceAugment,
1594
        logger *logrus.Entry) {
1✔
1595
        // nil port means it matches against all ports.  If we're here, it
1✔
1596
        // means this is a rule that matches all ports with all
1✔
1597
        // destinations, so there's no need to augment anything.
1✔
1598
        if prs.port == nil ||
1✔
1599
                prs.port.Port == nil {
2✔
1600
                return
1✔
1601
        }
1✔
1602

1603
        portkey := portKey(prs.port)
1✔
1604
        cont.indexMutex.Lock()
1✔
1605
        entries := make(map[string]*portIndexEntry)
1✔
1606
        entry := cont.targetPortIndex[portkey]
1✔
1607
        if entry != nil && prs.port.Port.Type == intstr.String {
2✔
1608
                for _, port := range entry.port.ports {
2✔
1609
                        portstring := strconv.Itoa(port)
1✔
1610
                        key := portProto(prs.port.Protocol) + "-" + "num" + "-" + portstring
1✔
1611
                        portEntry := cont.targetPortIndex[key]
1✔
1612
                        if portEntry != nil {
2✔
1613
                                entries[portstring] = portEntry
1✔
1614
                        }
1✔
1615
                }
1616
        } else if entry != nil {
2✔
1617
                if len(entry.port.ports) > 0 {
2✔
1618
                        entries[strconv.Itoa(entry.port.ports[0])] = entry
1✔
1619
                }
1✔
1620
        }
1621
        for key, portentry := range entries {
2✔
1622
                for servicekey := range portentry.serviceKeys {
2✔
1623
                        serviceobj, _, err := cont.serviceIndexer.GetByKey(servicekey)
1✔
1624
                        if err != nil {
1✔
1625
                                logger.Error("Could not lookup service for "+
×
1626
                                        servicekey+": ", err.Error())
×
1627
                                continue
×
1628
                        }
1629
                        if serviceobj == nil {
1✔
1630
                                continue
×
1631
                        }
1632
                        service := serviceobj.(*v1.Service)
1✔
1633

1✔
1634
                        for _, svcPort := range service.Spec.Ports {
2✔
1635
                                if svcPort.Protocol != *prs.port.Protocol ||
1✔
1636
                                        svcPort.TargetPort.String() !=
1✔
1637
                                                key {
1✔
1638
                                        continue
×
1639
                                }
1640
                                proto := portProto(&svcPort.Protocol)
1✔
1641
                                port := strconv.Itoa(int(svcPort.Port))
1✔
1642

1✔
1643
                                updateServiceAugmentForService(portAugments,
1✔
1644
                                        proto, port, service)
1✔
1645

1✔
1646
                                logger.WithFields(logrus.Fields{
1✔
1647
                                        "proto":   proto,
1✔
1648
                                        "port":    port,
1✔
1649
                                        "service": servicekey,
1✔
1650
                                }).Debug("Allowing egress for service by port")
1✔
1651
                        }
1652
                }
1653
        }
1654
        cont.indexMutex.Unlock()
1✔
1655
}
1656

1657
// The egress NetworkPolicy API were designed with the iptables
1658
// implementation in mind and don't contemplate that the layer 4 load
1659
// balancer could happen separately from the policy.  In particular,
1660
// it expects load balancer operations to be applied before the policy
1661
// is applied in both directions, so network policies would apply only
1662
// to pods and not to service IPs. This presents a problem for egress
1663
// policies on ACI since the security groups are applied before load
1664
// balancer operations when egressing, and after when ingressing.
1665
//
1666
// To solve this problem, we use some indexes to discover situations
1667
// when an egress policy covers all the endpoints associated with a
1668
// particular service, and automatically add a rule that allows egress
1669
// to the corresponding service cluster IP and ports.
1670
//
1671
// Note that this differs slightly from the behavior you'd see if you
1672
// applied the load balancer rule first: If the egress policy allows
1673
// access to a subset of the allowed IPs you'd see random failures
1674
// depending on which destination is chosen, while with this approach
1675
// it's all or nothing.  This should not impact any correctly-written
1676
// network policies.
1677
//
1678
// To do this, we work first from the set of pods and subnets matches
1679
// by the egress policy.  We use this to find using the
1680
// endpointsIpIndex all services that contain at least one of the
1681
// matched pods or subnets.  For each of these candidate services, we
1682
// find service ports for which _all_ referenced endpoints are allowed
1683
// by the egress policy.  Note that a service will have the service
1684
// port and the target port; the NetworkPolicy (confusingly) refers to
1685
// the target port.
1686
//
1687
// Once confirmed matches are found, we augment the egress policy with
1688
// extra rules to allow egress to the service IPs and service ports.
1689
//
1690
// As a special case, for rules that match everything, we also have a
1691
// backup index that works through ports which should allow more
1692
// efficient matching when allowing egress to all.
1693
func (cont *AciController) buildServiceAugment(subj apicapi.ApicObject,
1694
        localsubj *hppv1.HostprotSubj,
1695
        portRemoteSubs map[string]*portRemoteSubnet, logger *logrus.Entry) {
1✔
1696
        portAugments := make(map[string]*portServiceAugment)
1✔
1697
        for _, prs := range portRemoteSubs {
2✔
1698
                // TODO ipv6
1✔
1699
                if prs.subnetMap["0.0.0.0/0"] {
2✔
1700
                        cont.getServiceAugmentByPort(prs, portAugments, logger)
1✔
1701
                } else {
2✔
1702
                        cont.getServiceAugmentBySubnet(prs, portAugments, logger)
1✔
1703
                }
1✔
1704
        }
1705
        for _, augment := range portAugments {
2✔
1706
                var remoteIpsv4 []string
1✔
1707
                var remoteIpsv6 []string
1✔
1708
                for ipstr := range augment.ipMap {
2✔
1709
                        ip := net.ParseIP(ipstr)
1✔
1710
                        if ip == nil {
1✔
1711
                                continue
×
1712
                        } else if ip.To4() != nil {
2✔
1713
                                remoteIpsv4 = append(remoteIpsv4, ipstr)
1✔
1714
                        } else if ip.To16() != nil {
3✔
1715
                                remoteIpsv6 = append(remoteIpsv6, ipstr)
1✔
1716
                        }
1✔
1717
                }
1718
                cont.log.Debug("Service Augment: ", augment)
1✔
1719
                if !cont.config.EnableHppDirect && subj != nil {
2✔
1720
                        if len(remoteIpsv4) > 0 {
2✔
1721
                                cont.buildNetPolSubjRule(subj,
1✔
1722
                                        "service_"+augment.proto+"_"+augment.port,
1✔
1723
                                        "egress", "ipv4", augment.proto, augment.port, remoteIpsv4, false)
1✔
1724
                        }
1✔
1725
                        if len(remoteIpsv6) > 0 {
2✔
1726
                                cont.buildNetPolSubjRule(subj,
1✔
1727
                                        "service_"+augment.proto+"_"+augment.port,
1✔
1728
                                        "egress", "ipv6", augment.proto, augment.port, remoteIpsv6, false)
1✔
1729
                        }
1✔
1730
                } else if cont.config.EnableHppDirect && localsubj != nil {
×
1731
                        if len(remoteIpsv4) > 0 {
×
1732
                                cont.buildLocalNetPolSubjRule(localsubj,
×
1733
                                        "service_"+augment.proto+"_"+augment.port,
×
1734
                                        "egress", "ipv4", augment.proto, augment.port, nil, nil, remoteIpsv4)
×
1735
                        }
×
1736
                        if len(remoteIpsv6) > 0 {
×
1737
                                cont.buildLocalNetPolSubjRule(localsubj,
×
1738
                                        "service_"+augment.proto+"_"+augment.port,
×
1739
                                        "egress", "ipv6", augment.proto, augment.port, nil, nil, remoteIpsv6)
×
1740
                        }
×
1741
                }
1742
        }
1743
}
1744

1745
func isAllowAllForAllNamespaces(peers []v1net.NetworkPolicyPeer) bool {
1✔
1746
        addPodSubnetAsRemIp := false
1✔
1747
        if peers != nil && len(peers) > 0 {
2✔
1748
                var emptyPodSel, emptyNsSel bool
1✔
1749
                emptyPodSel = true
1✔
1750
                for _, peer := range peers {
2✔
1751
                        // namespaceSelector: {}
1✔
1752
                        if peer.NamespaceSelector != nil && peer.NamespaceSelector.MatchLabels == nil && peer.NamespaceSelector.MatchExpressions == nil {
1✔
1753
                                emptyNsSel = true
×
1754
                        }
×
1755
                        // podSelector has some fields
1756
                        if peer.PodSelector != nil && (peer.PodSelector.MatchLabels != nil || peer.PodSelector.MatchExpressions != nil) {
2✔
1757
                                emptyPodSel = false
1✔
1758
                        }
1✔
1759
                }
1760
                if emptyNsSel && emptyPodSel {
1✔
1761
                        addPodSubnetAsRemIp = true
×
1762
                }
×
1763
        }
1764
        return addPodSubnetAsRemIp
1✔
1765
}
1766

1767
func (cont *AciController) handleRemIpContUpdate(ns string) bool {
1✔
1768
        cont.hppMutex.Lock()
1✔
1769
        defer cont.hppMutex.Unlock()
1✔
1770

1✔
1771
        sysNs := os.Getenv("SYSTEM_NAMESPACE")
1✔
1772
        aobj, err := cont.getHostprotRemoteIpContainer(ns, sysNs)
1✔
1773
        isUpdate := err == nil
1✔
1774

1✔
1775
        if err != nil && !errors.IsNotFound(err) {
1✔
1776
                cont.log.Error("Error getting HostprotRemoteIpContainers CR: ", err)
×
1777
                return true
×
1778
        }
×
1779

1780
        if !isUpdate {
2✔
1781
                aobj = &hppv1.HostprotRemoteIpContainer{
1✔
1782
                        ObjectMeta: metav1.ObjectMeta{
1✔
1783
                                Name:      ns,
1✔
1784
                                Namespace: sysNs,
1✔
1785
                        },
1✔
1786
                        Spec: hppv1.HostprotRemoteIpContainerSpec{
1✔
1787
                                Name:             ns,
1✔
1788
                                HostprotRemoteIp: []hppv1.HostprotRemoteIp{},
1✔
1789
                        },
1✔
1790
                }
1✔
1791
        } else {
1✔
1792
                cont.log.Debug("HostprotRemoteIpContainers CR already exists: ", aobj)
×
1793
        }
×
1794

1795
        remIpCont, exists := cont.nsRemoteIpCont[ns]
1✔
1796
        if !exists {
2✔
1797
                if isUpdate {
1✔
1798
                        if !cont.deleteHostprotRemoteIpContainer(ns, sysNs) {
×
1799
                                return true
×
1800
                        }
×
1801
                } else {
1✔
1802
                        cont.log.Error("Couldn't find the ns in nsRemoteIpCont cache: ", ns)
1✔
1803
                        return false
1✔
1804
                }
1✔
1805
        }
1806

1807
        aobj.Spec.HostprotRemoteIp = buildHostprotRemoteIpList(remIpCont)
1✔
1808

1✔
1809
        if isUpdate {
1✔
1810
                if !cont.updateHostprotRemoteIpContainer(aobj, sysNs) {
×
1811
                        return true
×
1812
                }
×
1813
        } else {
1✔
1814
                if !cont.createHostprotRemoteIpContainer(aobj, sysNs) {
1✔
1815
                        return true
×
1816
                }
×
1817
        }
1818

1819
        return false
1✔
1820
}
1821

1822
func buildHostprotRemoteIpList(remIpConts map[string]remoteIpCont) []hppv1.HostprotRemoteIp {
1✔
1823
        hostprotRemoteIpList := []hppv1.HostprotRemoteIp{}
1✔
1824

1✔
1825
        for _, remIpCont := range remIpConts {
2✔
1826
                for ip, labels := range remIpCont {
2✔
1827
                        remIpObj := hppv1.HostprotRemoteIp{
1✔
1828
                                Addr: ip,
1✔
1829
                        }
1✔
1830
                        for key, val := range labels {
2✔
1831
                                remIpObj.HppEpLabel = append(remIpObj.HppEpLabel, hppv1.HppEpLabel{
1✔
1832
                                        Key:   key,
1✔
1833
                                        Value: val,
1✔
1834
                                })
1✔
1835
                        }
1✔
1836
                        hostprotRemoteIpList = append(hostprotRemoteIpList, remIpObj)
1✔
1837
                }
1838
        }
1839

1840
        return hostprotRemoteIpList
1✔
1841
}
1842

1843
func (cont *AciController) deleteHppCr(np *v1net.NetworkPolicy) bool {
1✔
1844
        key, err := cache.MetaNamespaceKeyFunc(np)
1✔
1845
        logger := networkPolicyLogger(cont.log, np)
1✔
1846
        if err != nil {
1✔
1847
                logger.Error("Could not create network policy key: ", err)
×
1848
                return false
×
1849
        }
×
1850
        hash, err := util.CreateHashFromNetPol(np)
1✔
1851
        if err != nil {
1✔
1852
                logger.Error("Could not create hash from network policy: ", err)
×
1853
                return false
×
1854
        }
×
1855
        labelKey := cont.aciNameForKey("np", hash)
1✔
1856
        ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
1857
        hppName := strings.ReplaceAll(labelKey, "_", "-")
1✔
1858
        hpp, _ := cont.getHostprotPol(hppName, ns)
1✔
1859
        if hpp == nil {
2✔
1860
                logger.Error("Could not find hostprotPol: ", hppName)
1✔
1861
                return false
1✔
1862
        }
1✔
1863
        netPols := hpp.Spec.NetworkPolicies
1✔
1864
        newNetPols := make([]string, 0)
1✔
1865
        for _, npName := range netPols {
2✔
1866
                if npName != key {
2✔
1867
                        newNetPols = append(newNetPols, npName)
1✔
1868
                }
1✔
1869
        }
1870

1871
        hpp.Spec.NetworkPolicies = newNetPols
1✔
1872

1✔
1873
        if len(newNetPols) > 0 {
2✔
1874
                return cont.updateHostprotPol(hpp, ns)
1✔
1875
        } else {
2✔
1876
                return cont.deleteHostprotPol(hppName, ns)
1✔
1877
        }
1✔
1878
}
1879

1880
func (cont *AciController) updateNodeIpsHostprotRemoteIpContainer(nodeIps map[string]bool) {
1✔
1881
        ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
1882
        name := "nodeips"
1✔
1883

1✔
1884
        aobj, err := cont.getHostprotRemoteIpContainer(name, ns)
1✔
1885
        isUpdate := err == nil
1✔
1886

1✔
1887
        if err != nil && !errors.IsNotFound(err) {
1✔
1888
                cont.log.Error("Error getting HostprotRemoteIpContainers CR: ", err)
×
1889
                return
×
1890
        }
×
1891

1892
        if !isUpdate {
2✔
1893
                aobj = &hppv1.HostprotRemoteIpContainer{
1✔
1894
                        ObjectMeta: metav1.ObjectMeta{
1✔
1895
                                Name:      name,
1✔
1896
                                Namespace: ns,
1✔
1897
                        },
1✔
1898
                        Spec: hppv1.HostprotRemoteIpContainerSpec{
1✔
1899
                                Name:             name,
1✔
1900
                                HostprotRemoteIp: []hppv1.HostprotRemoteIp{},
1✔
1901
                        },
1✔
1902
                }
1✔
1903
        } else {
2✔
1904
                cont.log.Debug("HostprotRemoteIpContainers CR already exists: ", aobj)
1✔
1905
        }
1✔
1906

1907
        existingIps := make(map[string]bool)
1✔
1908
        for _, ip := range aobj.Spec.HostprotRemoteIp {
2✔
1909
                existingIps[ip.Addr] = true
1✔
1910
        }
1✔
1911

1912
        for ip := range nodeIps {
2✔
1913
                if !existingIps[ip] {
2✔
1914
                        aobj.Spec.HostprotRemoteIp = append(aobj.Spec.HostprotRemoteIp, hppv1.HostprotRemoteIp{Addr: ip})
1✔
1915
                }
1✔
1916
        }
1917

1918
        if isUpdate {
2✔
1919
                cont.updateHostprotRemoteIpContainer(aobj, ns)
1✔
1920
        } else {
2✔
1921
                cont.createHostprotRemoteIpContainer(aobj, ns)
1✔
1922
        }
1✔
1923
}
1924

1925
func (cont *AciController) deleteNodeIpsHostprotRemoteIpContainer(nodeIps map[string]bool) {
1✔
1926
        ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
1927
        name := "nodeips"
1✔
1928

1✔
1929
        aobj, _ := cont.getHostprotRemoteIpContainer(name, ns)
1✔
1930
        if aobj == nil {
1✔
1931
                return
×
1932
        }
×
1933

1934
        newHostprotRemoteIps := aobj.Spec.HostprotRemoteIp[:0]
1✔
1935
        for _, hostprotRemoteIp := range aobj.Spec.HostprotRemoteIp {
2✔
1936
                if len(nodeIps) > 0 && !nodeIps[hostprotRemoteIp.Addr] {
2✔
1937
                        newHostprotRemoteIps = append(newHostprotRemoteIps, hostprotRemoteIp)
1✔
1938
                }
1✔
1939
        }
1940

1941
        aobj.Spec.HostprotRemoteIp = newHostprotRemoteIps
1✔
1942

1✔
1943
        if len(newHostprotRemoteIps) > 0 {
2✔
1944
                cont.updateHostprotRemoteIpContainer(aobj, ns)
1✔
1945
        } else {
2✔
1946
                cont.deleteHostprotRemoteIpContainer(name, ns)
1✔
1947
        }
1✔
1948
}
1949

1950
func (cont *AciController) updateNodeHostprotRemoteIpContainer(name string, nodeIps map[string]bool) {
1✔
1951
        ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
1952

1✔
1953
        aobj, err := cont.getHostprotRemoteIpContainer(name, ns)
1✔
1954
        isUpdate := err == nil
1✔
1955

1✔
1956
        if err != nil && !errors.IsNotFound(err) {
1✔
1957
                cont.log.Error("Error getting HostprotRemoteIpContainers CR: ", err)
×
1958
                return
×
1959
        }
×
1960

1961
        if !isUpdate {
2✔
1962
                aobj = &hppv1.HostprotRemoteIpContainer{
1✔
1963
                        ObjectMeta: metav1.ObjectMeta{
1✔
1964
                                Name:      name,
1✔
1965
                                Namespace: ns,
1✔
1966
                        },
1✔
1967
                        Spec: hppv1.HostprotRemoteIpContainerSpec{
1✔
1968
                                Name:             name,
1✔
1969
                                HostprotRemoteIp: []hppv1.HostprotRemoteIp{},
1✔
1970
                        },
1✔
1971
                }
1✔
1972
        } else {
2✔
1973
                cont.log.Debug("HostprotRemoteIpContainers CR already exists: ", aobj)
1✔
1974
        }
1✔
1975

1976
        aobj.Spec.HostprotRemoteIp = make([]hppv1.HostprotRemoteIp, 0, len(nodeIps))
1✔
1977
        for ip := range nodeIps {
2✔
1978
                aobj.Spec.HostprotRemoteIp = append(aobj.Spec.HostprotRemoteIp, hppv1.HostprotRemoteIp{Addr: ip})
1✔
1979
        }
1✔
1980

1981
        if isUpdate {
2✔
1982
                cont.updateHostprotRemoteIpContainer(aobj, ns)
1✔
1983
        } else {
2✔
1984
                cont.createHostprotRemoteIpContainer(aobj, ns)
1✔
1985
        }
1✔
1986
}
1987

1988
func (cont *AciController) deleteNodeHostprotRemoteIpContainer(name string) {
1✔
1989
        ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
1990

1✔
1991
        if _, err := cont.getHostprotRemoteIpContainer(name, ns); err == nil {
2✔
1992
                cont.deleteHostprotRemoteIpContainer(name, ns)
1✔
1993
        }
1✔
1994
}
1995

1996
func (cont *AciController) createNodeHostProtPol(name, nodeName string, nodeIps map[string]bool) {
1✔
1997
        ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
1998
        hppName := strings.ReplaceAll(name, "_", "-")
1✔
1999

1✔
2000
        hpp, err := cont.getHostprotPol(hppName, ns)
1✔
2001
        isUpdate := hpp != nil && err == nil
1✔
2002

1✔
2003
        if err != nil && !errors.IsNotFound(err) {
1✔
2004
                cont.log.Error("Error getting HPP CR: ", err)
×
2005
                return
×
2006
        }
×
2007

2008
        if !isUpdate {
1✔
2009
                hpp = &hppv1.HostprotPol{
×
2010
                        ObjectMeta: metav1.ObjectMeta{
×
2011
                                Name:      hppName,
×
2012
                                Namespace: ns,
×
2013
                        },
×
2014
                        Spec: hppv1.HostprotPolSpec{
×
2015
                                Name:            name,
×
2016
                                NetworkPolicies: []string{name},
×
2017
                                HostprotSubj:    []hppv1.HostprotSubj{},
×
2018
                        },
×
2019
                }
×
2020
        } else {
1✔
2021
                cont.log.Debug("HPP CR already exists: ", hpp)
1✔
2022
                hpp.Spec.HostprotSubj = []hppv1.HostprotSubj{}
1✔
2023
        }
1✔
2024

2025
        if len(nodeIps) > 0 {
2✔
2026
                cont.updateNodeHostprotRemoteIpContainer(nodeName, nodeIps)
1✔
2027
                cont.updateNodeIpsHostprotRemoteIpContainer(nodeIps)
1✔
2028

1✔
2029
                hostprotSubj := hppv1.HostprotSubj{
1✔
2030
                        Name: "local-node",
1✔
2031
                        HostprotRule: []hppv1.HostprotRule{
1✔
2032
                                {
1✔
2033
                                        Name:                "allow-all-egress",
1✔
2034
                                        Direction:           "egress",
1✔
2035
                                        Ethertype:           "ipv4",
1✔
2036
                                        ConnTrack:           "normal",
1✔
2037
                                        RsRemoteIpContainer: []string{nodeName},
1✔
2038
                                },
1✔
2039
                                {
1✔
2040
                                        Name:                "allow-all-ingress",
1✔
2041
                                        Direction:           "ingress",
1✔
2042
                                        Ethertype:           "ipv4",
1✔
2043
                                        ConnTrack:           "normal",
1✔
2044
                                        RsRemoteIpContainer: []string{nodeName},
1✔
2045
                                },
1✔
2046
                        },
1✔
2047
                }
1✔
2048

1✔
2049
                hpp.Spec.HostprotSubj = append(hpp.Spec.HostprotSubj, hostprotSubj)
1✔
2050
        } else {
2✔
2051
                cont.deleteNodeHostprotRemoteIpContainer(nodeName)
1✔
2052
                cont.deleteNodeIpsHostprotRemoteIpContainer(nodeIps)
1✔
2053
        }
1✔
2054

2055
        if isUpdate {
2✔
2056
                cont.updateHostprotPol(hpp, ns)
1✔
2057
        } else {
1✔
2058
                cont.createHostprotPol(hpp, ns)
×
2059
        }
×
2060
}
2061

2062
func (cont *AciController) handleNetPolUpdate(np *v1net.NetworkPolicy) bool {
1✔
2063
        if cont.config.ChainedMode {
1✔
2064
                return false
×
2065
        }
×
2066
        key, err := cache.MetaNamespaceKeyFunc(np)
1✔
2067
        logger := networkPolicyLogger(cont.log, np)
1✔
2068
        if err != nil {
1✔
2069
                logger.Error("Could not create network policy key: ", err)
×
2070
                return false
×
2071
        }
×
2072

2073
        peerPodKeys := cont.netPolIngressPods.GetPodForObj(key)
1✔
2074
        peerPodKeys =
1✔
2075
                append(peerPodKeys, cont.netPolEgressPods.GetPodForObj(key)...)
1✔
2076
        var peerPods []*v1.Pod
1✔
2077
        peerNs := make(map[string]*v1.Namespace)
1✔
2078
        for _, podkey := range peerPodKeys {
2✔
2079
                podobj, exists, err := cont.podIndexer.GetByKey(podkey)
1✔
2080
                if exists && err == nil {
2✔
2081
                        pod := podobj.(*v1.Pod)
1✔
2082
                        if _, nsok := peerNs[pod.ObjectMeta.Namespace]; !nsok {
2✔
2083
                                nsobj, exists, err :=
1✔
2084
                                        cont.namespaceIndexer.GetByKey(pod.ObjectMeta.Namespace)
1✔
2085
                                if !exists || err != nil {
1✔
2086
                                        continue
×
2087
                                }
2088
                                peerNs[pod.ObjectMeta.Namespace] = nsobj.(*v1.Namespace)
1✔
2089
                        }
2090
                        peerPods = append(peerPods, pod)
1✔
2091
                }
2092
        }
2093
        ptypeset := make(map[v1net.PolicyType]bool)
1✔
2094
        for _, t := range np.Spec.PolicyTypes {
2✔
2095
                ptypeset[t] = true
1✔
2096
        }
1✔
2097
        var labelKey string
1✔
2098

1✔
2099
        if !cont.config.EnableHppDirect {
2✔
2100
                if cont.config.HppOptimization {
2✔
2101
                        hash, err := util.CreateHashFromNetPol(np)
1✔
2102
                        if err != nil {
1✔
2103
                                logger.Error("Could not create hash from network policy: ", err)
×
2104
                                return false
×
2105
                        }
×
2106
                        labelKey = cont.aciNameForKey("np", hash)
1✔
2107
                } else {
1✔
2108
                        labelKey = cont.aciNameForKey("np", key)
1✔
2109
                }
1✔
2110
                hpp := apicapi.NewHostprotPol(cont.config.AciPolicyTenant, labelKey)
1✔
2111
                // Generate ingress policies
1✔
2112
                if np.Spec.PolicyTypes == nil || ptypeset[v1net.PolicyTypeIngress] {
2✔
2113
                        subjIngress :=
1✔
2114
                                apicapi.NewHostprotSubj(hpp.GetDn(), "networkpolicy-ingress")
1✔
2115

1✔
2116
                        for i, ingress := range np.Spec.Ingress {
2✔
2117
                                addPodSubnetAsRemIp := isAllowAllForAllNamespaces(ingress.From)
1✔
2118
                                remoteSubnets, _, _, _, _ := cont.getPeerRemoteSubnets(ingress.From,
1✔
2119
                                        np.Namespace, peerPods, peerNs, logger)
1✔
2120
                                cont.buildNetPolSubjRules(strconv.Itoa(i), subjIngress,
1✔
2121
                                        "ingress", ingress.From, remoteSubnets, ingress.Ports, logger, key, np, addPodSubnetAsRemIp)
1✔
2122
                        }
1✔
2123
                        hpp.AddChild(subjIngress)
1✔
2124
                }
2125
                // Generate egress policies
2126
                if np.Spec.PolicyTypes == nil || ptypeset[v1net.PolicyTypeEgress] {
2✔
2127
                        subjEgress :=
1✔
2128
                                apicapi.NewHostprotSubj(hpp.GetDn(), "networkpolicy-egress")
1✔
2129

1✔
2130
                        portRemoteSubs := make(map[string]*portRemoteSubnet)
1✔
2131

1✔
2132
                        for i, egress := range np.Spec.Egress {
2✔
2133
                                addPodSubnetAsRemIp := isAllowAllForAllNamespaces(egress.To)
1✔
2134
                                remoteSubnets, _, _, subnetMap, _ := cont.getPeerRemoteSubnets(egress.To,
1✔
2135
                                        np.Namespace, peerPods, peerNs, logger)
1✔
2136
                                cont.buildNetPolSubjRules(strconv.Itoa(i), subjEgress,
1✔
2137
                                        "egress", egress.To, remoteSubnets, egress.Ports, logger, key, np, addPodSubnetAsRemIp)
1✔
2138

1✔
2139
                                // creating a rule to egress to all on a given port needs
1✔
2140
                                // to enable access to any service IPs/ports that have
1✔
2141
                                // that port as their target port.
1✔
2142
                                if len(egress.To) == 0 {
2✔
2143
                                        subnetMap = map[string]bool{
1✔
2144
                                                "0.0.0.0/0": true,
1✔
2145
                                        }
1✔
2146
                                }
1✔
2147
                                for idx := range egress.Ports {
2✔
2148
                                        port := egress.Ports[idx]
1✔
2149
                                        portkey := portKey(&port)
1✔
2150
                                        updatePortRemoteSubnets(portRemoteSubs, portkey, &port, subnetMap,
1✔
2151
                                                port.Port != nil && port.Port.Type == intstr.Int)
1✔
2152
                                }
1✔
2153
                                if len(egress.Ports) == 0 {
2✔
2154
                                        updatePortRemoteSubnets(portRemoteSubs, "", nil, subnetMap,
1✔
2155
                                                false)
1✔
2156
                                }
1✔
2157
                        }
2158
                        cont.buildServiceAugment(subjEgress, nil, portRemoteSubs, logger)
1✔
2159
                        hpp.AddChild(subjEgress)
1✔
2160
                }
2161
                if cont.config.HppOptimization {
2✔
2162
                        cont.addToHppCache(labelKey, key, apicapi.ApicSlice{hpp}, &hppv1.HostprotPol{})
1✔
2163
                }
1✔
2164
                cont.apicConn.WriteApicObjects(labelKey, apicapi.ApicSlice{hpp})
1✔
2165
        } else {
1✔
2166
                hash, err := util.CreateHashFromNetPol(np)
1✔
2167
                if err != nil {
1✔
2168
                        logger.Error("Could not create hash from network policy: ", err)
×
2169
                        return false
×
2170
                }
×
2171
                labelKey = cont.aciNameForKey("np", hash)
1✔
2172
                ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
2173
                hppName := strings.ReplaceAll(labelKey, "_", "-")
1✔
2174
                hpp, err := cont.getHostprotPol(hppName, ns)
1✔
2175
                isUpdate := err == nil
1✔
2176

1✔
2177
                if err != nil && !errors.IsNotFound(err) {
1✔
2178
                        logger.Error("Error getting HPP CR: ", err)
×
2179
                        return false
×
2180
                }
×
2181

2182
                if isUpdate {
1✔
2183
                        logger.Debug("HPP CR already exists: ", hpp)
×
2184
                        if !slices.Contains(hpp.Spec.NetworkPolicies, key) {
×
2185
                                hpp.Spec.NetworkPolicies = append(hpp.Spec.NetworkPolicies, key)
×
2186
                        }
×
2187
                        hpp.Spec.HostprotSubj = nil
×
2188
                } else {
1✔
2189
                        hpp = &hppv1.HostprotPol{
1✔
2190
                                ObjectMeta: metav1.ObjectMeta{
1✔
2191
                                        Name:      hppName,
1✔
2192
                                        Namespace: ns,
1✔
2193
                                },
1✔
2194
                                Spec: hppv1.HostprotPolSpec{
1✔
2195
                                        Name:            labelKey,
1✔
2196
                                        NetworkPolicies: []string{key},
1✔
2197
                                        HostprotSubj:    nil,
1✔
2198
                                },
1✔
2199
                        }
1✔
2200
                }
1✔
2201

2202
                // Generate ingress policies
2203
                if np.Spec.PolicyTypes == nil || ptypeset[v1net.PolicyTypeIngress] {
2✔
2204
                        subjIngress := &hppv1.HostprotSubj{
1✔
2205
                                Name:         "networkpolicy-ingress",
1✔
2206
                                HostprotRule: []hppv1.HostprotRule{},
1✔
2207
                        }
1✔
2208

1✔
2209
                        for i, ingress := range np.Spec.Ingress {
2✔
2210
                                remoteSubnets, peerNsList, peerremote, _, peerIpBlock := cont.getPeerRemoteSubnets(ingress.From,
1✔
2211
                                        np.Namespace, peerPods, peerNs, logger)
1✔
2212
                                if isAllowAllForAllNamespaces(ingress.From) {
1✔
2213
                                        peerNsList = append(peerNsList, "nodeips")
×
2214
                                }
×
2215
                                if !(len(ingress.From) > 0 && len(remoteSubnets) == 0) {
2✔
2216
                                        cont.buildLocalNetPolSubjRules(strconv.Itoa(i), subjIngress,
1✔
2217
                                                "ingress", peerNsList, peerremote.podSelectors, ingress.Ports,
1✔
2218
                                                logger, key, np, peerIpBlock)
1✔
2219
                                }
1✔
2220
                        }
2221
                        hpp.Spec.HostprotSubj = append(hpp.Spec.HostprotSubj, *subjIngress)
1✔
2222
                }
2223

2224
                if np.Spec.PolicyTypes == nil || ptypeset[v1net.PolicyTypeEgress] {
2✔
2225
                        subjEgress := &hppv1.HostprotSubj{
1✔
2226
                                Name:         "networkpolicy-egress",
1✔
2227
                                HostprotRule: []hppv1.HostprotRule{},
1✔
2228
                        }
1✔
2229

1✔
2230
                        portRemoteSubs := make(map[string]*portRemoteSubnet)
1✔
2231

1✔
2232
                        for i, egress := range np.Spec.Egress {
2✔
2233
                                remoteSubnets, peerNsList, peerremote, subnetMap, peerIpBlock := cont.getPeerRemoteSubnets(egress.To,
1✔
2234
                                        np.Namespace, peerPods, peerNs, logger)
1✔
2235
                                if isAllowAllForAllNamespaces(egress.To) {
1✔
2236
                                        peerNsList = append(peerNsList, "nodeips")
×
2237
                                }
×
2238
                                if !(len(egress.To) > 0 && len(remoteSubnets) == 0) {
2✔
2239
                                        cont.buildLocalNetPolSubjRules(strconv.Itoa(i), subjEgress,
1✔
2240
                                                "egress", peerNsList, peerremote.podSelectors, egress.Ports, logger, key, np, peerIpBlock)
1✔
2241
                                }
1✔
2242

2243
                                if len(egress.To) == 0 {
2✔
2244
                                        subnetMap = map[string]bool{"0.0.0.0/0": true}
1✔
2245
                                }
1✔
2246
                                for idx := range egress.Ports {
2✔
2247
                                        port := egress.Ports[idx]
1✔
2248
                                        portkey := portKey(&port)
1✔
2249
                                        updatePortRemoteSubnets(portRemoteSubs, portkey, &port, subnetMap,
1✔
2250
                                                port.Port != nil && port.Port.Type == intstr.Int)
1✔
2251
                                }
1✔
2252
                                if len(egress.Ports) == 0 {
1✔
2253
                                        updatePortRemoteSubnets(portRemoteSubs, "", nil, subnetMap,
×
2254
                                                false)
×
2255
                                }
×
2256
                        }
2257
                        cont.buildServiceAugment(nil, subjEgress, portRemoteSubs, logger)
1✔
2258
                        hpp.Spec.HostprotSubj = append(hpp.Spec.HostprotSubj, *subjEgress)
1✔
2259
                }
2260

2261
                cont.addToHppCache(labelKey, key, apicapi.ApicSlice{}, hpp)
1✔
2262

1✔
2263
                if isUpdate {
1✔
2264
                        cont.updateHostprotPol(hpp, ns)
×
2265
                } else {
1✔
2266
                        cont.createHostprotPol(hpp, ns)
1✔
2267
                }
1✔
2268
        }
2269
        return false
1✔
2270
}
2271

2272
func (cont *AciController) updateNsRemoteIpCont(pod *v1.Pod, deleted bool) bool {
1✔
2273
        podips := ipsForPod(pod)
1✔
2274
        podns := pod.ObjectMeta.Namespace
1✔
2275
        podname := pod.ObjectMeta.Name
1✔
2276
        podlabels := pod.ObjectMeta.Labels
1✔
2277
        remipconts, ok := cont.nsRemoteIpCont[podns]
1✔
2278

1✔
2279
        if deleted {
2✔
2280
                if !ok {
2✔
2281
                        return true
1✔
2282
                }
1✔
2283

2284
                present := false
1✔
2285
                if remipcont, remipcontok := remipconts[podname]; remipcontok {
1✔
2286
                        for _, ip := range podips {
×
2287
                                if _, ipok := remipcont[ip]; ipok {
×
2288
                                        delete(remipcont, ip)
×
2289
                                        present = true
×
2290
                                }
×
2291
                        }
2292
                        if len(remipcont) < 1 {
×
2293
                                delete(remipconts, podname)
×
2294
                        }
×
2295
                }
2296

2297
                if len(remipconts) < 1 {
1✔
2298
                        delete(cont.nsRemoteIpCont, podns)
×
2299
                        cont.apicConn.ClearApicObjects(cont.aciNameForKey("hostprot-ns-", podns))
×
2300
                        return false
×
2301
                }
×
2302

2303
                if !present {
2✔
2304
                        return false
1✔
2305
                }
1✔
2306
        } else {
1✔
2307
                if !ok {
2✔
2308
                        remipconts = make(remoteIpConts)
1✔
2309
                        cont.nsRemoteIpCont[podns] = remipconts
1✔
2310
                }
1✔
2311

2312
                remipcont, remipcontok := remipconts[podname]
1✔
2313
                if !remipcontok {
2✔
2314
                        remipcont = make(remoteIpCont)
1✔
2315
                }
1✔
2316
                for _, ip := range podips {
2✔
2317
                        remipcont[ip] = podlabels
1✔
2318
                }
1✔
2319
                remipconts[podname] = remipcont
1✔
2320
        }
2321

2322
        return true
1✔
2323
}
2324

2325
func (cont *AciController) addToHppCache(labelKey, key string, hpp apicapi.ApicSlice, hppcr *hppv1.HostprotPol) {
1✔
2326
        cont.indexMutex.Lock()
1✔
2327
        hppRef, ok := cont.hppRef[labelKey]
1✔
2328
        if ok {
2✔
2329
                var found bool
1✔
2330
                for _, npkey := range hppRef.Npkeys {
2✔
2331
                        if npkey == key {
2✔
2332
                                found = true
1✔
2333
                                break
1✔
2334
                        }
2335
                }
2336
                if !found {
1✔
2337
                        hppRef.RefCount++
×
2338
                        hppRef.Npkeys = append(hppRef.Npkeys, key)
×
2339
                }
×
2340
                hppRef.HppObj = hpp
1✔
2341
                hppRef.HppCr = *hppcr
1✔
2342
                cont.hppRef[labelKey] = hppRef
1✔
2343
        } else {
1✔
2344
                var newHppRef hppReference
1✔
2345
                newHppRef.RefCount++
1✔
2346
                newHppRef.HppObj = hpp
1✔
2347
                newHppRef.HppCr = *hppcr
1✔
2348
                newHppRef.Npkeys = append(newHppRef.Npkeys, key)
1✔
2349
                cont.hppRef[labelKey] = newHppRef
1✔
2350
        }
1✔
2351
        cont.indexMutex.Unlock()
1✔
2352
}
2353

2354
func (cont *AciController) removeFromHppCache(np *v1net.NetworkPolicy, key string) (string, bool) {
1✔
2355
        var labelKey string
1✔
2356
        var noRef bool
1✔
2357
        hash, err := util.CreateHashFromNetPol(np)
1✔
2358
        if err != nil {
1✔
2359
                cont.log.Error("Could not create hash from network policy: ", err)
×
2360
                cont.log.Error("Failed to remove np from hpp cache")
×
2361
                return labelKey, noRef
×
2362
        }
×
2363
        labelKey = cont.aciNameForKey("np", hash)
1✔
2364
        cont.indexMutex.Lock()
1✔
2365
        hppRef, ok := cont.hppRef[labelKey]
1✔
2366
        if ok {
2✔
2367
                for i, npkey := range hppRef.Npkeys {
2✔
2368
                        if npkey == key {
2✔
2369
                                hppRef.Npkeys = append(hppRef.Npkeys[:i], hppRef.Npkeys[i+1:]...)
1✔
2370
                                hppRef.RefCount--
1✔
2371
                                break
1✔
2372
                        }
2373
                }
2374
                if hppRef.RefCount > 0 {
1✔
2375
                        cont.hppRef[labelKey] = hppRef
×
2376
                } else {
1✔
2377
                        delete(cont.hppRef, labelKey)
1✔
2378
                        noRef = true
1✔
2379
                }
1✔
2380
        }
2381
        cont.indexMutex.Unlock()
1✔
2382
        return labelKey, noRef
1✔
2383
}
2384

2385
func getNetworkPolicyEgressIpBlocks(np *v1net.NetworkPolicy) map[string]bool {
1✔
2386
        subnets := make(map[string]bool)
1✔
2387
        for _, egress := range np.Spec.Egress {
2✔
2388
                for _, to := range egress.To {
2✔
2389
                        if to.IPBlock != nil && to.IPBlock.CIDR != "" {
2✔
2390
                                subnets[to.IPBlock.CIDR] = true
1✔
2391
                        }
1✔
2392
                }
2393
        }
2394
        return subnets
1✔
2395
}
2396

2397
func (cont *AciController) networkPolicyAdded(obj interface{}) {
1✔
2398
        np := obj.(*v1net.NetworkPolicy)
1✔
2399
        npkey, err := cache.MetaNamespaceKeyFunc(np)
1✔
2400
        if err != nil {
1✔
2401
                networkPolicyLogger(cont.log, np).
×
2402
                        Error("Could not create network policy key: ", err)
×
2403
                return
×
2404
        }
×
2405
        if cont.config.ChainedMode {
1✔
2406
                return
×
2407
        }
×
2408
        cont.netPolPods.UpdateSelectorObj(obj)
1✔
2409
        cont.netPolIngressPods.UpdateSelectorObj(obj)
1✔
2410
        cont.netPolEgressPods.UpdateSelectorObj(obj)
1✔
2411
        cont.indexMutex.Lock()
1✔
2412
        subnets := getNetworkPolicyEgressIpBlocks(np)
1✔
2413
        cont.updateIpIndex(cont.netPolSubnetIndex, nil, subnets, npkey)
1✔
2414

1✔
2415
        ports := cont.getNetPolTargetPorts(np)
1✔
2416
        cont.updateTargetPortIndex(false, npkey, nil, ports)
1✔
2417
        if isNamedPortPresenInNp(np) {
2✔
2418
                cont.nmPortNp[npkey] = true
1✔
2419
        }
1✔
2420
        cont.indexMutex.Unlock()
1✔
2421
        cont.queueNetPolUpdateByKey(npkey)
1✔
2422
}
2423

2424
func (cont *AciController) networkPolicyChanged(oldobj interface{},
2425
        newobj interface{}) {
×
2426
        oldnp := oldobj.(*v1net.NetworkPolicy)
×
2427
        newnp := newobj.(*v1net.NetworkPolicy)
×
2428
        npkey, err := cache.MetaNamespaceKeyFunc(newnp)
×
2429
        if err != nil {
×
2430
                networkPolicyLogger(cont.log, newnp).
×
2431
                        Error("Could not create network policy key: ", err)
×
2432
                return
×
2433
        }
×
2434

2435
        if cont.config.HppOptimization || cont.config.EnableHppDirect {
×
2436
                if !reflect.DeepEqual(oldnp.Spec, newnp.Spec) {
×
2437
                        cont.removeFromHppCache(oldnp, npkey)
×
2438
                }
×
2439
        }
2440

2441
        cont.indexMutex.Lock()
×
2442
        oldSubnets := getNetworkPolicyEgressIpBlocks(oldnp)
×
2443
        newSubnets := getNetworkPolicyEgressIpBlocks(newnp)
×
2444
        cont.updateIpIndex(cont.netPolSubnetIndex, oldSubnets, newSubnets, npkey)
×
2445

×
2446
        oldPorts := cont.getNetPolTargetPorts(oldnp)
×
2447
        newPorts := cont.getNetPolTargetPorts(newnp)
×
2448
        cont.updateTargetPortIndex(false, npkey, oldPorts, newPorts)
×
2449
        cont.indexMutex.Unlock()
×
2450

×
2451
        if !reflect.DeepEqual(oldnp.Spec.PodSelector, newnp.Spec.PodSelector) {
×
2452
                cont.netPolPods.UpdateSelectorObjNoCallback(newobj)
×
2453
        }
×
2454
        if !reflect.DeepEqual(oldnp.Spec.PolicyTypes, newnp.Spec.PolicyTypes) {
×
2455
                peerPodKeys := cont.netPolPods.GetPodForObj(npkey)
×
2456
                for _, podkey := range peerPodKeys {
×
2457
                        cont.podQueue.Add(podkey)
×
2458
                }
×
2459
        }
2460
        var queue bool
×
2461
        if !reflect.DeepEqual(oldnp.Spec.Ingress, newnp.Spec.Ingress) {
×
2462
                cont.netPolIngressPods.UpdateSelectorObjNoCallback(newobj)
×
2463
                queue = true
×
2464
        }
×
2465
        if !reflect.DeepEqual(oldnp.Spec.Egress, newnp.Spec.Egress) {
×
2466
                cont.netPolEgressPods.UpdateSelectorObjNoCallback(newobj)
×
2467
                queue = true
×
2468
        }
×
2469
        if cont.config.EnableHppDirect && !reflect.DeepEqual(oldnp.Spec, newnp.Spec) {
×
2470
                cont.deleteHppCr(oldnp)
×
2471
                queue = true
×
2472
        }
×
2473
        if queue {
×
2474
                cont.queueNetPolUpdateByKey(npkey)
×
2475
        }
×
2476
}
2477

2478
func (cont *AciController) networkPolicyDeleted(obj interface{}) {
1✔
2479
        np, isNetworkpolicy := obj.(*v1net.NetworkPolicy)
1✔
2480
        if !isNetworkpolicy {
1✔
2481
                deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
×
2482
                if !ok {
×
2483
                        networkPolicyLogger(cont.log, np).
×
2484
                                Error("Received unexpected object: ", obj)
×
2485
                        return
×
2486
                }
×
2487
                np, ok = deletedState.Obj.(*v1net.NetworkPolicy)
×
2488
                if !ok {
×
2489
                        networkPolicyLogger(cont.log, np).
×
2490
                                Error("DeletedFinalStateUnknown contained non-Networkpolicy object: ", deletedState.Obj)
×
2491
                        return
×
2492
                }
×
2493
        }
2494
        npkey, err := cache.MetaNamespaceKeyFunc(np)
1✔
2495
        if err != nil {
1✔
2496
                networkPolicyLogger(cont.log, np).
×
2497
                        Error("Could not create network policy key: ", err)
×
2498
                return
×
2499
        }
×
2500

2501
        var labelKey string
1✔
2502
        var noHppRef bool
1✔
2503
        if cont.config.HppOptimization || cont.config.EnableHppDirect {
1✔
2504
                labelKey, noHppRef = cont.removeFromHppCache(np, npkey)
×
2505
        } else {
1✔
2506
                labelKey = cont.aciNameForKey("np", npkey)
1✔
2507
                noHppRef = true
1✔
2508
        }
1✔
2509

2510
        cont.indexMutex.Lock()
1✔
2511
        subnets := getNetworkPolicyEgressIpBlocks(np)
1✔
2512
        cont.updateIpIndex(cont.netPolSubnetIndex, subnets, nil, npkey)
1✔
2513

1✔
2514
        ports := cont.getNetPolTargetPorts(np)
1✔
2515
        cont.updateTargetPortIndex(false, npkey, ports, nil)
1✔
2516
        if isNamedPortPresenInNp(np) {
2✔
2517
                delete(cont.nmPortNp, npkey)
1✔
2518
        }
1✔
2519
        cont.indexMutex.Unlock()
1✔
2520

1✔
2521
        cont.netPolPods.DeleteSelectorObj(obj)
1✔
2522
        cont.netPolIngressPods.DeleteSelectorObj(obj)
1✔
2523
        cont.netPolEgressPods.DeleteSelectorObj(obj)
1✔
2524
        if noHppRef && labelKey != "" {
2✔
2525
                cont.apicConn.ClearApicObjects(labelKey)
1✔
2526
        }
1✔
2527
        if cont.config.EnableHppDirect {
1✔
2528
                cont.deleteHppCr(np)
×
2529
        }
×
2530
}
2531

2532
func (sep *serviceEndpoint) SetNpServiceAugmentForService(servicekey string, service *v1.Service, prs *portRemoteSubnet,
2533
        portAugments map[string]*portServiceAugment, subnetIndex cidranger.Ranger, logger *logrus.Entry) {
1✔
2534
        cont := sep.cont
1✔
2535
        endpointsobj, _, err := cont.endpointsIndexer.GetByKey(servicekey)
1✔
2536
        if err != nil {
1✔
2537
                logger.Error("Could not lookup endpoints for "+
×
2538
                        servicekey+": ", err.Error())
×
2539
                return
×
2540
        }
×
2541
        if endpointsobj == nil {
1✔
2542
                return
×
2543
        }
×
2544
        endpoints := endpointsobj.(*v1.Endpoints)
1✔
2545
        portstrings := make(map[string]bool)
1✔
2546
        ports := cont.getPortNums(prs.port)
1✔
2547
        for _, port := range ports {
2✔
2548
                portstrings[strconv.Itoa(port)] = true
1✔
2549
        }
1✔
2550
        for _, svcPort := range service.Spec.Ports {
2✔
2551
                _, ok := portstrings[svcPort.TargetPort.String()]
1✔
2552
                if prs.port != nil &&
1✔
2553
                        (svcPort.Protocol != *prs.port.Protocol || !ok) {
1✔
2554
                        // egress rule does not match service target port
×
2555
                        continue
×
2556
                }
2557
                for _, subset := range endpoints.Subsets {
2✔
2558
                        var foundEpPort *v1.EndpointPort
1✔
2559
                        for ix := range subset.Ports {
2✔
2560
                                if subset.Ports[ix].Name == svcPort.Name ||
1✔
2561
                                        (len(service.Spec.Ports) == 1 &&
1✔
2562
                                                subset.Ports[ix].Name == "") {
2✔
2563
                                        foundEpPort = &subset.Ports[ix]
1✔
2564
                                        break
1✔
2565
                                }
2566
                        }
2567
                        if foundEpPort == nil {
1✔
2568
                                continue
×
2569
                        }
2570

2571
                        incomplete := false
1✔
2572
                        incomplete = incomplete ||
1✔
2573
                                !checkEndpoints(subnetIndex, subset.Addresses)
1✔
2574
                        incomplete = incomplete || !checkEndpoints(subnetIndex,
1✔
2575
                                subset.NotReadyAddresses)
1✔
2576

1✔
2577
                        if incomplete {
2✔
2578
                                continue
1✔
2579
                        }
2580

2581
                        proto := portProto(&foundEpPort.Protocol)
1✔
2582
                        port := strconv.Itoa(int(svcPort.Port))
1✔
2583
                        updateServiceAugmentForService(portAugments,
1✔
2584
                                proto, port, service)
1✔
2585

1✔
2586
                        logger.WithFields(logrus.Fields{
1✔
2587
                                "proto":   proto,
1✔
2588
                                "port":    port,
1✔
2589
                                "service": servicekey,
1✔
2590
                        }).Debug("Allowing egress for service by subnet match")
1✔
2591
                }
2592
        }
2593
}
2594

2595
func (seps *serviceEndpointSlice) SetNpServiceAugmentForService(servicekey string, service *v1.Service,
2596
        prs *portRemoteSubnet, portAugments map[string]*portServiceAugment,
2597
        subnetIndex cidranger.Ranger, logger *logrus.Entry) {
1✔
2598
        cont := seps.cont
1✔
2599
        portstrings := make(map[string]bool)
1✔
2600
        ports := cont.getPortNums(prs.port)
1✔
2601
        for _, port := range ports {
2✔
2602
                portstrings[strconv.Itoa(port)] = true
1✔
2603
        }
1✔
2604
        label := map[string]string{discovery.LabelServiceName: service.ObjectMeta.Name}
1✔
2605
        selector := labels.SelectorFromSet(label)
1✔
2606
        cache.ListAllByNamespace(cont.endpointSliceIndexer, service.ObjectMeta.Namespace, selector,
1✔
2607
                func(endpointSliceobj interface{}) {
2✔
2608
                        endpointSlices := endpointSliceobj.(*discovery.EndpointSlice)
1✔
2609
                        for _, svcPort := range service.Spec.Ports {
2✔
2610
                                _, ok := portstrings[svcPort.TargetPort.String()]
1✔
2611
                                if prs.port != nil &&
1✔
2612
                                        (svcPort.Protocol != *prs.port.Protocol || !ok) {
2✔
2613
                                        // egress rule does not match service target port
1✔
2614
                                        continue
1✔
2615
                                }
2616
                                var foundEpPort *discovery.EndpointPort
1✔
2617
                                for ix := range endpointSlices.Ports {
2✔
2618
                                        if *endpointSlices.Ports[ix].Name == svcPort.Name ||
1✔
2619
                                                (len(service.Spec.Ports) == 1 &&
1✔
2620
                                                        *endpointSlices.Ports[ix].Name == "") {
2✔
2621
                                                foundEpPort = &endpointSlices.Ports[ix]
1✔
2622
                                                cont.log.Debug("Found EpPort: ", foundEpPort)
1✔
2623
                                                break
1✔
2624
                                        }
2625
                                }
2626
                                if foundEpPort == nil {
1✔
2627
                                        return
×
2628
                                }
×
2629
                                // @FIXME for non ready address
2630
                                incomplete := false
1✔
2631
                                for _, endpoint := range endpointSlices.Endpoints {
2✔
2632
                                        incomplete = incomplete || !checkEndpointslices(subnetIndex, endpoint.Addresses)
1✔
2633
                                }
1✔
2634
                                if incomplete {
2✔
2635
                                        continue
1✔
2636
                                }
2637
                                proto := portProto(foundEpPort.Protocol)
1✔
2638
                                port := strconv.Itoa(int(svcPort.Port))
1✔
2639
                                cont.log.Debug("updateServiceAugmentForService: ", service)
1✔
2640
                                updateServiceAugmentForService(portAugments,
1✔
2641
                                        proto, port, service)
1✔
2642

1✔
2643
                                logger.WithFields(logrus.Fields{
1✔
2644
                                        "proto":   proto,
1✔
2645
                                        "port":    port,
1✔
2646
                                        "service": servicekey,
1✔
2647
                                }).Debug("Allowing egress for service by subnet match")
1✔
2648
                        }
2649
                })
2650
}
2651

2652
func isNamedPortPresenInNp(np *v1net.NetworkPolicy) bool {
1✔
2653
        for _, egress := range np.Spec.Egress {
2✔
2654
                for _, p := range egress.Ports {
2✔
2655
                        if p.Port.Type == intstr.String {
2✔
2656
                                return true
1✔
2657
                        }
1✔
2658
                }
2659
        }
2660
        return false
1✔
2661
}
2662

2663
func (cont *AciController) checkPodNmpMatchesNp(npkey, podkey string) bool {
1✔
2664
        podobj, exists, err := cont.podIndexer.GetByKey(podkey)
1✔
2665
        if err != nil {
1✔
2666
                return false
×
2667
        }
×
2668
        if !exists || podobj == nil {
2✔
2669
                return false
1✔
2670
        }
1✔
2671
        pod := podobj.(*v1.Pod)
1✔
2672
        npobj, npexists, nperr := cont.networkPolicyIndexer.GetByKey(npkey)
1✔
2673
        if npexists && nperr == nil && npobj != nil {
2✔
2674
                np := npobj.(*v1net.NetworkPolicy)
1✔
2675
                for _, egress := range np.Spec.Egress {
2✔
2676
                        for _, p := range egress.Ports {
2✔
2677
                                if p.Port.Type == intstr.String {
2✔
2678
                                        _, err := k8util.LookupContainerPortNumberByName(*pod, p.Port.String())
1✔
2679
                                        if err == nil {
2✔
2680
                                                return true
1✔
2681
                                        }
1✔
2682
                                }
2683
                        }
2684
                }
2685
        }
2686
        return false
1✔
2687
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc