/
node.go
1626 lines (1409 loc) · 51.3 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
// Copyright 2018-2021 Authors of Cilium
//
// 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 linux
import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"reflect"
"time"
"github.com/cilium/cilium/pkg/cidr"
"github.com/cilium/cilium/pkg/counter"
"github.com/cilium/cilium/pkg/datapath"
"github.com/cilium/cilium/pkg/datapath/link"
"github.com/cilium/cilium/pkg/datapath/linux/arp"
"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"
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/neighborsmap"
"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"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
)
const (
wildcardIPv4 = "0.0.0.0"
wildcardIPv6 = "0::0"
success = "success"
failed = "failed"
)
const (
neighFileName = "neigh-link.json"
)
// NeighLink contains the details of a NeighLink
type NeighLink struct {
Name string `json:"link-name"`
}
type linuxNodeHandler struct {
mutex lock.Mutex
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
neighDiscoveryLink netlink.Link
neighNextHopByNode map[nodeTypes.Identity]string // val = string(net.IP)
neighNextHopRefCount counter.StringCounter
neighByNextHop map[string]*netlink.Neigh // key = string(net.IP)
neighLastPingByNextHop map[string]time.Time // key = string(net.IP)
wgAgent datapath.WireguardAgent
}
// 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, wgAgent datapath.WireguardAgent) datapath.NodeHandler {
return &linuxNodeHandler{
nodeAddressing: nodeAddressing,
datapathConfig: datapathConfig,
nodes: map[nodeTypes.Identity]*nodeTypes.Node{},
neighNextHopByNode: map[nodeTypes.Identity]string{},
neighNextHopRefCount: counter.StringCounter{},
neighByNextHop: map[string]*netlink.Neigh{},
neighLastPingByNextHop: map[string]time.Time{},
wgAgent: wgAgent,
}
}
// 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 *cidr.CIDR, oldIP, newIP net.IP, firstAddition, encapEnabled bool, oldEncryptKey, newEncryptKey uint8) {
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 != nil && 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, newCIDR.IP, 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 == nil && oldCIDR != nil:
fallthrough
// Node allocation CIDR has changed
case oldCIDR != nil && newCIDR != nil && !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 *cidr.CIDR, oldIP, newIP net.IP, oldKey, newKey uint8) bool {
// No CIDR provided
if newCIDR == nil {
return false
}
// Newly announced CIDR
if oldCIDR == nil {
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 *cidr.CIDR, quietMode bool) {
if oldCIDR == nil {
return
}
log.WithField("allocCIDR", oldCIDR).Debug("Deleting tunnel map entry")
if err := tunnel.TunnelMap.DeleteTunnelEndpoint(oldCIDR.IP); err != nil {
if !quietMode {
log.WithError(err).WithFields(logrus.Fields{
"allocCIDR": oldCIDR,
}).Error("Unable to delete in tunnel endpoint map")
}
}
}
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,
}
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) updateDirectRoute(oldCIDR, newCIDR *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 newCIDR != nil && firstAddition {
n.deleteDirectRoute(newCIDR, newIP)
}
return nil
}
if cidrNodeMappingUpdateRequired(oldCIDR, newCIDR, oldIP, newIP, 0, 0) {
log.WithFields(logrus.Fields{
logfields.IPAddr: newIP,
"allocCIDR": newCIDR,
}).Debug("Updating direct route")
if routeSpec, err := installDirectRoute(newCIDR, newIP); err != nil {
log.WithError(err).Warningf("Unable to install direct node route %s", routeSpec.String())
return err
}
}
// Determine whether an old route must be deleted. The below switch
// lists all conditions in which case the route derived from oldCIDR
// and oldIP must be deleted.
switch {
// CIDR no longer announced
case newCIDR == nil && oldCIDR != nil:
fallthrough
// node IP has changed
case !oldIP.Equal(newIP):
fallthrough
// Node allocation CIDR has changed
case oldCIDR != nil && newCIDR != nil && !oldCIDR.Equal(newCIDR):
n.deleteDirectRoute(oldCIDR, oldIP)
}
return nil
}
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,
}
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, 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")
}
nexthop = n.nodeAddressing.IPv4().Router()
local = nexthop
} 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")
}
nexthop = n.nodeAddressing.IPv6().Router()
local = n.nodeAddressing.IPv6().PrimaryExternal()
}
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,
}, 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")
}
}
// 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.IPNet, 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, nil
}
func getV4LinkLocalIp() (*net.IPNet, error) {
return getLinkLocalIp(netlink.FAMILY_V4)
}
func getV6LinkLocalIp() (*net.IPNet, error) {
return getLinkLocalIp(netlink.FAMILY_V6)
}
func tunnelEnabled() bool {
return option.Config.Tunnel != option.TunnelDisabled
}
func (n *linuxNodeHandler) enableSubnetIPsec(v4CIDR, v6CIDR []*net.IPNet) {
var spi uint8
var err error
zeroMark := false
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 conntract that may be using
// the mark fields. This uses XFRM_OUTPUT_MARK added in 4.14 kernels.
if option.Config.EnableEndpointRoutes {
zeroMark = true
}
for _, cidr := range v4CIDR {
ipsecIPv4Wildcard := &net.IPNet{IP: net.ParseIP(wildcardIPv4), Mask: net.IPv4Mask(0, 0, 0, 0)}
if !option.Config.EnableEndpointRoutes {
n.replaceNodeIPSecInRoute(cidr)
}
n.replaceNodeIPSecOutRoute(cidr)
spi, err = ipsec.UpsertIPsecEndpoint(ipsecIPv4Wildcard, cidr, ipsecIPv4Wildcard, ipsec.IPSecDirOut, zeroMark, tunnelEnabled())
upsertIPsecLog(err, "CNI Out IPv4", ipsecIPv4Wildcard, cidr, spi)
if n.nodeConfig.EncryptNode {
n.replaceNodeExternalIPSecOutRoute(cidr)
} else {
linkAddr, err := getV4LinkLocalIp()
if err != nil {
upsertIPsecLog(err, "getV4LinkLocalIP failed", ipsecIPv4Wildcard, cidr, spi)
}
spi, err := ipsec.UpsertIPsecEndpoint(linkAddr, ipsecIPv4Wildcard, cidr, ipsec.IPSecDirIn, zeroMark, tunnelEnabled())
upsertIPsecLog(err, "CNI In IPv4", linkAddr, ipsecIPv4Wildcard, spi)
}
}
for _, cidr := range v6CIDR {
ipsecIPv6Wildcard := &net.IPNet{IP: net.ParseIP(wildcardIPv6), Mask: net.CIDRMask(0, 0)}
n.replaceNodeIPSecInRoute(cidr)
n.replaceNodeIPSecOutRoute(cidr)
spi, err := ipsec.UpsertIPsecEndpoint(ipsecIPv6Wildcard, cidr, ipsecIPv6Wildcard, ipsec.IPSecDirOut, zeroMark, tunnelEnabled())
upsertIPsecLog(err, "CNI Out IPv6", cidr, ipsecIPv6Wildcard, spi)
if n.nodeConfig.EncryptNode {
n.replaceNodeExternalIPSecOutRoute(cidr)
} else {
linkAddr, err := getV6LinkLocalIp()
if err != nil {
upsertIPsecLog(err, "getV6LinkLocalIP failed", ipsecIPv6Wildcard, cidr, spi)
}
spi, err := ipsec.UpsertIPsecEndpoint(linkAddr, ipsecIPv6Wildcard, cidr, ipsec.IPSecDirIn, zeroMark, tunnelEnabled())
upsertIPsecLog(err, "CNI In IPv6", linkAddr, ipsecIPv6Wildcard, spi)
}
}
}
func (n *linuxNodeHandler) encryptNode(newNode *nodeTypes.Node) {
var spi uint8
var err error
if n.nodeConfig.EnableIPv4 && n.nodeConfig.EncryptNode {
internalIPv4 := n.nodeAddressing.IPv4().PrimaryExternal()
exactMask := net.IPv4Mask(255, 255, 255, 255)
ipsecLocal := &net.IPNet{IP: internalIPv4, Mask: exactMask}
if newNode.IsLocal() {
ipsecIPv4Wildcard := &net.IPNet{IP: net.ParseIP(wildcardIPv4), Mask: net.IPv4Mask(0, 0, 0, 0)}
n.replaceNodeIPSecInRoute(ipsecLocal)
spi, err = ipsec.UpsertIPsecEndpoint(ipsecLocal, ipsecIPv4Wildcard, ipsecLocal, ipsec.IPSecDirIn, false, tunnelEnabled())
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, ipsecLocal, ipsec.IPSecDirOutNode, false, tunnelEnabled())
upsertIPsecLog(err, "EncryptNode IPv4", ipsecLocal, ipsecRemote, spi)
}
remoteIPv4 := newNode.GetCiliumInternalIP(false)
if remoteIPv4 != nil && !n.subnetEncryption() {
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 {
ipsecRemoteT := &net.IPNet{IP: remoteIPv4T, Mask: exactMask}
err = ipsec.UpsertIPsecEndpointPolicy(ipsecWildcard, ipsecRemote, ipsecLocal, ipsecRemoteT, ipsec.IPSecDirOutNode)
}
upsertIPsecLog(err, "EncryptNode Cilium IPv4", ipsecWildcard, ipsecRemote, spi)
}
}
}
if n.nodeConfig.EnableIPv6 && n.nodeConfig.EncryptNode {
internalIPv6 := n.nodeAddressing.IPv6().PrimaryExternal()
exactMask := net.CIDRMask(128, 128)
ipsecLocal := &net.IPNet{IP: internalIPv6, Mask: exactMask}
if newNode.IsLocal() {
ipsecIPv6Wildcard := &net.IPNet{IP: net.ParseIP(wildcardIPv6), Mask: net.CIDRMask(0, 0)}
n.replaceNodeIPSecInRoute(ipsecLocal)
spi, err = ipsec.UpsertIPsecEndpoint(ipsecLocal, ipsecIPv6Wildcard, ipsecLocal, ipsec.IPSecDirIn, false, tunnelEnabled())
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, ipsecLocal, ipsec.IPSecDirOut, false, tunnelEnabled())
upsertIPsecLog(err, "EncryptNode IPv6", ipsecLocal, ipsecRemote, spi)
}
remoteIPv6 := newNode.GetCiliumInternalIP(true)
if remoteIPv6 != nil && !n.subnetEncryption() {
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 {
ipsecRemoteT := &net.IPNet{IP: remoteIPv6T, Mask: exactMask}
err = ipsec.UpsertIPsecEndpointPolicy(ipsecWildcard, ipsecRemote, ipsecLocal, ipsecRemoteT, ipsec.IPSecDirOutNode)
}
upsertIPsecLog(err, "EncryptNode Cilium IPv6", ipsecWildcard, ipsecRemote, spi)
}
}
}
}
func getSrcAndNextHopIPv4(nodeIPv4 net.IP) (srcIPv4, nextHopIPv4 net.IP, err error) {
// Figure out whether nodeIPv4 is directly reachable (i.e. in the same L2)
routes, err := netlink.RouteGet(nodeIPv4)
if err != nil {
return nil, nil, fmt.Errorf("failed to retrieve route for remote node IP: %w", err)
}
if len(routes) == 0 {
return nil, nil, fmt.Errorf("remote node IP is non-routable")
}
// Use the first available route by default
srcIPv4 = make(net.IP, net.IPv4len)
nextHopIPv4 = nodeIPv4
copy(srcIPv4, routes[0].Src.To4())
for _, route := range routes {
if route.Gw != nil {
// nodeIPv4 is in a different L2 subnet, so it must be reachable through
// a gateway. Send arping to the gw IP addr instead of nodeIPv4.
// NOTE: we currently don't handle multipath, so only one gw can be used.
copy(srcIPv4, route.Src.To4())
copy(nextHopIPv4, route.Gw.To4())
break
}
}
return srcIPv4, nextHopIPv4, nil
}
// insertNeighbor inserts a permanent ARP entry for a nexthop to the given
// "newNode" (ip route get newNodeIP.GetNodeIP()). The L2 addr of the nexthop
// is determined by sending ARP request for the nexthop from an iface specified
// by n.neighDiscoveryLink.
//
// The given "refresh" param denotes whether the method is called by a controller
// which tries to update ARP entries previously inserted by insertNeighbor(). In
// this case it does not bail out early if the ARP entry already exists, and
// sends the ARP request anyway.
func (n *linuxNodeHandler) insertNeighbor(ctx context.Context, newNode *nodeTypes.Node, refresh bool) {
var link netlink.Link
n.neighLock.Lock()
if n.neighDiscoveryLink == nil || reflect.ValueOf(n.neighDiscoveryLink).IsNil() {
n.neighLock.Unlock()
// Nothing to do - the discovery link was not set yet
return
}
link = n.neighDiscoveryLink
n.neighLock.Unlock()
newNodeIP := newNode.GetNodeIP(false).To4()
nextHopIPv4 := make(net.IP, len(newNodeIP))
copy(nextHopIPv4, newNodeIP)
scopedLog := log.WithFields(logrus.Fields{
logfields.LogSubsys: "node-neigh-debug",
logfields.Interface: link.Attrs().Name,
})
srcIPv4, nextHopIPv4, err := getSrcAndNextHopIPv4(nextHopIPv4)
if err != nil {
scopedLog.WithError(err).Info("Unable to determine source and nexthop IP addr")
return
}
nextHopStr := nextHopIPv4.String()
scopedLog = scopedLog.WithField(logfields.IPAddr, nextHopIPv4)
n.neighLock.Lock()
nextHopIsNew := false
if existingNextHopStr, found := n.neighNextHopByNode[newNode.Identity()]; found {
if existingNextHopStr != nextHopStr && 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.
if err := netlink.NeighDel(neigh); err != nil {
scopedLog.WithFields(logrus.Fields{
logfields.IPAddr: neigh.IP,
logfields.HardwareAddr: neigh.HardwareAddr,
logfields.LinkIndex: neigh.LinkIndex,
}).WithError(err).Info("Unable to remove neighbor entry")
}
delete(n.neighByNextHop, existingNextHopStr)
delete(n.neighLastPingByNextHop, existingNextHopStr)
if option.Config.NodePortHairpin {
neighborsmap.NeighRetire(net.ParseIP(existingNextHopStr))
}
}
}
} 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.neighNextHopByNode[newNode.Identity()] = nextHopStr
if refresh {
if lastPing, found := n.neighLastPingByNextHop[nextHopStr]; found &&
time.Now().Sub(lastPing) < option.Config.ARPPingRefreshPeriod {
n.neighLock.Unlock()
// 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
}
}
n.neighLock.Unlock() // to allow concurrent arpings below
// nextHop hasn't been arpinged before OR we are refreshing neigh entry
var hwAddr net.HardwareAddr
var now time.Time
if nextHopIsNew || refresh {
hwAddr, err = arp.PingOverLink(link, srcIPv4, nextHopIPv4)
if err != nil {
scopedLog.WithError(err).Debug("arping failed")
metrics.ArpingRequestsTotal.WithLabelValues(failed).Inc()
return
}
metrics.ArpingRequestsTotal.WithLabelValues(success).Inc()
now = time.Now()
}
n.neighLock.Lock()
defer n.neighLock.Unlock()
if hwAddr != nil {
if prev, found := n.neighLastPingByNextHop[nextHopStr]; found && prev.After(now) {
// Do not update the neigh entry if there was another goroutine which
// issued arping after us, as it might have a more recent hwAddr value.
return
}
n.neighLastPingByNextHop[nextHopStr] = now
if prevHwAddr, found := n.neighByNextHop[nextHopStr]; found && prevHwAddr.String() == hwAddr.String() {
// Nothing to update, return early to avoid calling to netlink. This
// is based on the assumption that n.neighByNextHop gets populated
// after the netlink call to insert the neigh has succeeded.
return
}
if option.Config.NodePortHairpin {
// Remove nextHopIPv4 entry in the neigh BPF map. Otherwise,
// we risk to silently blackhole packets instead of emitting
// DROP_NO_FIB if the netlink.NeighSet() below fails.
defer neighborsmap.NeighRetire(nextHopIPv4)
}
scopedLog = scopedLog.WithField(logfields.HardwareAddr, hwAddr)
neigh := netlink.Neigh{
LinkIndex: link.Attrs().Index,
IP: nextHopIPv4,
HardwareAddr: hwAddr,
State: netlink.NUD_PERMANENT,
}
// Don't proceed if the refresh controller cancelled the context
select {
case <-ctx.Done():
return
default:
}
if err := netlink.NeighSet(&neigh); err != nil {
scopedLog.WithError(err).Info("Unable to insert neighbor")
return
}
n.neighByNextHop[nextHopStr] = &neigh
}
}
func (n *linuxNodeHandler) refreshNeighbor(ctx context.Context, nodeToRefresh *nodeTypes.Node, completed chan struct{}) {
defer close(completed)
n.insertNeighbor(ctx, nodeToRefresh, true)
}
func (n *linuxNodeHandler) deleteNeighbor(oldNode *nodeTypes.Node) {
n.neighLock.Lock()
defer n.neighLock.Unlock()
nextHopStr, found := n.neighNextHopByNode[oldNode.Identity()]
if !found {
return
}
defer func() { delete(n.neighNextHopByNode, oldNode.Identity()) }()
if n.neighNextHopRefCount.Delete(nextHopStr) {
neigh, found := n.neighByNextHop[nextHopStr]
delete(n.neighByNextHop, nextHopStr)
delete(n.neighLastPingByNextHop, nextHopStr)
if found {
if err := netlink.NeighDel(neigh); err != nil {
log.WithFields(logrus.Fields{
logfields.LogSubsys: "node-neigh-debug",
logfields.IPAddr: neigh.IP,
logfields.HardwareAddr: neigh.HardwareAddr,
logfields.LinkIndex: neigh.LinkIndex,
}).WithError(err).Info("Unable to remove neighbor entry")
return
}
if option.Config.NodePortHairpin {
neighborsmap.NeighRetire(neigh.IP)
}
}
}
}
func (n *linuxNodeHandler) enableIPsec(newNode *nodeTypes.Node) {
var spi uint8
var err error
if newNode.IsLocal() {
n.replaceHostRules()
}
if n.nodeConfig.EnableIPv4 && newNode.IPv4AllocCIDR != nil {
new4Net := &net.IPNet{IP: newNode.IPv4AllocCIDR.IP, Mask: newNode.IPv4AllocCIDR.Mask}
if newNode.IsLocal() {
n.replaceNodeIPSecInRoute(new4Net)
ciliumInternalIPv4 := newNode.GetCiliumInternalIP(false)
if ciliumInternalIPv4 != nil {
ipsecLocal := &net.IPNet{IP: ciliumInternalIPv4, Mask: n.nodeAddressing.IPv4().AllocationCIDR().Mask}
ipsecIPv4Wildcard := &net.IPNet{IP: net.ParseIP(wildcardIPv4), Mask: net.IPv4Mask(0, 0, 0, 0)}
spi, err = ipsec.UpsertIPsecEndpoint(ipsecLocal, ipsecIPv4Wildcard, ipsecLocal, ipsec.IPSecDirIn, false, tunnelEnabled())
upsertIPsecLog(err, "local IPv4", ipsecLocal, ipsecIPv4Wildcard, spi)
}
} else {
if ciliumInternalIPv4 := newNode.GetCiliumInternalIP(false); ciliumInternalIPv4 != nil {
ipsecLocal := &net.IPNet{IP: n.nodeAddressing.IPv4().Router(), Mask: n.nodeAddressing.IPv4().AllocationCIDR().Mask}
ipsecRemote := &net.IPNet{IP: ciliumInternalIPv4, Mask: newNode.IPv4AllocCIDR.Mask}
n.replaceNodeIPSecOutRoute(new4Net)
spi, err = ipsec.UpsertIPsecEndpoint(ipsecLocal, ipsecRemote, ipsecLocal, ipsec.IPSecDirOut, false, tunnelEnabled())
upsertIPsecLog(err, "IPv4", ipsecLocal, ipsecRemote, spi)
/* Insert wildcard policy rules for traffic skipping back through host */
ipsecIPv4Wildcard := &net.IPNet{IP: net.ParseIP(wildcardIPv4), Mask: net.IPv4Mask(0, 0, 0, 0)}
if err = ipsec.IpSecReplacePolicyFwd(ipsecIPv4Wildcard, ipsecRemote, ipsecLocal, ipsecRemote); err != nil {
log.WithError(err).Warning("egress unable to replace policy fwd:")
}
}
}
}
if n.nodeConfig.EnableIPv6 && newNode.IPv6AllocCIDR != nil {
new6Net := &net.IPNet{IP: newNode.IPv6AllocCIDR.IP, Mask: newNode.IPv6AllocCIDR.Mask}
if newNode.IsLocal() {
n.replaceNodeIPSecInRoute(new6Net)
ciliumInternalIPv6 := newNode.GetCiliumInternalIP(true)
if ciliumInternalIPv6 != nil {
ipsecLocal := &net.IPNet{IP: ciliumInternalIPv6, Mask: n.nodeAddressing.IPv6().AllocationCIDR().Mask}
ipsecIPv6Wildcard := &net.IPNet{IP: net.ParseIP(wildcardIPv6), Mask: net.CIDRMask(0, 0)}
spi, err = ipsec.UpsertIPsecEndpoint(ipsecLocal, ipsecIPv6Wildcard, ipsecLocal, ipsec.IPSecDirIn, false, tunnelEnabled())
upsertIPsecLog(err, "local IPv6", ipsecLocal, ipsecIPv6Wildcard, spi)
}
} else {
if ciliumInternalIPv6 := newNode.GetCiliumInternalIP(true); ciliumInternalIPv6 != nil {
ipsecLocal := &net.IPNet{IP: n.nodeAddressing.IPv6().Router(), Mask: net.CIDRMask(0, 0)}
ipsecRemote := &net.IPNet{IP: ciliumInternalIPv6, Mask: newNode.IPv6AllocCIDR.Mask}
n.replaceNodeIPSecOutRoute(new6Net)
spi, err := ipsec.UpsertIPsecEndpoint(ipsecLocal, ipsecRemote, ipsecLocal, ipsec.IPSecDirOut, false, tunnelEnabled())
upsertIPsecLog(err, "IPv6", ipsecLocal, ipsecRemote, spi)
}
}
}
}
func (n *linuxNodeHandler) subnetEncryption() bool {
return len(n.nodeConfig.IPv4PodSubnets) > 0 || len(n.nodeConfig.IPv6PodSubnets) > 0
}
// Must be called with linuxNodeHandler.mutex held.
func (n *linuxNodeHandler) nodeUpdate(oldNode, newNode *nodeTypes.Node, firstAddition bool) error {
var (
oldIP4Cidr, oldIP6Cidr *cidr.CIDR
oldIP4, oldIP6 net.IP
newIP4 = newNode.GetNodeIP(false)
newIP6 = newNode.GetNodeIP(true)
oldKey, newKey uint8
isLocalNode = false
)
if oldNode != nil {
oldIP4Cidr = oldNode.IPv4AllocCIDR
oldIP6Cidr = oldNode.IPv6AllocCIDR
oldIP4 = oldNode.GetNodeIP(false)
oldIP6 = oldNode.GetNodeIP(true)
oldKey = oldNode.EncryptionKey
}
if n.nodeConfig.EnableIPSec && !n.subnetEncryption() && !n.nodeConfig.EncryptNode {
n.enableIPsec(newNode)
newKey = newNode.EncryptionKey
}
if n.enableNeighDiscovery && !newNode.IsLocal() {
// Running insertNeighbor in a separate goroutine relies on the following
// assumptions:
// 1. newNode is accessed only by reads.
// 2. It is safe to invoke insertNeighbor for the same node.
go n.insertNeighbor(context.Background(), newNode, false)
}
if n.nodeConfig.EnableIPSec && !n.subnetEncryption() {
n.encryptNode(newNode)
}
if newNode.IsLocal() {
isLocalNode = true
if n.nodeConfig.EnableLocalNodeRoute {
n.updateOrRemoveNodeRoutes([]*cidr.CIDR{oldIP4Cidr}, []*cidr.CIDR{newNode.IPv4AllocCIDR}, isLocalNode)
n.updateOrRemoveNodeRoutes([]*cidr.CIDR{oldIP6Cidr}, []*cidr.CIDR{newNode.IPv6AllocCIDR}, isLocalNode)
}
if n.subnetEncryption() {
n.enableSubnetIPsec(n.nodeConfig.IPv4PodSubnets, n.nodeConfig.IPv6PodSubnets)
}
return nil
}
if option.Config.EnableWireguard && newNode.WireguardPubKey != "" {
if err := n.wgAgent.UpdatePeer(newNode.Name, newNode.WireguardPubKey, newIP4, newIP6); err != nil {
log.WithError(err).
WithField(logfields.NodeName, newNode.Name).
Warning("Failed to update wireguard configuration for peer")
}
}
if n.nodeConfig.EnableAutoDirectRouting {
n.updateDirectRoute(oldIP4Cidr, newNode.IPv4AllocCIDR, oldIP4, newIP4, firstAddition, n.nodeConfig.EnableIPv4)
n.updateDirectRoute(oldIP6Cidr, newNode.IPv6AllocCIDR, oldIP6, newIP6, firstAddition, n.nodeConfig.EnableIPv6)
return nil
}
if n.nodeConfig.EnableEncapsulation {
// Update the tunnel mapping of the node. In case the
// node has changed its CIDR range, a new entry in the
// map is created and the old entry is removed.
updateTunnelMapping(oldIP4Cidr, newNode.IPv4AllocCIDR, oldIP4, newIP4, firstAddition, n.nodeConfig.EnableIPv4, oldKey, newKey)
// Not a typo, the IPv4 host IP is used to build the IPv6 overlay
updateTunnelMapping(oldIP6Cidr, newNode.IPv6AllocCIDR, oldIP4, newIP4, firstAddition, n.nodeConfig.EnableIPv6, oldKey, newKey)