1
2
3
4
19
20 package kubelet
21
22 import (
23 "time"
24
25 "k8s.io/apimachinery/pkg/util/wait"
26 "k8s.io/klog/v2"
27 utiliptables "k8s.io/kubernetes/pkg/util/iptables"
28 utilexec "k8s.io/utils/exec"
29 )
30
31 const (
32
33
34 KubeIPTablesHintChain utiliptables.Chain = "KUBE-IPTABLES-HINT"
35
36
37 KubeFirewallChain utiliptables.Chain = "KUBE-FIREWALL"
38 )
39
40 func (kl *Kubelet) initNetworkUtil() {
41 exec := utilexec.New()
42 iptClients := []utiliptables.Interface{
43 utiliptables.New(exec, utiliptables.ProtocolIPv4),
44 utiliptables.New(exec, utiliptables.ProtocolIPv6),
45 }
46
47 for i := range iptClients {
48 iptClient := iptClients[i]
49 if kl.syncIPTablesRules(iptClient) {
50 klog.InfoS("Initialized iptables rules.", "protocol", iptClient.Protocol())
51 go iptClient.Monitor(
52 utiliptables.Chain("KUBE-KUBELET-CANARY"),
53 []utiliptables.Table{utiliptables.TableMangle, utiliptables.TableNAT, utiliptables.TableFilter},
54 func() { kl.syncIPTablesRules(iptClient) },
55 1*time.Minute, wait.NeverStop,
56 )
57 } else {
58 klog.InfoS("Failed to initialize iptables rules; some functionality may be missing.", "protocol", iptClient.Protocol())
59 }
60 }
61 }
62
63
64
65 func (kl *Kubelet) syncIPTablesRules(iptClient utiliptables.Interface) bool {
66
67
68 if _, err := iptClient.EnsureChain(utiliptables.TableMangle, KubeIPTablesHintChain); err != nil {
69 klog.ErrorS(err, "Failed to ensure that iptables hint chain exists")
70 return false
71 }
72
73 if !iptClient.IsIPv6() {
74
75
76
77
78
79
80
81
82 if _, err := iptClient.EnsureChain(utiliptables.TableFilter, KubeFirewallChain); err != nil {
83 klog.ErrorS(err, "Failed to ensure that filter table KUBE-FIREWALL chain exists")
84 return false
85 }
86
87 if _, err := iptClient.EnsureRule(utiliptables.Prepend, utiliptables.TableFilter, utiliptables.ChainOutput, "-j", string(KubeFirewallChain)); err != nil {
88 klog.ErrorS(err, "Failed to ensure that OUTPUT chain jumps to KUBE-FIREWALL")
89 return false
90 }
91 if _, err := iptClient.EnsureRule(utiliptables.Prepend, utiliptables.TableFilter, utiliptables.ChainInput, "-j", string(KubeFirewallChain)); err != nil {
92 klog.ErrorS(err, "Failed to ensure that INPUT chain jumps to KUBE-FIREWALL")
93 return false
94 }
95
96
97
98
99
100
101
102 if _, err := iptClient.EnsureRule(utiliptables.Append, utiliptables.TableFilter, KubeFirewallChain,
103 "-m", "comment", "--comment", "block incoming localnet connections",
104 "--dst", "127.0.0.0/8",
105 "!", "--src", "127.0.0.0/8",
106 "-m", "conntrack",
107 "!", "--ctstate", "RELATED,ESTABLISHED,DNAT",
108 "-j", "DROP"); err != nil {
109 klog.ErrorS(err, "Failed to ensure rule to drop invalid localhost packets in filter table KUBE-FIREWALL chain")
110 return false
111 }
112 }
113
114 return true
115 }
116
View as plain text