forked from projectcalico/felix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bpf_test.go
3143 lines (2732 loc) · 112 KB
/
bpf_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2021 Tigera, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build fvtests
package fv_test
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net"
"os"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/davecgh/go-spew/spew"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/kubernetes"
"github.com/projectcalico/libcalico-go/lib/apiconfig"
api "github.com/projectcalico/libcalico-go/lib/apis/v3"
client "github.com/projectcalico/libcalico-go/lib/clientv3"
"github.com/projectcalico/libcalico-go/lib/ipam"
cnet "github.com/projectcalico/libcalico-go/lib/net"
"github.com/projectcalico/libcalico-go/lib/numorstring"
options2 "github.com/projectcalico/libcalico-go/lib/options"
"github.com/projectcalico/felix/bpf"
"github.com/projectcalico/felix/bpf/conntrack"
"github.com/projectcalico/felix/bpf/nat"
. "github.com/projectcalico/felix/fv/connectivity"
"github.com/projectcalico/felix/fv/containers"
"github.com/projectcalico/felix/fv/infrastructure"
"github.com/projectcalico/felix/fv/utils"
"github.com/projectcalico/felix/fv/workload"
"github.com/projectcalico/felix/timeshim"
)
// We run with and without connection-time load balancing for a couple of reasons:
// - We can only test the non-connection time NAT logic (and node ports) with it disabled.
// - Since the connection time program applies to the whole host, the different felix nodes actually share the
// connection-time program. This is a bit of a broken test but it's better than nothing since all felix nodes
// should be programming the same NAT mappings.
var _ = describeBPFTests(withProto("tcp"), withConnTimeLoadBalancingEnabled(), withNonProtocolDependentTests())
var _ = describeBPFTests(withProto("udp"), withConnTimeLoadBalancingEnabled())
var _ = describeBPFTests(withProto("udp"), withConnTimeLoadBalancingEnabled(), withUDPUnConnected())
var _ = describeBPFTests(withProto("tcp"))
var _ = describeBPFTests(withProto("udp"))
var _ = describeBPFTests(withProto("udp"), withUDPUnConnected())
var _ = describeBPFTests(withProto("udp"), withUDPConnectedRecvMsg(), withConnTimeLoadBalancingEnabled())
var _ = describeBPFTests(withTunnel("ipip"), withProto("tcp"), withConnTimeLoadBalancingEnabled())
var _ = describeBPFTests(withTunnel("ipip"), withProto("udp"), withConnTimeLoadBalancingEnabled())
var _ = describeBPFTests(withTunnel("ipip"), withProto("tcp"))
var _ = describeBPFTests(withTunnel("ipip"), withProto("udp"))
var _ = describeBPFTests(withProto("tcp"), withDSR())
var _ = describeBPFTests(withProto("udp"), withDSR())
var _ = describeBPFTests(withTunnel("ipip"), withProto("tcp"), withDSR())
var _ = describeBPFTests(withTunnel("ipip"), withProto("udp"), withDSR())
var _ = describeBPFTests(withTunnel("wireguard"), withProto("tcp"))
var _ = describeBPFTests(withTunnel("wireguard"), withProto("tcp"), withConnTimeLoadBalancingEnabled())
// Run a stripe of tests with BPF logging disabled since the compiler tends to optimise the code differently
// with debug disabled and that can lead to verifier issues.
var _ = describeBPFTests(withProto("tcp"),
withConnTimeLoadBalancingEnabled(),
withBPFLogLevel("info"))
type bpfTestOptions struct {
connTimeEnabled bool
protocol string
udpUnConnected bool
bpfLogLevel string
tunnel string
dsr bool
udpConnRecvMsg bool
nonProtoTests bool
}
type bpfTestOpt func(opts *bpfTestOptions)
func withProto(proto string) bpfTestOpt {
return func(opts *bpfTestOptions) {
opts.protocol = proto
}
}
func withConnTimeLoadBalancingEnabled() bpfTestOpt {
return func(opts *bpfTestOptions) {
opts.connTimeEnabled = true
}
}
func withNonProtocolDependentTests() bpfTestOpt {
return func(opts *bpfTestOptions) {
opts.nonProtoTests = true
}
}
func withBPFLogLevel(level string) bpfTestOpt {
return func(opts *bpfTestOptions) {
opts.bpfLogLevel = level
}
}
func withTunnel(tunnel string) bpfTestOpt {
return func(opts *bpfTestOptions) {
opts.tunnel = tunnel
}
}
func withUDPUnConnected() bpfTestOpt {
return func(opts *bpfTestOptions) {
opts.udpUnConnected = true
}
}
func withDSR() bpfTestOpt {
return func(opts *bpfTestOptions) {
opts.dsr = true
}
}
func withUDPConnectedRecvMsg() bpfTestOpt {
return func(opts *bpfTestOptions) {
opts.udpConnRecvMsg = true
}
}
const expectedRouteDump = `10.65.0.0/16: remote in-pool nat-out
10.65.0.2/32: local workload in-pool nat-out idx -
10.65.0.3/32: local workload in-pool nat-out idx -
10.65.0.4/32: local workload in-pool nat-out idx -
10.65.1.0/26: remote workload in-pool nat-out nh FELIX_1
10.65.2.0/26: remote workload in-pool nat-out nh FELIX_2
111.222.0.1/32: local host
111.222.1.1/32: remote host
111.222.2.1/32: remote host
FELIX_0/32: local host idx -
FELIX_1/32: remote host
FELIX_2/32: remote host`
const expectedRouteDumpWithTunnelAddr = `10.65.0.0/16: remote in-pool nat-out
10.65.0.1/32: local host
10.65.0.2/32: local workload in-pool nat-out idx -
10.65.0.3/32: local workload in-pool nat-out idx -
10.65.0.4/32: local workload in-pool nat-out idx -
10.65.1.0/26: remote workload in-pool nat-out nh FELIX_1
10.65.2.0/26: remote workload in-pool nat-out nh FELIX_2
111.222.0.1/32: local host
111.222.1.1/32: remote host
111.222.2.1/32: remote host
FELIX_0/32: local host idx -
FELIX_1/32: remote host
FELIX_2/32: remote host`
const extIP = "10.1.2.3"
func describeBPFTests(opts ...bpfTestOpt) bool {
if os.Getenv("FELIX_FV_ENABLE_BPF") != "true" {
// Non-BPF run.
return true
}
testOpts := bpfTestOptions{
bpfLogLevel: "debug",
tunnel: "none",
}
for _, o := range opts {
o(&testOpts)
}
testIfTCP := testOpts.protocol == "tcp"
protoExt := ""
if testOpts.udpUnConnected {
protoExt = "-unconnected"
}
if testOpts.udpConnRecvMsg {
protoExt = "-conn-recvmsg"
}
desc := fmt.Sprintf("_BPF_ _BPF-SAFE_ BPF tests (%s%s, ct=%v, log=%s, tunnel=%s, dsr=%v)",
testOpts.protocol, protoExt, testOpts.connTimeEnabled,
testOpts.bpfLogLevel, testOpts.tunnel, testOpts.dsr,
)
return infrastructure.DatastoreDescribe(desc, []apiconfig.DatastoreType{apiconfig.Kubernetes}, func(getInfra infrastructure.InfraFactory) {
var (
infra infrastructure.DatastoreInfra
felixes []*infrastructure.Felix
calicoClient client.Interface
cc *Checker
externalClient *containers.Container
deadWorkload *workload.Workload
options infrastructure.TopologyOptions
numericProto uint8
felixPanicExpected bool
)
switch testOpts.protocol {
case "tcp":
numericProto = 6
case "udp":
numericProto = 17
default:
Fail("bad protocol option")
}
BeforeEach(func() {
felixPanicExpected = false
infra = getInfra()
cc = &Checker{
CheckSNAT: true,
}
cc.Protocol = testOpts.protocol
if testOpts.protocol == "udp" && testOpts.udpUnConnected {
cc.Protocol += "-noconn"
}
if testOpts.protocol == "udp" && testOpts.udpConnRecvMsg {
cc.Protocol += "-recvmsg"
}
options = infrastructure.DefaultTopologyOptions()
options.FelixLogSeverity = "debug"
options.NATOutgoingEnabled = true
options.AutoHEPsEnabled = true
// override IPIP being enabled by default
options.IPIPEnabled = false
options.IPIPRoutesEnabled = false
switch testOpts.tunnel {
case "none":
// nothing
case "ipip":
options.IPIPEnabled = true
options.IPIPRoutesEnabled = true
case "wireguard":
// Delay running Felix until Node resource has been created.
options.DelayFelixStart = true
options.TriggerDelayedFelixStart = true
// Wireguard doesn't support IPv6, disable it.
options.EnableIPv6 = false
// Allocate tunnel address for Wireguard.
options.WireguardEnabled = true
// Enable Wireguard.
options.ExtraEnvVars["FELIX_WIREGUARDENABLED"] = "true"
default:
Fail("bad tunnel option")
}
options.ExtraEnvVars["FELIX_BPFConnectTimeLoadBalancingEnabled"] = fmt.Sprint(testOpts.connTimeEnabled)
options.ExtraEnvVars["FELIX_BPFLogLevel"] = fmt.Sprint(testOpts.bpfLogLevel)
if testOpts.dsr {
options.ExtraEnvVars["FELIX_BPFExternalServiceMode"] = "dsr"
}
options.ExternalIPs = true
options.ExtraEnvVars["FELIX_BPFExtToServiceConnmark"] = "0x80"
})
JustAfterEach(func() {
if CurrentGinkgoTestDescription().Failed {
currBpfsvcs, currBpfeps := dumpNATmaps(felixes)
for i, felix := range felixes {
felix.Exec("iptables-save", "-c")
felix.Exec("ip", "r")
felix.Exec("ip", "link")
felix.Exec("ip", "addr")
felix.Exec("ip", "route", "show", "cached")
felix.Exec("calico-bpf", "ipsets", "dump")
felix.Exec("calico-bpf", "routes", "dump")
felix.Exec("calico-bpf", "nat", "dump")
felix.Exec("calico-bpf", "conntrack", "dump")
felix.Exec("calico-bpf", "arp", "dump")
log.Infof("[%d]FrontendMap: %+v", i, currBpfsvcs[i])
log.Infof("[%d]NATBackend: %+v", i, currBpfeps[i])
log.Infof("[%d]SendRecvMap: %+v", i, dumpSendRecvMap(felix))
}
externalClient.Exec("ip", "route", "show", "cached")
}
})
AfterEach(func() {
log.Info("AfterEach starting")
for _, f := range felixes {
if !felixPanicExpected {
f.Exec("calico-bpf", "connect-time", "clean")
}
f.Stop()
}
externalClient.Stop()
log.Info("AfterEach done")
})
AfterEach(func() {
infra.Stop()
})
createPolicy := func(policy *api.GlobalNetworkPolicy) *api.GlobalNetworkPolicy {
log.WithField("policy", dumpResource(policy)).Info("Creating policy")
policy, err := calicoClient.GlobalNetworkPolicies().Create(utils.Ctx, policy, utils.NoOptions)
Expect(err).NotTo(HaveOccurred())
return policy
}
updatePolicy := func(policy *api.GlobalNetworkPolicy) *api.GlobalNetworkPolicy {
log.WithField("policy", dumpResource(policy)).Info("Updating policy")
policy, err := calicoClient.GlobalNetworkPolicies().Update(utils.Ctx, policy, utils.NoOptions)
Expect(err).NotTo(HaveOccurred())
return policy
}
_ = updatePolicy
Describe("with a single node and an allow-all policy", func() {
var (
hostW *workload.Workload
w [2]*workload.Workload
wepCopy [2]*api.WorkloadEndpoint
)
if !testOpts.connTimeEnabled {
// These tests don't depend on NAT.
return
}
if testOpts.tunnel != "none" {
// Single node so tunnel doesn't matter.
return
}
JustBeforeEach(func() {
felixes, calicoClient = infrastructure.StartNNodeTopology(1, options, infra)
hostW = workload.Run(
felixes[0],
"host",
"default",
felixes[0].IP, // Same IP as felix means "run in the host's namespace"
"8055",
testOpts.protocol)
// Start a couple of workloads so we can check workload-to-workload and workload-to-host.
for i := 0; i < 2; i++ {
wIP := fmt.Sprintf("10.65.0.%d", i+2)
w[i] = workload.Run(felixes[0], fmt.Sprintf("w%d", i), "default", wIP, "8055", testOpts.protocol)
w[i].WorkloadEndpoint.Labels = map[string]string{"name": w[i].Name}
// WEP gets clobbered when we add it to the datastore, take a copy so we can re-create the WEP.
wepCopy[i] = w[i].WorkloadEndpoint
w[i].ConfigureInInfra(infra)
}
err := infra.AddDefaultDeny()
Expect(err).NotTo(HaveOccurred())
pol := api.NewGlobalNetworkPolicy()
pol.Namespace = "fv"
pol.Name = "policy-1"
pol.Spec.Ingress = []api.Rule{{Action: "Allow"}}
pol.Spec.Egress = []api.Rule{{Action: "Allow"}}
pol.Spec.Selector = "all()"
pol = createPolicy(pol)
})
if testOpts.bpfLogLevel == "debug" && testOpts.protocol == "tcp" {
Describe("with custom IptablesMarkMask", func() {
BeforeEach(func() {
// Disable core dumps, we know we're about to cause a panic.
options.ExtraEnvVars["GOTRACEBACK"] = ""
felixPanicExpected = true
})
It("0xffff000 not covering BPF bits should panic", func() {
felixPanicExpected = true
panicC := felixes[0].WatchStdoutFor(regexp.MustCompile("PANIC.*IptablesMarkMask doesn't cover bits that are used"))
fc := api.NewFelixConfiguration()
fc.Name = "default"
mark := uint32(0x0ffff000)
fc.Spec.IptablesMarkMask = &mark
fc, err := calicoClient.FelixConfigurations().Create(context.Background(), fc, options2.SetOptions{})
Expect(err).NotTo(HaveOccurred())
Eventually(panicC, "5s", "100ms").Should(BeClosed())
})
It("0xfff00000 only covering BPF bits should panic", func() {
panicC := felixes[0].WatchStdoutFor(regexp.MustCompile("PANIC.*Not enough mark bits available"))
fc := api.NewFelixConfiguration()
fc.Name = "default"
mark := uint32(0xfff00000)
fc.Spec.IptablesMarkMask = &mark
fc, err := calicoClient.FelixConfigurations().Create(context.Background(), fc, options2.SetOptions{})
Expect(err).NotTo(HaveOccurred())
Eventually(panicC, "5s", "100ms").Should(BeClosed())
})
})
}
Describe("with DefaultEndpointToHostAction=DROP", func() {
BeforeEach(func() {
options.ExtraEnvVars["FELIX_DefaultEndpointToHostAction"] = "DROP"
})
It("should only allow traffic from workload to workload", func() {
cc.ExpectSome(w[0], w[1])
cc.ExpectSome(w[1], w[0])
cc.ExpectNone(w[1], hostW)
cc.ExpectSome(hostW, w[0])
cc.CheckConnectivity()
})
})
getMapIDByPath := func(felix *infrastructure.Felix, filename string) (int, error) {
out, err := felix.ExecOutput("bpftool", "map", "show", "pinned", filename, "-j")
if err != nil {
return 0, err
}
var mapMeta struct {
ID int `json:"id"`
Error string `json:"error"`
}
err = json.Unmarshal([]byte(out), &mapMeta)
if err != nil {
return 0, err
}
if mapMeta.Error != "" {
return 0, errors.New(mapMeta.Error)
}
return mapMeta.ID, nil
}
mustGetMapIDByPath := func(felix *infrastructure.Felix, filename string) int {
var mapID int
Eventually(func() error {
var err error
mapID, err = getMapIDByPath(felix, filename)
return err
}, "5s").ShouldNot(HaveOccurred())
return mapID
}
Describe("with DefaultEndpointToHostAction=ACCEPT", func() {
BeforeEach(func() {
options.ExtraEnvVars["FELIX_DefaultEndpointToHostAction"] = "ACCEPT"
})
It("should allow traffic from workload to workload and to/from host", func() {
cc.ExpectSome(w[0], w[1])
cc.ExpectSome(w[1], w[0])
cc.ExpectSome(w[1], hostW)
cc.ExpectSome(hostW, w[0])
cc.CheckConnectivity()
})
})
if testOpts.protocol != "udp" { // No need to run these tests per-protocol.
mapPath := conntrack.Map(&bpf.MapContext{}).Path()
Describe("with map repinning enabled", func() {
BeforeEach(func() {
options.ExtraEnvVars["FELIX_DebugBPFMapRepinEnabled"] = "true"
})
It("should repin maps", func() {
// Wait for the first felix to create its maps.
mapID := mustGetMapIDByPath(felixes[0], mapPath)
// Now, start a completely independent felix, which will get its own bpffs. It should re-pin the
// maps, picking up the ones from the first felix.
extraFelix, _ := infrastructure.StartSingleNodeTopology(options, infra)
defer extraFelix.Stop()
secondMapID := mustGetMapIDByPath(extraFelix, mapPath)
Expect(mapID).NotTo(BeNumerically("==", 0))
Expect(mapID).To(BeNumerically("==", secondMapID))
})
})
Describe("with map repinning disabled", func() {
It("should repin maps", func() {
// Wait for the first felix to create its maps.
mapID := mustGetMapIDByPath(felixes[0], mapPath)
// Now, start a completely independent felix, which will get its own bpffs. It should make its own
// maps.
extraFelix, _ := infrastructure.StartSingleNodeTopology(options, infra)
defer extraFelix.Stop()
secondMapID := mustGetMapIDByPath(extraFelix, mapPath)
Expect(mapID).NotTo(BeNumerically("==", 0))
Expect(mapID).NotTo(BeNumerically("==", secondMapID))
})
})
It("should clean up jump maps", func() {
numJumpMaps := func() int {
output, err := felixes[0].ExecOutput("sh", "-c", "find /sys/fs/bpf/tc -name cali_jump")
Expect(err).NotTo(HaveOccurred())
return strings.Count(output, "cali_jump")
}
expJumpMaps := func(numWorkloads int) int {
numHostIfaces := 1
expectedNumMaps := 2*numWorkloads + 2*numHostIfaces
return expectedNumMaps
}
// Check start-of-day number of interfaces.
Eventually(numJumpMaps, "15s", "200ms").Should(
BeNumerically("==", expJumpMaps(len(w))),
"Unexpected number of jump maps at start of day")
// Remove a workload.
w[0].RemoveFromInfra(infra)
w[0].Stop()
// Need a long timeout here because felix throttles cleanups.
Eventually(numJumpMaps, "15s", "200ms").Should(
BeNumerically("==", expJumpMaps(len(w)-1)),
"Unexpected number of jump maps after removing workload")
})
It("should recover if the BPF programs are removed", func() {
flapInterface := func() {
By("Flapping interface")
felixes[0].Exec("ip", "link", "set", "down", w[0].InterfaceName)
felixes[0].Exec("ip", "link", "set", "up", w[0].InterfaceName)
}
recreateWEP := func() {
By("Recreating WEP.")
w[0].RemoveFromInfra(infra)
w[0].WorkloadEndpoint = wepCopy[0]
w[0].ConfigureInInfra(infra)
}
for _, trigger := range []func(){flapInterface, recreateWEP} {
// Wait for initial programming to complete.
cc.Expect(Some, w[0], w[1])
cc.CheckConnectivity()
cc.ResetExpectations()
By("handling ingress program removal")
felixes[0].Exec("tc", "filter", "del", "ingress", "dev", w[0].InterfaceName)
// Removing the ingress program should break connectivity due to the lack of "seen" mark.
cc.Expect(None, w[0], w[1])
cc.CheckConnectivity()
cc.ResetExpectations()
// Trigger felix to recover.
trigger()
cc.Expect(Some, w[0], w[1])
cc.CheckConnectivity()
// Check the program is put back.
Eventually(func() string {
out, _ := felixes[0].ExecOutput("tc", "filter", "show", "ingress", "dev", w[0].InterfaceName)
return out
}, "5s", "200ms").Should(ContainSubstring("calico_from_workload_ep"))
By("handling egress program removal")
felixes[0].Exec("tc", "filter", "del", "egress", "dev", w[0].InterfaceName)
// Removing the egress program doesn't stop traffic.
// Trigger felix to recover.
trigger()
// Check the program is put back.
Eventually(func() string {
out, _ := felixes[0].ExecOutput("tc", "filter", "show", "egress", "dev", w[0].InterfaceName)
return out
}, "5s", "200ms").Should(ContainSubstring("calico_to_workload_ep"))
cc.CheckConnectivity()
By("Handling qdisc removal")
felixes[0].Exec("tc", "qdisc", "delete", "dev", w[0].InterfaceName, "clsact")
// Trigger felix to recover.
trigger()
// Check programs are put back.
Eventually(func() string {
out, _ := felixes[0].ExecOutput("tc", "filter", "show", "ingress", "dev", w[0].InterfaceName)
return out
}, "5s", "200ms").Should(ContainSubstring("calico_from_workload_ep"))
Eventually(func() string {
out, _ := felixes[0].ExecOutput("tc", "filter", "show", "egress", "dev", w[0].InterfaceName)
return out
}, "5s", "200ms").Should(ContainSubstring("calico_to_workload_ep"))
cc.CheckConnectivity()
cc.ResetExpectations()
// Add a policy to block traffic.
By("Adding deny policy")
denyPol := api.NewGlobalNetworkPolicy()
denyPol.Name = "policy-2"
var one float64 = 1
denyPol.Spec.Order = &one
denyPol.Spec.Ingress = []api.Rule{{Action: "Deny"}}
denyPol.Spec.Egress = []api.Rule{{Action: "Deny"}}
denyPol.Spec.Selector = "all()"
denyPol = createPolicy(denyPol)
cc.Expect(None, w[0], w[1])
cc.Expect(None, w[1], w[0])
cc.CheckConnectivity()
cc.ResetExpectations()
By("Removing deny policy")
_, err := calicoClient.GlobalNetworkPolicies().Delete(context.Background(), "policy-2", options2.DeleteOptions{})
Expect(err).NotTo(HaveOccurred())
cc.Expect(Some, w[0], w[1])
cc.Expect(Some, w[1], w[0])
cc.CheckConnectivity()
cc.ResetExpectations()
}
})
}
if testOpts.nonProtoTests {
// We can only test that felix _sets_ this because the flag is one-way and cannot be unset.
It("should enable the kernel.unprivileged_bpf_disabled sysctl", func() {
Eventually(func() string {
out, err := felixes[0].ExecOutput("sysctl", "kernel.unprivileged_bpf_disabled")
if err != nil {
log.WithError(err).Error("Failed to run sysctl")
}
return out
}).Should(ContainSubstring("kernel.unprivileged_bpf_disabled = 1"))
})
}
})
const numNodes = 3
var (
w [numNodes][2]*workload.Workload
hostW [numNodes]*workload.Workload
)
setupCluster := func() {
felixes, calicoClient = infrastructure.StartNNodeTopology(numNodes, options, infra)
addWorkload := func(run bool, ii, wi, port int, labels map[string]string) *workload.Workload {
if labels == nil {
labels = make(map[string]string)
}
wIP := fmt.Sprintf("10.65.%d.%d", ii, wi+2)
wName := fmt.Sprintf("w%d%d", ii, wi)
w := workload.New(felixes[ii], wName, "default",
wIP, strconv.Itoa(port), testOpts.protocol)
if run {
w.Start()
}
labels["name"] = w.Name
labels["workload"] = "regular"
w.WorkloadEndpoint.Labels = labels
w.ConfigureInInfra(infra)
if options.UseIPPools {
// Assign the workload's IP in IPAM, this will trigger calculation of routes.
err := calicoClient.IPAM().AssignIP(context.Background(), ipam.AssignIPArgs{
IP: cnet.MustParseIP(wIP),
HandleID: &w.Name,
Attrs: map[string]string{
ipam.AttributeNode: felixes[ii].Hostname,
},
Hostname: felixes[ii].Hostname,
})
Expect(err).NotTo(HaveOccurred())
}
return w
}
// Start a host networked workload on each host for connectivity checks.
for ii := range felixes {
// We tell each host-networked workload to open:
// TODO: Copied from another test
// - its normal (uninteresting) port, 8055
// - port 2379, which is both an inbound and an outbound failsafe port
// - port 22, which is an inbound failsafe port.
// This allows us to test the interaction between do-not-track policy and failsafe
// ports.
hostW[ii] = workload.Run(
felixes[ii],
fmt.Sprintf("host%d", ii),
"default",
felixes[ii].IP, // Same IP as felix means "run in the host's namespace"
"8055",
testOpts.protocol)
hostW[ii].WorkloadEndpoint.Labels = map[string]string{"name": hostW[ii].Name}
hostW[ii].ConfigureInInfra(infra)
// Two workloads on each host so we can check the same host and other host cases.
w[ii][0] = addWorkload(true, ii, 0, 8055, map[string]string{"port": "8055"})
w[ii][1] = addWorkload(true, ii, 1, 8056, nil)
}
// Create a workload on node 0 that does not run, but we can use it to set up paths
deadWorkload = addWorkload(false, 0, 2, 8057, nil)
// We will use this container to model an external client trying to connect into
// workloads on a host. Create a route in the container for the workload CIDR.
// TODO: Copied from another test
externalClient = containers.Run("external-client",
containers.RunOpts{AutoRemove: true},
"--privileged", // So that we can add routes inside the container.
utils.Config.BusyboxImage,
"/bin/sh", "-c", "sleep 1000")
_ = externalClient
err := infra.AddDefaultDeny()
Expect(err).NotTo(HaveOccurred())
}
Describe(fmt.Sprintf("with a %d node cluster", numNodes), func() {
BeforeEach(func() {
setupCluster()
})
if testOpts.protocol == "udp" && testOpts.udpUnConnected {
It("should have no connectivity to a pod before it is added to the datamodel", func() {
// Above BeforeEach adds a default-deny but for this test we want policy to be open
// so that it's only the lack of datastore configuration that blocks traffic.
policy := api.NewNetworkPolicy()
policy.Name = "allow-all"
policy.Namespace = "default"
one := float64(1)
policy.Spec.Order = &one
policy.Spec.Ingress = []api.Rule{{Action: api.Allow}}
policy.Spec.Egress = []api.Rule{{Action: api.Allow}}
policy.Spec.Selector = "all()"
_, err := calicoClient.NetworkPolicies().Create(utils.Ctx, policy, utils.NoOptions)
// The hardest path to secure with BPF is packets to the newly-added workload. We can't block
// the traffic with BPF until we have a BPF program in place so we rely on iptables catch-alls.
// Set up a workload but do not add it to the datastore.
dpOnlyWorkload := workload.New(felixes[1], "w-dp", "default", "10.65.1.5", "8057", testOpts.protocol)
err = dpOnlyWorkload.Start()
Expect(err).NotTo(HaveOccurred())
felixes[1].Exec("ip", "route", "add", dpOnlyWorkload.IP, "dev", dpOnlyWorkload.InterfaceName, "scope", "link")
// Attach tcpdump to the workload so we can verify that we don't see any packets at all. We need
// to verify ingress and egress separately since a round-trip test would be blocked by either.
tcpdump := dpOnlyWorkload.AttachTCPDump()
tcpdump.SetLogEnabled(true)
pattern := fmt.Sprintf(`IP .* %s\.8057: UDP`, dpOnlyWorkload.IP)
tcpdump.AddMatcher("UDP-8057", regexp.MustCompile(pattern))
tcpdump.Start()
defer tcpdump.Stop()
// Send packets in the background.
var wg sync.WaitGroup
wg.Add(1)
ctx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second)
defer cancelFn()
go func() {
defer wg.Done()
defer GinkgoRecover()
for {
if ctx.Err() != nil {
return
}
_, err = w[1][0].RunCmd("/pktgen", w[1][0].IP, dpOnlyWorkload.IP, "udp",
"--port-src", "30444", "--port-dst", "8057")
Expect(err).NotTo(HaveOccurred())
time.Sleep(100 * (time.Millisecond))
}
}()
defer wg.Wait()
Consistently(tcpdump.MatchCountFn("UDP-8057"), "5s", "200ms").Should(
BeNumerically("==", 0),
"Traffic to the workload should be blocked before datastore is configured")
dpOnlyWorkload.ConfigureInInfra(infra)
Eventually(tcpdump.MatchCountFn("UDP-8057"), "5s", "200ms").Should(
BeNumerically(">", 0),
"Traffic to the workload should be allowed after datastore is configured")
})
}
It("should have correct routes", func() {
expectedRoutes := expectedRouteDump
if felixes[0].ExpectedIPIPTunnelAddr != "" || felixes[0].ExpectedVXLANTunnelAddr != "" || felixes[0].ExpectedWireguardTunnelAddr != "" {
expectedRoutes = expectedRouteDumpWithTunnelAddr
}
dumpRoutes := func() string {
out, err := felixes[0].ExecOutput("calico-bpf", "routes", "dump")
if err != nil {
return fmt.Sprint(err)
}
lines := strings.Split(out, "\n")
var filteredLines []string
idxRE := regexp.MustCompile(`idx \d+`)
for _, l := range lines {
l = strings.TrimLeft(l, " ")
if len(l) == 0 {
continue
}
l = strings.ReplaceAll(l, felixes[0].IP, "FELIX_0")
l = strings.ReplaceAll(l, felixes[1].IP, "FELIX_1")
l = strings.ReplaceAll(l, felixes[2].IP, "FELIX_2")
l = idxRE.ReplaceAllLiteralString(l, "idx -")
filteredLines = append(filteredLines, l)
}
sort.Strings(filteredLines)
return strings.Join(filteredLines, "\n")
}
Eventually(dumpRoutes).Should(Equal(expectedRoutes), dumpRoutes)
})
It("should only allow traffic from the local host by default", func() {
// Same host, other workload.
cc.ExpectNone(w[0][0], w[0][1])
cc.ExpectNone(w[0][1], w[0][0])
// Workloads on other host.
cc.ExpectNone(w[0][0], w[1][0])
cc.ExpectNone(w[1][0], w[0][0])
// Hosts.
cc.ExpectSome(felixes[0], w[0][0])
cc.ExpectNone(felixes[1], w[0][0])
cc.CheckConnectivity()
})
It("should allow host -> host", func() {
// XXX as long as there is no HEP policy
// using hostW as a sink
cc.Expect(Some, felixes[0], hostW[1])
cc.Expect(Some, felixes[1], hostW[0])
cc.CheckConnectivity()
})
Context("with a policy allowing ingress to w[0][0] from all regular workloads", func() {
var (
pol *api.GlobalNetworkPolicy
k8sClient *kubernetes.Clientset
)
BeforeEach(func() {
pol = api.NewGlobalNetworkPolicy()
pol.Namespace = "fv"
pol.Name = "policy-1"
pol.Spec.Ingress = []api.Rule{
{
Action: "Allow",
Source: api.EntityRule{
Selector: "workload=='regular'",
},
},
}
pol.Spec.Egress = []api.Rule{
{
Action: "Allow",
Source: api.EntityRule{
Selector: "workload=='regular'",
},
},
}
pol.Spec.Selector = "workload=='regular'"
pol = createPolicy(pol)
k8sClient = infra.(*infrastructure.K8sDatastoreInfra).K8sClient
_ = k8sClient
})
It("should handle NAT outgoing", func() {
By("SNATting outgoing traffic with the flag set")
cc.ExpectSNAT(w[0][0], felixes[0].IP, hostW[1])
cc.CheckConnectivity()
if testOpts.tunnel == "none" {
By("Leaving traffic alone with the flag clear")
pool, err := calicoClient.IPPools().Get(context.TODO(), "test-pool", options2.GetOptions{})
Expect(err).NotTo(HaveOccurred())
pool.Spec.NATOutgoing = false
pool, err = calicoClient.IPPools().Update(context.TODO(), pool, options2.SetOptions{})
Expect(err).NotTo(HaveOccurred())
cc.ResetExpectations()
cc.ExpectSNAT(w[0][0], w[0][0].IP, hostW[1])
cc.CheckConnectivity()
By("SNATting again with the flag set")
pool.Spec.NATOutgoing = true
pool, err = calicoClient.IPPools().Update(context.TODO(), pool, options2.SetOptions{})
Expect(err).NotTo(HaveOccurred())
cc.ResetExpectations()
cc.ExpectSNAT(w[0][0], felixes[0].IP, hostW[1])
cc.CheckConnectivity()
}
})
It("connectivity from all workloads via workload 0's main IP", func() {
cc.ExpectSome(w[0][1], w[0][0])
cc.ExpectSome(w[1][0], w[0][0])
cc.ExpectSome(w[1][1], w[0][0])
cc.CheckConnectivity()
})
// Test doesn't use services so ignore the runs with those turned on.
if testOpts.protocol == "tcp" && !testOpts.connTimeEnabled && !testOpts.dsr {
It("should not be able to spoof TCP", func() {
// Make sure the workload is up and has configured its routes.
By("Having basic connectivity")
cc.Expect(Some, w[0][0], w[1][0])
cc.CheckConnectivity()
// Add a second interface to the workload, this will allow us to adjust the routes
// inside the workload to move connections from one interface to the other.
By("Having basic connectivity after setting up the spoof interface")
w[0][0].AddSpoofInterface()
// Check that the route manipulation succeeded.
cc.CheckConnectivity()
cc.ResetExpectations()
// PHASE 1: basic single-shot connectivity checks to check that the test infra
// is basically doing what we want. I.e. if felix and the workload disagree on
// interface then new connections get dropped.
// Switch routes to use the spoofed interface, should fail.
By("Workload using spoof0, felix expecting eth0, should fail")
w[0][0].UseSpoofInterface(true)
cc.Expect(None, w[0][0], w[1][0])
cc.CheckConnectivity()
cc.ResetExpectations()
By("Workload using spoof0, felix expecting spoof0, should succeed")
w[0][0].RemoveFromInfra(infra)
w[0][0].ConfigureInInfraAsSpoofInterface(infra)
cc.Expect(Some, w[0][0], w[1][0])
cc.CheckConnectivity()
cc.ResetExpectations()
By("Both back to eth0, should succeed")
w[0][0].RemoveSpoofWEPFromInfra(infra)
w[0][0].ConfigureInInfra(infra)
w[0][0].UseSpoofInterface(false)
cc.Expect(Some, w[0][0], w[1][0])
cc.CheckConnectivity()
cc.ResetExpectations()
// PHASE 2: keep a connection up and move it from one interface to the other using the pod's
// routes. To the host this looks like one workload is spoofing the other.
By("Starting permanent connection")
pc := w[0][0].StartPersistentConnection(w[1][0].IP, 8055, workload.PersistentConnectionOpts{
MonitorConnectivity: true,
})
defer pc.Stop()
expectPongs := func() {
EventuallyWithOffset(1, pc.SinceLastPong, "5s").Should(
BeNumerically("<", time.Second),
"Expected to see pong responses on the connection but didn't receive any")
log.Info("Pongs received within last 1s")
}
expectNoPongs := func() {
EventuallyWithOffset(1, pc.SinceLastPong, "5s").Should(
BeNumerically(">", time.Second),
"Expected to see pong responses stop but continued to receive them")
log.Info("No pongs received for >1s")
}
// Simulate a second WEP for the spoof interface.
w[0][0].ConfigureOtherWEPInInfraAsSpoofInterface(infra)
// Should get some pongs to start with...
By("Should get pongs to start with")