/
iptables.go
1630 lines (1440 loc) · 52.2 KB
/
iptables.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 iptables
import (
"bufio"
"context"
"fmt"
"net"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/blang/semver/v4"
"github.com/mattn/go-shellwords"
"github.com/sirupsen/logrus"
"github.com/cilium/cilium/pkg/backoff"
"github.com/cilium/cilium/pkg/byteorder"
"github.com/cilium/cilium/pkg/command/exec"
"github.com/cilium/cilium/pkg/datapath"
"github.com/cilium/cilium/pkg/datapath/linux/linux_defaults"
"github.com/cilium/cilium/pkg/datapath/linux/route"
"github.com/cilium/cilium/pkg/defaults"
"github.com/cilium/cilium/pkg/ip"
ipamOption "github.com/cilium/cilium/pkg/ipam/option"
lb "github.com/cilium/cilium/pkg/loadbalancer"
"github.com/cilium/cilium/pkg/lock"
"github.com/cilium/cilium/pkg/logging/logfields"
"github.com/cilium/cilium/pkg/modules"
"github.com/cilium/cilium/pkg/node"
"github.com/cilium/cilium/pkg/option"
"github.com/cilium/cilium/pkg/sysctl"
"github.com/cilium/cilium/pkg/versioncheck"
)
const (
oldCiliumPrefix = "OLD_"
ciliumInputChain = "CILIUM_INPUT"
ciliumOutputChain = "CILIUM_OUTPUT"
ciliumOutputRawChain = "CILIUM_OUTPUT_raw"
ciliumPostNatChain = "CILIUM_POST_nat"
ciliumOutputNatChain = "CILIUM_OUTPUT_nat"
ciliumPreNatChain = "CILIUM_PRE_nat"
ciliumPostMangleChain = "CILIUM_POST_mangle"
ciliumPreMangleChain = "CILIUM_PRE_mangle"
ciliumPreRawChain = "CILIUM_PRE_raw"
ciliumForwardChain = "CILIUM_FORWARD"
feederDescription = "cilium-feeder:"
xfrmDescription = "cilium-xfrm-notrack:"
ciliumNodeIpsetV4 = "cilium_node_set_v4"
ciliumNodeIpsetV6 = "cilium_node_set_v6"
)
// Minimum iptables versions supporting the -w and -w<seconds> flags
var (
isWaitMinVersion = versioncheck.MustCompile(">=1.4.20")
isWaitSecondsMinVersion = versioncheck.MustCompile(">=1.4.22")
noTrackPorts = func(port uint16) []*lb.L4Addr {
return []*lb.L4Addr{
{
Protocol: lb.TCP,
Port: port,
},
{
Protocol: lb.UDP,
Port: port,
},
}
}
)
const (
waitString = "-w"
)
type iptablesInterface interface {
getProg() string
getIpset() string
getVersion() (semver.Version, error)
runProgOutput(args []string) (string, error)
runProg(args []string) error
}
type ipt struct {
prog string
ipset string
waitArgs []string
}
func (ipt *ipt) initArgs(waitSeconds int) {
v, err := ipt.getVersion()
if err == nil {
switch {
case isWaitSecondsMinVersion(v):
ipt.waitArgs = []string{waitString, fmt.Sprintf("%d", waitSeconds)}
case isWaitMinVersion(v):
ipt.waitArgs = []string{waitString}
}
}
}
// package name is iptables so we use ip4tables internally for "iptables"
var (
ip4tables = &ipt{prog: "iptables", ipset: ciliumNodeIpsetV4}
ip6tables = &ipt{prog: "ip6tables", ipset: ciliumNodeIpsetV6}
ipset = &ipt{prog: "ipset"}
)
func (ipt *ipt) getProg() string {
return ipt.prog
}
func (ipt *ipt) getIpset() string {
return ipt.ipset
}
func (ipt *ipt) getVersion() (semver.Version, error) {
b, err := exec.WithTimeout(defaults.ExecTimeout, ipt.prog, "--version").CombinedOutput(log, false)
if err != nil {
return semver.Version{}, err
}
v := regexp.MustCompile("v([0-9]+(\\.[0-9]+)+)")
vString := v.FindStringSubmatch(string(b))
if vString == nil {
return semver.Version{}, fmt.Errorf("no iptables version found in string: %s", string(b))
}
return versioncheck.Version(vString[1])
}
func (ipt *ipt) runProgOutput(args []string) (string, error) {
fullCommand := fmt.Sprintf("%s %s", ipt.getProg(), strings.Join(args, " "))
log.Debugf("Running '%s' command", fullCommand)
// Add wait argument to deal with concurrent calls that would fail otherwise
iptArgs := make([]string, 0, len(ipt.waitArgs)+len(args))
iptArgs = append(iptArgs, ipt.waitArgs...)
iptArgs = append(iptArgs, args...)
out, err := exec.WithTimeout(defaults.ExecTimeout, ipt.prog, iptArgs...).Output(log, false)
if err != nil {
return "", fmt.Errorf("unable to run '%s' iptables command: %w", fullCommand, err)
}
return string(out), nil
}
func (ipt *ipt) runProg(args []string) error {
_, err := ipt.runProgOutput(args)
return err
}
// skipPodTrafficConntrack returns true if it's possible to install iptables
// `-j CT --notrack` rules to skip tracking pod traffic.
func skipPodTrafficConntrack(ipv6 bool) bool {
return !ipv6 && option.Config.InstallNoConntrackIptRules
}
// KernelHasNetfilter probes whether iptables related modules are present in
// the kernel and returns true if indeed the case, else false.
func KernelHasNetfilter() bool {
modulesManager := &modules.ModulesManager{}
if err := modulesManager.Init(); err != nil {
return true
}
if found, _ := modulesManager.FindModules(
"ip_tables", "iptable_mangle", "iptable_raw", "iptable_filter"); found {
return true
}
if found, _ := modulesManager.FindModules(
"ip6_tables", "ip6table_mangle", "ip6table_raw", "ip6table_filter"); found {
return true
}
return false
}
func reverseRule(rule string) ([]string, error) {
if strings.HasPrefix(rule, "-A") {
// From: -A POSTROUTING -m comment [...]
// To: -D POSTROUTING -m comment [...]
return shellwords.Parse(strings.Replace(rule, "-A", "-D", 1))
}
if strings.HasPrefix(rule, "-I") {
// From: -I POSTROUTING -m comment [...]
// To: -D POSTROUTING -m comment [...]
return shellwords.Parse(strings.Replace(rule, "-I", "-D", 1))
}
return []string{}, nil
}
func ruleReferencesDisabledChain(rule string) (bool, string) {
for _, disabledChain := range option.Config.DisableIptablesFeederRules {
if strings.Contains(rule, " "+strings.ToUpper(disabledChain)+" ") {
return true, disabledChain
}
}
return false, ""
}
func isDisabledChain(chain string) bool {
for _, disabledChain := range option.Config.DisableIptablesFeederRules {
if strings.EqualFold(chain, disabledChain) {
return true
}
}
return false
}
func (m *IptablesManager) removeCiliumRules(table string, prog iptablesInterface, match string) error {
rules, err := prog.runProgOutput([]string{"-t", table, "-S"})
if err != nil {
return err
}
scanner := bufio.NewScanner(strings.NewReader(rules))
for scanner.Scan() {
rule := scanner.Text()
// All rules installed by cilium either belong to a chain with
// the name CILIUM_ or call a chain with the name CILIUM_:
// -A CILIUM_FORWARD -o cilium_host -m comment --comment "cilium: any->cluster on cilium_host forward accept" -j ACCEPT
// -A POSTROUTING -m comment --comment "cilium-feeder: CILIUM_POST" -j CILIUM_POST
if !strings.Contains(rule, match) {
continue
}
// Temporary fix while Iptables is upgraded to >= 1.8.5
// (See GH-20884).
//
// The version currently shipped with Cilium (1.8.4) does not
// support the deletion of NOTRACK rules, so we will just ignore
// them here and let the agent remove them when it deletes the
// entire chain.
if strings.Contains(rule, "-j NOTRACK") {
continue
}
// do not remove feeder for chains that are set to be disabled
// ie catch the beginning of the rule like -A POSTROUTING to match it against
// disabled chains
if skip, disabledChain := ruleReferencesDisabledChain(rule); skip {
log.WithField(logfields.Chain, disabledChain).Info("Skipping the removal of feeder chain")
continue
}
reversedRule, err := reverseRule(rule)
if err != nil {
log.WithError(err).WithField(logfields.Object, rule).Warnf("Unable to parse %s rule into slice. Leaving rule behind.", prog)
continue
}
if len(reversedRule) > 0 {
deleteRule := append([]string{"-t", table}, reversedRule...)
if err := prog.runProg(deleteRule); err != nil {
return err
}
}
}
return nil
}
// IptablesManager manages the iptables-related configuration for Cilium.
type IptablesManager struct {
// This lock ensures there are no concurrent executions of the InstallRules() and
// InstallProxyRules() methods, as otherwise we may end up with errors (as rules may have
// been already removed or installed by a different execution of the method) or with an
// inconsistent ruleset
lock.Mutex
haveIp6tables bool
haveSocketMatch bool
haveBPFSocketAssign bool
ipEarlyDemuxDisabled bool
}
// Init initializes the iptables manager and checks for iptables kernel modules
// availability.
func (m *IptablesManager) Init() {
modulesManager := &modules.ModulesManager{}
haveIp6tables := true
if err := modulesManager.Init(); err != nil {
log.WithError(err).Fatal(
"Unable to get information about kernel modules")
}
if err := modulesManager.FindOrLoadModules(
"ip_tables", "iptable_nat", "iptable_mangle", "iptable_raw",
"iptable_filter"); err != nil {
log.WithError(err).Warning(
"iptables modules could not be initialized. It probably means that iptables is not available on this system")
}
if err := modulesManager.FindOrLoadModules(
"ip6_tables", "ip6table_mangle", "ip6table_raw", "ip6table_filter"); err != nil {
if option.Config.EnableIPv6 {
log.WithError(err).Fatal(
"IPv6 is enabled and ip6tables modules could not be initialized (try disabling IPv6 in Cilium or loading ip6_tables, ip6table_mangle, ip6table_raw and ip6table_filter kernel modules)")
}
log.WithError(err).Debug(
"ip6tables kernel modules could not be loaded, so IPv6 cannot be used")
haveIp6tables = false
}
ipv6Disabled, err := os.ReadFile("/sys/module/ipv6/parameters/disable")
if err != nil {
if option.Config.EnableIPv6 {
log.WithError(err).Fatal(
"IPv6 is enabled but IPv6 kernel support could not be probed")
}
log.WithError(err).Warning(
"Unable to read /sys/module/ipv6/parameters/disable, disabling IPv6 iptables support")
haveIp6tables = false
} else if strings.TrimSuffix(string(ipv6Disabled), "\n") == "1" {
log.Debug(
"Kernel does not support IPv6, disabling IPv6 iptables support")
haveIp6tables = false
}
m.haveIp6tables = haveIp6tables
if err := modulesManager.FindOrLoadModules("xt_socket"); err != nil {
if option.Config.Tunnel == option.TunnelDisabled {
// xt_socket module is needed to circumvent an explicit drop in ip_forward()
// logic for packets for which a local socket is found by ip early
// demux. xt_socket performs a local socket match and sets an skb mark on
// match, which will divert the packet to the local stack using our policy
// routing rule, thus avoiding being processed by ip_forward() at all.
//
// If xt_socket module does not exist we can disable ip early demux to to
// avoid the explicit drop in ip_forward(). This is not needed in tunneling
// modes, as then we'll set the skb mark in the bpf logic before the policy
// routing stage so that the packet is routed locally instead of being
// forwarded by ip_forward().
//
// We would not need the xt_socket at all if the datapath universally would
// set the "to proxy" skb mark bits on before the packet hits policy routing
// stage. Currently this is not true for endpoint routing modes.
log.WithError(err).Warning("xt_socket kernel module could not be loaded")
if option.Config.EnableXTSocketFallback {
v4disabled := true
v6disabled := true
if option.Config.EnableIPv4 {
v4disabled = sysctl.Disable("net.ipv4.ip_early_demux") == nil
}
if option.Config.EnableIPv6 {
v6disabled = sysctl.Disable("net.ipv6.ip_early_demux") == nil
}
if v4disabled && v6disabled {
m.ipEarlyDemuxDisabled = true
log.Warning("Disabled ip_early_demux to allow proxy redirection with original source/destination address without xt_socket support also in non-tunneled datapath modes.")
} else {
log.WithError(err).Warning("Could not disable ip_early_demux, traffic redirected due to an HTTP policy or visibility may be dropped unexpectedly")
}
}
}
} else {
m.haveSocketMatch = true
}
m.haveBPFSocketAssign = option.Config.EnableBPFTProxy
ip4tables.initArgs(int(option.Config.IPTablesLockTimeout / time.Second))
ip6tables.initArgs(int(option.Config.IPTablesLockTimeout / time.Second))
}
// SupportsOriginalSourceAddr tells if an L7 proxy can use POD's original source address and port in
// the upstream connection to allow the destination to properly derive the source security ID from
// the source IP address.
func (m *IptablesManager) SupportsOriginalSourceAddr() bool {
// Original source address use works if xt_socket match is supported, or if ip early demux
// is disabled, but it is not needed when tunneling is used as the tunnel header carries
// the source security ID.
return (m.haveSocketMatch || m.ipEarlyDemuxDisabled) && option.Config.Tunnel == option.TunnelDisabled
}
// removeRules removes iptables rules installed by Cilium.
func (m *IptablesManager) removeRules(prefix string) error {
// Set of tables that have had iptables rules in any Cilium version
tables := []string{"nat", "mangle", "raw", "filter"}
for _, t := range tables {
if err := m.removeCiliumRules(t, ip4tables, prefix+"CILIUM_"); err != nil {
return err
}
if m.haveIp6tables {
if err := m.removeCiliumRules(t, ip6tables, prefix+"CILIUM_"); err != nil {
return err
}
}
}
for _, c := range ciliumChains {
c.name = prefix + c.name
if err := c.remove(true, m.haveIp6tables); err != nil {
return err
}
}
return nil
}
// renameChains renames iptables chains installed by Cilium.
func (m *IptablesManager) renameChains(prefix string) error {
for _, c := range ciliumChains {
if err := c.rename(true, m.haveIp6tables, prefix+c.name); err != nil {
return err
}
}
return nil
}
func (m *IptablesManager) ingressProxyRule(l4Match, markMatch, mark, port, name string) []string {
return []string{
"-t", "mangle",
"-A", ciliumPreMangleChain,
"-p", l4Match,
"-m", "mark", "--mark", markMatch,
"-m", "comment", "--comment", "cilium: TPROXY to host " + name + " proxy",
"-j", "TPROXY",
"--tproxy-mark", mark,
"--on-port", port}
}
func (m *IptablesManager) inboundProxyRedirectRule(cmd string) []string {
// Mark host proxy transparent connections to be routed to the local stack.
// This comes before the TPROXY rules in the chain, and setting the mark
// without the proxy port number will make the TPROXY rule to not match,
// as we do not want to try to tproxy packets that are going to the stack
// already.
// This rule is needed for couple of reasons:
// 1. route return traffic to the proxy
// 2. route original direction traffic that would otherwise be intercepted
// by ip_early_demux
toProxyMark := fmt.Sprintf("%#08x", linux_defaults.MagicMarkIsToProxy)
return []string{
"-t", "mangle",
cmd, ciliumPreMangleChain,
"-m", "socket", "--transparent",
"-m", "comment", "--comment", "cilium: any->pod redirect proxied traffic to host proxy",
"-j", "MARK",
"--set-mark", toProxyMark}
}
func (m *IptablesManager) iptIngressProxyRule(rules string, prog iptablesInterface, l4proto string, proxyPort uint16, name string) error {
// Match
port := uint32(byteorder.HostToNetwork16(proxyPort)) << 16
ingressMarkMatch := fmt.Sprintf("%#x", linux_defaults.MagicMarkIsToProxy|port)
// TPROXY params
ingressProxyMark := fmt.Sprintf("%#x", linux_defaults.MagicMarkIsToProxy)
ingressProxyPort := fmt.Sprintf("%d", proxyPort)
if strings.Contains(rules, fmt.Sprintf("CILIUM_PRE_mangle -p %s -m mark --mark %s", l4proto, ingressMarkMatch)) {
return nil
}
rule := m.ingressProxyRule(l4proto, ingressMarkMatch, ingressProxyMark, ingressProxyPort, name)
return prog.runProg(rule)
}
func (m *IptablesManager) egressProxyRule(l4Match, markMatch, mark, port, name string) []string {
return []string{
"-t", "mangle",
"-A", ciliumPreMangleChain,
"-p", l4Match,
"-m", "mark", "--mark", markMatch,
"-m", "comment", "--comment", "cilium: TPROXY to host " + name + " proxy",
"-j", "TPROXY",
"--tproxy-mark", mark,
"--on-port", port}
}
func (m *IptablesManager) iptEgressProxyRule(rules string, prog iptablesInterface, l4proto string, proxyPort uint16, name string) error {
// Match
port := uint32(byteorder.HostToNetwork16(proxyPort)) << 16
egressMarkMatch := fmt.Sprintf("%#x", linux_defaults.MagicMarkIsToProxy|port)
// TPROXY params
egressProxyMark := fmt.Sprintf("%#x", linux_defaults.MagicMarkIsToProxy)
egressProxyPort := fmt.Sprintf("%d", proxyPort)
if strings.Contains(rules, fmt.Sprintf("-A CILIUM_PRE_mangle -p %s -m mark --mark %s", l4proto, egressMarkMatch)) {
return nil
}
rule := m.egressProxyRule(l4proto, egressMarkMatch, egressProxyMark, egressProxyPort, name)
return prog.runProg(rule)
}
func (m *IptablesManager) installStaticProxyRules() error {
// match traffic to a proxy (upper 16 bits has the proxy port, which is masked out)
matchToProxy := fmt.Sprintf("%#08x/%#08x", linux_defaults.MagicMarkIsToProxy, linux_defaults.MagicMarkHostMask)
// proxy return traffic has 0 ID in the mask
matchProxyReply := fmt.Sprintf("%#08x/%#08x", linux_defaults.MagicMarkIsProxy, linux_defaults.MagicMarkProxyNoIDMask)
// L7 proxy upstream return traffic has Endpoint ID in the mask
matchL7ProxyUpstream := fmt.Sprintf("%#08x/%#08x", linux_defaults.MagicMarkIsProxyEPID, linux_defaults.MagicMarkProxyMask)
if option.Config.EnableIPv4 {
// No conntrack for traffic to proxy
if err := ip4tables.runProg([]string{
"-t", "raw",
"-A", ciliumPreRawChain,
"-m", "mark", "--mark", matchToProxy,
"-m", "comment", "--comment", "cilium: NOTRACK for proxy traffic",
"-j", "CT", "--notrack"}); err != nil {
return err
}
// Explicit ACCEPT for the proxy traffic. Needed when the INPUT defaults to DROP.
// Matching needs to be the same as for the NOTRACK rule above.
if err := ip4tables.runProg([]string{
"-t", "filter",
"-A", ciliumInputChain,
"-m", "mark", "--mark", matchToProxy,
"-m", "comment", "--comment", "cilium: ACCEPT for proxy traffic",
"-j", "ACCEPT"}); err != nil {
return err
}
// No conntrack for proxy return traffic that is heading to lxc+
if err := ip4tables.runProg([]string{
"-t", "raw",
"-A", ciliumOutputRawChain,
"-o", "lxc+",
"-m", "mark", "--mark", matchProxyReply,
"-m", "comment", "--comment", "cilium: NOTRACK for proxy return traffic",
"-j", "CT", "--notrack"}); err != nil {
return err
}
// No conntrack for proxy return traffic that is heading to cilium_host
if err := ip4tables.runProg([]string{
"-t", "raw",
"-A", ciliumOutputRawChain,
"-o", defaults.HostDevice,
"-m", "mark", "--mark", matchProxyReply,
"-m", "comment", "--comment", "cilium: NOTRACK for proxy return traffic",
"-j", "CT", "--notrack"}); err != nil {
return err
}
// No conntrack for proxy upstream traffic that is heading to lxc+
if err := ip4tables.runProg([]string{
"-t", "raw",
"-A", ciliumOutputRawChain,
"-o", "lxc+",
"-m", "mark", "--mark", matchL7ProxyUpstream,
"-m", "comment", "--comment", "cilium: NOTRACK for L7 proxy upstream traffic",
"-j", "CT", "--notrack"}); err != nil {
return err
}
// No conntrack for proxy upstream traffic that is heading to cilium_host
if err := ip4tables.runProg([]string{
"-t", "raw",
"-A", ciliumOutputRawChain,
"-o", defaults.HostDevice,
"-m", "mark", "--mark", matchL7ProxyUpstream,
"-m", "comment", "--comment", "cilium: NOTRACK for L7 proxy upstream traffic",
"-j", "CT", "--notrack"}); err != nil {
return err
}
// Explicit ACCEPT for the proxy return traffic. Needed when the OUTPUT defaults to DROP.
// Matching needs to be the same as for the NOTRACK rule above.
if err := ip4tables.runProg([]string{
"-t", "filter",
"-A", ciliumOutputChain,
"-m", "mark", "--mark", matchProxyReply,
"-m", "comment", "--comment", "cilium: ACCEPT for proxy return traffic",
"-j", "ACCEPT"}); err != nil {
return err
}
// Explicit ACCEPT for the l7 proxy upstream traffic. Needed when the OUTPUT defaults to DROP.
// TODO: See if this is really needed. We do not have an ACCEPT for normal proxy upstream traffic.
if err := ip4tables.runProg([]string{
"-t", "filter",
"-A", ciliumOutputChain,
"-m", "mark", "--mark", matchL7ProxyUpstream,
"-m", "comment", "--comment", "cilium: ACCEPT for l7 proxy upstream traffic",
"-j", "ACCEPT"}); err != nil {
return err
}
if m.haveSocketMatch {
// Direct inbound TPROXYed traffic towards the socket
if err := ip4tables.runProg(m.inboundProxyRedirectRule("-A")); err != nil {
return err
}
}
}
if option.Config.EnableIPv6 {
// No conntrack for traffic to ingress proxy
if err := ip6tables.runProg([]string{
"-t", "raw",
"-A", ciliumPreRawChain,
"-m", "mark", "--mark", matchToProxy,
"-m", "comment", "--comment", "cilium: NOTRACK for proxy traffic",
"-j", "CT", "--notrack"}); err != nil {
return err
}
// Explicit ACCEPT for the proxy traffic. Needed when the INPUT defaults to DROP.
// Matching needs to be the same as for the NOTRACK rule above.
if err := ip6tables.runProg([]string{
"-t", "filter",
"-A", ciliumInputChain,
"-m", "mark", "--mark", matchToProxy,
"-m", "comment", "--comment", "cilium: ACCEPT for proxy traffic",
"-j", "ACCEPT"}); err != nil {
return err
}
// No conntrack for proxy return traffic
if err := ip6tables.runProg([]string{
"-t", "raw",
"-A", ciliumOutputRawChain,
"-m", "mark", "--mark", matchProxyReply,
"-m", "comment", "--comment", "cilium: NOTRACK for proxy return traffic",
"-j", "CT", "--notrack"}); err != nil {
return err
}
// Explicit ACCEPT for the proxy return traffic. Needed when the OUTPUT defaults to DROP.
// Matching needs to be the same as for the NOTRACK rule above.
if err := ip6tables.runProg([]string{
"-t", "filter",
"-A", ciliumOutputChain,
"-m", "mark", "--mark", matchProxyReply,
"-m", "comment", "--comment", "cilium: ACCEPT for proxy return traffic",
"-j", "ACCEPT"}); err != nil {
return err
}
if m.haveSocketMatch {
// Direct inbound TPROXYed traffic towards the socket
if err := ip6tables.runProg(m.inboundProxyRedirectRule("-A")); err != nil {
return err
}
}
}
return nil
}
func (m *IptablesManager) doCopyProxyRules(prog iptablesInterface, table string, re *regexp.Regexp, match, oldChain, newChain string) error {
rules, err := prog.runProgOutput([]string{"-t", table, "-S"})
if err != nil {
return err
}
scanner := bufio.NewScanner(strings.NewReader(rules))
for scanner.Scan() {
rule := scanner.Text()
if !re.MatchString(rule) || !strings.Contains(rule, match) {
continue
}
args, err := shellwords.Parse(strings.Replace(rule, oldChain, newChain, 1))
if err != nil {
log.WithFields(logrus.Fields{
"table": table,
"prog": prog.getProg(),
logfields.Object: rule,
}).WithError(err).Warn("Unable to parse TPROXY rule, disruption to traffic selected by L7 policy possible")
continue
}
copyRule := append([]string{"-t", table}, args...)
if err := prog.runProg(copyRule); err != nil {
return err
}
}
return nil
}
var tproxyMatch = regexp.MustCompile("CILIUM_PRE_mangle .*cilium: TPROXY")
// copies old proxy rules
func (m *IptablesManager) copyProxyRules(oldChain string, match string) error {
if option.Config.EnableIPv4 {
if err := m.doCopyProxyRules(ip4tables, "mangle", tproxyMatch, match, oldChain, ciliumPreMangleChain); err != nil {
return err
}
}
if option.Config.EnableIPv6 {
if err := m.doCopyProxyRules(ip6tables, "mangle", tproxyMatch, match, oldChain, ciliumPreMangleChain); err != nil {
return err
}
}
return nil
}
// Redirect packets to the host proxy via TPROXY, as directed by the Cilium
// datapath bpf programs via skb marks (egress) or DSCP (ingress).
func (m *IptablesManager) addProxyRules(prog iptablesInterface, proxyPort uint16, ingress bool, name string) error {
rules, err := prog.runProgOutput([]string{"-t", "mangle", "-S"})
if err != nil {
return err
}
for _, proto := range []string{"tcp", "udp"} {
if ingress {
if err := m.iptIngressProxyRule(rules, prog, proto, proxyPort, name); err != nil {
return err
}
} else {
if err := m.iptEgressProxyRule(rules, prog, proto, proxyPort, name); err != nil {
return err
}
}
}
// Delete all other rules for this same proxy name
// These may accumulate if there is a bind failure on a previously used port
portMatch := fmt.Sprintf("TPROXY --on-port %d ", proxyPort)
scanner := bufio.NewScanner(strings.NewReader(rules))
for scanner.Scan() {
rule := scanner.Text()
if !strings.Contains(rule, "-A CILIUM_PRE_mangle ") || !strings.Contains(rule, "cilium: TPROXY to host "+name) || strings.Contains(rule, portMatch) {
continue
}
args, err := shellwords.Parse(strings.Replace(rule, "-A", "-D", 1))
if err != nil {
log.WithError(err).WithField(logfields.Object, rule).Warnf("Unable to parse %s TPROXY rule", prog)
continue
}
deleteRule := append([]string{"-t", "mangle"}, args...)
if err := prog.runProg(deleteRule); err != nil {
return err
}
}
return nil
}
// install or remove rules for a single proxy port
func (m *IptablesManager) iptProxyRules(proxyPort uint16, ingress bool, name string) error {
if option.Config.EnableIPv4 {
if err := m.addProxyRules(ip4tables, proxyPort, ingress, name); err != nil {
return err
}
}
if option.Config.EnableIPv6 {
if err := m.addProxyRules(ip6tables, proxyPort, ingress, name); err != nil {
return err
}
}
return nil
}
func (m *IptablesManager) endpointNoTrackRules(prog iptablesInterface, cmd string, IP string, port *lb.L4Addr) error {
protocol := strings.ToLower(port.Protocol)
p := strconv.FormatUint(uint64(port.Port), 10)
if err := prog.runProg([]string{
"-t", "raw",
cmd, ciliumPreRawChain,
"-p", protocol,
"-d", IP,
"--dport", p,
"-j", "CT",
"--notrack"}); err != nil {
return err
}
if err := prog.runProg([]string{
"-t", "filter",
cmd, ciliumInputChain,
"-p", protocol,
"-d", IP,
"--dport",
p, "-j",
"ACCEPT"}); err != nil {
return err
}
if err := prog.runProg([]string{
"-t", "raw",
cmd, ciliumOutputRawChain,
"-p", protocol,
"-d", IP,
"--dport", p,
"-j", "CT",
"--notrack"}); err != nil {
return err
}
if err := prog.runProg([]string{
"-t", "filter",
cmd, ciliumOutputChain,
"-p", protocol,
"-d", IP,
"--dport", p,
"-j", "ACCEPT"}); err != nil {
return err
}
if err := prog.runProg([]string{
"-t", "raw",
cmd, ciliumOutputRawChain,
"-p", protocol,
"-s", IP,
"--sport", p,
"-j", "CT",
"--notrack"}); err != nil {
return err
}
if err := prog.runProg([]string{
"-t", "filter",
cmd, ciliumOutputChain,
"-p", protocol,
"-s", IP,
"--sport", p,
"-j", "ACCEPT"}); err != nil {
return err
}
return nil
}
// InstallNoTrackRules is explicitly called when a pod has valid "io.cilium.no-track-port" annotation.
// When InstallNoConntrackIptRules flag is set, a super set of v4 NOTRACK rules will be automatically
// installed upon agent bootstrap (via function addNoTrackPodTrafficRules) and this function will be skipped.
// When InstallNoConntrackIptRules is not set, this function will be executed to install NOTRACK rules.
// The rules installed by this function is very specific, for now, the only user is node-local-dns pods.
func (m *IptablesManager) InstallNoTrackRules(IP string, port uint16, ipv6 bool) error {
m.Lock()
defer m.Unlock()
// Do not install per endpoint NOTRACK rules if we are already skipping
// conntrack for all pod traffic.
if skipPodTrafficConntrack(ipv6) {
return nil
}
prog := ip4tables
if ipv6 {
prog = ip6tables
}
for _, p := range noTrackPorts(port) {
if err := m.endpointNoTrackRules(prog, "-A", IP, p); err != nil {
return err
}
}
return nil
}
// See comments for InstallNoTrackRules.
func (m *IptablesManager) RemoveNoTrackRules(IP string, port uint16, ipv6 bool) error {
m.Lock()
defer m.Unlock()
// Do not install per endpoint NOTRACK rules if we are already skipping
// conntrack for all pod traffic.
if skipPodTrafficConntrack(ipv6) {
return nil
}
prog := ip4tables
if ipv6 {
prog = ip6tables
}
for _, p := range noTrackPorts(port) {
if err := m.endpointNoTrackRules(prog, "-D", IP, p); err != nil {
return err
}
}
return nil
}
func (m *IptablesManager) InstallProxyRules(ctx context.Context, proxyPort uint16, ingress bool, name string) error {
backoff := backoff.Exponential{
Min: 20 * time.Second,
Max: 3 * time.Minute,
Name: "iptables-proxy-rules-installer",
}
maxAttempts := 3
attempt := 0
for {
attempt += 1
err := m.doInstallProxyRules(proxyPort, ingress, name)
if err == nil {
log.Info("Iptables proxy rules installed")
return nil
}
if attempt == maxAttempts {
return fmt.Errorf("failed to install iptables proxy rules: %w", err)
}
log.WithError(err).Warning("Failed to install iptables proxy rules")
backoff.Wait(ctx)
}
}
func (m *IptablesManager) doInstallProxyRules(proxyPort uint16, ingress bool, name string) error {
m.Lock()
defer m.Unlock()
if m.haveBPFSocketAssign {
log.WithField("port", proxyPort).
Debug("Skipping proxy rule install due to BPF support")
return nil
}
return m.iptProxyRules(proxyPort, ingress, name)
}
// GetProxyPort finds a proxy port used for redirect 'name' installed earlier with InstallProxyRules.
// By convention "ingress" or "egress" is part of 'name' so it does not need to be specified explicitly.
// Returns 0 a TPROXY entry with 'name' can not be found.
func (m *IptablesManager) GetProxyPort(name string) uint16 {
prog := ip4tables
if !option.Config.EnableIPv4 {
prog = ip6tables
}
return m.doGetProxyPort(prog, name)
}
func (m *IptablesManager) doGetProxyPort(prog iptablesInterface, name string) uint16 {
rules, err := prog.runProgOutput([]string{"-t", "mangle", "-n", "-L", ciliumPreMangleChain})
if err != nil {
return 0
}
re := regexp.MustCompile(name + ".*TPROXY redirect (0.0.0.0|::):([1-9][0-9]*) mark")
strs := re.FindAllString(rules, -1)
if len(strs) == 0 {
return 0
}
// Pick the port number from the last match, as rules are appended to the end (-A)
portStr := re.ReplaceAllString(strs[len(strs)-1], "$2")
portUInt64, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
log.WithError(err).Debugf("Port number cannot be parsed: %s", portStr)
return 0
}
return uint16(portUInt64)
}
func getDeliveryInterface(ifName string) string {
switch {
case option.Config.EnableEndpointRoutes:
// aws-cni creates container interfaces with names like eni621c0fc8425.
if option.Config.CNIChainingMode == "aws-cni" {
return "eni+"
}
return "lxc+"
case option.Config.IPAM == ipamOption.IPAMENI ||
option.Config.IPAM == ipamOption.IPAMAlibabaCloud:
return "lxc+"
default:
return ifName
}
}
func (m *IptablesManager) installForwardChainRules(ifName, localDeliveryInterface, forwardChain string) error {
if option.Config.EnableIPv4 {
if err := m.installForwardChainRulesIpX(ip4tables, ifName, localDeliveryInterface, forwardChain); err != nil {
return err
}
}
if option.Config.EnableIPv6 {
return m.installForwardChainRulesIpX(ip6tables, ifName, localDeliveryInterface, forwardChain)
}
return nil
}
func (m *IptablesManager) installForwardChainRulesIpX(prog iptablesInterface, ifName, localDeliveryInterface, forwardChain string) error {
// While kube-proxy does change the policy of the iptables FORWARD chain
// it doesn't seem to handle all cases, e.g. host network pods that use
// the node IP which would still end up in default DENY. Similarly, for
// plain Docker setup, we would otherwise hit default DENY in FORWARD chain.
// Also, k8s 1.15 introduced "-m conntrack --ctstate INVALID -j DROP" which
// in the direct routing case can drop EP replies.
//
// Therefore, add the rules below to avoid having a user to manually opt-in.
// See also: https://github.com/kubernetes/kubernetes/issues/39823
// In here can only be basic ACCEPT rules, nothing more complicated.
//