/
route_linux.go
2099 lines (1958 loc) · 72.6 KB
/
route_linux.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 2020 Antrea Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package route
import (
"bytes"
"fmt"
"net"
"reflect"
"sort"
"strconv"
"sync"
"time"
"github.com/containernetworking/plugins/pkg/ip"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog/v2"
utilnet "k8s.io/utils/net"
"antrea.io/antrea/pkg/agent/config"
"antrea.io/antrea/pkg/agent/servicecidr"
"antrea.io/antrea/pkg/agent/types"
"antrea.io/antrea/pkg/agent/util/ipset"
"antrea.io/antrea/pkg/agent/util/iptables"
utilnetlink "antrea.io/antrea/pkg/agent/util/netlink"
"antrea.io/antrea/pkg/agent/util/sysctl"
binding "antrea.io/antrea/pkg/ovs/openflow"
"antrea.io/antrea/pkg/ovs/ovsconfig"
"antrea.io/antrea/pkg/util/env"
utilip "antrea.io/antrea/pkg/util/ip"
)
const (
vxlanPort = 4789
genevePort = 6081
// Antrea managed ipset.
// antreaPodIPSet contains all Per-Node IPAM Pod CIDRs of this cluster.
antreaPodIPSet = "ANTREA-POD-IP"
// antreaPodIP6Set contains all Per-Node IPAM IPv6 Pod CIDRs of this cluster.
antreaPodIP6Set = "ANTREA-POD-IP6"
// Antrea managed ipset. Max name length is 31 chars.
// localAntreaFlexibleIPAMPodIPSet contains all AntreaFlexibleIPAM Pod IPs of this Node.
localAntreaFlexibleIPAMPodIPSet = "LOCAL-FLEXIBLE-IPAM-POD-IP"
// localAntreaFlexibleIPAMPodIP6Set contains all AntreaFlexibleIPAM Pod IPv6s of this Node.
localAntreaFlexibleIPAMPodIP6Set = "LOCAL-FLEXIBLE-IPAM-POD-IP6"
// clusterNodeIPSet contains all other Node IPs in the cluster.
clusterNodeIPSet = "CLUSTER-NODE-IP"
// clusterNodeIP6Set contains all other Node IP6s in the cluster.
clusterNodeIP6Set = "CLUSTER-NODE-IP6"
// Antrea proxy NodePort IP
antreaNodePortIPSet = "ANTREA-NODEPORT-IP"
antreaNodePortIP6Set = "ANTREA-NODEPORT-IP6"
// Antrea managed iptables chains.
antreaForwardChain = "ANTREA-FORWARD"
antreaPreRoutingChain = "ANTREA-PREROUTING"
antreaPostRoutingChain = "ANTREA-POSTROUTING"
antreaInputChain = "ANTREA-INPUT"
antreaOutputChain = "ANTREA-OUTPUT"
antreaMangleChain = "ANTREA-MANGLE"
serviceIPv4CIDRKey = "serviceIPv4CIDRKey"
serviceIPv6CIDRKey = "serviceIPv6CIDRKey"
preNodeNetworkPolicyIngressRulesChain = "ANTREA-POL-PRE-INGRESS-RULES"
preNodeNetworkPolicyEgressRulesChain = "ANTREA-POL-PRE-EGRESS-RULES"
)
// Client implements Interface.
var _ Interface = &Client{}
var (
// globalVMAC is used in the IPv6 neighbor configuration to advertise ND solicitation for the IPv6 address of the
// host gateway interface on other Nodes.
globalVMAC, _ = net.ParseMAC("aa:bb:cc:dd:ee:ff")
// The system auto-generated IPv6 link-local route always uses "fe80::/64" as the destination regardless of the
// interface's global address's mask.
_, llrCIDR, _ = net.ParseCIDR("fe80::/64")
)
// Client takes care of routing container packets in host network, coordinating ip route, ip rule, iptables and ipset.
type Client struct {
nodeConfig *config.NodeConfig
networkConfig *config.NetworkConfig
noSNAT bool
iptables iptables.Interface
ipset ipset.Interface
netlink utilnetlink.Interface
// nodeRoutes caches ip routes to remote Pods. It's a map of podCIDR to routes.
nodeRoutes sync.Map
// nodeNeighbors caches IPv6 Neighbors to remote host gateway
nodeNeighbors sync.Map
// markToSNATIP caches marks to SNAT IPs. It's used in Egress feature.
markToSNATIP sync.Map
// iptablesInitialized is used to notify when iptables initialization is done.
iptablesInitialized chan struct{}
proxyAll bool
connectUplinkToBridge bool
multicastEnabled bool
isCloudEKS bool
nodeNetworkPolicyEnabled bool
// serviceRoutes caches ip routes about Services.
serviceRoutes sync.Map
// serviceNeighbors caches neighbors.
serviceNeighbors sync.Map
// nodePortsIPv4 caches all existing IPv4 NodePorts.
nodePortsIPv4 sync.Map
// nodePortsIPv6 caches all existing IPv6 NodePorts.
nodePortsIPv6 sync.Map
// clusterNodeIPs stores the IPv4 of all other Nodes in the cluster
clusterNodeIPs sync.Map
// clusterNodeIP6s stores the IPv6 of all other Nodes in the cluster
clusterNodeIP6s sync.Map
// egressRoutes caches ip routes about Egresses.
egressRoutes sync.Map
// The latest calculated Service CIDRs can be got from serviceCIDRProvider.
serviceCIDRProvider servicecidr.Interface
// nodeNetworkPolicyIPSetsIPv4 caches all existing IPv4 ipsets for NodeNetworkPolicy.
nodeNetworkPolicyIPSetsIPv4 sync.Map
// nodeNetworkPolicyIPSetsIPv6 caches all existing IPv6 ipsets for NodeNetworkPolicy.
nodeNetworkPolicyIPSetsIPv6 sync.Map
// nodeNetworkPolicyIPTablesIPv4 caches all existing IPv4 iptables chains and rules for NodeNetworkPolicy.
nodeNetworkPolicyIPTablesIPv4 sync.Map
// nodeNetworkPolicyIPTablesIPv6 caches all existing IPv6 iptables chains and rules for NodeNetworkPolicy.
nodeNetworkPolicyIPTablesIPv6 sync.Map
// deterministic represents whether to write iptables chains and rules for NodeNetworkPolicy deterministically when
// syncIPTables is called. Enabling it may carry a performance impact. It's disabled by default and should only be
// used in testing.
deterministic bool
}
// NewClient returns a route client.
func NewClient(networkConfig *config.NetworkConfig,
noSNAT bool,
proxyAll bool,
connectUplinkToBridge bool,
nodeNetworkPolicyEnabled bool,
multicastEnabled bool,
serviceCIDRProvider servicecidr.Interface) (*Client, error) {
return &Client{
networkConfig: networkConfig,
noSNAT: noSNAT,
proxyAll: proxyAll,
multicastEnabled: multicastEnabled,
connectUplinkToBridge: connectUplinkToBridge,
nodeNetworkPolicyEnabled: nodeNetworkPolicyEnabled,
ipset: ipset.NewClient(),
netlink: &netlink.Handle{},
isCloudEKS: env.IsCloudEKS(),
serviceCIDRProvider: serviceCIDRProvider,
}, nil
}
// Initialize initializes all infrastructures required to route container packets in host network.
// It is idempotent and can be safely called on every startup.
func (c *Client) Initialize(nodeConfig *config.NodeConfig, done func()) error {
c.nodeConfig = nodeConfig
c.iptablesInitialized = make(chan struct{})
var err error
// Sets up the ipset that will be used in iptables.
if err = c.syncIPSet(); err != nil {
return fmt.Errorf("failed to initialize ipset: %v", err)
}
c.iptables, err = iptables.New(c.networkConfig.IPv4Enabled, c.networkConfig.IPv6Enabled)
if err != nil {
return fmt.Errorf("error creating IPTables instance: %v", err)
}
// Sets up the iptables infrastructure required to route packets in host network.
// It's called in a goroutine because xtables lock may not be acquired immediately.
go func() {
klog.Info("Initializing iptables")
defer done()
defer close(c.iptablesInitialized)
var backoffTime = 2 * time.Second
for {
if err := c.syncIPTables(); err != nil {
klog.Errorf("Failed to initialize iptables: %v - will retry in %v", err, backoffTime)
time.Sleep(backoffTime)
continue
}
break
}
klog.Info("Initialized iptables")
}()
// Sets up the IP routes and IP rule required to route packets in host network.
if err := c.initIPRoutes(); err != nil {
return fmt.Errorf("failed to initialize ip routes: %v", err)
}
// Ensure IPv4 forwarding is enabled if it is a dual-stack or IPv4-only cluster.
if c.nodeConfig.NodeIPv4Addr != nil {
if err := sysctl.EnsureSysctlNetValue("ipv4/ip_forward", 1); err != nil {
return fmt.Errorf("failed to enable IPv4 forwarding: %w", err)
}
}
// Ensure IPv6 forwarding is enabled if it is a dual-stack or IPv6-only cluster.
if c.nodeConfig.NodeIPv6Addr != nil {
if err := sysctl.EnsureSysctlNetValue("ipv6/conf/all/forwarding", 1); err != nil {
return fmt.Errorf("failed to enable IPv6 forwarding: %w", err)
}
}
// Set up the IP routes and sysctl parameters to support all Services in AntreaProxy.
if c.proxyAll {
if err := c.initServiceIPRoutes(); err != nil {
return fmt.Errorf("failed to initialize Service IP routes: %v", err)
}
}
// Build static iptables rules for NodeNetworkPolicy.
if c.nodeNetworkPolicyEnabled {
c.initNodeNetworkPolicy()
}
return nil
}
// Run waits for iptables initialization, then periodically syncs iptables rules.
// It will not return until stopCh is closed.
func (c *Client) Run(stopCh <-chan struct{}) {
<-c.iptablesInitialized
klog.InfoS("Starting iptables, ipset and route sync", "interval", SyncInterval)
wait.Until(c.syncIPInfra, SyncInterval, stopCh)
}
// syncIPInfra is idempotent and can be safely called on every sync operation.
func (c *Client) syncIPInfra() {
// Sync ipset before syncing iptables rules
if err := c.syncIPSet(); err != nil {
klog.ErrorS(err, "Failed to sync ipset")
return
}
if err := c.syncIPTables(); err != nil {
klog.ErrorS(err, "Failed to sync iptables")
return
}
if err := c.syncRoute(); err != nil {
klog.ErrorS(err, "Failed to sync route")
}
klog.V(3).Info("Successfully synced iptables, ipset and route")
}
type routeKey struct {
linkIndex int
dst string
gw string
tableID int
}
func (c *Client) syncRoute() error {
routeList, err := c.netlink.RouteList(nil, netlink.FAMILY_ALL)
if err != nil {
return err
}
routeKeys := sets.New[routeKey]()
for i := range routeList {
r := &routeList[i]
if r.Dst == nil {
continue
}
routeKeys.Insert(routeKey{
linkIndex: r.LinkIndex,
dst: r.Dst.String(),
gw: r.Gw.String(),
tableID: r.Table,
})
}
restoreRoute := func(route *netlink.Route) bool {
if routeKeys.Has(routeKey{
linkIndex: route.LinkIndex,
dst: route.Dst.String(),
gw: route.Gw.String(),
tableID: route.Table,
}) {
return true
}
if err := c.netlink.RouteReplace(route); err != nil {
klog.ErrorS(err, "Failed to sync route", "Route", route)
return false
}
return true
}
c.nodeRoutes.Range(func(_, v interface{}) bool {
for _, route := range v.([]*netlink.Route) {
if !restoreRoute(route) {
return false
}
}
return true
})
if c.proxyAll {
c.serviceRoutes.Range(func(_, v interface{}) bool {
route := v.(*netlink.Route)
return restoreRoute(route)
})
}
c.egressRoutes.Range(func(_, v any) bool {
for _, route := range v.([]*netlink.Route) {
if !restoreRoute(route) {
return false
}
}
return true
})
// These routes are installed automatically by the kernel when the address is configured on
// the interface (with "proto kernel"). If these routes are deleted manually by mistake, we
// restore them as part of this sync (without "proto kernel"). An alternative would be to
// flap the interface, but this seems like a better approach.
gwAutoconfRoutes := []*netlink.Route{}
if c.nodeConfig.PodIPv4CIDR != nil {
gwAutoconfRoutes = append(gwAutoconfRoutes, &netlink.Route{
LinkIndex: c.nodeConfig.GatewayConfig.LinkIndex,
Dst: c.nodeConfig.PodIPv4CIDR,
Src: c.nodeConfig.GatewayConfig.IPv4,
Scope: netlink.SCOPE_LINK,
})
}
if c.nodeConfig.PodIPv6CIDR != nil {
// Here we assume the IPv6 link-local address always exists on antrea-gw0
// to avoid unexpected issues in the IPv6 forwarding.
gwAutoconfRoutes = append(gwAutoconfRoutes, &netlink.Route{
LinkIndex: c.nodeConfig.GatewayConfig.LinkIndex,
Dst: c.nodeConfig.PodIPv6CIDR,
Src: c.nodeConfig.GatewayConfig.IPv6,
Scope: netlink.SCOPE_LINK,
},
// Restore the IPv6 link-local route.
&netlink.Route{
LinkIndex: c.nodeConfig.GatewayConfig.LinkIndex,
Dst: llrCIDR,
Scope: netlink.SCOPE_LINK,
},
)
}
for _, route := range gwAutoconfRoutes {
restoreRoute(route)
}
return nil
}
// syncIPSet ensures that the required ipset exists and it has the initial members.
func (c *Client) syncIPSet() error {
// In policy-only mode, Node Pod CIDR is undefined.
if c.networkConfig.TrafficEncapMode.IsNetworkPolicyOnly() {
return nil
}
if err := c.ipset.CreateIPSet(antreaPodIPSet, ipset.HashNet, false); err != nil {
return err
}
if err := c.ipset.CreateIPSet(antreaPodIP6Set, ipset.HashNet, true); err != nil {
return err
}
// Loop all valid PodCIDR and add into the corresponding ipset.
for _, podCIDR := range []*net.IPNet{c.nodeConfig.PodIPv4CIDR, c.nodeConfig.PodIPv6CIDR} {
if podCIDR != nil {
ipsetName := getIPSetName(podCIDR.IP)
if err := c.ipset.AddEntry(ipsetName, podCIDR.String()); err != nil {
return err
}
}
}
// If proxy full is enabled, create NodePort ipset.
if c.proxyAll {
if err := c.ipset.CreateIPSet(antreaNodePortIPSet, ipset.HashIPPort, false); err != nil {
return err
}
if err := c.ipset.CreateIPSet(antreaNodePortIP6Set, ipset.HashIPPort, true); err != nil {
return err
}
c.nodePortsIPv4.Range(func(k, _ interface{}) bool {
ipSetEntry := k.(string)
if err := c.ipset.AddEntry(antreaNodePortIPSet, ipSetEntry); err != nil {
return false
}
return true
})
c.nodePortsIPv6.Range(func(k, _ interface{}) bool {
ipSetEntry := k.(string)
if err := c.ipset.AddEntry(antreaNodePortIP6Set, ipSetEntry); err != nil {
return false
}
return true
})
}
if c.connectUplinkToBridge {
if err := c.ipset.CreateIPSet(localAntreaFlexibleIPAMPodIPSet, ipset.HashIP, false); err != nil {
return err
}
if err := c.ipset.CreateIPSet(localAntreaFlexibleIPAMPodIP6Set, ipset.HashIP, true); err != nil {
return err
}
}
if c.multicastEnabled && c.networkConfig.TrafficEncapMode.SupportsEncap() {
if err := c.ipset.CreateIPSet(clusterNodeIPSet, ipset.HashIP, false); err != nil {
return err
}
if err := c.ipset.CreateIPSet(clusterNodeIP6Set, ipset.HashIP, true); err != nil {
return err
}
c.clusterNodeIPs.Range(func(_, v interface{}) bool {
ipsetEntry := v.(string)
if err := c.ipset.AddEntry(clusterNodeIPSet, ipsetEntry); err != nil {
return false
}
return true
})
c.clusterNodeIP6s.Range(func(_, v interface{}) bool {
ipSetEntry := v.(string)
if err := c.ipset.AddEntry(clusterNodeIP6Set, ipSetEntry); err != nil {
return false
}
return true
})
}
if c.nodeNetworkPolicyEnabled {
c.nodeNetworkPolicyIPSetsIPv4.Range(func(key, value any) bool {
ipsetName := key.(string)
ipsetEntries := value.(sets.Set[string])
if err := c.ipset.CreateIPSet(ipsetName, ipset.HashNet, false); err != nil {
return false
}
for ipsetEntry := range ipsetEntries {
if err := c.ipset.AddEntry(ipsetName, ipsetEntry); err != nil {
return false
}
}
return true
})
c.nodeNetworkPolicyIPSetsIPv6.Range(func(key, value any) bool {
ipsetName := key.(string)
ipsetEntries := value.(sets.Set[string])
if err := c.ipset.CreateIPSet(ipsetName, ipset.HashNet, true); err != nil {
return false
}
for ipsetEntry := range ipsetEntries {
if err := c.ipset.AddEntry(ipsetName, ipsetEntry); err != nil {
return false
}
}
return true
})
}
return nil
}
func getIPSetName(ip net.IP) string {
if ip.To4() == nil {
return antreaPodIP6Set
}
return antreaPodIPSet
}
func getNodePortIPSetName(isIPv6 bool) string {
if isIPv6 {
return antreaNodePortIP6Set
} else {
return antreaNodePortIPSet
}
}
func getLocalAntreaFlexibleIPAMPodIPSetName(isIPv6 bool) string {
if isIPv6 {
return localAntreaFlexibleIPAMPodIP6Set
} else {
return localAntreaFlexibleIPAMPodIPSet
}
}
// writeEKSMangleRules writes an additional iptables mangle rule to the
// iptablesData buffer, to set the traffic mark to the connection mark for
// traffic coming out of the gateway. This rule is needed for 2 cases:
// - for the reverse path for NodePort Service traffic (see
// https://github.com/antrea-io/antrea/issues/678).
// - for Pod-to-external traffic that needs to be SNATed (see
// https://github.com/antrea-io/antrea/issues/3946).
func (c *Client) writeEKSMangleRules(iptablesData *bytes.Buffer) {
// TODO: the following should be taking into account:
// 1) this rule is only needed if AWS_VPC_CNI_NODE_PORT_SUPPORT is set
// to true (which is the default) or if AWS_VPC_K8S_CNI_EXTERNALSNAT
// is set to false (which is also the default). If both settings are
// changed, we do not need to install the rule.
// 2) this option is not documented but the mark value can be
// configured with AWS_VPC_K8S_CNI_CONNMARK.
// While we do not have access to these environment variables, we could
// look for existing rules installed by the AWS VPC CNI, and determine
// whether we need to install this rule.
klog.V(2).InfoS("Add iptables mangle rules for EKS")
writeLine(iptablesData, []string{
"-A", antreaMangleChain,
"-m", "comment", "--comment", `"Antrea: AWS, primary ENI"`,
"-i", c.nodeConfig.GatewayConfig.Name, "-j", "CONNMARK",
"--restore-mark", "--nfmask", "0x80", "--ctmask", "0x80",
}...)
}
// writeEKSNATRules writes additional iptables nat rules to the iptablesData
// buffer. The first rule sets the connection mark for Pod-to-external traffic
// that needs to be SNATed. Without the mark, this traffic is not routed using
// the correct route table for Pods getting an IP address from a secondary
// network interface (ENI). The second rule restores the packet mark from the
// connection mark. That rule will only apply to the first packet of the
// connection. For subsequent packets, the rule installed buy writeEKSMangleRule
// will take care of restoring the mark. We need that rule because the mangle
// table is traversed before the nat table.
// See https://docs.aws.amazon.com/eks/latest/userguide/external-snat.html and
// https://github.com/antrea-io/antrea/issues/3946 for more details.
func (c *Client) writeEKSNATRules(iptablesData *bytes.Buffer) {
// TODO: just like for writeEKSMangleRule, these rules should ideally be
// installed conditionally, when AWS_VPC_K8S_CNI_EXTERNALSNAT is set to
// false (which is the default value).
klog.V(2).InfoS("Add iptables nat rules for EKS")
writeLine(iptablesData, []string{
"-A", antreaPreRoutingChain,
"-i", c.nodeConfig.GatewayConfig.Name,
"-m", "comment", "--comment", `"Antrea: AWS, outbound connections"`,
"-j", "AWS-CONNMARK-CHAIN-0",
}...)
// The AWS VPC CNI already installs the same rule in the PREROUTING
// chain. However, that rule will typically be visited before the
// ANTREA-PREROUTING chain, hence we need to install our own copy of the
// rule.
writeLine(iptablesData, []string{
"-A", antreaPreRoutingChain,
"-m", "comment", "--comment", `"Antrea: AWS, CONNMARK (first packet)"`,
"-j", "CONNMARK", "--restore-mark", "--nfmask", "0x80", "--ctmask", "0x80",
}...)
}
// syncIPTables ensure that the iptables infrastructure we use is set up.
// It's idempotent and can safely be called on every startup.
func (c *Client) syncIPTables() error {
// Create the antrea managed chains and link them to built-in chains.
// We cannot use iptables-restore for these jump rules because there
// are non antrea managed rules in built-in chains.
type jumpRule struct {
table string
srcChain string
dstChain string
comment string
}
jumpRules := []jumpRule{
{iptables.RawTable, iptables.PreRoutingChain, antreaPreRoutingChain, "Antrea: jump to Antrea prerouting rules"},
{iptables.RawTable, iptables.OutputChain, antreaOutputChain, "Antrea: jump to Antrea output rules"},
{iptables.FilterTable, iptables.ForwardChain, antreaForwardChain, "Antrea: jump to Antrea forwarding rules"},
{iptables.NATTable, iptables.PostRoutingChain, antreaPostRoutingChain, "Antrea: jump to Antrea postrouting rules"},
{iptables.MangleTable, iptables.PreRoutingChain, antreaMangleChain, "Antrea: jump to Antrea mangle rules"}, // TODO: unify the chain naming style
{iptables.MangleTable, iptables.OutputChain, antreaOutputChain, "Antrea: jump to Antrea output rules"},
}
if c.proxyAll || c.isCloudEKS {
jumpRules = append(jumpRules, jumpRule{iptables.NATTable, iptables.PreRoutingChain, antreaPreRoutingChain, "Antrea: jump to Antrea prerouting rules"})
}
if c.proxyAll {
jumpRules = append(jumpRules, jumpRule{iptables.NATTable, iptables.OutputChain, antreaOutputChain, "Antrea: jump to Antrea output rules"})
}
if c.nodeNetworkPolicyEnabled {
jumpRules = append(jumpRules, jumpRule{iptables.FilterTable, iptables.InputChain, antreaInputChain, "Antrea: jump to Antrea input rules"})
jumpRules = append(jumpRules, jumpRule{iptables.FilterTable, iptables.OutputChain, antreaOutputChain, "Antrea: jump to Antrea output rules"})
}
for _, rule := range jumpRules {
if err := c.iptables.EnsureChain(iptables.ProtocolDual, rule.table, rule.dstChain); err != nil {
return err
}
ruleSpec := []string{"-j", rule.dstChain, "-m", "comment", "--comment", rule.comment}
if err := c.iptables.AppendRule(iptables.ProtocolDual, rule.table, rule.srcChain, ruleSpec); err != nil {
return err
}
}
snatMarkToIPv4 := map[uint32]net.IP{}
snatMarkToIPv6 := map[uint32]net.IP{}
c.markToSNATIP.Range(func(key, value interface{}) bool {
snatMark := key.(uint32)
snatIP := value.(net.IP)
if snatIP.To4() != nil {
snatMarkToIPv4[snatMark] = snatIP
} else {
snatMarkToIPv6[snatMark] = snatIP
}
return true
})
nodeNetworkPolicyIPTablesIPv4 := map[string][]string{}
nodeNetworkPolicyIPTablesIPv6 := map[string][]string{}
c.nodeNetworkPolicyIPTablesIPv4.Range(func(key, value interface{}) bool {
chain := key.(string)
rules := value.([]string)
nodeNetworkPolicyIPTablesIPv4[chain] = rules
return true
})
c.nodeNetworkPolicyIPTablesIPv6.Range(func(key, value interface{}) bool {
chain := key.(string)
rules := value.([]string)
nodeNetworkPolicyIPTablesIPv6[chain] = rules
return true
})
// Use iptables-restore to configure IPv4 settings.
if c.networkConfig.IPv4Enabled {
iptablesData := c.restoreIptablesData(c.nodeConfig.PodIPv4CIDR,
antreaPodIPSet,
localAntreaFlexibleIPAMPodIPSet,
antreaNodePortIPSet,
clusterNodeIPSet,
config.VirtualNodePortDNATIPv4,
config.VirtualServiceIPv4,
snatMarkToIPv4,
nodeNetworkPolicyIPTablesIPv4,
false)
// Setting --noflush to keep the previous contents (i.e. non antrea managed chains) of the tables.
if err := c.iptables.Restore(iptablesData.String(), false, false); err != nil {
return err
}
}
// Use ip6tables-restore to configure IPv6 settings.
if c.networkConfig.IPv6Enabled {
iptablesData := c.restoreIptablesData(c.nodeConfig.PodIPv6CIDR,
antreaPodIP6Set,
localAntreaFlexibleIPAMPodIP6Set,
antreaNodePortIP6Set,
clusterNodeIP6Set,
config.VirtualNodePortDNATIPv6,
config.VirtualServiceIPv6,
snatMarkToIPv6,
nodeNetworkPolicyIPTablesIPv6,
true)
// Setting --noflush to keep the previous contents (i.e. non antrea managed chains) of the tables.
if err := c.iptables.Restore(iptablesData.String(), false, true); err != nil {
return err
}
}
return nil
}
func (c *Client) restoreIptablesData(podCIDR *net.IPNet,
podIPSet,
localAntreaFlexibleIPAMPodIPSet,
nodePortIPSet,
clusterNodeIPSet string,
nodePortDNATVirtualIP,
serviceVirtualIP net.IP,
snatMarkToIP map[uint32]net.IP,
nodeNetWorkPolicyIPTables map[string][]string,
isIPv6 bool) *bytes.Buffer {
// Create required rules in the antrea chains.
// Use iptables-restore as it flushes the involved chains and creates the desired rules
// with a single call, instead of string matching to clean up stale rules.
iptablesData := bytes.NewBuffer(nil)
// Write head lines anyway so the undesired rules can be deleted when changing encap mode.
writeLine(iptablesData, "*raw")
writeLine(iptablesData, iptables.MakeChainLine(antreaPreRoutingChain))
writeLine(iptablesData, iptables.MakeChainLine(antreaOutputChain))
if c.networkConfig.TrafficEncapMode.SupportsEncap() {
// For Geneve and VXLAN encapsulation packets, the request and response packets don't belong to a UDP connection
// so tracking them doesn't give the normal benefits of conntrack. Besides, kube-proxy may install great number
// of iptables rules in nat table. The first encapsulation packets of connections would have to go through all
// of the rules which wastes CPU and increases packet latency.
udpPort := 0
if c.networkConfig.TunnelType == ovsconfig.GeneveTunnel {
udpPort = genevePort
} else if c.networkConfig.TunnelType == ovsconfig.VXLANTunnel {
udpPort = vxlanPort
}
if udpPort > 0 {
writeLine(iptablesData, []string{
"-A", antreaPreRoutingChain,
"-m", "comment", "--comment", `"Antrea: do not track incoming encapsulation packets"`,
"-m", "udp", "-p", "udp", "--dport", strconv.Itoa(udpPort),
"-m", "addrtype", "--dst-type", "LOCAL",
"-j", iptables.NoTrackTarget,
}...)
writeLine(iptablesData, []string{
"-A", antreaOutputChain,
"-m", "comment", "--comment", `"Antrea: do not track outgoing encapsulation packets"`,
"-m", "udp", "-p", "udp", "--dport", strconv.Itoa(udpPort),
"-m", "addrtype", "--src-type", "LOCAL",
"-j", iptables.NoTrackTarget,
}...)
}
if c.multicastEnabled && c.networkConfig.TrafficEncapMode.SupportsEncap() {
// Drop the multicast packets forwarded from other Nodes in the cluster. This is because
// the packet sent out from the sender Pod is already received via tunnel port with encap mode,
// and the one forwarded via the underlay network is to send to external receivers
writeLine(iptablesData, []string{
"-A", antreaPreRoutingChain,
"-m", "comment", "--comment", `"Antrea: drop Pod multicast traffic forwarded via underlay network"`,
"-m", "set", "--match-set", clusterNodeIPSet, "src",
"-d", types.McastCIDR.String(),
"-j", iptables.DropTarget,
}...)
}
}
writeLine(iptablesData, "COMMIT")
// Write head lines anyway so the undesired rules can be deleted when noEncap -> encap.
writeLine(iptablesData, "*mangle")
writeLine(iptablesData, iptables.MakeChainLine(antreaMangleChain))
writeLine(iptablesData, iptables.MakeChainLine(antreaOutputChain))
// When Antrea is used to enforce NetworkPolicies in EKS, additional iptables
// mangle rules are required. See https://github.com/antrea-io/antrea/issues/678.
// These rules are only needed for IPv4.
if c.isCloudEKS && !isIPv6 {
c.writeEKSMangleRules(iptablesData)
}
// To make liveness/readiness probe traffic bypass ingress rules of Network Policies, mark locally generated packets
// that will be sent to OVS so we can identify them later in the OVS pipeline.
// It must match source address because kube-proxy ipvs mode will redirect ingress packets to output chain, and they
// will have non local source addresses.
writeLine(iptablesData, []string{
"-A", antreaOutputChain,
"-m", "comment", "--comment", `"Antrea: mark LOCAL output packets"`,
"-m", "addrtype", "--src-type", "LOCAL",
"-o", c.nodeConfig.GatewayConfig.Name,
"-j", iptables.MarkTarget, "--or-mark", fmt.Sprintf("%#08x", types.HostLocalSourceMark),
}...)
if c.connectUplinkToBridge {
writeLine(iptablesData, []string{
"-A", antreaOutputChain,
"-m", "comment", "--comment", `"Antrea: mark LOCAL output packets"`,
"-m", "addrtype", "--src-type", "LOCAL",
"-o", c.nodeConfig.OVSBridge,
"-j", iptables.MarkTarget, "--or-mark", fmt.Sprintf("%#08x", types.HostLocalSourceMark),
}...)
}
writeLine(iptablesData, "COMMIT")
writeLine(iptablesData, "*filter")
writeLine(iptablesData, iptables.MakeChainLine(antreaForwardChain))
var nodeNetworkPolicyIPTablesChains []string
for chain := range nodeNetWorkPolicyIPTables {
nodeNetworkPolicyIPTablesChains = append(nodeNetworkPolicyIPTablesChains, chain)
}
if c.deterministic {
sort.Sort(sort.StringSlice(nodeNetworkPolicyIPTablesChains))
}
for _, chain := range nodeNetworkPolicyIPTablesChains {
writeLine(iptablesData, iptables.MakeChainLine(chain))
}
writeLine(iptablesData, []string{
"-A", antreaForwardChain,
"-m", "comment", "--comment", `"Antrea: accept packets from local Pods"`,
"-i", c.nodeConfig.GatewayConfig.Name,
"-j", iptables.AcceptTarget,
}...)
writeLine(iptablesData, []string{
"-A", antreaForwardChain,
"-m", "comment", "--comment", `"Antrea: accept packets to local Pods"`,
"-o", c.nodeConfig.GatewayConfig.Name,
"-j", iptables.AcceptTarget,
}...)
if c.connectUplinkToBridge {
// Add accept rules for local AntreaFlexibleIPAM
// AntreaFlexibleIPAM Pods -> HostPort Pod
// AntreaFlexibleIPAM Pods -> NodePort Service -> Backend Pod
writeLine(iptablesData, []string{
"-A", antreaForwardChain,
"-m", "comment", "--comment", `"Antrea: accept packets from local AntreaFlexibleIPAM Pods"`,
"-m", "set", "--match-set", localAntreaFlexibleIPAMPodIPSet, "src",
"-j", iptables.AcceptTarget,
}...)
writeLine(iptablesData, []string{
"-A", antreaForwardChain,
"-m", "comment", "--comment", `"Antrea: accept packets to local AntreaFlexibleIPAM Pods"`,
"-m", "set", "--match-set", localAntreaFlexibleIPAMPodIPSet, "dst",
"-j", iptables.AcceptTarget,
}...)
}
for _, chain := range nodeNetworkPolicyIPTablesChains {
for _, rule := range nodeNetWorkPolicyIPTables[chain] {
writeLine(iptablesData, rule)
}
}
writeLine(iptablesData, "COMMIT")
writeLine(iptablesData, "*nat")
if c.proxyAll || c.isCloudEKS {
writeLine(iptablesData, iptables.MakeChainLine(antreaPreRoutingChain))
}
if c.proxyAll {
writeLine(iptablesData, []string{
"-A", antreaPreRoutingChain,
"-m", "comment", "--comment", `"Antrea: DNAT external to NodePort packets"`,
"-m", "set", "--match-set", nodePortIPSet, "dst,dst",
"-j", iptables.DNATTarget,
"--to-destination", nodePortDNATVirtualIP.String(),
}...)
writeLine(iptablesData, iptables.MakeChainLine(antreaOutputChain))
writeLine(iptablesData, []string{
"-A", antreaOutputChain,
"-m", "comment", "--comment", `"Antrea: DNAT local to NodePort packets"`,
"-m", "set", "--match-set", nodePortIPSet, "dst,dst",
"-j", iptables.DNATTarget,
"--to-destination", nodePortDNATVirtualIP.String(),
}...)
}
writeLine(iptablesData, iptables.MakeChainLine(antreaPostRoutingChain))
// The masqueraded multicast traffic will become unicast so we
// stop traversing this antreaPostRoutingChain for multicast traffic.
if c.multicastEnabled && c.networkConfig.TrafficEncapMode.SupportsNoEncap() {
writeLine(iptablesData, []string{
"-A", antreaPostRoutingChain,
"-m", "comment", "--comment", `"Antrea: skip masquerade for multicast traffic"`,
"-s", podCIDR.String(),
"-d", types.McastCIDR.String(),
"-j", iptables.ReturnTarget,
}...)
}
// Egress rules must be inserted before the default masquerade rule.
for snatMark, snatIP := range snatMarkToIP {
// Cannot reuse snatRuleSpec to generate the rule as it doesn't have "`" in the comment.
writeLine(iptablesData, []string{
"-A", antreaPostRoutingChain,
"-m", "comment", "--comment", `"Antrea: SNAT Pod to external packets"`,
"!", "-o", c.nodeConfig.GatewayConfig.Name,
"-m", "mark", "--mark", fmt.Sprintf("%#08x/%#08x", snatMark, types.SNATIPMarkMask),
"-j", iptables.SNATTarget, "--to", snatIP.String(),
}...)
}
if !c.noSNAT {
writeLine(iptablesData, []string{
"-A", antreaPostRoutingChain,
"-m", "comment", "--comment", `"Antrea: masquerade Pod to external packets"`,
"-s", podCIDR.String(), "-m", "set", "!", "--match-set", podIPSet, "dst",
"!", "-o", c.nodeConfig.GatewayConfig.Name,
"-j", iptables.MasqueradeTarget,
}...)
}
// For local traffic going out of the gateway interface, if the source IP does not match any
// of the gateway's IP addresses, the traffic needs to be masqueraded. Otherwise, we observe
// that ARP requests may advertise a different source IP address, in which case they will be
// dropped by the SpoofGuard table in the OVS pipeline. See description for the arp_announce
// sysctl parameter.
writeLine(iptablesData, []string{
"-A", antreaPostRoutingChain,
"-m", "comment", "--comment", `"Antrea: masquerade LOCAL traffic"`,
"-o", c.nodeConfig.GatewayConfig.Name,
"-m", "addrtype", "!", "--src-type", "LOCAL", "--limit-iface-out",
"-m", "addrtype", "--src-type", "LOCAL",
"-j", iptables.MasqueradeTarget, "--random-fully",
}...)
// If AntreaProxy full support is enabled, it SNATs the packets whose source IP is VirtualServiceIPv4/VirtualServiceIPv6
// so the packets can be routed back to this Node.
if c.proxyAll {
writeLine(iptablesData, []string{
"-A", antreaPostRoutingChain,
"-m", "comment", "--comment", `"Antrea: masquerade OVS virtual source IP"`,
"-s", serviceVirtualIP.String(),
"-j", iptables.MasqueradeTarget,
}...)
}
// This generates the rule to masquerade the packets destined for a hostPort whose backend is an AntreaIPAM VLAN Pod.
// For simplicity, in the following descriptions:
// - per-Node IPAM Pod is referred to as regular Pod.
// - AntreaIPAM Pod without VLAN is referred to as AntreaIPAM Pod.
// - AntreaIPAM Pod with VLAN is referred to as AntreaIPAM VLAN Pod.
// The common conditions are:
// - AntreaIPAM VLAN Pod exposes hostPort.
// - hostPort traffic is sent to underlay gateway after Node DNATed the traffic.
// - underlay gateway sends traffic back with a vlan tag.
// - SNAT is required to guarantee the reply traffic can be sent to Node to de-DNAT.
// Corresponding traffic models are:
// 01. Regular Pod (remote) -- hostPort [request] --> AntreaIPAM VLAN Pod
// 02. AntreaIPAM Pod -- hostPort [request] --> AntreaIPAM VLAN Pod
// 03. AntreaIPAM VLAN Pod -- hostPort [request] --> AntreaIPAM VLAN Pod (different subnet/VLAN)
// 04. External -- hostPort [request] --> AntreaIPAM VLAN Pod
// Below traffic models are already covered by portmap CNI:
// 01. AntreaIPAM VLAN Pod -- hostPort [request] --> AntreaIPAM VLAN Pod (same subnet)
// 02. Regular Pod (local) -- hostPort [request] --> AntreaIPAM VLAN Pod
if c.connectUplinkToBridge {
writeLine(iptablesData, []string{
"-A", antreaPostRoutingChain,
"-m", "comment", "--comment", `"Antrea: masquerade traffic to local AntreaIPAM hostPort Pod"`,
"!", "-s", podCIDR.String(),
"-m", "set", "--match-set", localAntreaFlexibleIPAMPodIPSet, "dst",
"-j", iptables.MasqueradeTarget,
}...)
}
// When Antrea is used to enforce NetworkPolicies in EKS, additional iptables
// nat rules are required. See https://github.com/antrea-io/antrea/issues/3946.
// These rules are only needed for IPv4.
if c.isCloudEKS && !isIPv6 {
c.writeEKSNATRules(iptablesData)
}
writeLine(iptablesData, "COMMIT")
return iptablesData
}
func (c *Client) initIPRoutes() error {
if c.networkConfig.TrafficEncapMode.IsNetworkPolicyOnly() {
gwLink, err := c.netlink.LinkByName(c.nodeConfig.GatewayConfig.Name)
if err != nil {
return fmt.Errorf("error getting link %s: %v", c.nodeConfig.GatewayConfig.Name, err)
}
if c.nodeConfig.NodeTransportIPv4Addr != nil {
_, gwIP, _ := net.ParseCIDR(fmt.Sprintf("%s/32", c.nodeConfig.NodeTransportIPv4Addr.IP.String()))
if err := c.netlink.AddrReplace(gwLink, &netlink.Addr{IPNet: gwIP}); err != nil {
return fmt.Errorf("failed to add address %s to gw %s: %v", gwIP, gwLink.Attrs().Name, err)
}
}
if c.nodeConfig.NodeTransportIPv6Addr != nil {
_, gwIP, _ := net.ParseCIDR(fmt.Sprintf("%s/128", c.nodeConfig.NodeTransportIPv6Addr.IP.String()))
if err := c.netlink.AddrReplace(gwLink, &netlink.Addr{IPNet: gwIP}); err != nil {
return fmt.Errorf("failed to add address %s to gw %s: %v", gwIP, gwLink.Attrs().Name, err)
}
}
}
return nil
}
func (c *Client) initServiceIPRoutes() error {
if c.networkConfig.IPv4Enabled {
if err := c.addVirtualServiceIPRoute(false); err != nil {
return err
}
if err := c.addVirtualNodePortDNATIPRoute(false); err != nil {
return err
}
}
if c.networkConfig.IPv6Enabled {
if err := c.addVirtualServiceIPRoute(true); err != nil {
return err
}
if err := c.addVirtualNodePortDNATIPRoute(true); err != nil {
return err
}
}
c.serviceCIDRProvider.AddEventHandler(func(serviceCIDRs []*net.IPNet) {
for _, serviceCIDR := range serviceCIDRs {
if err := c.addServiceCIDRRoute(serviceCIDR); err != nil {
klog.ErrorS(err, "Failed to install route for Service CIDR", "ServiceCIDR", serviceCIDR)
}
}
})
return nil
}
func (c *Client) initNodeNetworkPolicy() {
antreaInputChainRules := []string{
iptables.NewRuleBuilder(antreaInputChain).
SetComment("Antrea: jump to static ingress NodeNetworkPolicy rules").
SetTarget(preNodeNetworkPolicyIngressRulesChain).
Done().
GetRule(),
iptables.NewRuleBuilder(antreaInputChain).
SetComment("Antrea: jump to ingress NodeNetworkPolicy rules").
SetTarget(config.NodeNetworkPolicyIngressRulesChain).
Done().
GetRule(),
}
antreaOutputChainRules := []string{
iptables.NewRuleBuilder(antreaOutputChain).
SetComment("Antrea: jump to static egress NodeNetworkPolicy rules").
SetTarget(preNodeNetworkPolicyEgressRulesChain).
Done().
GetRule(),
iptables.NewRuleBuilder(antreaOutputChain).
SetComment("Antrea: jump to egress NodeNetworkPolicy rules").
SetTarget(config.NodeNetworkPolicyEgressRulesChain).
Done().