Debian Codegraph @

plugins/meta/firewall/firewall_iptables_test.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 "encoding/json"
19 "fmt"
20 "strings"
21
22 "github.com/coreos/go-iptables/iptables"
23 . "github.com/onsi/ginkgo/v2"
24 . "github.com/onsi/gomega"
25 "github.com/vishvananda/netlink"
26
27 "github.com/containernetworking/cni/pkg/skel"
28 "github.com/containernetworking/cni/pkg/types"
29 types040 "github.com/containernetworking/cni/pkg/types/040"
30 current "github.com/containernetworking/cni/pkg/types/100"
31 "github.com/containernetworking/cni/pkg/version"
32 "github.com/containernetworking/plugins/pkg/netlinksafe"
33 "github.com/containernetworking/plugins/pkg/ns"
34 "github.com/containernetworking/plugins/pkg/testutils"
35 )
36
37 func findChains(chains []string) (bool, bool) {
38 var foundAdmin, foundPriv bool
39 for _, ch := range chains {
40 switch ch {
41 case "CNI-ADMIN":
42 foundAdmin = true
43 case "CNI-FORWARD":
44 foundPriv = true
45 }
46 }
47 return foundAdmin, foundPriv
48 }
49
50 func findForwardJumpRules(rules []string) (bool, bool) {
51 var foundAdmin, foundPriv bool
52 for _, rule := range rules {
53 if strings.Contains(rule, "-j CNI-ADMIN") {
54 foundAdmin = true
55 } else if strings.Contains(rule, "-j CNI-FORWARD") {
56 foundPriv = true
57 }
58 }
59 return foundAdmin, foundPriv
60 }
61
62 func findForwardAllowRules(rules []string, ip string) (bool, bool) {
63 var foundOne, foundTwo bool
64 for _, rule := range rules {
65 if !strings.HasSuffix(rule, "-j ACCEPT") {
66 continue
67 }
68 if strings.Contains(rule, fmt.Sprintf(" -s %s ", ip)) {
69 foundOne = true
70 } else if strings.Contains(rule, fmt.Sprintf(" -d %s ", ip)) && strings.Contains(rule, "RELATED,ESTABLISHED") {
71 foundTwo = true
72 }
73 }
74 return foundOne, foundTwo
75 }
76
77 func getPrevResult(bytes []byte) *current.Result {
78 type TmpConf struct {
79 types.NetConf
80 RawPrevResult map[string]interface{} `json:"prevResult,omitempty"`
81 PrevResult *current.Result `json:"-"`
82 }
83
84 conf := &TmpConf{}
85 err := json.Unmarshal(bytes, conf)
86 Expect(err).NotTo(HaveOccurred())
87 if conf.RawPrevResult == nil {
88 return nil
89 }
90
91 resultBytes, err := json.Marshal(conf.RawPrevResult)
92 Expect(err).NotTo(HaveOccurred())
93 res, err := version.NewResult(conf.CNIVersion, resultBytes)
94 Expect(err).NotTo(HaveOccurred())
95 prevResult, err := current.NewResultFromResult(res)
96 Expect(err).NotTo(HaveOccurred())
97
98 return prevResult
99 }
100
101 func validateFullRuleset(bytes []byte) {
102 prevResult := getPrevResult(bytes)
103
104 for _, ip := range prevResult.IPs {
105 ipt, err := iptables.NewWithProtocol(protoForIP(ip.Address))
106 Expect(err).NotTo(HaveOccurred())
107
108 // Ensure chains
109 chains, err := ipt.ListChains("filter")
110 Expect(err).NotTo(HaveOccurred())
111 foundAdmin, foundPriv := findChains(chains)
112 Expect(foundAdmin).To(BeTrue())
113 Expect(foundPriv).To(BeTrue())
114
115 // Look for the FORWARD chain jump rules to our custom chains
116 rules, err := ipt.List("filter", "FORWARD")
117 Expect(err).NotTo(HaveOccurred())
118 Expect(len(rules)).Should(BeNumerically(">", 1))
119 _, foundPriv = findForwardJumpRules(rules)
120 Expect(foundPriv).To(BeTrue())
121
122 // Look for the allow rules in our custom FORWARD chain
123 rules, err = ipt.List("filter", "CNI-FORWARD")
124 Expect(err).NotTo(HaveOccurred())
125 Expect(len(rules)).Should(BeNumerically(">", 1))
126 foundAdmin, _ = findForwardJumpRules(rules)
127 Expect(foundAdmin).To(BeTrue())
128
129 // Look for the IP allow rules
130 foundOne, foundTwo := findForwardAllowRules(rules, ipString(ip.Address))
131 Expect(foundOne).To(BeTrue())
132 Expect(foundTwo).To(BeTrue())
133 }
134 }
135
136 func validateCleanedUp(bytes []byte) {
137 prevResult := getPrevResult(bytes)
138
139 for _, ip := range prevResult.IPs {
140 ipt, err := iptables.NewWithProtocol(protoForIP(ip.Address))
141 Expect(err).NotTo(HaveOccurred())
142
143 // Our private and admin chains don't get cleaned up
144 chains, err := ipt.ListChains("filter")
145 Expect(err).NotTo(HaveOccurred())
146 foundAdmin, foundPriv := findChains(chains)
147 Expect(foundAdmin).To(BeTrue())
148 Expect(foundPriv).To(BeTrue())
149
150 // Look for the FORWARD chain jump rules to our custom chains
151 rules, err := ipt.List("filter", "FORWARD")
152 Expect(err).NotTo(HaveOccurred())
153 _, foundPriv = findForwardJumpRules(rules)
154 Expect(foundPriv).To(BeTrue())
155
156 // Look for the allow rules in our custom FORWARD chain
157 rules, err = ipt.List("filter", "CNI-FORWARD")
158 Expect(err).NotTo(HaveOccurred())
159 foundAdmin, _ = findForwardJumpRules(rules)
160 Expect(foundAdmin).To(BeTrue())
161
162 // Expect no IP address rules for this IP
163 foundOne, foundTwo := findForwardAllowRules(rules, ipString(ip.Address))
164 Expect(foundOne).To(BeFalse())
165 Expect(foundTwo).To(BeFalse())
166 }
167 }
168
169 func makeIptablesConf(ver string) []byte {
170 return []byte(fmt.Sprintf(`{
171 "name": "test",
172 "type": "firewall",
173 "backend": "iptables",
174 "ifName": "dummy0",
175 "cniVersion": "%s",
176 "prevResult": {
177 "cniVersion": "%s",
178 "interfaces": [
179 {"name": "dummy0"}
180 ],
181 "ips": [
182 {
183 "version": "4",
184 "address": "10.0.0.2/24",
185 "interface": 0
186 },
187 {
188 "version": "6",
189 "address": "2001:db8:1:2::1/64",
190 "interface": 0
191 }
192 ]
193 }
194 }`, ver, ver))
195 }
196
197 var _ = Describe("firewall plugin iptables backend", func() {
198 var originalNS, targetNS ns.NetNS
199 const IFNAME string = "dummy0"
200
201 BeforeEach(func() {
202 // Create a new NetNS so we don't modify the host
203 var err error
204 originalNS, err = testutils.NewNS()
205 Expect(err).NotTo(HaveOccurred())
206
207 err = originalNS.Do(func(ns.NetNS) error {
208 defer GinkgoRecover()
209
210 linkAttrs := netlink.NewLinkAttrs()
211 linkAttrs.Name = IFNAME
212 err = netlink.LinkAdd(&netlink.Dummy{
213 LinkAttrs: linkAttrs,
214 })
215 Expect(err).NotTo(HaveOccurred())
216 _, err = netlinksafe.LinkByName(IFNAME)
217 Expect(err).NotTo(HaveOccurred())
218 return nil
219 })
220 Expect(err).NotTo(HaveOccurred())
221
222 targetNS, err = testutils.NewNS()
223 Expect(err).NotTo(HaveOccurred())
224 })
225
226 AfterEach(func() {
227 Expect(originalNS.Close()).To(Succeed())
228 Expect(targetNS.Close()).To(Succeed())
229 })
230
231 // firewall plugin requires a prevResult and thus only supports 0.3.0
232 // and later CNI versions
233 for _, ver := range []string{"0.3.0", "0.3.1", "0.4.0", "1.0.0"} {
234 // Redefine ver inside for scope so real value is picked up by each dynamically defined It()
235 // See Gingkgo's "Patterns for dynamically generating tests" documentation.
236 ver := ver
237
238 It(fmt.Sprintf("[%s] passes prevResult through unchanged", ver), func() {
239 fullConf := makeIptablesConf(ver)
240 args := &skel.CmdArgs{
241 ContainerID: "dummy",
242 Netns: targetNS.Path(),
243 IfName: IFNAME,
244 StdinData: fullConf,
245 }
246
247 err := originalNS.Do(func(ns.NetNS) error {
248 defer GinkgoRecover()
249
250 r, _, err := testutils.CmdAdd(targetNS.Path(), args.ContainerID, IFNAME, fullConf, func() error {
251 return cmdAdd(args)
252 })
253 Expect(err).NotTo(HaveOccurred())
254
255 result, err := current.GetResult(r)
256 Expect(err).NotTo(HaveOccurred())
257
258 Expect(result.Interfaces).To(HaveLen(1))
259 Expect(result.Interfaces[0].Name).To(Equal(IFNAME))
260 Expect(result.IPs).To(HaveLen(2))
261 Expect(result.IPs[0].Address.String()).To(Equal("10.0.0.2/24"))
262 Expect(result.IPs[1].Address.String()).To(Equal("2001:db8:1:2::1/64"))
263 return nil
264 })
265 Expect(err).NotTo(HaveOccurred())
266 })
267
268 It(fmt.Sprintf("[%s] installs the right iptables rules on the host", ver), func() {
269 fullConf := makeIptablesConf(ver)
270 args := &skel.CmdArgs{
271 ContainerID: "dummy",
272 Netns: targetNS.Path(),
273 IfName: IFNAME,
274 StdinData: fullConf,
275 }
276
277 err := originalNS.Do(func(ns.NetNS) error {
278 defer GinkgoRecover()
279
280 _, _, err := testutils.CmdAdd(targetNS.Path(), args.ContainerID, IFNAME, fullConf, func() error {
281 return cmdAdd(args)
282 })
283 Expect(err).NotTo(HaveOccurred())
284
285 validateFullRuleset(fullConf)
286
287 // ensure creation is idempotent
288 _, _, err = testutils.CmdAdd(targetNS.Path(), args.ContainerID, IFNAME, fullConf, func() error {
289 return cmdAdd(args)
290 })
291 Expect(err).NotTo(HaveOccurred())
292
293 return nil
294 })
295 Expect(err).NotTo(HaveOccurred())
296 })
297
298 It(fmt.Sprintf("[%s] correctly handles a custom IptablesAdminChainName", ver), func() {
299 conf := []byte(fmt.Sprintf(`{
300 "name": "test",
301 "type": "firewall",
302 "backend": "iptables",
303 "ifName": "dummy0",
304 "cniVersion": "%s",
305 "iptablesAdminChainName": "CNI-foobar",
306 "prevResult": {
307 "cniVersion": "%s",
308 "interfaces": [
309 {"name": "dummy0"}
310 ],
311 "ips": [
312 {
313 "version": "4",
314 "address": "10.0.0.2/24",
315 "interface": 0
316 },
317 {
318 "version": "6",
319 "address": "2001:db8:1:2::1/64",
320 "interface": 0
321 }
322 ]
323 }
324 }`, ver, ver))
325
326 args := &skel.CmdArgs{
327 ContainerID: "dummy",
328 Netns: targetNS.Path(),
329 IfName: IFNAME,
330 StdinData: conf,
331 }
332
333 err := originalNS.Do(func(ns.NetNS) error {
334 defer GinkgoRecover()
335
336 _, _, err := testutils.CmdAdd(targetNS.Path(), args.ContainerID, IFNAME, conf, func() error {
337 return cmdAdd(args)
338 })
339 Expect(err).NotTo(HaveOccurred())
340
341 var ipt *iptables.IPTables
342 for _, proto := range []iptables.Protocol{iptables.ProtocolIPv4, iptables.ProtocolIPv6} {
343 ipt, err = iptables.NewWithProtocol(proto)
344 Expect(err).NotTo(HaveOccurred())
345
346 // Ensure custom admin chain name
347 chains, err := ipt.ListChains("filter")
348 Expect(err).NotTo(HaveOccurred())
349 var foundAdmin bool
350 for _, ch := range chains {
351 if ch == "CNI-foobar" {
352 foundAdmin = true
353 }
354 }
355 Expect(foundAdmin).To(BeTrue())
356 }
357
358 return nil
359 })
360 Expect(err).NotTo(HaveOccurred())
361 })
362
363 It(fmt.Sprintf("[%s] installs iptables rules, checks rules, then cleans up on delete", ver), func() {
364 fullConf := makeIptablesConf(ver)
365 args := &skel.CmdArgs{
366 ContainerID: "dummy",
367 Netns: targetNS.Path(),
368 IfName: IFNAME,
369 StdinData: fullConf,
370 }
371
372 err := originalNS.Do(func(ns.NetNS) error {
373 defer GinkgoRecover()
374
375 r, _, err := testutils.CmdAddWithArgs(args, func() error {
376 return cmdAdd(args)
377 })
378 Expect(err).NotTo(HaveOccurred())
379
380 _, err = types040.GetResult(r)
381 Expect(err).NotTo(HaveOccurred())
382
383 if testutils.SpecVersionHasCHECK(ver) {
384 err = testutils.CmdCheckWithArgs(args, func() error {
385 return cmdCheck(args)
386 })
387 Expect(err).NotTo(HaveOccurred())
388 validateFullRuleset(fullConf)
389 }
390
391 err = testutils.CmdDelWithArgs(args, func() error {
392 return cmdDel(args)
393 })
394 Expect(err).NotTo(HaveOccurred())
395 validateCleanedUp(fullConf)
396 return nil
397 })
398 Expect(err).NotTo(HaveOccurred())
399 })
400 }
401 })