-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
ipsec_linux.go
1117 lines (981 loc) · 35.2 KB
/
ipsec_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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
//go:build linux
package ipsec
import (
"bufio"
"context"
"encoding/hex"
"fmt"
"io"
"net"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/fsnotify/fsnotify"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
"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/fswatcher"
"github.com/cilium/cilium/pkg/inctimer"
"github.com/cilium/cilium/pkg/lock"
"github.com/cilium/cilium/pkg/logging/logfields"
"github.com/cilium/cilium/pkg/maps/encrypt"
"github.com/cilium/cilium/pkg/node"
"github.com/cilium/cilium/pkg/nodediscovery"
"github.com/cilium/cilium/pkg/option"
)
type IPSecDir string
const (
IPSecDirIn IPSecDir = "IPSEC_IN"
IPSecDirOut IPSecDir = "IPSEC_OUT"
IPSecDirBoth IPSecDir = "IPSEC_BOTH"
IPSecDirOutNode IPSecDir = "IPSEC_OUT_NODE"
// Constants used to decode the IPsec secret in both formats:
// 1. [spi] aead-algo aead-key icv-len
// 2. [spi] auth-algo auth-key enc-algo enc-key [IP]
offsetSPI = 0
offsetAeadAlgo = 1
offsetAeadKey = 2
offsetICV = 3
offsetAuthAlgo = 1
offsetAuthKey = 2
offsetEncAlgo = 3
offsetEncKey = 4
offsetIP = 5
maxOffset = offsetIP
// ipSecXfrmMarkSPIShift defines how many bits the SPI is shifted when
// encoded in a XfrmMark
ipSecXfrmMarkSPIShift = 12
defaultDropPriority = 100
oldXFRMOutPolicyPriority = 50
)
type ipSecKey struct {
Spi uint8
ReqID int
Auth *netlink.XfrmStateAlgo
Crypt *netlink.XfrmStateAlgo
Aead *netlink.XfrmStateAlgo
}
var (
ipSecLock lock.RWMutex
// ipSecKeysGlobal can be accessed by multiple subsystems concurrently,
// so it should be accessed only through the getIPSecKeys and
// loadIPSecKeys functions, which will ensure the proper lock is held
ipSecKeysGlobal = make(map[string]*ipSecKey)
// ipSecCurrentKeySPI is the SPI of the IPSec currently in use
ipSecCurrentKeySPI uint8
// ipSecKeysRemovalTime is used to track at which time a given key is
// replaced with a newer one, allowing to reclaim old keys only after
// enough time has passed since their replacement
ipSecKeysRemovalTime = make(map[uint8]time.Time)
wildcardIPv4 = net.ParseIP("0.0.0.0")
wildcardCIDRv4 = &net.IPNet{
IP: wildcardIPv4,
Mask: net.IPv4Mask(0, 0, 0, 0),
}
wildcardIPv6 = net.ParseIP("0::0")
wildcardCIDRv6 = &net.IPNet{
IP: wildcardIPv6,
Mask: net.CIDRMask(0, 128),
}
defaultDropMark = &netlink.XfrmMark{
Value: linux_defaults.RouteMarkEncrypt,
Mask: linux_defaults.IPsecMarkMaskIn,
}
defaultDropPolicyIPv4 = &netlink.XfrmPolicy{
Dir: netlink.XFRM_DIR_OUT,
Src: wildcardCIDRv4,
Dst: wildcardCIDRv4,
Mark: defaultDropMark,
Action: netlink.XFRM_POLICY_BLOCK,
Priority: defaultDropPriority,
}
defaultDropPolicyIPv6 = &netlink.XfrmPolicy{
Dir: netlink.XFRM_DIR_OUT,
Src: wildcardCIDRv6,
Dst: wildcardCIDRv6,
Mark: defaultDropMark,
Action: netlink.XFRM_POLICY_BLOCK,
Priority: defaultDropPriority,
}
// To attempt to remove any stale XFRM configs once at startup, after
// we've added the catch-all default-drop policy.
removeStaleIPv4XFRMOnce sync.Once
removeStaleIPv6XFRMOnce sync.Once
)
func getIPSecKeys(ip net.IP) *ipSecKey {
ipSecLock.RLock()
defer ipSecLock.RUnlock()
key, scoped := ipSecKeysGlobal[ip.String()]
if scoped == false {
key, _ = ipSecKeysGlobal[""]
}
return key
}
func ipSecNewState() *netlink.XfrmState {
state := netlink.XfrmState{
Mode: netlink.XFRM_MODE_TUNNEL,
Proto: netlink.XFRM_PROTO_ESP,
ESN: false,
}
return &state
}
func ipSecNewPolicy() *netlink.XfrmPolicy {
policy := netlink.XfrmPolicy{}
return &policy
}
func ipSecAttachPolicyTempl(policy *netlink.XfrmPolicy, keys *ipSecKey, srcIP, dstIP net.IP, spi bool, optional int) {
tmpl := netlink.XfrmPolicyTmpl{
Proto: netlink.XFRM_PROTO_ESP,
Mode: netlink.XFRM_MODE_TUNNEL,
Reqid: keys.ReqID,
Dst: dstIP,
Src: srcIP,
Optional: optional,
}
if spi {
tmpl.Spi = int(keys.Spi)
}
policy.Tmpls = append(policy.Tmpls, tmpl)
}
func ipSecJoinState(state *netlink.XfrmState, keys *ipSecKey) {
if keys.Aead != nil {
state.Aead = keys.Aead
} else {
state.Crypt = keys.Crypt
state.Auth = keys.Auth
}
state.Spi = int(keys.Spi)
state.Reqid = keys.ReqID
}
// xfrmStateReplace attempts to add a new XFRM state only if one doesn't
// already exist. If it doesn't but some other XFRM state conflicts, then
// we attempt to remove the conflicting state before trying to add again.
func xfrmStateReplace(new *netlink.XfrmState) error {
states, err := netlink.XfrmStateList(netlink.FAMILY_ALL)
if err != nil {
return fmt.Errorf("Cannot get XFRM state: %s", err)
}
scopedLog := log.WithFields(logrus.Fields{
logfields.SPI: new.Spi,
logfields.SourceIP: new.Src,
logfields.DestinationIP: new.Dst,
})
// Check if the XFRM state already exists
for _, s := range states {
if xfrmIPEqual(s.Src, new.Src) && xfrmIPEqual(s.Dst, new.Dst) &&
xfrmMarkEqual(s.OutputMark, new.OutputMark) &&
xfrmMarkEqual(s.Mark, new.Mark) && s.Spi == new.Spi {
return nil
}
}
oldXFRMMark := &netlink.XfrmMark{
Value: ipSecXfrmMarkSetSPI(linux_defaults.RouteMarkEncrypt, uint8(new.Spi)),
Mask: linux_defaults.IPsecOldMarkMaskOut,
}
for _, s := range states {
// This is the XFRM OUT state from a previous Cilium version.
// Because its mark matches the new mark (0xXXXX3e00/0xffffff00 ∈
// 0x3e00/0xff00), the kernel considers the two states conflict and we
// won't be able to add the new one until the old one is removed.
//
// Thus, we temporarily remove the old, conflicting XFRM state and
// re-add it in a defer. In between the removal of the old state and
// the addition of the new, we can have a packet drops due to the
// missing state. These drops should be limited to the specific node
// pair we are handling here and the window during which they can
// happen should be really small. This is also specific to the upgrade
// and can be removed in v1.15. Finally, this shouldn't happen with ENI
// and Azure IPAM modes because they don't have such conflicting states.
if xfrmIPEqual(s.Src, new.Src) && xfrmIPEqual(s.Dst, new.Dst) &&
xfrmMarkEqual(s.OutputMark, new.OutputMark) &&
xfrmMarkEqual(s.Mark, oldXFRMMark) && s.Spi == new.Spi {
err := netlink.XfrmStateDel(&s)
if err != nil {
scopedLog.WithError(err).Error("Failed to remove old XFRM state")
} else {
scopedLog.Infof("Temporarily removed old XFRM state")
defer func(oldXFRMState netlink.XfrmState) {
if err := netlink.XfrmStateAdd(&oldXFRMState); err != nil {
scopedLog.WithError(err).Errorf("Failed to re-add old XFRM state")
}
}(s)
}
}
}
// It doesn't exist so let's attempt to add it.
firstAttemptErr := netlink.XfrmStateAdd(new)
if !os.IsExist(firstAttemptErr) {
return firstAttemptErr
}
scopedLog.Error("Failed to add XFRM state due to conflicting state")
// An existing state conflicts with this one. We need to remove the
// existing one first.
deletedSomething, err := xfrmDeleteConflictingState(states, new)
if err != nil {
return err
}
// If no conflicting state was found and deleted, there's no point in
// attempting to add again.
if !deletedSomething {
return firstAttemptErr
}
return netlink.XfrmStateAdd(new)
}
// Attempt to remove any XFRM state that conflicts with the state we just tried
// to add. To find those conflicting states, we need to use the same logic that
// the kernel used to reject our check with EEXIST. That logic is upstream in
// __xfrm_state_lookup.
func xfrmDeleteConflictingState(states []netlink.XfrmState, new *netlink.XfrmState) (bool, error) {
deletedSomething := false
for _, s := range states {
if new.Spi == s.Spi && (new.Mark == nil) == (s.Mark == nil) &&
(new.Mark == nil || new.Mark.Value&new.Mark.Mask&s.Mark.Mask == s.Mark.Value) &&
xfrmIPEqual(new.Src, s.Src) && xfrmIPEqual(new.Dst, s.Dst) {
err := netlink.XfrmStateDel(&s)
if err == nil {
deletedSomething = true
log.WithFields(logrus.Fields{
logfields.SPI: s.Spi,
logfields.SourceIP: s.Src,
logfields.DestinationIP: s.Dst,
}).Info("Removed a conflicting XFRM state")
} else {
return deletedSomething, fmt.Errorf("Failed to remove a conflicting XFRM state: %w", err)
}
}
}
return deletedSomething, nil
}
// This function compares two IP addresses and returns true if they are equal.
// This is unfortunately necessary because our netlink library returns nil IPv6
// addresses as nil IPv4 addresses and net.IP.Equal rightfully considers those
// are different.
func xfrmIPEqual(ip1, ip2 net.IP) bool {
if ip1.IsUnspecified() && ip2.IsUnspecified() {
return true
}
return ip1.Equal(ip2)
}
// Returns true if two XFRM marks are identical. They should be either both nil
// or have the same mark value and mask.
func xfrmMarkEqual(mark1, mark2 *netlink.XfrmMark) bool {
if (mark1 == nil) != (mark2 == nil) {
return false
}
return mark1 == nil || (mark1.Value == mark2.Value && mark1.Mask == mark2.Mask)
}
func ipSecReplaceStateIn(localIP, remoteIP net.IP, zeroMark bool) (uint8, error) {
key := getIPSecKeys(remoteIP)
if key == nil {
return 0, fmt.Errorf("IPSec key missing")
}
state := ipSecNewState()
ipSecJoinState(state, key)
state.Src = remoteIP
state.Dst = localIP
state.Mark = &netlink.XfrmMark{
Value: linux_defaults.RouteMarkDecrypt,
Mask: linux_defaults.IPsecMarkMaskIn,
}
if !zeroMark {
state.OutputMark = &netlink.XfrmMark{
Value: linux_defaults.RouteMarkDecrypt,
Mask: linux_defaults.RouteMarkMask,
}
} else {
state.OutputMark = &netlink.XfrmMark{
Value: 0,
Mask: linux_defaults.RouteMarkMask,
}
}
return key.Spi, xfrmStateReplace(state)
}
func ipSecReplaceStateOut(localIP, remoteIP net.IP, nodeID uint16) (uint8, error) {
key := getIPSecKeys(localIP)
if key == nil {
return 0, fmt.Errorf("IPSec key missing")
}
state := ipSecNewState()
ipSecJoinState(state, key)
state.Src = localIP
state.Dst = remoteIP
state.Mark = generateEncryptMark(key.Spi, nodeID)
state.OutputMark = &netlink.XfrmMark{
Value: linux_defaults.RouteMarkEncrypt,
Mask: linux_defaults.RouteMarkMask,
}
return key.Spi, xfrmStateReplace(state)
}
func _ipSecReplacePolicyInFwd(src, dst *net.IPNet, tmplSrc, tmplDst net.IP, proxyMark bool, dir netlink.Dir) error {
optional := int(0)
key := getIPSecKeys(dst.IP)
if key == nil {
return fmt.Errorf("IPSec key missing")
}
wildcardIP := wildcardIPv4
wildcardCIDR := wildcardCIDRv4
if tmplDst.To4() == nil {
wildcardIP = wildcardIPv6
wildcardCIDR = wildcardCIDRv6
}
policy := ipSecNewPolicy()
policy.Dir = dir
if dir == netlink.XFRM_DIR_IN {
policy.Src = src
policy.Dst = dst
policy.Mark = &netlink.XfrmMark{
Mask: linux_defaults.IPsecMarkMaskIn,
}
if proxyMark {
// We require a policy to match on packets going to the proxy which are
// therefore carrying the proxy mark. We however don't need a policy
// for the encrypted packets because there is already a state matching
// them.
policy.Mark.Value = linux_defaults.RouteMarkToProxy
// We must mark the IN policy for the proxy optional simply because it
// is lacking a corresponding state.
optional = 1
// We set the source tmpl address to 0/0 to explicit that it
// doesn't matter.
tmplSrc = wildcardIP
} else {
policy.Mark.Value = linux_defaults.RouteMarkDecrypt
}
}
// We always make forward rules optional. The only reason we have these
// at all is to appease the XFRM route hooks, we don't really care about
// policy because Cilium BPF programs do that.
if dir == netlink.XFRM_DIR_FWD {
optional = 1
policy.Priority = linux_defaults.IPsecFwdPriority
// In case of fwd policies, we should tell the kernel the tmpl src
// doesn't matter; we want all fwd packets to go through.
policy.Src = wildcardCIDR
policy.Dst = wildcardCIDR
}
ipSecAttachPolicyTempl(policy, key, tmplSrc, tmplDst, false, optional)
return netlink.XfrmPolicyUpdate(policy)
}
func ipSecReplacePolicyIn(src, dst *net.IPNet, tmplSrc, tmplDst net.IP) error {
if err := _ipSecReplacePolicyInFwd(src, dst, tmplSrc, tmplDst, true, netlink.XFRM_DIR_IN); err != nil {
return err
}
return _ipSecReplacePolicyInFwd(src, dst, tmplSrc, tmplDst, false, netlink.XFRM_DIR_IN)
}
func IpSecReplacePolicyFwd(dst *net.IPNet, tmplDst net.IP) error {
// The source CIDR and IP aren't used in the case of FWD policies.
return _ipSecReplacePolicyInFwd(nil, dst, net.IP{}, tmplDst, false, netlink.XFRM_DIR_FWD)
}
// Installs a catch-all policy for outgoing traffic that has the encryption
// bit. The goal here is to catch any traffic that may passthrough our
// encryption while we are replacing XFRM policies & states. Those operations
// cannot always be performed atomically so we may have brief moments where
// there is no XFRM policy to encrypt a subset of traffic. This policy ensures
// we drop such traffic and don't let it flow in plain text.
//
// We do need to match on the mark because there is also traffic flowing
// through XFRM that we don't want to encrypt (e.g., hostns traffic).
func IPsecDefaultDropPolicy(ipv6 bool) error {
defaultDropPolicy := defaultDropPolicyIPv4
family := netlink.FAMILY_V4
if ipv6 {
defaultDropPolicy = defaultDropPolicyIPv6
family = netlink.FAMILY_V6
}
err := netlink.XfrmPolicyUpdate(defaultDropPolicy)
// We move the existing XFRM OUT policy to a lower priority to allow the
// new priorities to take precedence.
// This code can be removed in Cilium v1.15 to instead remove the old XFRM
// OUT policy and state.
removeStaleXFRMOnce := &removeStaleIPv4XFRMOnce
if ipv6 {
removeStaleXFRMOnce = &removeStaleIPv6XFRMOnce
}
removeStaleXFRMOnce.Do(func() {
deprioritizeOldOutPolicy(family)
})
return err
}
// Lowers the priority of the old XFRM OUT policy. We rely on the mark mask to
// identify it. By lowering the priority, we will allow the new XFRM OUT
// policies to take precedence. We cannot simply remove and replace the old
// XFRM OUT configs because that would cause traffic interruptions on upgrades.
func deprioritizeOldOutPolicy(family int) {
policies, err := netlink.XfrmPolicyList(family)
if err != nil {
log.WithError(err).Error("Cannot get XFRM policies")
}
for _, p := range policies {
if p.Dir == netlink.XFRM_DIR_OUT && p.Mark.Mask == linux_defaults.IPsecOldMarkMaskOut {
p.Priority = oldXFRMOutPolicyPriority
if err := netlink.XfrmPolicyUpdate(&p); err != nil {
log.WithError(err).WithFields(logrus.Fields{
logfields.SourceCIDR: p.Src,
logfields.DestinationCIDR: p.Dst,
}).Error("Failed to deprioritize old XFRM policy")
}
}
}
}
// ipSecXfrmMarkSetSPI takes a XfrmMark base value, an SPI, returns the mark
// value with the SPI value encoded in it
func ipSecXfrmMarkSetSPI(markValue uint32, spi uint8) uint32 {
return markValue | (uint32(spi) << ipSecXfrmMarkSPIShift)
}
// ipSecXfrmMarkGetSPI extracts from a XfrmMark value the encoded SPI
func ipSecXfrmMarkGetSPI(markValue uint32) uint8 {
return uint8(markValue >> ipSecXfrmMarkSPIShift & 0xF)
}
func getSPIFromXfrmPolicy(policy *netlink.XfrmPolicy) uint8 {
if policy.Mark == nil {
return 0
}
return ipSecXfrmMarkGetSPI(policy.Mark.Value)
}
func getNodeIDFromXfrmMark(mark *netlink.XfrmMark) uint16 {
if mark == nil {
return 0
}
return uint16(mark.Value >> 16)
}
func generateEncryptMark(spi uint8, nodeID uint16) *netlink.XfrmMark {
val := ipSecXfrmMarkSetSPI(linux_defaults.RouteMarkEncrypt, spi)
val |= uint32(nodeID) << 16
return &netlink.XfrmMark{
Value: val,
Mask: linux_defaults.IPsecMarkMaskOut,
}
}
func ipSecReplacePolicyOut(src, dst *net.IPNet, tmplSrc, tmplDst net.IP, nodeID uint16, dir IPSecDir) error {
// TODO: Remove old policy pointing to target net
key := getIPSecKeys(dst.IP)
if key == nil {
return fmt.Errorf("IPSec key missing")
}
policy := ipSecNewPolicy()
if dir == IPSecDirOutNode {
policy.Src = wildcardCIDRv4
} else {
policy.Src = src
}
policy.Dst = dst
policy.Dir = netlink.XFRM_DIR_OUT
policy.Mark = generateEncryptMark(key.Spi, nodeID)
ipSecAttachPolicyTempl(policy, key, tmplSrc, tmplDst, true, 0)
return netlink.XfrmPolicyUpdate(policy)
}
// Returns true if the given mark matches on the node ID. This works because
// the node ID match is always in the first 16 bits.
func matchesOnNodeID(mark *netlink.XfrmMark) bool {
return mark != nil &&
mark.Mask&linux_defaults.IPsecMarkMaskNodeID == linux_defaults.IPsecMarkMaskNodeID
}
func ipsecDeleteXfrmState(nodeID uint16) {
scopedLog := log.WithFields(logrus.Fields{
logfields.NodeID: nodeID,
})
xfrmStateList, err := netlink.XfrmStateList(netlink.FAMILY_ALL)
if err != nil {
scopedLog.WithError(err).Warning("Failed to list XFRM states for deletion")
return
}
for _, s := range xfrmStateList {
if matchesOnNodeID(s.Mark) && getNodeIDFromXfrmMark(s.Mark) == nodeID {
if err := netlink.XfrmStateDel(&s); err != nil {
scopedLog.WithError(err).Warning("Failed to delete XFRM state")
}
}
}
}
func ipsecDeleteXfrmPolicy(nodeID uint16) {
scopedLog := log.WithFields(logrus.Fields{
logfields.NodeID: nodeID,
})
xfrmPolicyList, err := netlink.XfrmPolicyList(netlink.FAMILY_ALL)
if err != nil {
scopedLog.WithError(err).Warning("Failed to list XFRM policies for deletion")
return
}
for _, p := range xfrmPolicyList {
if matchesOnNodeID(p.Mark) && getNodeIDFromXfrmMark(p.Mark) == nodeID {
if err := netlink.XfrmPolicyDel(&p); err != nil {
scopedLog.WithError(err).Warning("Failed to delete XFRM policy")
}
}
}
}
/* UpsertIPsecEndpoint updates the IPSec context for a new endpoint inserted in
* the ipcache. Currently we support a global crypt/auth keyset that will encrypt
* all traffic between endpoints. An IPSec context consists of two pieces a policy
* and a state, the security policy database (SPD) and security association
* database (SAD). These are implemented using the Linux kernels XFRM implementation.
*
* For all traffic that matches a policy, the policy tuple used is
* (sip/mask, dip/mask, dev) with an optional mark field used in the Cilium implementation
* to ensure only expected traffic is encrypted. The state hashtable is searched for
* a matching state associated with that flow. The Linux kernel will do a series of
* hash lookups to find the most specific state (xfrm_dst) possible. The hash keys searched are
* the following, (daddr, saddr, reqid, encap_family), (daddr, wildcard, reqid, encap),
* (mark, daddr, spi, proto, encap). Any "hits" in the hash table will subsequently
* have the SPI checked to ensure it also matches. Encap is ignored in our case here
* and can be used with UDP encap if wanted.
*
* The implications of the (inflexible!) hash key implementation is that in-order
* to have a policy/state match we _must_ insert a state for each daddr. For Cilium
* this translates to a state entry per node. We learn the nodes/endpoints by
* listening to ipcache events. Finally, because IPSec is unidirectional a state
* is needed for both ingress and egress. Denoted by the DIR on the xfrm cmd line
* in the policy lookup. In the Cilium case, where we have IPSec between all
* endpoints this results in two policy rules per node, one for ingress
* and one for egress.
*
* For a concrete example consider two cluster nodes using transparent mode e.g.
* without an IPSec tunnel IP. Cluster Node A has host_ip 10.156.0.1 with an
* endpoint assigned to IP 10.156.2.2 and cluster Node B has host_ip 10.182.0.1
* with an endpoint using IP 10.182.3.3. Then on Node A there will be a two policy
* entries and a set of State entries,
*
* Policy1(src=10.182.0.0/16,dst=10.156.0.1/16,dir=in,tmpl(spi=#spi,reqid=#reqid))
* Policy2(src=10.156.0.0/16,dst=10.182.0.1/16,dir=out,tmpl(spi=#spi,reqid=#reqid))
* State1(src=*,dst=10.182.0.1,spi=#spi,reqid=#reqid,...)
* State2(src=*,dst=10.156.0.1,spi=#spi,reqid=#reqid,...)
*
* Design Note: For newer kernels a BPF xfrm interface would greatly simplify the
* state space. Basic idea would be to reference a state using any key generated
* from BPF program allowing for a single state per security ctx.
*/
func UpsertIPsecEndpoint(local, remote *net.IPNet, outerLocal, outerRemote net.IP, remoteNodeID uint16, dir IPSecDir, outputMark bool) (uint8, error) {
var spi uint8
var err error
/* TODO: state reference ID is (dip,spi) which can be duplicated in the current global
* mode. The duplication is on _all_ ingress states because dst_ip == host_ip in this
* case and only a single spi entry is in use. Currently no check is done to avoid
* attempting to add duplicate (dip,spi) states and we get 'file exist' error. These
* errors are expected at the moment but perhaps it would be better to avoid calling
* netlink API at all when we "know" an entry is a duplicate. To do this the xfer
* state would need to be cached in the ipcache.
*/
if !outerLocal.Equal(outerRemote) {
if dir == IPSecDirIn || dir == IPSecDirBoth {
if spi, err = ipSecReplaceStateIn(outerLocal, outerRemote, outputMark); err != nil {
return 0, fmt.Errorf("unable to replace local state: %s", err)
}
if err = ipSecReplacePolicyIn(remote, local, outerRemote, outerLocal); err != nil {
if !os.IsExist(err) {
return 0, fmt.Errorf("unable to replace policy in: %s", err)
}
}
if err = IpSecReplacePolicyFwd(local, outerLocal); err != nil {
if !os.IsExist(err) {
return 0, fmt.Errorf("unable to replace policy fwd: %s", err)
}
}
}
if dir == IPSecDirOut || dir == IPSecDirOutNode || dir == IPSecDirBoth {
if spi, err = ipSecReplaceStateOut(outerLocal, outerRemote, remoteNodeID); err != nil {
return 0, fmt.Errorf("unable to replace remote state: %s", err)
}
if err = ipSecReplacePolicyOut(local, remote, outerLocal, outerRemote, remoteNodeID, dir); err != nil {
if !os.IsExist(err) {
return 0, fmt.Errorf("unable to replace policy out: %s", err)
}
}
}
}
return spi, nil
}
// UpsertIPsecEndpointPolicy adds a policy to the xfrm rules. Used to add a policy when the state
// rule is already available.
func UpsertIPsecEndpointPolicy(local, remote *net.IPNet, localTmpl, remoteTmpl net.IP, remoteNodeID uint16, dir IPSecDir) error {
if err := ipSecReplacePolicyOut(local, remote, localTmpl, remoteTmpl, remoteNodeID, dir); err != nil {
if !os.IsExist(err) {
return fmt.Errorf("unable to replace templated policy out: %s", err)
}
}
return nil
}
// DeleteIPsecEndpoint deletes a endpoint associated with the remote IP address
func DeleteIPsecEndpoint(nodeID uint16) {
ipsecDeleteXfrmState(nodeID)
ipsecDeleteXfrmPolicy(nodeID)
}
func isXfrmPolicyCilium(policy netlink.XfrmPolicy) bool {
if policy.Mark == nil {
// Check if its our fwd rule, we don't have a mark
// on this rule so use priority.
if policy.Dir == netlink.XFRM_DIR_FWD &&
policy.Priority == linux_defaults.IPsecFwdPriority {
return true
}
return false
}
if (policy.Mark.Value & linux_defaults.RouteMarkDecrypt) != 0 {
return true
}
if (policy.Mark.Value & linux_defaults.RouteMarkEncrypt) != 0 {
return true
}
return false
}
func isXfrmStateCilium(state netlink.XfrmState) bool {
if state.Mark == nil {
return false
}
if (state.Mark.Value & linux_defaults.RouteMarkDecrypt) != 0 {
return true
}
if (state.Mark.Value & linux_defaults.RouteMarkEncrypt) != 0 {
return true
}
return false
}
// DeleteXfrm remove any remaining XFRM policy or state from tables
func DeleteXfrm() {
xfrmPolicyList, err := netlink.XfrmPolicyList(netlink.FAMILY_ALL)
if err == nil {
for _, p := range xfrmPolicyList {
if isXfrmPolicyCilium(p) {
if err := netlink.XfrmPolicyDel(&p); err != nil {
log.WithError(err).Warning("deleting xfrm policy failed")
}
}
}
}
xfrmStateList, err := netlink.XfrmStateList(netlink.FAMILY_ALL)
if err == nil {
for _, s := range xfrmStateList {
if isXfrmStateCilium(s) {
if err := netlink.XfrmStateDel(&s); err != nil {
log.WithError(err).Warning("deleting old xfrm state failed")
}
}
}
}
}
func decodeIPSecKey(keyRaw string) (int, []byte, error) {
// As we have released the v1.4.0 docs telling the users to write the
// k8s secret with the prefix "0x" we have to remove it if it is present,
// so we can decode the secret.
if keyRaw == "\"\"" {
return 0, nil, nil
}
keyTrimmed := strings.TrimPrefix(keyRaw, "0x")
key, err := hex.DecodeString(keyTrimmed)
return len(keyTrimmed), key, err
}
// LoadIPSecKeysFile imports IPSec auth and crypt keys from a file. The format
// is to put a key per line as follows, (auth-algo auth-key enc-algo enc-key)
// Returns the authentication overhead in bytes, the key ID, and an error.
func LoadIPSecKeysFile(path string) (int, uint8, error) {
log.WithField(logfields.Path, path).Info("Loading IPsec keyfile")
file, err := os.Open(path)
if err != nil {
return 0, 0, err
}
defer file.Close()
return loadIPSecKeys(file)
}
func loadIPSecKeys(r io.Reader) (int, uint8, error) {
var spi uint8
var keyLen int
ipSecLock.Lock()
defer ipSecLock.Unlock()
if err := encrypt.MapCreate(); err != nil {
return 0, 0, fmt.Errorf("Encrypt map create failed: %v", err)
}
scanner := bufio.NewScanner(r)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
var oldSpi uint8
var aeadKey, authKey []byte
offsetBase := 0
ipSecKey := &ipSecKey{
ReqID: 1,
}
// Scanning IPsec keys with one of the following formats:
// 1. [spi] aead-algo aead-key icv-len
// 2. [spi] auth-algo auth-key enc-algo enc-key [IP]
s := strings.Split(scanner.Text(), " ")
if len(s) < 3 {
// Regardless of the format used, the IPsec secret should have at
// least 3 fields separated by white spaces.
return 0, 0, fmt.Errorf("missing IPSec key or invalid format")
}
spiI, err := strconv.Atoi(s[offsetSPI])
if err != nil {
// If no version info is provided assume using key format without
// versioning and assign SPI.
log.Warning("IPsec secrets without an SPI as the first argument are deprecated and will be unsupported in v1.13.")
spiI = 1
offsetBase = -1
}
if spiI > linux_defaults.IPsecMaxKeyVersion {
return 0, 0, fmt.Errorf("encryption key space exhausted. ID must be nonzero and less than %d. Attempted %q", linux_defaults.IPsecMaxKeyVersion+1, s[offsetSPI])
}
if spiI == 0 {
return 0, 0, fmt.Errorf("zero is not a valid key ID. ID must be nonzero and less than %d. Attempted %q", linux_defaults.IPsecMaxKeyVersion+1, s[offsetSPI])
}
spi = uint8(spiI)
if len(s) > offsetBase+maxOffset+1 {
return 0, 0, fmt.Errorf("invalid format: too many fields in the IPsec secret")
} else if len(s) == offsetBase+offsetICV+1 {
// We're in the first case, with "[spi] aead-algo aead-key icv-len".
aeadName := s[offsetBase+offsetAeadAlgo]
if !strings.HasPrefix(aeadName, "rfc") {
return 0, 0, fmt.Errorf("invalid AEAD algorithm %q", aeadName)
}
_, aeadKey, err = decodeIPSecKey(s[offsetBase+offsetAeadKey])
if err != nil {
return 0, 0, fmt.Errorf("unable to decode AEAD key string %q", s[offsetBase+offsetAeadKey])
}
icvLen, err := strconv.Atoi(s[offsetICV+offsetBase])
if err != nil {
return 0, 0, fmt.Errorf("ICV length is invalid or missing")
}
if icvLen != 96 && icvLen != 128 && icvLen != 256 {
return 0, 0, fmt.Errorf("only ICV lengths 96, 128, and 256 are accepted")
}
ipSecKey.Aead = &netlink.XfrmStateAlgo{
Name: aeadName,
Key: aeadKey,
ICVLen: icvLen,
}
keyLen = icvLen / 8
} else {
// We're in the second case, with "[spi] auth-algo auth-key enc-algo enc-key [IP]".
authAlgo := s[offsetBase+offsetAuthAlgo]
keyLen, authKey, err = decodeIPSecKey(s[offsetBase+offsetAuthKey])
if err != nil {
return 0, 0, fmt.Errorf("unable to decode authentication key string %q", s[offsetBase+offsetAuthKey])
}
encAlgo := s[offsetBase+offsetEncAlgo]
_, encKey, err := decodeIPSecKey(s[offsetBase+offsetEncKey])
if err != nil {
return 0, 0, fmt.Errorf("unable to decode encryption key string %q", s[offsetBase+offsetEncKey])
}
ipSecKey.Auth = &netlink.XfrmStateAlgo{
Name: authAlgo,
Key: authKey,
}
ipSecKey.Crypt = &netlink.XfrmStateAlgo{
Name: encAlgo,
Key: encKey,
}
}
ipSecKey.Spi = spi
if len(s) == offsetBase+offsetIP+1 {
// The IPsec secret has the optional IP address field at the end.
log.Warning("IPsec secrets with an IP address as the last argument are deprecated and will be unsupported in v1.13.")
if ipSecKeysGlobal[s[offsetBase+offsetIP]] != nil {
oldSpi = ipSecKeysGlobal[s[offsetBase+offsetIP]].Spi
}
ipSecKeysGlobal[s[offsetBase+offsetIP]] = ipSecKey
} else {
if ipSecKeysGlobal[""] != nil {
oldSpi = ipSecKeysGlobal[""].Spi
}
ipSecKeysGlobal[""] = ipSecKey
}
ipSecKeysRemovalTime[oldSpi] = time.Now()
ipSecCurrentKeySPI = spi
}
return keyLen, spi, nil
}
func SetIPSecSPI(spi uint8) error {
scopedLog := log
if err := encrypt.MapUpdateContext(0, spi); err != nil {
scopedLog.WithError(err).Warn("cilium_encrypt_state map updated failed:")
return err
}
return nil
}
// DeleteIPsecEncryptRoute removes nodes in main routing table by walking
// routes and matching route protocol type.
func DeleteIPsecEncryptRoute() {
filter := &netlink.Route{
Protocol: route.EncryptRouteProtocol,
}
for _, family := range []int{netlink.FAMILY_V4, netlink.FAMILY_V6} {
routes, err := netlink.RouteListFiltered(family, filter, netlink.RT_FILTER_PROTOCOL)
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())
}
}
}
}
func keyfileWatcher(ctx context.Context, watcher *fswatcher.Watcher, keyfilePath string, nodediscovery *nodediscovery.NodeDiscovery, nodeHandler datapath.NodeHandler) {
for {
select {
case event := <-watcher.Events:
if event.Op&(fsnotify.Create|fsnotify.Write) == 0 {
continue
}
_, spi, err := LoadIPSecKeysFile(keyfilePath)
if err != nil {
log.WithError(err).Errorf("Failed to load IPsec keyfile")
continue
}
// Update the IPSec key identity in the local node.
// This will set addrs.ipsecKeyIdentity in the node
// package
node.SetIPsecKeyIdentity(spi)
// AllNodeValidateImplementation will eventually call
// nodeUpdate(), which is responsible for updating the
// IPSec policies and states for all the different EPs
// with ipsec.UpsertIPsecEndpoint()
nodeHandler.AllNodeValidateImplementation()
// Publish the updated node information to k8s/KVStore
nodediscovery.UpdateLocalNode()
// Push SPI update into BPF datapath now that XFRM state
// is configured.
if err := SetIPSecSPI(spi); err != nil {
log.WithError(err).Errorf("Failed to set IPsec SPI")
continue
}
case err := <-watcher.Errors:
log.WithError(err).WithField(logfields.Path, keyfilePath).
Warning("Error encountered while watching file with fsnotify")
case <-ctx.Done():
watcher.Close()
return
}
}
}
func StartKeyfileWatcher(ctx context.Context, keyfilePath string, nodediscovery *nodediscovery.NodeDiscovery, nodeHandler datapath.NodeHandler) error {
if !option.Config.EnableIPsecKeyWatcher {
return nil
}
watcher, err := fswatcher.New([]string{keyfilePath})
if err != nil {
return err
}
go keyfileWatcher(ctx, watcher, keyfilePath, nodediscovery, nodeHandler)
return nil
}
// ipSecSPICanBeReclaimed is used to test whether a given SPI can be reclaimed
// or not (i.e. if it's not in use, and if not, if enough time has passed since
// when it was replaced by a newer one).
//
// In addition to the SPI, this function takes also a reclaimTimestamp
// parameter which represents the time at which we started reclaiming old keys.
// This is needed as we need to test the same SPI multiple times (since for any
// given SPI there are multiple policies and states associated with it), and we
// don't want to get inconsistent results because we are calling time.Now()
// directly in this function.
func ipSecSPICanBeReclaimed(spi uint8, reclaimTimestamp time.Time) bool {
// The SPI associated with the key currently in use should not be reclaimed
if spi == ipSecCurrentKeySPI {
return false
}
// Otherwise retrieve the time at which the key for the given SPI was removed
keyRemovalTime, ok := ipSecKeysRemovalTime[spi]
if !ok {
// If not found in the keyRemovalTime map, assume the key was
// deleted just now.
// In this way if the agent gets restarted before an old key is
// removed we will always wait at least IPsecKeyRotationDuration time
// before reclaiming it
ipSecKeysRemovalTime[spi] = time.Now()