Debian Codegraph @

plugins/meta/portmap/portmap_iptables.go

raw symbols SCIP
1 // Copyright 2017 CNI authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package main
16
17 import (
18 "fmt"
19 "net"
20 "sort"
21 "strconv"
22 "strings"
23
24 "github.com/coreos/go-iptables/iptables"
25 "github.com/vishvananda/netlink"
26
27 "github.com/containernetworking/plugins/pkg/utils"
28 )
29
30 // This creates the chains to be added to iptables. The basic structure is
31 // a bit complex for efficiency's sake. We create 2 chains: a summary chain
32 // that is shared between invocations, and an invocation (container)-specific
33 // chain. This minimizes the number of operations on the top level, but allows
34 // for easy cleanup.
35 //
36 // The basic setup (all operations are on the nat table) is:
37 //
38 // DNAT case (rewrite destination IP and port):
39 // PREROUTING, OUTPUT: --dst-type local -j CNI-HOSTPORT-DNAT
40 // CNI-HOSTPORT-DNAT: --destination-ports 8080,8081 -j CNI-DN-abcd123
41 // CNI-DN-abcd123: -p tcp --dport 8080 -j DNAT --to-destination 192.0.2.33:80
42 // CNI-DN-abcd123: -p tcp --dport 8081 -j DNAT ...
43
44 // The names of the top-level summary chains.
45 // These should never be changed, or else upgrading will require manual
46 // intervention.
47 const (
48 TopLevelDNATChainName = "CNI-HOSTPORT-DNAT"
49 SetMarkChainName = "CNI-HOSTPORT-SETMARK"
50 MarkMasqChainName = "CNI-HOSTPORT-MASQ"
51 OldTopLevelSNATChainName = "CNI-HOSTPORT-SNAT"
52 )
53
54 type portMapperIPTables struct{}
55
56 // forwardPorts establishes port forwarding to a given container IP.
57 // containerNet.IP can be either v4 or v6.
58 func (*portMapperIPTables) forwardPorts(config *PortMapConf, containerNet net.IPNet) error {
59 isV6 := (containerNet.IP.To4() == nil)
60
61 var ipt *iptables.IPTables
62 var err error
63
64 if isV6 {
65 ipt, err = iptables.NewWithProtocol(iptables.ProtocolIPv6)
66 } else {
67 ipt, err = iptables.NewWithProtocol(iptables.ProtocolIPv4)
68 }
69 if err != nil {
70 return fmt.Errorf("failed to open iptables: %v", err)
71 }
72
73 // Enable masquerading for traffic as necessary.
74 // The DNAT chain sets a mark bit for traffic that needs masq:
75 // - connections from localhost
76 // - hairpin traffic back to the container
77 // Idempotently create the rule that masquerades traffic with this mark.
78 // Need to do this first; the DNAT rules reference these chains
79 if *config.SNAT {
80 if config.ExternalSetMarkChain == nil {
81 setMarkChain := genSetMarkChain(*config.MarkMasqBit)
82 if err := setMarkChain.setup(ipt); err != nil {
83 return fmt.Errorf("unable to create chain %s: %v", setMarkChain.name, err)
84 }
85
86 masqChain := genMarkMasqChain(*config.MarkMasqBit)
87 if err := masqChain.setup(ipt); err != nil {
88 return fmt.Errorf("unable to create chain %s: %v", setMarkChain.name, err)
89 }
90 }
91 }
92
93 // Generate the DNAT (actual port forwarding) rules
94 toplevelDnatChain := genToplevelDnatChain()
95 if err := toplevelDnatChain.setup(ipt); err != nil {
96 return fmt.Errorf("failed to create top-level DNAT chain: %v", err)
97 }
98
99 dnatChain := genDnatChain(config.Name, config.ContainerID)
100 // First, idempotently tear down this chain in case there was some
101 // sort of collision or bad state.
102 fillDnatRules(&dnatChain, config, containerNet)
103 if err := dnatChain.setup(ipt); err != nil {
104 return fmt.Errorf("unable to setup DNAT: %v", err)
105 }
106
107 return nil
108 }
109
110 func (*portMapperIPTables) checkPorts(config *PortMapConf, containerNet net.IPNet) error {
111 isV6 := (containerNet.IP.To4() == nil)
112 dnatChain := genDnatChain(config.Name, config.ContainerID)
113 fillDnatRules(&dnatChain, config, containerNet)
114
115 // check is called for each address, not once for all addresses
116 var ip4t *iptables.IPTables
117 var err4 error
118 var ip6t *iptables.IPTables
119 var err6 error
120
121 if isV6 {
122 ip6t, err6 = maybeGetIptables(true)
123 } else {
124 ip4t, err4 = maybeGetIptables(false)
125 }
126
127 if ip4t == nil && ip6t == nil {
128 err := fmt.Errorf("neither iptables nor ip6tables is usable")
129 err = fmt.Errorf("%v, (iptables) %v", err, err4)
130 err = fmt.Errorf("%v, (ip6tables) %v", err, err6)
131 return err
132 }
133
134 if ip4t != nil {
135 if err := dnatChain.check(ip4t); err != nil {
136 return fmt.Errorf("could not check ipv4 dnat: %v", err)
137 }
138 }
139
140 if ip6t != nil {
141 if err := dnatChain.check(ip6t); err != nil {
142 return fmt.Errorf("could not check ipv6 dnat: %v", err)
143 }
144 }
145
146 return nil
147 }
148
149 // genToplevelDnatChain creates the top-level summary chain that we'll
150 // add our chain to. This is easy, because creating chains is idempotent.
151 // IMPORTANT: do not change this, or else upgrading plugins will require
152 // manual intervention.
153 func genToplevelDnatChain() chain {
154 return chain{
155 table: "nat",
156 name: TopLevelDNATChainName,
157 entryRules: [][]string{{
158 "-m", "addrtype",
159 "--dst-type", "LOCAL",
160 }},
161 entryChains: []string{"PREROUTING", "OUTPUT"},
162 }
163 }
164
165 // genDnatChain creates the per-container chain.
166 // Conditions are any static entry conditions for the chain.
167 func genDnatChain(netName, containerID string) chain {
168 return chain{
169 table: "nat",
170 name: utils.MustFormatChainNameWithPrefix(netName, containerID, "DN-"),
171 entryChains: []string{TopLevelDNATChainName},
172 }
173 }
174
175 // dnatRules generates the destination NAT rules, one per port, to direct
176 // traffic from hostip:hostport to podip:podport
177 func fillDnatRules(c *chain, config *PortMapConf, containerNet net.IPNet) {
178 isV6 := (containerNet.IP.To4() == nil)
179 comment := trimComment(fmt.Sprintf(`dnat name: "%s" id: "%s"`, config.Name, config.ContainerID))
180 entries := config.RuntimeConfig.PortMaps
181 setMarkChainName := SetMarkChainName
182 if config.ExternalSetMarkChain != nil {
183 setMarkChainName = *config.ExternalSetMarkChain
184 }
185
186 // Generate the dnat entry rules. We'll use multiport, but it ony accepts
187 // up to 15 rules, so partition the list if needed.
188 // Do it in a stable order for testing
189 protoPorts := groupByProto(entries)
190 protos := []string{}
191 for proto := range protoPorts {
192 protos = append(protos, proto)
193 }
194 sort.Strings(protos)
195 for _, proto := range protos {
196 for _, portSpec := range splitPortList(protoPorts[proto]) {
197 r := []string{
198 "-m", "comment",
199 "--comment", comment,
200 "-m", "multiport",
201 "-p", proto,
202 "--destination-ports", portSpec,
203 }
204
205 if isV6 && config.ConditionsV6 != nil && len(*config.ConditionsV6) > 0 {
206 r = append(r, *config.ConditionsV6...)
207 } else if !isV6 && config.ConditionsV4 != nil && len(*config.ConditionsV4) > 0 {
208 r = append(r, *config.ConditionsV4...)
209 }
210 c.entryRules = append(c.entryRules, r)
211 }
212 }
213
214 // For every entry, generate 3 rules:
215 // - mark hairpin for masq
216 // - mark localhost for masq (for v4)
217 // - do dnat
218 // the ordering is important here; the mark rules must be first.
219 c.rules = make([][]string, 0, 3*len(entries))
220 for _, entry := range entries {
221 // If a HostIP is given, only process the entry if host and container address families match
222 // and append it to the iptables rules
223 addRuleBaseDst := false
224 if entry.HostIP != "" {
225 hostIP := net.ParseIP(entry.HostIP)
226 isHostV6 := (hostIP.To4() == nil)
227
228 if isV6 != isHostV6 {
229 continue
230 }
231
232 // Unspecified addresses can not be used as destination
233 if !hostIP.IsUnspecified() {
234 addRuleBaseDst = true
235 }
236 }
237
238 ruleBase := []string{
239 "-p", entry.Protocol,
240 "--dport", strconv.Itoa(entry.HostPort),
241 }
242 if addRuleBaseDst {
243 ruleBase = append(ruleBase,
244 "-d", entry.HostIP)
245 }
246
247 // Add mark-to-masquerade rules for hairpin and localhost
248 if *config.SNAT {
249 // hairpin
250 hpRule := make([]string, len(ruleBase), len(ruleBase)+4)
251 copy(hpRule, ruleBase)
252
253 masqCIDR := containerNet.String()
254 if config.MasqAll {
255 if isV6 {
256 masqCIDR = "::/0"
257 } else {
258 masqCIDR = "0.0.0.0/0"
259 }
260 }
261
262 hpRule = append(hpRule,
263 "-s", masqCIDR,
264 "-j", setMarkChainName,
265 )
266 c.rules = append(c.rules, hpRule)
267
268 if !isV6 && !config.MasqAll {
269 // localhost
270 localRule := make([]string, len(ruleBase), len(ruleBase)+4)
271 copy(localRule, ruleBase)
272
273 localRule = append(localRule,
274 "-s", "127.0.0.1",
275 "-j", setMarkChainName,
276 )
277 c.rules = append(c.rules, localRule)
278 }
279 }
280
281 // The actual dnat rule
282 dnatRule := make([]string, len(ruleBase), len(ruleBase)+4)
283 copy(dnatRule, ruleBase)
284 dnatRule = append(dnatRule,
285 "-j", "DNAT",
286 "--to-destination", fmtIPPort(containerNet.IP, entry.ContainerPort),
287 )
288 c.rules = append(c.rules, dnatRule)
289 }
290 }
291
292 // genSetMarkChain creates the SETMARK chain - the chain that sets the
293 // "to-be-masqueraded" mark and returns.
294 // Chains are idempotent, so we'll always create this.
295 func genSetMarkChain(markBit int) chain {
296 markValue := 1 << uint(markBit)
297 markDef := fmt.Sprintf("%#x/%#x", markValue, markValue)
298 ch := chain{
299 table: "nat",
300 name: SetMarkChainName,
301 rules: [][]string{{
302 "-m", "comment",
303 "--comment", "CNI portfwd masquerade mark",
304 "-j", "MARK",
305 "--set-xmark", markDef,
306 }},
307 }
308 return ch
309 }
310
311 // genMarkMasqChain creates the chain that masquerades all packets marked
312 // in the SETMARK chain
313 func genMarkMasqChain(markBit int) chain {
314 markValue := 1 << uint(markBit)
315 markDef := fmt.Sprintf("%#x/%#x", markValue, markValue)
316 ch := chain{
317 table: "nat",
318 name: MarkMasqChainName,
319 entryChains: []string{"POSTROUTING"},
320 // Only this entry chain needs to be prepended, because otherwise it is
321 // stomped on by the masquerading rules created by the CNI ptp and bridge
322 // plugins.
323 prependEntry: true,
324 entryRules: [][]string{{
325 "-m", "comment",
326 "--comment", "CNI portfwd requiring masquerade",
327 }},
328 rules: [][]string{{
329 "-m", "mark",
330 "--mark", markDef,
331 "-j", "MASQUERADE",
332 }},
333 }
334 return ch
335 }
336
337 // genOldSnatChain is no longer used, but used to be created. We'll try and
338 // tear it down in case the plugin version changed between ADD and DEL
339 func genOldSnatChain(netName, containerID string) chain {
340 return chain{
341 table: "nat",
342 name: utils.MustFormatChainNameWithPrefix(netName, containerID, "SN-"),
343 entryChains: []string{OldTopLevelSNATChainName},
344 }
345 }
346
347 // unforwardPorts deletes any iptables rules created by this plugin.
348 // It should be idempotent - it will not error if the chain does not exist.
349 //
350 // We also need to be a bit clever about how we handle errors with initializing
351 // iptables. We may be on a system with no ip(6)tables, or no kernel support
352 // for that protocol. The ADD would be successful, since it only adds forwarding
353 // based on the addresses assigned to the container. However, at DELETE time we
354 // don't know which protocols were used.
355 // So, we first check that iptables is "generally OK" by doing a check. If
356 // not, we ignore the error, unless neither v4 nor v6 are OK.
357 func (*portMapperIPTables) unforwardPorts(config *PortMapConf) error {
358 dnatChain := genDnatChain(config.Name, config.ContainerID)
359
360 // Might be lying around from old versions
361 oldSnatChain := genOldSnatChain(config.Name, config.ContainerID)
362
363 ip4t, err4 := maybeGetIptables(false)
364 ip6t, err6 := maybeGetIptables(true)
365 if ip4t == nil && ip6t == nil {
366 err := fmt.Errorf("neither iptables nor ip6tables is usable")
367 err = fmt.Errorf("%v, (iptables) %v", err, err4)
368 err = fmt.Errorf("%v, (ip6tables) %v", err, err6)
369 return err
370 }
371
372 if ip4t != nil {
373 if err := dnatChain.teardown(ip4t); err != nil {
374 return fmt.Errorf("could not teardown ipv4 dnat: %v", err)
375 }
376 oldSnatChain.teardown(ip4t)
377 }
378
379 if ip6t != nil {
380 if err := dnatChain.teardown(ip6t); err != nil {
381 return fmt.Errorf("could not teardown ipv6 dnat: %v", err)
382 }
383 oldSnatChain.teardown(ip6t)
384 }
385 return nil
386 }
387
388 // maybeGetIptables implements the soft error swallowing. If iptables is
389 // usable for the given protocol, returns a handle, otherwise nil
390 func maybeGetIptables(isV6 bool) (*iptables.IPTables, error) {
391 proto := iptables.ProtocolIPv4
392 if isV6 {
393 proto = iptables.ProtocolIPv6
394 }
395
396 ipt, err := iptables.NewWithProtocol(proto)
397 if err != nil {
398 return nil, err
399 }
400
401 _, err = ipt.List("nat", "OUTPUT")
402 if err != nil {
403 return nil, err
404 }
405
406 return ipt, nil
407 }
408
409 // deletePortmapStaleConnections delete the UDP conntrack entries on the specified IP family
410 // from the ports mapped to the container
411 func deletePortmapStaleConnections(portMappings []PortMapEntry, family netlink.InetFamily) error {
412 for _, pm := range portMappings {
413 // skip if is not UDP
414 if strings.ToLower(pm.Protocol) != "udp" {
415 continue
416 }
417 err := utils.DeleteConntrackEntriesForDstPort(uint16(pm.HostPort), utils.PROTOCOL_UDP, family)
418 if err != nil {
419 return err
420 }
421 }
422 return nil
423 }