File: firewall_firewalld_test.go

package info (click to toggle)
golang-github-containernetworking-plugins 1.1.1%2Bds1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 1,672 kB
  • sloc: sh: 132; makefile: 11
file content (296 lines) | stat: -rw-r--r-- 8,147 bytes parent folder | download
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
// Copyright 2018 CNI authors
//
// 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 main

import (
	"bufio"
	"fmt"
	"os/exec"
	"strings"
	"sync"
	"syscall"

	"github.com/containernetworking/cni/pkg/invoke"
	"github.com/containernetworking/cni/pkg/skel"
	current "github.com/containernetworking/cni/pkg/types/100"
	"github.com/containernetworking/plugins/pkg/ns"
	"github.com/containernetworking/plugins/pkg/testutils"

	"github.com/godbus/dbus/v5"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

const ifname = "eth0"

type fakeFirewalld struct {
	zone   string
	source string
}

func (f *fakeFirewalld) clear() {
	f.zone = ""
	f.source = ""
}

func (f *fakeFirewalld) AddSource(zone, source string) (string, *dbus.Error) {
	f.zone = zone
	f.source = source
	return "", nil
}

func (f *fakeFirewalld) RemoveSource(zone, source string) (string, *dbus.Error) {
	f.zone = zone
	f.source = source
	return "", nil
}

func (f *fakeFirewalld) QuerySource(zone, source string) (bool, *dbus.Error) {
	if f.zone != zone {
		return false, nil
	}
	if f.source != source {
		return false, nil
	}
	return true, nil
}

func spawnSessionDbus(wg *sync.WaitGroup) (string, *exec.Cmd) {
	// Start a private D-Bus session bus
	path, err := invoke.FindInPath("dbus-daemon", []string{
		"/bin", "/sbin", "/usr/bin", "/usr/sbin",
	})
	Expect(err).NotTo(HaveOccurred())
	cmd := exec.Command(path, "--session", "--print-address", "--nofork", "--nopidfile")
	stdout, err := cmd.StdoutPipe()
	Expect(err).NotTo(HaveOccurred())
	err = cmd.Start()
	Expect(err).NotTo(HaveOccurred())

	// Wait for dbus-daemon to print the bus address
	bytes, err := bufio.NewReader(stdout).ReadString('\n')
	Expect(err).NotTo(HaveOccurred())
	busAddr := strings.TrimSpace(string(bytes))
	Expect(busAddr).NotTo(BeEmpty())

	var startWg sync.WaitGroup
	wg.Add(1)
	startWg.Add(1)
	go func() {
		defer GinkgoRecover()

		startWg.Done()
		err = cmd.Wait()
		Expect(err).NotTo(HaveOccurred())
		wg.Done()
	}()

	startWg.Wait()
	return busAddr, cmd
}

func makeFirewalldConf(ver, ifname string, ns ns.NetNS) []byte {
	return []byte(fmt.Sprintf(`{
	  "cniVersion": "%s",
	  "name": "firewalld-test",
	  "type": "firewall",
	  "backend": "firewalld",
	  "zone": "trusted",
	  "prevResult": {
	    "cniVersion": "%s",
	    "interfaces": [
	      {"name": "%s", "sandbox": "%s"}
	    ],
	    "ips": [
	      {
		"version": "4",
		"address": "10.0.0.2/24",
		"gateway": "10.0.0.1",
		"interface": 0
	      }
	    ]
	  }
	}`, ver, ver, ifname, ns.Path()))
}

var _ = Describe("firewalld test", func() {
	var (
		targetNs ns.NetNS
		cmd      *exec.Cmd
		conn     *dbus.Conn
		wg       sync.WaitGroup
		fwd      *fakeFirewalld
		busAddr  string
	)

	BeforeEach(func() {
		var err error
		targetNs, err = testutils.NewNS()
		Expect(err).NotTo(HaveOccurred())

		// Start a private D-Bus session bus
		busAddr, cmd = spawnSessionDbus(&wg)
		conn, err = dbus.Dial(busAddr)
		Expect(err).NotTo(HaveOccurred())
		err = conn.Auth(nil)
		Expect(err).NotTo(HaveOccurred())
		err = conn.Hello()
		Expect(err).NotTo(HaveOccurred())

		// Start our fake firewalld
		reply, err := conn.RequestName(firewalldName, dbus.NameFlagDoNotQueue)
		Expect(err).NotTo(HaveOccurred())
		Expect(reply).To(Equal(dbus.RequestNameReplyPrimaryOwner))

		fwd = &fakeFirewalld{}
		// Because firewalld D-Bus methods start with lower-case, and
		// because in Go lower-case methods are private, we need to remap
		// Go public methods to the D-Bus name
		methods := map[string]string{
			"AddSource":    firewalldAddSourceMethod,
			"QuerySource":  firewalldQuerySourceMethod,
			"RemoveSource": firewalldRemoveSourceMethod,
		}
		conn.ExportWithMap(fwd, methods, firewalldPath, firewalldZoneInterface)

		// Make sure the plugin uses our private session bus
		testConn = conn
	})

	AfterEach(func() {
		_, err := conn.ReleaseName(firewalldName)
		Expect(err).NotTo(HaveOccurred())

		err = cmd.Process.Signal(syscall.SIGTERM)
		Expect(err).NotTo(HaveOccurred())

		wg.Wait()

		Expect(targetNs.Close()).To(Succeed())
		Expect(testutils.UnmountNS(targetNs)).To(Succeed())
	})

	// firewall plugin requires a prevResult and thus only supports 0.3.0
	// and later CNI versions
	for _, ver := range []string{"0.3.0", "0.3.1", "0.4.0", "1.0.0"} {
		// Redefine ver inside for scope so real value is picked up by each dynamically defined It()
		// See Gingkgo's "Patterns for dynamically generating tests" documentation.
		ver := ver

		It(fmt.Sprintf("[%s] works with a config", ver), func() {
			Expect(isFirewalldRunning()).To(BeTrue())

			conf := makeFirewalldConf(ver, ifname, targetNs)
			args := &skel.CmdArgs{
				ContainerID: "dummy",
				Netns:       targetNs.Path(),
				IfName:      ifname,
				StdinData:   []byte(conf),
			}
			_, _, err := testutils.CmdAdd(targetNs.Path(), args.ContainerID, ifname, []byte(conf), func() error {
				return cmdAdd(args)
			})
			Expect(err).NotTo(HaveOccurred())
			Expect(fwd.zone).To(Equal("trusted"))
			Expect(fwd.source).To(Equal("10.0.0.2/32"))
			fwd.clear()

			err = testutils.CmdDel(targetNs.Path(), args.ContainerID, ifname, func() error {
				return cmdDel(args)
			})
			Expect(err).NotTo(HaveOccurred())
			Expect(fwd.zone).To(Equal("trusted"))
			Expect(fwd.source).To(Equal("10.0.0.2/32"))
		})

		It(fmt.Sprintf("[%s] defaults to the firewalld backend", ver), func() {
			Expect(isFirewalldRunning()).To(BeTrue())

			conf := makeFirewalldConf(ver, ifname, targetNs)
			args := &skel.CmdArgs{
				ContainerID: "dummy",
				Netns:       targetNs.Path(),
				IfName:      ifname,
				StdinData:   []byte(conf),
			}
			_, _, err := testutils.CmdAdd(targetNs.Path(), args.ContainerID, ifname, []byte(conf), func() error {
				return cmdAdd(args)
			})
			Expect(err).NotTo(HaveOccurred())
			Expect(fwd.zone).To(Equal("trusted"))
			Expect(fwd.source).To(Equal("10.0.0.2/32"))
		})

		It(fmt.Sprintf("[%s] passes through the prevResult", ver), func() {
			Expect(isFirewalldRunning()).To(BeTrue())

			conf := makeFirewalldConf(ver, ifname, targetNs)
			args := &skel.CmdArgs{
				ContainerID: "dummy",
				Netns:       targetNs.Path(),
				IfName:      ifname,
				StdinData:   []byte(conf),
			}
			r, _, err := testutils.CmdAdd(targetNs.Path(), args.ContainerID, ifname, []byte(conf), func() error {
				return cmdAdd(args)
			})
			Expect(err).NotTo(HaveOccurred())

			result, err := current.GetResult(r)
			Expect(err).NotTo(HaveOccurred())

			Expect(len(result.Interfaces)).To(Equal(1))
			Expect(result.Interfaces[0].Name).To(Equal("eth0"))
			Expect(len(result.IPs)).To(Equal(1))
			Expect(result.IPs[0].Address.String()).To(Equal("10.0.0.2/24"))
		})

		It(fmt.Sprintf("[%s] works with Check", ver), func() {
			Expect(isFirewalldRunning()).To(BeTrue())

			conf := makeFirewalldConf(ver, ifname, targetNs)
			args := &skel.CmdArgs{
				ContainerID: "dummy",
				Netns:       targetNs.Path(),
				IfName:      ifname,
				StdinData:   []byte(conf),
			}
			r, _, err := testutils.CmdAddWithArgs(args, func() error {
				return cmdAdd(args)
			})
			Expect(err).NotTo(HaveOccurred())
			Expect(fwd.zone).To(Equal("trusted"))
			Expect(fwd.source).To(Equal("10.0.0.2/32"))

			if testutils.SpecVersionHasCHECK(ver) {
				_, err = current.GetResult(r)
				Expect(err).NotTo(HaveOccurred())

				err = testutils.CmdCheckWithArgs(args, func() error {
					return cmdCheck(args)
				})
				Expect(err).NotTo(HaveOccurred())
			}

			err = testutils.CmdDelWithArgs(args, func() error {
				return cmdDel(args)
			})
			Expect(err).NotTo(HaveOccurred())
			Expect(fwd.zone).To(Equal("trusted"))
			Expect(fwd.source).To(Equal("10.0.0.2/32"))
		})
	}
})