/
iptables.go
1151 lines (1068 loc) · 39.8 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
// Copyright 2016-2019 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 iptables
import (
"bufio"
"bytes"
"fmt"
"regexp"
"strings"
"time"
"github.com/cilium/cilium/pkg/byteorder"
"github.com/cilium/cilium/pkg/command/exec"
"github.com/cilium/cilium/pkg/datapath/linux/linux_defaults"
"github.com/cilium/cilium/pkg/defaults"
ipamOption "github.com/cilium/cilium/pkg/ipam/option"
"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"
go_version "github.com/blang/semver"
"github.com/mattn/go-shellwords"
)
const (
ciliumPrefix = "CILIUM_"
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"
CiliumTransientForwardChain = "CILIUM_TRANSIENT_FORWARD"
feederDescription = "cilium-feeder:"
xfrmDescription = "cilium-xfrm-notrack:"
)
// Minimum iptables versions supporting the -w and -w<seconds> flags
var (
isWaitMinVersion = versioncheck.MustCompile(">=1.4.20")
isWaitSecondsMinVersion = versioncheck.MustCompile(">=1.4.22")
)
const (
waitString = "-w"
)
type customChain struct {
name string
table string
hook string
feederArgs []string
ipv6 bool // ip6tables chain in addition to iptables chain
}
func getVersion(prog string) (go_version.Version, error) {
b, err := exec.WithTimeout(defaults.ExecTimeout, prog, "--version").CombinedOutput(log, false)
if err != nil {
return go_version.Version{}, err
}
v := regexp.MustCompile("v([0-9]+(\\.[0-9]+)+)")
vString := v.FindStringSubmatch(string(b))
if vString == nil {
return go_version.Version{}, fmt.Errorf("no iptables version found in string: %s", string(b))
}
return versioncheck.Version(vString[1])
}
func runProgCombinedOutput(prog string, args []string, quiet bool) ([]byte, error) {
out, err := exec.WithTimeout(defaults.ExecTimeout, prog, args...).CombinedOutput(log, !quiet)
return out, err
}
func runProg(prog string, args []string, quiet bool) error {
_, err := runProgCombinedOutput(prog, args, quiet)
return err
}
func getFeedRule(name, args string) []string {
ruleTail := []string{"-m", "comment", "--comment", feederDescription + " " + name, "-j", name}
if args == "" {
return ruleTail
}
argsList, err := shellwords.Parse(args)
if err != nil {
log.WithError(err).WithField(logfields.Object, args).Fatal("Unable to parse rule into argument slice")
}
return append(argsList, ruleTail...)
}
// 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 (c *customChain) add(waitArgs []string) error {
var err error
if option.Config.EnableIPv4 {
err = runProg("iptables", append(waitArgs, "-t", c.table, "-N", c.name), false)
}
if err == nil && option.Config.EnableIPv6 && c.ipv6 == true {
err = runProg("ip6tables", append(waitArgs, "-t", c.table, "-N", c.name), false)
}
return err
}
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 (m *IptablesManager) removeCiliumRules(table, prog, match string) {
args := append(m.waitArgs, "-t", table, "-S")
out, err := exec.WithTimeout(defaults.ExecTimeout, prog, args...).CombinedOutput(log, true)
if err != nil {
return
}
scanner := bufio.NewScanner(bytes.NewReader(out))
for scanner.Scan() {
rule := scanner.Text()
log.WithField(logfields.Object, logfields.Repr(rule)).Debugf("Considering removing %s rule", prog)
if match != CiliumTransientForwardChain && strings.Contains(rule, CiliumTransientForwardChain) {
continue
}
// 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) {
// do not remove feeder for chains that are set to be disabled
// ie catch the begining of the rule like -A POSTROUTING to match it against
// disabled chains
skipFeeder := false
for _, disabledChain := range option.Config.DisableIptablesFeederRules {
// we skip if the match is CiliumTransientForwardChain since we don't want to touch it
if match != CiliumTransientForwardChain && strings.Contains(rule, " "+strings.ToUpper(disabledChain)+" ") {
log.WithField("chain", disabledChain).Info("Skipping the removal of feeder chain")
skipFeeder = true
break
}
}
if skipFeeder {
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(append(m.waitArgs, "-t", table), reversedRule...)
log.WithField(logfields.Object, logfields.Repr(deleteRule)).Debugf("Removing %s rule", prog)
err = runProg(prog, deleteRule, true)
if err != nil {
log.WithError(err).WithField(logfields.Object, rule).Warnf("Unable to delete Cilium %s rule", prog)
}
}
}
}
}
func (c *customChain) remove(waitArgs []string, quiet bool) {
doProcess := func(c *customChain, prog string, args []string, operation string, quiet bool) {
combinedOutput, err := runProgCombinedOutput(prog, args, true)
if err != nil {
// If the chain is for transient rules and deletion
// fails for a reason other than the chain not being
// present, log the error.
// This is to help debug #11276.
msgChainNotFound := ": No chain/target/match by that name.\n"
debugTransientRules := c.name == CiliumTransientForwardChain &&
string(combinedOutput) != prog+msgChainNotFound
if !quiet || debugTransientRules {
log.Warnf(string(combinedOutput))
log.WithError(err).WithField(logfields.Object, args).Warnf("Unable to process chain %s with %s (%s)", c.name, prog, operation)
}
}
}
doRemove := func(c *customChain, prog string, waitArgs []string, quiet bool) {
args := append(waitArgs, "-t", c.table, "-F", c.name)
doProcess(c, prog, args, "flush", quiet)
args = append(waitArgs, "-t", c.table, "-X", c.name)
doProcess(c, prog, args, "delete", quiet)
}
if option.Config.EnableIPv4 {
prog := "iptables"
doRemove(c, prog, waitArgs, quiet)
}
if option.Config.EnableIPv6 && c.ipv6 {
prog := "ip6tables"
doRemove(c, prog, waitArgs, quiet)
}
}
func (c *customChain) installFeeder(waitArgs []string) error {
installMode := "-A"
if option.Config.PrependIptablesChains {
installMode = "-I"
}
for _, feedArgs := range c.feederArgs {
if option.Config.EnableIPv4 {
err := runProg("iptables", append(append(waitArgs, "-t", c.table, installMode, c.hook), getFeedRule(c.name, feedArgs)...), true)
if err != nil {
return err
}
}
if option.Config.EnableIPv6 && c.ipv6 == true {
err := runProg("ip6tables", append(append(waitArgs, "-t", c.table, installMode, c.hook), getFeedRule(c.name, feedArgs)...), true)
if err != nil {
return err
}
}
}
return nil
}
// ciliumChains is the list of custom iptables chain used by Cilium. Custom
// chains are used to allow for simple replacements of all rules.
//
// WARNING: If you change or remove any of the feeder rules you have to ensure
// that the old feeder rules is also removed on agent start, otherwise,
// flushing and removing the custom chains will fail.
var ciliumChains = []customChain{
{
name: ciliumInputChain,
table: "filter",
hook: "INPUT",
feederArgs: []string{""},
ipv6: true,
},
{
name: ciliumOutputChain,
table: "filter",
hook: "OUTPUT",
feederArgs: []string{""},
ipv6: true,
},
{
name: ciliumOutputRawChain,
table: "raw",
hook: "OUTPUT",
feederArgs: []string{""},
ipv6: true,
},
{
name: ciliumPostNatChain,
table: "nat",
hook: "POSTROUTING",
feederArgs: []string{""},
},
{
name: ciliumOutputNatChain,
table: "nat",
hook: "OUTPUT",
feederArgs: []string{""},
},
{
name: ciliumPreNatChain,
table: "nat",
hook: "PREROUTING",
feederArgs: []string{""},
},
{
name: ciliumPostMangleChain,
table: "mangle",
hook: "POSTROUTING",
feederArgs: []string{""},
},
{
name: ciliumPreMangleChain,
table: "mangle",
hook: "PREROUTING",
feederArgs: []string{""},
ipv6: true,
},
{
name: ciliumPreRawChain,
table: "raw",
hook: "PREROUTING",
feederArgs: []string{""},
ipv6: true,
},
{
name: ciliumForwardChain,
table: "filter",
hook: "FORWARD",
feederArgs: []string{""},
},
}
var transientChain = customChain{
name: CiliumTransientForwardChain,
table: "filter",
hook: "FORWARD",
feederArgs: []string{""},
}
// IptablesManager manages the iptables-related configuration for Cilium.
type IptablesManager struct {
haveIp6tables bool
haveSocketMatch bool
ipEarlyDemuxDisabled bool
waitArgs []string
}
// Init initializes the iptables manager and checks for iptables kernel modules
// availability.
func (m *IptablesManager) Init() {
modulesManager := &modules.ModulesManager{}
ip6tables := 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).Warning(
"IPv6 is enabled and ip6tables modules could not be initialized")
}
log.WithError(err).Debug(
"ip6tables kernel modules could not be loaded, so IPv6 cannot be used")
ip6tables = false
}
m.haveIp6tables = ip6tables
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
}
v, err := getVersion("iptables")
if err == nil {
switch {
case isWaitSecondsMinVersion(v):
m.waitArgs = []string{waitString, fmt.Sprintf("%d", option.Config.IPTablesLockTimeout/time.Second)}
case isWaitMinVersion(v):
m.waitArgs = []string{waitString}
}
}
}
// 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, or if the datapath is in a tunneling mode.
return m.haveSocketMatch || m.ipEarlyDemuxDisabled || option.Config.Tunnel != option.TunnelDisabled
}
// RemoveRules removes iptables rules installed by Cilium.
func (m *IptablesManager) RemoveRules(quiet bool) {
// Set of tables that have had iptables rules in any Cilium version
tables := []string{"nat", "mangle", "raw", "filter"}
for _, t := range tables {
m.removeCiliumRules(t, "iptables", ciliumPrefix)
}
// Set of tables that have had ip6tables rules in any Cilium version
if m.haveIp6tables {
tables6 := []string{"mangle", "raw", "filter"}
for _, t := range tables6 {
m.removeCiliumRules(t, "ip6tables", ciliumPrefix)
}
}
for _, c := range ciliumChains {
c.remove(m.waitArgs, quiet)
}
}
func (m *IptablesManager) ingressProxyRule(cmd, l4Match, markMatch, mark, port, name string) []string {
return append(m.waitArgs,
"-t", "mangle",
cmd, 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 append(m.waitArgs,
"-t", "mangle",
cmd, ciliumPreMangleChain,
"-m", "socket", "--transparent", "--nowildcard",
"-m", "comment", "--comment", "cilium: any->pod redirect proxied traffic to host proxy",
"-j", "MARK",
"--set-mark", toProxyMark)
}
func (m *IptablesManager) iptIngressProxyRule(cmd string, l4proto string, proxyPort uint16, name string) error {
// Match
port := uint32(byteorder.HostToNetwork(proxyPort).(uint16)) << 16
ingressMarkMatch := fmt.Sprintf("%#08x", linux_defaults.MagicMarkIsToProxy|port)
// TPROXY params
ingressProxyMark := fmt.Sprintf("%#08x", linux_defaults.MagicMarkIsToProxy)
ingressProxyPort := fmt.Sprintf("%d", proxyPort)
var err error
if option.Config.EnableIPv4 {
err = runProg("iptables",
m.ingressProxyRule(cmd, l4proto, ingressMarkMatch,
ingressProxyMark, ingressProxyPort, name),
false)
}
if err == nil && option.Config.EnableIPv6 {
err = runProg("ip6tables",
m.ingressProxyRule(cmd, l4proto, ingressMarkMatch,
ingressProxyMark, ingressProxyPort, name),
false)
}
return err
}
func (m *IptablesManager) egressProxyRule(cmd, l4Match, markMatch, mark, port, name string) []string {
return append(m.waitArgs,
"-t", "mangle",
cmd, 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(cmd string, l4proto string, proxyPort uint16, name string) error {
// Match
port := uint32(byteorder.HostToNetwork(proxyPort).(uint16)) << 16
egressMarkMatch := fmt.Sprintf("%#08x", linux_defaults.MagicMarkIsToProxy|port)
// TPROXY params
egressProxyMark := fmt.Sprintf("%#08x", linux_defaults.MagicMarkIsToProxy)
egressProxyPort := fmt.Sprintf("%d", proxyPort)
var err error
if option.Config.EnableIPv4 {
err = runProg("iptables",
m.egressProxyRule(cmd, l4proto, egressMarkMatch,
egressProxyMark, egressProxyPort, name),
false)
}
if err == nil && option.Config.EnableIPv6 {
err = runProg("ip6tables",
m.egressProxyRule(cmd, l4proto, egressMarkMatch,
egressProxyMark, egressProxyPort, name),
false)
}
return err
}
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)
var err error
if option.Config.EnableIPv4 {
// No conntrack for traffic to proxy
err = runProg("iptables", append(
m.waitArgs,
"-t", "raw",
"-A", ciliumPreRawChain,
"-m", "mark", "--mark", matchToProxy,
"-m", "comment", "--comment", "cilium: NOTRACK for proxy traffic",
"-j", "NOTRACK"), false)
if err == nil {
// 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.
err = runProg("iptables", append(
m.waitArgs,
"-t", "filter",
"-A", ciliumInputChain,
"-m", "mark", "--mark", matchToProxy,
"-m", "comment", "--comment", "cilium: ACCEPT for proxy traffic",
"-j", "ACCEPT"), false)
}
if err == nil {
// No conntrack for proxy return traffic that is heading to lxc+
err = runProg("iptables", append(
m.waitArgs,
"-t", "raw",
"-A", ciliumOutputRawChain,
"-o", "lxc+",
"-m", "mark", "--mark", matchProxyReply,
"-m", "comment", "--comment", "cilium: NOTRACK for proxy return traffic",
"-j", "NOTRACK"), false)
}
if err == nil {
// No conntrack for proxy return traffic that is heading to cilium_host
err = runProg("iptables", append(
m.waitArgs,
"-t", "raw",
"-A", ciliumOutputRawChain,
"-o", "cilium_host",
"-m", "mark", "--mark", matchProxyReply,
"-m", "comment", "--comment", "cilium: NOTRACK for proxy return traffic",
"-j", "NOTRACK"), false)
}
if err == nil {
// 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.
err = runProg("iptables", append(
m.waitArgs,
"-t", "filter",
"-A", ciliumOutputChain,
"-m", "mark", "--mark", matchProxyReply,
"-m", "comment", "--comment", "cilium: ACCEPT for proxy return traffic",
"-j", "ACCEPT"), false)
}
if err == nil && m.haveSocketMatch {
// Direct inbound TPROXYed traffic towards the socket
err = runProg("iptables", m.inboundProxyRedirectRule("-A"), false)
}
}
if err == nil && option.Config.EnableIPv6 {
// No conntrack for traffic to ingress proxy
err = runProg("ip6tables", append(
m.waitArgs,
"-t", "raw",
"-A", ciliumPreRawChain,
"-m", "mark", "--mark", matchToProxy,
"-m", "comment", "--comment", "cilium: NOTRACK for proxy traffic",
"-j", "NOTRACK"), false)
if err == nil {
// 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.
err = runProg("ip6tables", append(
m.waitArgs,
"-t", "filter",
"-A", ciliumInputChain,
"-m", "mark", "--mark", matchToProxy,
"-m", "comment", "--comment", "cilium: ACCEPT for proxy traffic",
"-j", "ACCEPT"), false)
}
if err == nil {
// No conntrack for proxy return traffic
err = runProg("ip6tables", append(
m.waitArgs,
"-t", "raw",
"-A", ciliumOutputRawChain,
"-m", "mark", "--mark", matchProxyReply,
"-m", "comment", "--comment", "cilium: NOTRACK for proxy return traffic",
"-j", "NOTRACK"), false)
}
if err == nil {
// 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.
err = runProg("ip6tables", append(
m.waitArgs,
"-t", "filter",
"-A", ciliumOutputChain,
"-m", "mark", "--mark", matchProxyReply,
"-m", "comment", "--comment", "cilium: ACCEPT for proxy return traffic",
"-j", "ACCEPT"), false)
}
if err == nil && m.haveSocketMatch {
// Direct inbound TPROXYed traffic towards the socket
err = runProg("ip6tables", m.inboundProxyRedirectRule("-A"), false)
}
}
return err
}
// install or remove rules for a single proxy port
func (m *IptablesManager) iptProxyRules(cmd string, proxyPort uint16, ingress bool, name string) error {
// Redirect packets to the host proxy via TPROXY, as directed by the Cilium
// datapath bpf programs via skb marks (egress) or DSCP (ingress).
if ingress {
if err := m.iptIngressProxyRule(cmd, "tcp", proxyPort, name); err != nil {
return err
}
if err := m.iptIngressProxyRule(cmd, "udp", proxyPort, name); err != nil {
return err
}
} else {
if err := m.iptEgressProxyRule(cmd, "tcp", proxyPort, name); err != nil {
return err
}
if err := m.iptEgressProxyRule(cmd, "udp", proxyPort, name); err != nil {
return err
}
}
return nil
}
func (m *IptablesManager) InstallProxyRules(proxyPort uint16, ingress bool, name string) error {
return m.iptProxyRules("-A", proxyPort, ingress, name)
}
func (m *IptablesManager) RemoveProxyRules(proxyPort uint16, ingress bool, name string) error {
return m.iptProxyRules("-D", proxyPort, ingress, name)
}
func (m *IptablesManager) remoteSnatDstAddrExclusion() string {
switch {
case option.Config.IPv4NativeRoutingCIDR() != nil:
return option.Config.IPv4NativeRoutingCIDR().String()
default:
return node.GetIPv4AllocRange().String()
}
}
func getDeliveryInterface(ifName string) string {
deliveryInterface := ifName
if option.Config.IPAM == ipamOption.IPAMENI || option.Config.EnableEndpointRoutes {
deliveryInterface = "lxc+"
}
return deliveryInterface
}
func (m *IptablesManager) installForwardChainRules(ifName, localDeliveryInterface, forwardChain string) error {
transient := ""
if forwardChain == CiliumTransientForwardChain {
transient = " (transient)"
}
// 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.
//
// The 2nd and 3rd rule are for the case of nodeport traffic where the backend is
// remote. The traffic flow in FORWARD is as follows:
//
// - Node serving nodeport request:
// IN=eno1 OUT=cilium_host
// IN=cilium_host OUT=eno1
//
// - Node running backend:
// IN=eno1 OUT=cilium_host
// IN=lxc... OUT=eno1
if err := runProg("iptables", append(
m.waitArgs,
"-A", forwardChain,
"-o", ifName,
"-m", "comment", "--comment", "cilium"+transient+": any->cluster on "+ifName+" forward accept",
"-j", "ACCEPT"), false); err != nil {
return err
}
if err := runProg("iptables", append(
m.waitArgs,
"-A", forwardChain,
"-i", ifName,
"-m", "comment", "--comment", "cilium"+transient+": cluster->any on "+ifName+" forward accept (nodeport)",
"-j", "ACCEPT"), false); err != nil {
return err
}
if err := runProg("iptables", append(
m.waitArgs,
"-A", forwardChain,
"-i", "lxc+",
"-m", "comment", "--comment", "cilium"+transient+": cluster->any on lxc+ forward accept",
"-j", "ACCEPT"), false); err != nil {
return err
}
// Proxy return traffic to a remote source needs '-i cilium_net'.
// TODO: Make 'cilium_net' configurable if we ever support other than "cilium_host" as the Cilium host device.
if ifName == "cilium_host" {
ifPeerName := "cilium_net"
if err := runProg("iptables", append(
m.waitArgs,
"-A", forwardChain,
"-i", ifPeerName,
"-m", "comment", "--comment", "cilium"+transient+": cluster->any on "+ifPeerName+" forward accept (nodeport)",
"-j", "ACCEPT"), false); err != nil {
return err
}
}
// In case the delivery interface and the host interface are not the
// same (enable-endpoint-routes), a separate set of rules to allow
// from/to delivery interface is required.
if localDeliveryInterface != ifName {
if err := runProg("iptables", append(
m.waitArgs,
"-A", forwardChain,
"-o", localDeliveryInterface,
"-m", "comment", "--comment", "cilium"+transient+": any->cluster on "+localDeliveryInterface+" forward accept",
"-j", "ACCEPT"), false); err != nil {
return err
}
if err := runProg("iptables", append(
m.waitArgs,
"-A", forwardChain,
"-i", localDeliveryInterface,
"-m", "comment", "--comment", "cilium"+transient+": cluster->any on "+localDeliveryInterface+" forward accept (nodeport)",
"-j", "ACCEPT"), false); err != nil {
return err
}
}
return nil
}
// TransientRulesStart installs iptables rules for Cilium that need to be
// kept in-tact during agent restart which removes/installs its main rules.
// Transient rules are then removed once iptables rule update cycle has
// completed. This is mainly due to interactions with kube-proxy.
func (m *IptablesManager) TransientRulesStart(ifName string) error {
if option.Config.EnableIPv4 {
localDeliveryInterface := getDeliveryInterface(ifName)
m.TransientRulesEnd(true)
if err := transientChain.add(m.waitArgs); err != nil {
return fmt.Errorf("cannot add custom chain %s: %s", transientChain.name, err)
}
if err := m.installForwardChainRules(ifName, localDeliveryInterface, transientChain.name); err != nil {
return fmt.Errorf("cannot install forward chain rules to %s: %s", transientChain.name, err)
}
if err := transientChain.installFeeder(m.waitArgs); err != nil {
return fmt.Errorf("cannot install feeder rule %s: %s", transientChain.feederArgs, err)
}
}
return nil
}
// TransientRulesEnd removes Cilium related rules installed from TransientRulesStart.
func (m *IptablesManager) TransientRulesEnd(quiet bool) {
if option.Config.EnableIPv4 {
m.removeCiliumRules("filter", "iptables", CiliumTransientForwardChain)
transientChain.remove(m.waitArgs, quiet)
}
}
// InstallRules installs iptables rules for Cilium in specific use-cases
// (most specifically, interaction with kube-proxy).
func (m *IptablesManager) InstallRules(ifName string) error {
matchFromIPSecEncrypt := fmt.Sprintf("%#08x/%#08x", linux_defaults.RouteMarkDecrypt, linux_defaults.RouteMarkMask)
matchFromIPSecDecrypt := fmt.Sprintf("%#08x/%#08x", linux_defaults.RouteMarkEncrypt, linux_defaults.RouteMarkMask)
for _, c := range ciliumChains {
if err := c.add(m.waitArgs); err != nil {
// do not return error for chain creation that are linked to disabled feeder rules
skipFeeder := false
for _, disabledChain := range option.Config.DisableIptablesFeederRules {
if strings.ToLower(c.hook) == strings.ToLower(disabledChain) {
skipFeeder = true
break
}
}
if skipFeeder {
log.WithField("chain", c.name).Warningf("ignoring creation of chain since feeder rules for %s is disabled", c.hook)
continue
}
return fmt.Errorf("cannot add custom chain %s: %s", c.name, err)
}
}
if err := m.installStaticProxyRules(); err != nil {
return fmt.Errorf("cannot add static proxy rules: %s", err)
}
if err := m.addCiliumAcceptXfrmRules(); err != nil {
return err
}
localDeliveryInterface := getDeliveryInterface(ifName)
if option.Config.EnableIPv4 {
if err := m.installForwardChainRules(ifName, localDeliveryInterface, ciliumForwardChain); err != nil {
return fmt.Errorf("cannot install forward chain rules to %s: %s", transientChain.name, err)
}
// Mark all packets sourced from processes running on the host with a
// special marker so that we can differentiate traffic sourced locally
// vs. traffic from the outside world that was masqueraded to appear
// like it's from the host.
//
// Originally we set this mark only for traffic destined to the
// ifName device, to ensure that any traffic directly reaching
// to a Cilium-managed IP could be classified as from the host.
//
// However, there's another case where a local process attempts to
// reach a service IP which is backed by a Cilium-managed pod. The
// service implementation is outside of Cilium's control, for example,
// handled by kube-proxy. We can tag even this traffic with a magic
// mark, then when the service implementation proxies it back into
// Cilium the BPF will see this mark and understand that the packet
// originated from the host.
matchFromProxy := fmt.Sprintf("%#08x/%#08x", linux_defaults.MagicMarkIsProxy, linux_defaults.MagicMarkProxyMask)
markAsFromHost := fmt.Sprintf("%#08x/%#08x", linux_defaults.MagicMarkHost, linux_defaults.MagicMarkHostMask)
if err := runProg("iptables", append(
m.waitArgs,
"-t", "filter",
"-A", ciliumOutputChain,
"-m", "mark", "!", "--mark", matchFromIPSecDecrypt, // Don't match ipsec traffic
"-m", "mark", "!", "--mark", matchFromIPSecEncrypt, // Don't match ipsec traffic
"-m", "mark", "!", "--mark", matchFromProxy, // Don't match proxy traffic
"-m", "comment", "--comment", "cilium: host->any mark as from host",
"-j", "MARK", "--set-xmark", markAsFromHost), false); err != nil {
return err
}
if option.Config.Masquerade && !option.Config.EnableBPFMasquerade {
// Masquerade all egress traffic leaving the node
//
// This rule must be first as it has different exclusion criteria
// than the other rules in this table.
//
// The following conditions must be met:
// * May not leave on a cilium_ interface, this excludes all
// tunnel traffic
// * Must originate from an IP in the local allocation range
// * Must not be reply if BPF NodePort is enabled
// * Tunnel mode:
// * May not be targeted to an IP in the local allocation
// range
// * Non-tunnel mode:
// * May not be targeted to an IP in the cluster range
if option.Config.EgressMasqueradeInterfaces != "" {
if err := runProg("iptables", append(
m.waitArgs,
"-t", "nat",
"-A", ciliumPostNatChain,
"!", "-d", m.remoteSnatDstAddrExclusion(),
"-o", option.Config.EgressMasqueradeInterfaces,
"-m", "comment", "--comment", "cilium masquerade non-cluster",
"-j", "MASQUERADE"), false); err != nil {
return err
}
} else {
if err := runProg("iptables", append(
m.waitArgs,
"-t", "nat",
"-A", ciliumPostNatChain,
"-s", node.GetIPv4AllocRange().String(),
"!", "-d", m.remoteSnatDstAddrExclusion(),
"!", "-o", "cilium_+",
"-m", "comment", "--comment", "cilium masquerade non-cluster",
"-j", "MASQUERADE"), false); err != nil {
return err
}
}
// The following rules exclude traffic from the remaining rules in this chain.
// If any of these rules match, none of the remaining rules in this chain
// are considered.
// Exclude traffic for other than interface from the masquarade rules.
// RETURN fro the chain as it is possible that other rules need to be matched.
if err := runProg("iptables", append(
m.waitArgs,
"-t", "nat",
"-A", ciliumPostNatChain,
"!", "-o", localDeliveryInterface,
"-m", "comment", "--comment", "exclude non-"+ifName+" traffic from masquerade",
"-j", "RETURN"), false); err != nil {
return err
}
// Exclude proxy return traffic from the masquarade rules
if err := runProg("iptables", append(
m.waitArgs,
"-t", "nat",
"-A", ciliumPostNatChain,
"-m", "mark", "--mark", matchFromProxy, // Don't match proxy (return) traffic
"-m", "comment", "--comment", "exclude proxy return traffic from masquarade",
"-j", "ACCEPT"), false); err != nil {
return err
}
if option.Config.Tunnel != option.TunnelDisabled {
// Masquerade all traffic from the host into the ifName
// interface if the source is not the internal IP
//
// The following conditions must be met:
// * Must be targeted for the ifName interface
// * Must be targeted to an IP that is not local
// * Tunnel mode:
// * May not already be originating from the masquerade IP
// * Non-tunnel mode:
// * May not orignate from any IP inside of the cluster range
if err := runProg("iptables", append(
m.waitArgs,
"-t", "nat",
"-A", ciliumPostNatChain,
"!", "-s", node.GetHostMasqueradeIPv4().String(),
"!", "-d", node.GetIPv4AllocRange().String(),
"-o", "cilium_host",
"-m", "comment", "--comment", "cilium host->cluster masquerade",
"-j", "SNAT", "--to-source", node.GetHostMasqueradeIPv4().String()), false); err != nil {
return err
}
}
// Masquerade all traffic from the host into local
// endpoints if the source is 127.0.0.1. This is
// required to force replies out of the endpoint's