-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
node.go
2089 lines (1825 loc) · 66.6 KB
/
node.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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package linux
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"path/filepath"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
"github.com/cilium/cilium/pkg/cidr"
cmtypes "github.com/cilium/cilium/pkg/clustermesh/types"
"github.com/cilium/cilium/pkg/counter"
"github.com/cilium/cilium/pkg/datapath/link"
"github.com/cilium/cilium/pkg/datapath/linux/ipsec"
"github.com/cilium/cilium/pkg/datapath/linux/linux_defaults"
"github.com/cilium/cilium/pkg/datapath/linux/route"
datapath "github.com/cilium/cilium/pkg/datapath/types"
"github.com/cilium/cilium/pkg/idpool"
ipamOption "github.com/cilium/cilium/pkg/ipam/option"
"github.com/cilium/cilium/pkg/lock"
"github.com/cilium/cilium/pkg/logging/logfields"
"github.com/cilium/cilium/pkg/maps/nodemap"
"github.com/cilium/cilium/pkg/maps/tunnel"
"github.com/cilium/cilium/pkg/metrics"
"github.com/cilium/cilium/pkg/node"
nodeTypes "github.com/cilium/cilium/pkg/node/types"
"github.com/cilium/cilium/pkg/option"
)
const (
wildcardIPv4 = "0.0.0.0"
wildcardIPv6 = "0::0"
neighFileName = "neigh-link.json"
)
// NeighLink contains the details of a NeighLink
type NeighLink struct {
Name string `json:"link-name"`
}
type linuxNodeHandler struct {
mutex lock.RWMutex
isInitialized bool
nodeConfig datapath.LocalNodeConfiguration
nodeAddressing datapath.NodeAddressing
datapathConfig DatapathConfiguration
nodes map[nodeTypes.Identity]*nodeTypes.Node
enableNeighDiscovery bool
neighLock lock.Mutex // protects neigh* fields below
neighDiscoveryLinks []netlink.Link
neighNextHopByNode4 map[nodeTypes.Identity]map[string]string // val = (key=link, value=string(net.IP))
neighNextHopByNode6 map[nodeTypes.Identity]map[string]string // val = (key=link, value=string(net.IP))
// All three mappings below hold both IPv4 and IPv6 entries.
neighNextHopRefCount counter.StringCounter
neighByNextHop map[string]*netlink.Neigh // key = string(net.IP)
neighLastPingByNextHop map[string]time.Time // key = string(net.IP)
nodeMap nodemap.Map
// Pool of available IDs for nodes.
nodeIDs idpool.IDPool
// Node-scoped unique IDs for the nodes.
nodeIDsByIPs map[string]uint16
// reverse map of the above
nodeIPsByIDs map[uint16]string
ipsecMetricCollector prometheus.Collector
ipsecMetricOnce sync.Once
}
var (
_ datapath.NodeHandler = (*linuxNodeHandler)(nil)
_ datapath.NodeIDHandler = (*linuxNodeHandler)(nil)
_ datapath.NodeNeighbors = (*linuxNodeHandler)(nil)
)
// NewNodeHandler returns a new node handler to handle node events and
// implement the implications in the Linux datapath
func NewNodeHandler(datapathConfig DatapathConfiguration, nodeAddressing datapath.NodeAddressing, nodeMap nodemap.Map) *linuxNodeHandler {
return &linuxNodeHandler{
nodeAddressing: nodeAddressing,
datapathConfig: datapathConfig,
nodes: map[nodeTypes.Identity]*nodeTypes.Node{},
neighNextHopByNode4: map[nodeTypes.Identity]map[string]string{},
neighNextHopByNode6: map[nodeTypes.Identity]map[string]string{},
neighNextHopRefCount: counter.StringCounter{},
neighByNextHop: map[string]*netlink.Neigh{},
neighLastPingByNextHop: map[string]time.Time{},
nodeMap: nodeMap,
nodeIDs: idpool.NewIDPool(minNodeID, maxNodeID),
nodeIDsByIPs: map[string]uint16{},
nodeIPsByIDs: map[uint16]string{},
ipsecMetricCollector: ipsec.NewXFRMCollector(),
}
}
// updateTunnelMapping is called when a node update is received while running
// with encapsulation mode enabled. The CIDR and IP of both the old and new
// node are provided as context. The caller expects the tunnel mapping in the
// datapath to be updated.
func updateTunnelMapping(oldCIDR, newCIDR cmtypes.PrefixCluster, oldIP, newIP net.IP,
firstAddition, encapEnabled bool, oldEncryptKey, newEncryptKey uint8, nodeID uint16) {
if !encapEnabled {
// When the protocol family is disabled, the initial node addition will
// trigger a deletion to clean up leftover entries. The deletion happens
// in quiet mode as we don't know whether it exists or not
if newCIDR.IsValid() && firstAddition {
deleteTunnelMapping(newCIDR, true)
}
return
}
if cidrNodeMappingUpdateRequired(oldCIDR, newCIDR, oldIP, newIP, oldEncryptKey, newEncryptKey) {
log.WithFields(logrus.Fields{
logfields.IPAddr: newIP,
"allocCIDR": newCIDR,
}).Debug("Updating tunnel map entry")
if err := tunnel.TunnelMap().SetTunnelEndpoint(newEncryptKey, nodeID, newCIDR.AddrCluster(), newIP); err != nil {
log.WithError(err).WithFields(logrus.Fields{
"allocCIDR": newCIDR,
}).Error("bpf: Unable to update in tunnel endpoint map")
}
}
// Determine whether an old tunnel mapping must be cleaned up. The
// below switch lists all conditions in which case the oldCIDR must be
// removed from the tunnel mapping
switch {
// CIDR no longer announced
case !newCIDR.IsValid() && oldCIDR.IsValid():
fallthrough
// Node allocation CIDR has changed
case oldCIDR.IsValid() && newCIDR.IsValid() && !oldCIDR.Equal(newCIDR):
deleteTunnelMapping(oldCIDR, false)
}
}
// cidrNodeMappingUpdateRequired returns true if the change from an old node
// CIDR and node IP to a new node CIDR and node IP requires to insert/update
// the new node CIDR.
func cidrNodeMappingUpdateRequired(oldCIDR, newCIDR cmtypes.PrefixCluster, oldIP, newIP net.IP, oldKey, newKey uint8) bool {
// No CIDR provided
if !newCIDR.IsValid() {
return false
}
// Newly announced CIDR
if !oldCIDR.IsValid() {
return true
}
// Change in node IP
if !oldIP.Equal(newIP) {
return true
}
if newKey != oldKey {
return true
}
// CIDR changed
return !oldCIDR.Equal(newCIDR)
}
func deleteTunnelMapping(oldCIDR cmtypes.PrefixCluster, quietMode bool) {
if !oldCIDR.IsValid() {
return
}
log.WithFields(logrus.Fields{
"allocPrefixCluster": oldCIDR.String(),
"quietMode": quietMode,
}).Debug("Deleting tunnel map entry")
addrCluster := oldCIDR.AddrCluster()
if !quietMode {
if err := tunnel.TunnelMap().DeleteTunnelEndpoint(addrCluster); err != nil {
log.WithError(err).WithFields(logrus.Fields{
"allocPrefixCluster": oldCIDR.String(),
}).Error("Unable to delete in tunnel endpoint map")
}
} else {
_ = tunnel.TunnelMap().SilentDeleteTunnelEndpoint(addrCluster)
}
}
func createDirectRouteSpec(CIDR *cidr.CIDR, nodeIP net.IP) (routeSpec *netlink.Route, err error) {
var routes []netlink.Route
routeSpec = &netlink.Route{
Dst: CIDR.IPNet,
Gw: nodeIP,
Protocol: linux_defaults.RTProto,
}
routes, err = netlink.RouteGet(nodeIP)
if err != nil {
err = fmt.Errorf("unable to lookup route for node %s: %s", nodeIP, err)
return
}
if len(routes) == 0 {
err = fmt.Errorf("no route found to destination %s", nodeIP.String())
return
}
if routes[0].Gw != nil && !routes[0].Gw.IsUnspecified() && !routes[0].Gw.Equal(nodeIP) {
err = fmt.Errorf("route to destination %s contains gateway %s, must be directly reachable",
nodeIP, routes[0].Gw.String())
return
}
linkIndex := routes[0].LinkIndex
// Special treatment if the route points to the loopback, lookup the
// local route and use that ifindex
if linkIndex == 1 {
family := netlink.FAMILY_V4
dst := &net.IPNet{IP: nodeIP, Mask: net.CIDRMask(32, 32)}
if nodeIP.To4() == nil {
family = netlink.FAMILY_V6
dst.Mask = net.CIDRMask(128, 128)
}
filter := &netlink.Route{
Table: 255, // local table
Dst: dst,
}
routes, err = netlink.RouteListFiltered(family, filter, netlink.RT_FILTER_DST|netlink.RT_FILTER_TABLE)
if err != nil {
err = fmt.Errorf("unable to find local route for destination %s: %s", nodeIP, err)
return
}
if len(routes) == 0 {
err = fmt.Errorf("unable to find local route for destination %s which is routed over loopback", nodeIP)
return
}
linkIndex = routes[0].LinkIndex
}
routeSpec.LinkIndex = linkIndex
return
}
func installDirectRoute(CIDR *cidr.CIDR, nodeIP net.IP) (routeSpec *netlink.Route, err error) {
routeSpec, err = createDirectRouteSpec(CIDR, nodeIP)
if err != nil {
return
}
err = netlink.RouteReplace(routeSpec)
return
}
func (n *linuxNodeHandler) updateDirectRoutes(oldCIDRs, newCIDRs []*cidr.CIDR, oldIP, newIP net.IP, firstAddition, directRouteEnabled bool) error {
if !directRouteEnabled {
// When the protocol family is disabled, the initial node addition will
// trigger a deletion to clean up leftover entries. The deletion happens
// in quiet mode as we don't know whether it exists or not
if firstAddition {
n.deleteAllDirectRoutes(newCIDRs, newIP)
}
return nil
}
var addedCIDRs, removedCIDRs []*cidr.CIDR
if oldIP.Equal(newIP) {
addedCIDRs, removedCIDRs = cidr.DiffCIDRLists(oldCIDRs, newCIDRs)
} else {
// if the node IP changed, then we need to update all routes with the
// new IP, but we also want to remove any of the old routes with the
// old IP, in case the output device changed
addedCIDRs, removedCIDRs = newCIDRs, oldCIDRs
}
log.WithFields(logrus.Fields{
"newIP": newIP,
"oldIP": oldIP,
"addedCIDRs": addedCIDRs,
"removedCIDRs": removedCIDRs,
}).Debug("Updating direct route")
for _, cidr := range addedCIDRs {
if routeSpec, err := installDirectRoute(cidr, newIP); err != nil {
log.WithError(err).Warningf("Unable to install direct node route %s", routeSpec.String())
return err
}
}
n.deleteAllDirectRoutes(removedCIDRs, oldIP)
return nil
}
func (n *linuxNodeHandler) deleteAllDirectRoutes(CIDRs []*cidr.CIDR, nodeIP net.IP) {
for _, cidr := range CIDRs {
n.deleteDirectRoute(cidr, nodeIP)
}
}
func (n *linuxNodeHandler) deleteDirectRoute(CIDR *cidr.CIDR, nodeIP net.IP) {
if CIDR == nil {
return
}
family := netlink.FAMILY_V4
if CIDR.IP.To4() == nil {
family = netlink.FAMILY_V6
}
filter := &netlink.Route{
Dst: CIDR.IPNet,
Gw: nodeIP,
Protocol: linux_defaults.RTProto,
}
routes, err := netlink.RouteListFiltered(family, filter, netlink.RT_FILTER_DST|netlink.RT_FILTER_GW)
if err != nil {
log.WithError(err).Error("Unable to list direct routes")
return
}
for _, rt := range routes {
if err := netlink.RouteDel(&rt); err != nil {
log.WithError(err).Warningf("Unable to delete direct node route %s", rt.String())
}
}
}
// createNodeRouteSpec creates a route spec that points the specified prefix to the host
// device via the router IP. The route is configured with a computed MTU for non-local
// nodes (i.e isLocalNode is set to false).
//
// Example:
// 10.10.0.0/24 via 10.10.0.1 dev cilium_host src 10.10.0.1
// f00d::a0a:0:0:0/112 via f00d::a0a:0:0:1 dev cilium_host src fd04::11 metric 1024 pref medium
func (n *linuxNodeHandler) createNodeRouteSpec(prefix *cidr.CIDR, isLocalNode bool) (route.Route, error) {
var (
local net.IP
nexthop *net.IP
mtu int
)
if prefix.IP.To4() != nil {
if n.nodeAddressing.IPv4() == nil {
return route.Route{}, fmt.Errorf("IPv4 addressing unavailable")
}
if n.nodeAddressing.IPv4().Router() == nil {
return route.Route{}, fmt.Errorf("IPv4 router address unavailable")
}
local = n.nodeAddressing.IPv4().Router()
nexthop = &local
} else {
if n.nodeAddressing.IPv6() == nil {
return route.Route{}, fmt.Errorf("IPv6 addressing unavailable")
}
if n.nodeAddressing.IPv6().Router() == nil {
return route.Route{}, fmt.Errorf("IPv6 router address unavailable")
}
if n.nodeAddressing.IPv6().PrimaryExternal() == nil {
return route.Route{}, fmt.Errorf("External IPv6 address unavailable")
}
// For ipv6, kernel will reject "ip r a $cidr via $ipv6_cilium_host dev cilium_host"
// with "Error: Gateway can not be a local address". Instead, we have to remove "via"
// as "ip r a $cidr dev cilium_host" to make it work.
nexthop = nil
local = n.nodeAddressing.IPv6().Router()
}
if !isLocalNode {
mtu = n.nodeConfig.MtuConfig.GetRouteMTU()
}
// The default routing table accounts for encryption overhead for encrypt-node traffic
return route.Route{
Nexthop: nexthop,
Local: local,
Device: n.datapathConfig.HostDevice,
Prefix: *prefix.IPNet,
MTU: mtu,
Priority: option.Config.RouteMetric,
Proto: linux_defaults.RTProto,
}, nil
}
func (n *linuxNodeHandler) lookupNodeRoute(prefix *cidr.CIDR, isLocalNode bool) (*route.Route, error) {
if prefix == nil {
return nil, nil
}
routeSpec, err := n.createNodeRouteSpec(prefix, isLocalNode)
if err != nil {
return nil, err
}
return route.Lookup(routeSpec)
}
func (n *linuxNodeHandler) updateNodeRoute(prefix *cidr.CIDR, addressFamilyEnabled bool, isLocalNode bool) error {
if prefix == nil || !addressFamilyEnabled {
return nil
}
nodeRoute, err := n.createNodeRouteSpec(prefix, isLocalNode)
if err != nil {
return err
}
if err := route.Upsert(nodeRoute); err != nil {
log.WithError(err).WithFields(nodeRoute.LogFields()).Warning("Unable to update route")
return err
}
return nil
}
func (n *linuxNodeHandler) deleteNodeRoute(prefix *cidr.CIDR, isLocalNode bool) error {
if prefix == nil {
return nil
}
nodeRoute, err := n.createNodeRouteSpec(prefix, isLocalNode)
if err != nil {
return err
}
if err := route.Delete(nodeRoute); err != nil {
log.WithError(err).WithFields(nodeRoute.LogFields()).Warning("Unable to delete route")
return err
}
return nil
}
func (n *linuxNodeHandler) familyEnabled(c *cidr.CIDR) bool {
return (c.IP.To4() != nil && n.nodeConfig.EnableIPv4) || (c.IP.To4() == nil && n.nodeConfig.EnableIPv6)
}
func (n *linuxNodeHandler) updateOrRemoveNodeRoutes(old, new []*cidr.CIDR, isLocalNode bool) {
addedAuxRoutes, removedAuxRoutes := cidr.DiffCIDRLists(old, new)
for _, prefix := range addedAuxRoutes {
if prefix != nil {
n.updateNodeRoute(prefix, n.familyEnabled(prefix), isLocalNode)
}
}
for _, prefix := range removedAuxRoutes {
if rt, _ := n.lookupNodeRoute(prefix, isLocalNode); rt != nil {
n.deleteNodeRoute(prefix, isLocalNode)
}
}
}
func (n *linuxNodeHandler) NodeAdd(newNode nodeTypes.Node) error {
n.mutex.Lock()
defer n.mutex.Unlock()
n.nodes[newNode.Identity()] = &newNode
if n.isInitialized {
return n.nodeUpdate(nil, &newNode, true)
}
return nil
}
func (n *linuxNodeHandler) NodeUpdate(oldNode, newNode nodeTypes.Node) error {
n.mutex.Lock()
defer n.mutex.Unlock()
n.nodes[newNode.Identity()] = &newNode
if n.isInitialized {
return n.nodeUpdate(&oldNode, &newNode, false)
}
return nil
}
func upsertIPsecLog(err error, spec string, loc, rem *net.IPNet, spi uint8) {
scopedLog := log.WithFields(logrus.Fields{
logfields.Reason: spec,
"local-ip": loc,
"remote-ip": rem,
"spi": spi,
})
if err != nil {
scopedLog.WithError(err).Error("IPsec enable failed")
} else {
scopedLog.Debug("IPsec enable succeeded")
}
}
func (n *linuxNodeHandler) registerIpsecMetricOnce() {
n.ipsecMetricOnce.Do(func() {
metrics.Register(n.ipsecMetricCollector)
})
}
func (n *linuxNodeHandler) enableSubnetIPsec(v4CIDR, v6CIDR []*net.IPNet) {
n.replaceHostRules()
for _, cidr := range v4CIDR {
if !option.Config.EnableEndpointRoutes {
n.replaceNodeIPSecInRoute(cidr)
}
n.replaceNodeIPSecOutRoute(cidr)
if n.nodeConfig.EncryptNode {
n.replaceNodeExternalIPSecOutRoute(cidr)
}
}
for _, cidr := range v6CIDR {
n.replaceNodeIPSecInRoute(cidr)
n.replaceNodeIPSecOutRoute(cidr)
if n.nodeConfig.EncryptNode {
n.replaceNodeExternalIPSecOutRoute(cidr)
}
}
}
// encryptNode handles setting the IPsec state for node encryption (subnet
// encryption = disabled).
func (n *linuxNodeHandler) encryptNode(newNode *nodeTypes.Node) {
var spi uint8
var err error
if n.nodeConfig.EnableIPv4 {
internalIPv4 := n.nodeAddressing.IPv4().PrimaryExternal()
exactMask := net.IPv4Mask(255, 255, 255, 255)
ipsecLocal := &net.IPNet{IP: internalIPv4, Mask: exactMask}
if newNode.IsLocal() {
wildcardIP := net.ParseIP(wildcardIPv4)
ipsecIPv4Wildcard := &net.IPNet{IP: wildcardIP, Mask: net.IPv4Mask(0, 0, 0, 0)}
n.replaceNodeIPSecInRoute(ipsecLocal)
spi, err = ipsec.UpsertIPsecEndpoint(ipsecLocal, ipsecIPv4Wildcard, internalIPv4, wildcardIP, 0, ipsec.IPSecDirIn, false)
upsertIPsecLog(err, "EncryptNode local IPv4", ipsecLocal, ipsecIPv4Wildcard, spi)
} else {
if remoteIPv4 := newNode.GetNodeIP(false); remoteIPv4 != nil {
ipsecRemote := &net.IPNet{IP: remoteIPv4, Mask: exactMask}
n.replaceNodeExternalIPSecOutRoute(ipsecRemote)
spi, err = ipsec.UpsertIPsecEndpoint(ipsecLocal, ipsecRemote, internalIPv4, remoteIPv4, 0, ipsec.IPSecDirOutNode, false)
upsertIPsecLog(err, "EncryptNode IPv4", ipsecLocal, ipsecRemote, spi)
}
remoteIPv4 := newNode.GetCiliumInternalIP(false)
if remoteIPv4 != nil {
mask := newNode.IPv4AllocCIDR.Mask
ipsecRemoteRoute := &net.IPNet{IP: remoteIPv4.Mask(mask), Mask: mask}
ipsecRemote := &net.IPNet{IP: remoteIPv4, Mask: mask}
ipsecWildcard := &net.IPNet{IP: net.ParseIP(wildcardIPv4), Mask: net.IPv4Mask(0, 0, 0, 0)}
n.replaceNodeExternalIPSecOutRoute(ipsecRemoteRoute)
if remoteIPv4T := newNode.GetNodeIP(false); remoteIPv4T != nil {
err = ipsec.UpsertIPsecEndpointPolicy(ipsecWildcard, ipsecRemote, internalIPv4, remoteIPv4T, 0, ipsec.IPSecDirOutNode)
}
upsertIPsecLog(err, "EncryptNode Cilium IPv4", ipsecWildcard, ipsecRemote, spi)
}
}
}
if n.nodeConfig.EnableIPv6 {
internalIPv6 := n.nodeAddressing.IPv6().PrimaryExternal()
exactMask := net.CIDRMask(128, 128)
ipsecLocal := &net.IPNet{IP: internalIPv6, Mask: exactMask}
if newNode.IsLocal() {
wildcardIP := net.ParseIP(wildcardIPv6)
ipsecIPv6Wildcard := &net.IPNet{IP: wildcardIP, Mask: net.CIDRMask(0, 0)}
n.replaceNodeIPSecInRoute(ipsecLocal)
spi, err = ipsec.UpsertIPsecEndpoint(ipsecLocal, ipsecIPv6Wildcard, internalIPv6, wildcardIP, 0, ipsec.IPSecDirIn, false)
upsertIPsecLog(err, "EncryptNode local IPv6", ipsecLocal, ipsecIPv6Wildcard, spi)
} else {
if remoteIPv6 := newNode.GetNodeIP(true); remoteIPv6 != nil {
ipsecRemote := &net.IPNet{IP: remoteIPv6, Mask: exactMask}
n.replaceNodeExternalIPSecOutRoute(ipsecRemote)
spi, err = ipsec.UpsertIPsecEndpoint(ipsecLocal, ipsecRemote, internalIPv6, remoteIPv6, 0, ipsec.IPSecDirOut, false)
upsertIPsecLog(err, "EncryptNode IPv6", ipsecLocal, ipsecRemote, spi)
}
remoteIPv6 := newNode.GetCiliumInternalIP(true)
if remoteIPv6 != nil {
mask := newNode.IPv6AllocCIDR.Mask
ipsecRemoteRoute := &net.IPNet{IP: remoteIPv6.Mask(mask), Mask: mask}
ipsecRemote := &net.IPNet{IP: remoteIPv6, Mask: mask}
ipsecWildcard := &net.IPNet{IP: net.ParseIP(wildcardIPv6), Mask: net.CIDRMask(0, 0)}
n.replaceNodeExternalIPSecOutRoute(ipsecRemoteRoute)
if remoteIPv6T := newNode.GetNodeIP(true); remoteIPv6T != nil {
err = ipsec.UpsertIPsecEndpointPolicy(ipsecWildcard, ipsecRemote, internalIPv6, remoteIPv6T, 0, ipsec.IPSecDirOutNode)
}
upsertIPsecLog(err, "EncryptNode Cilium IPv6", ipsecWildcard, ipsecRemote, spi)
}
}
}
}
func getNextHopIP(nodeIP net.IP, link netlink.Link) (nextHopIP net.IP, err error) {
// Figure out whether nodeIP is directly reachable (i.e. in the same L2)
routes, err := netlink.RouteGetWithOptions(nodeIP, &netlink.RouteGetOptions{Oif: link.Attrs().Name})
if err != nil {
return nil, fmt.Errorf("failed to retrieve route for remote node IP: %w", err)
}
if len(routes) == 0 {
return nil, fmt.Errorf("remote node IP is non-routable")
}
nextHopIP = nodeIP
for _, route := range routes {
if route.Gw != nil {
// nodeIP is in a different L2 subnet, so it must be reachable through
// a gateway. Perform neighbor discovery to the gw IP addr instead of
// nodeIP. NOTE: We currently don't handle multipath, so only one gw
// can be used.
copy(nextHopIP, route.Gw.To16())
break
}
}
return nextHopIP, nil
}
type NextHop struct {
Name string
IP net.IP
IsNew bool
}
func (n *linuxNodeHandler) insertNeighborCommon(scopedLog *logrus.Entry, ctx context.Context, nextHop NextHop, link netlink.Link, refresh bool) {
if refresh {
if lastPing, found := n.neighLastPingByNextHop[nextHop.Name]; found &&
time.Now().Sub(lastPing) < option.Config.ARPPingRefreshPeriod {
// Last ping was issued less than option.Config.ARPPingRefreshPeriod
// ago, so skip it (e.g. to avoid ddos'ing the same GW if nodes are
// L3 connected)
return
}
}
// Don't proceed if the refresh controller cancelled the context
select {
case <-ctx.Done():
return
default:
}
n.neighLastPingByNextHop[nextHop.Name] = time.Now()
neigh := netlink.Neigh{
LinkIndex: link.Attrs().Index,
IP: nextHop.IP,
Flags: netlink.NTF_EXT_LEARNED | netlink.NTF_USE,
HardwareAddr: nil,
}
if option.Config.ARPPingKernelManaged {
neigh.Flags = netlink.NTF_EXT_LEARNED
neigh.FlagsExt = netlink.NTF_EXT_MANAGED
} else if nextHop.IsNew {
// Quirk for older kernels above. We cannot directly create a
// dynamic NUD_* with NTF_EXT_LEARNED|NTF_USE without having
// the following kernel fixes:
// e4400bbf5b15 ("net, neigh: Fix NTF_EXT_LEARNED in combination with NTF_USE")
// 3dc20f4762c6 ("net, neigh: Enable state migration between NUD_PERMANENT and NTF_USE")
// Thus, first initialize the neighbor as NTF_EXT_LEARNED and
// then do the subsequent ping via NTF_USE.
//
// Notes on use of the NUD_STALE state. We have two scenarios:
// 1) Old entry was a PERMANENT one. In this case, the kernel
// takes the PERMANENT's lladdr in __neigh_update() and uses
// it for temporary STALE state. This ensures that whoever
// does a lookup in this short window can continue keep using
// the lladdr. The subsequent NTF_USE will trigger a fresh
// resolution in neigh_event_send() given STALE dictates it
// (as opposed to REACHABLE).
// 2) Old entry was a dynamic + externally learned one. This
// is similar as the PERMANENT one if the entry was NUD_VALID
// before. The subsequent NTF_USE will trigger a new resolution.
// 3) Old entry was non-existent. Given we don't push down a
// corresponding lladdr, the neighbor entry gets created by the
// kernel, but given prior state was not NUD_VALID then the
// __neigh_update() will error out (EINVAL). However, the entry
// is in the kernel, and subsequent NTF_USE will trigger a proper
// resolution. Hence, below NeighSet() does _not_ bail out given
// errors are expected in this case.
neighInit := netlink.Neigh{
LinkIndex: link.Attrs().Index,
IP: nextHop.IP,
State: netlink.NUD_STALE,
Flags: netlink.NTF_EXT_LEARNED,
HardwareAddr: nil,
}
if err := netlink.NeighSet(&neighInit); err != nil {
scopedLog.WithError(err).WithFields(logrus.Fields{
"neighbor": fmt.Sprintf("%+v", neighInit),
}).Debug("Unable to insert new next hop")
}
}
if err := netlink.NeighSet(&neigh); err != nil {
scopedLog.WithError(err).WithFields(logrus.Fields{
"neighbor": fmt.Sprintf("%+v", neigh),
}).Info("Unable to refresh next hop")
return
}
n.neighByNextHop[nextHop.Name] = &neigh
}
func (n *linuxNodeHandler) insertNeighbor4(ctx context.Context, newNode *nodeTypes.Node, link netlink.Link, refresh bool) {
newNodeIP := newNode.GetNodeIP(false)
nextHopIPv4 := make(net.IP, len(newNodeIP))
copy(nextHopIPv4, newNodeIP)
scopedLog := log.WithFields(logrus.Fields{
logfields.LogSubsys: "node-neigh-debug",
logfields.Interface: link.Attrs().Name,
logfields.IPAddr: newNodeIP,
})
nextHopIPv4, err := getNextHopIP(nextHopIPv4, link)
if err != nil {
scopedLog.WithError(err).Info("Unable to determine next hop address")
return
}
nextHopStr := nextHopIPv4.String()
scopedLog = scopedLog.WithField(logfields.NextHop, nextHopIPv4)
n.neighLock.Lock()
defer n.neighLock.Unlock()
nextHopByLink, found := n.neighNextHopByNode4[newNode.Identity()]
if !found {
nextHopByLink = make(map[string]string)
n.neighNextHopByNode4[newNode.Identity()] = nextHopByLink
}
nextHopIsNew := false
if existingNextHopStr, found := nextHopByLink[link.Attrs().Name]; found {
if existingNextHopStr != nextHopStr {
if n.neighNextHopRefCount.Delete(existingNextHopStr) {
neigh, found := n.neighByNextHop[existingNextHopStr]
if found {
// Note that we don't move the removal via netlink which might
// block from the hot path (e.g. with defer), as this case can
// happen very rarely.
//
// The neighbor's HW address is ignored on delete. Only the IP
// address and device is checked.
if err := netlink.NeighDel(neigh); err != nil {
scopedLog.WithFields(logrus.Fields{
logfields.NextHop: neigh.IP,
logfields.LinkIndex: neigh.LinkIndex,
}).WithError(err).Info("Unable to remove next hop")
}
delete(n.neighByNextHop, existingNextHopStr)
delete(n.neighLastPingByNextHop, existingNextHopStr)
}
}
// Given nextHop has changed and we removed the old one, we
// now need to increment ref counter for the new one.
nextHopIsNew = n.neighNextHopRefCount.Add(nextHopStr)
}
} else {
// nextHop for the given node was previously not found, so let's
// increment ref counter. This can happen upon regular NodeUpdate
// event or by the periodic ARP refresher which got executed before
// NodeUpdate().
nextHopIsNew = n.neighNextHopRefCount.Add(nextHopStr)
}
n.neighNextHopByNode4[newNode.Identity()][link.Attrs().Name] = nextHopStr
nh := NextHop{
Name: nextHopStr,
IP: nextHopIPv4,
IsNew: nextHopIsNew,
}
n.insertNeighborCommon(scopedLog, ctx, nh, link, refresh)
}
func (n *linuxNodeHandler) insertNeighbor6(ctx context.Context, newNode *nodeTypes.Node, link netlink.Link, refresh bool) {
newNodeIP := newNode.GetNodeIP(true)
nextHopIPv6 := make(net.IP, len(newNodeIP))
copy(nextHopIPv6, newNodeIP)
scopedLog := log.WithFields(logrus.Fields{
logfields.LogSubsys: "node-neigh-debug",
logfields.Interface: link.Attrs().Name,
logfields.IPAddr: newNodeIP,
})
nextHopIPv6, err := getNextHopIP(nextHopIPv6, link)
if err != nil {
scopedLog.WithError(err).Info("Unable to determine next hop address")
return
}
nextHopStr := nextHopIPv6.String()
scopedLog = scopedLog.WithField(logfields.NextHop, nextHopIPv6)
n.neighLock.Lock()
defer n.neighLock.Unlock()
nextHopByLink, found := n.neighNextHopByNode6[newNode.Identity()]
if !found {
nextHopByLink = make(map[string]string)
n.neighNextHopByNode6[newNode.Identity()] = nextHopByLink
}
nextHopIsNew := false
if existingNextHopStr, found := nextHopByLink[link.Attrs().Name]; found {
if existingNextHopStr != nextHopStr {
if n.neighNextHopRefCount.Delete(existingNextHopStr) {
// nextHop has changed and nobody else is using it, so remove the old one.
neigh, found := n.neighByNextHop[existingNextHopStr]
if found {
// Note that we don't move the removal via netlink which might
// block from the hot path (e.g. with defer), as this case can
// happen very rarely.
//
// The neighbor's HW address is ignored on delete. Only the IP
// address and device is checked.
if err := netlink.NeighDel(neigh); err != nil {
scopedLog.WithFields(logrus.Fields{
logfields.NextHop: neigh.IP,
logfields.LinkIndex: neigh.LinkIndex,
}).WithError(err).Info("Unable to remove next hop")
}
delete(n.neighByNextHop, existingNextHopStr)
delete(n.neighLastPingByNextHop, existingNextHopStr)
}
}
// Given nextHop has changed and we removed the old one, we
// now need to increment ref counter for the new one.
nextHopIsNew = n.neighNextHopRefCount.Add(nextHopStr)
}
} else {
// nextHop for the given node was previously not found, so let's
// increment ref counter. This can happen upon regular NodeUpdate
// event or by the periodic ARP refresher which got executed before
// NodeUpdate().
nextHopIsNew = n.neighNextHopRefCount.Add(nextHopStr)
}
n.neighNextHopByNode6[newNode.Identity()][link.Attrs().Name] = nextHopStr
nh := NextHop{
Name: nextHopStr,
IP: nextHopIPv6,
IsNew: nextHopIsNew,
}
n.insertNeighborCommon(scopedLog, ctx, nh, link, refresh)
}
// insertNeighbor inserts a non-GC'able neighbor entry for a nexthop to the given
// "newNode" (ip route get newNodeIP.GetNodeIP()). The L2 addr of the nexthop is
// determined by the Linux kernel's neighboring subsystem. The related iface for
// the neighbor is specified by n.neighDiscoveryLink.
//
// The given "refresh" param denotes whether the method is called by a controller
// which tries to update neighbor entries previously inserted by insertNeighbor().
// In this case the kernel refreshes the entry via NTF_USE.
func (n *linuxNodeHandler) insertNeighbor(ctx context.Context, newNode *nodeTypes.Node, refresh bool) {
var links []netlink.Link
n.neighLock.Lock()
if n.neighDiscoveryLinks == nil || len(n.neighDiscoveryLinks) == 0 {
n.neighLock.Unlock()
// Nothing to do - the discovery link was not set yet
return
}
links = n.neighDiscoveryLinks
n.neighLock.Unlock()
if newNode.GetNodeIP(false).To4() != nil {
for _, l := range links {
n.insertNeighbor4(ctx, newNode, l, refresh)
}
}
if newNode.GetNodeIP(true).To16() != nil {
for _, l := range links {
n.insertNeighbor6(ctx, newNode, l, refresh)
}
}
}
func (n *linuxNodeHandler) refreshNeighbor(ctx context.Context, nodeToRefresh *nodeTypes.Node, completed chan struct{}) {
defer close(completed)
n.insertNeighbor(ctx, nodeToRefresh, true)
}
func (n *linuxNodeHandler) deleteNeighborCommon(nextHopStr string) {
if n.neighNextHopRefCount.Delete(nextHopStr) {
neigh, found := n.neighByNextHop[nextHopStr]
delete(n.neighByNextHop, nextHopStr)
delete(n.neighLastPingByNextHop, nextHopStr)
if found {
// Neighbor's HW address is ignored on delete. Only IP
// address and device is checked.
if err := netlink.NeighDel(neigh); err != nil {
log.WithFields(logrus.Fields{
logfields.LogSubsys: "node-neigh-debug",
logfields.NextHop: neigh.IP,
logfields.LinkIndex: neigh.LinkIndex,
}).WithError(err).Info("Unable to remove next hop")
}
}
}
}
func (n *linuxNodeHandler) deleteNeighbor4(oldNode *nodeTypes.Node) {
n.neighLock.Lock()
defer n.neighLock.Unlock()
nextHopByLink, found := n.neighNextHopByNode4[oldNode.Identity()]
if !found {
return
}
defer func() { delete(n.neighNextHopByNode4, oldNode.Identity()) }()
for _, nextHopStr := range nextHopByLink {
n.deleteNeighborCommon(nextHopStr)
}
}
func (n *linuxNodeHandler) deleteNeighbor6(oldNode *nodeTypes.Node) {
n.neighLock.Lock()
defer n.neighLock.Unlock()
nextHopByLink, found := n.neighNextHopByNode6[oldNode.Identity()]
if !found {
return
}
defer func() { delete(n.neighNextHopByNode6, oldNode.Identity()) }()
for _, nextHopStr := range nextHopByLink {
n.deleteNeighborCommon(nextHopStr)
}
}
func (n *linuxNodeHandler) deleteNeighbor(oldNode *nodeTypes.Node) {
n.deleteNeighbor4(oldNode)
n.deleteNeighbor6(oldNode)
}
// getDefaultEncryptionInterface() is needed to find the interface used when
// populating neighbor table and doing arpRequest. For most configurations
// there is only a single interface so choosing [0] works by choosing the only
// interface. However EKS, uses multiple interfaces, but fortunately for us
// in EKS any interface would work so pick the [0] index here as well.
func getDefaultEncryptionInterface() string {
iface := ""
if len(option.Config.EncryptInterface) > 0 {
iface = option.Config.EncryptInterface[0]
}
return iface
}
func getLinkLocalIP(family int) (net.IP, error) {
iface := getDefaultEncryptionInterface()
link, err := netlink.LinkByName(iface)
if err != nil {
return nil, err
}
addr, err := netlink.AddrList(link, family)
if err != nil {
return nil, err
}
return addr[0].IPNet.IP, nil
}
func getV4LinkLocalIP() (net.IP, error) {
return getLinkLocalIP(netlink.FAMILY_V4)
}
func getV6LinkLocalIP() (net.IP, error) {
return getLinkLocalIP(netlink.FAMILY_V6)
}
func (n *linuxNodeHandler) enableIPsec(newNode *nodeTypes.Node) {
if newNode.IsLocal() {
n.replaceHostRules()
}
// In endpoint routes mode we use the stack to route packets after
// the packet is decrypted so set skb->mark to zero from XFRM stack
// to avoid confusion in netfilters and conntrack that may be using
// the mark fields. This uses XFRM_OUTPUT_MARK added in 4.14 kernels.
zeroMark := option.Config.EnableEndpointRoutes
n.enableIPsecIPv4(newNode, zeroMark)
n.enableIPsecIPv6(newNode, zeroMark)