-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmock-nftables.go
515 lines (424 loc) · 10.7 KB
/
mock-nftables.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
package whalewall
import (
"bytes"
"fmt"
"slices"
"strings"
"sync"
"syscall"
"github.com/google/nftables"
"github.com/google/nftables/expr"
"github.com/mitchellh/copystructure"
"go.uber.org/zap"
)
const anonSetName = "__set%d"
var setAllocNum = 1
type firewallClient interface {
AddTable(t *nftables.Table) *nftables.Table
AddChain(c *nftables.Chain) *nftables.Chain
DelChain(c *nftables.Chain)
ListChainsOfTableFamily(family nftables.TableFamily) ([]*nftables.Chain, error)
AddSet(s *nftables.Set, vals []nftables.SetElement) error
DelSet(s *nftables.Set)
SetAddElements(s *nftables.Set, vals []nftables.SetElement) error
SetDeleteElements(s *nftables.Set, vals []nftables.SetElement) error
AddRule(r *nftables.Rule) *nftables.Rule
DelRule(r *nftables.Rule) error
InsertRule(r *nftables.Rule) *nftables.Rule
GetRules(t *nftables.Table, c *nftables.Chain) ([]*nftables.Rule, error)
Flush() error
}
type mockFirewall struct {
logger *zap.SugaredLogger
changed bool
tables map[string]*table
chains map[string]chain
unsetLookupExprs []*expr.Lookup
flushErr error
bf baseFirewallReaderWriter
}
type table struct {
Sets setMap
newAnonSets map[string]bool
}
type setMap map[string][]nftables.SetElement
type chain struct {
Chain *nftables.Chain
Rules []*nftables.Rule
}
type baseFirewallReaderWriter interface {
readBaseFirewall(f func(base *mockFirewall))
writeBaseFirewall(f func(base *mockFirewall))
}
type mockFirewallCreatorI interface {
newMockFirewall() *mockFirewall
baseFirewallReaderWriter
}
func newMockFirewallCreator(logger *zap.Logger) mockFirewallCreatorI {
m := &mockFirewallCreator{
baseFirewall: &mockFirewall{
tables: make(map[string]*table),
chains: make(map[string]chain),
},
logger: logger,
}
return m
}
type mockFirewallCreator struct {
baseFirewall *mockFirewall
mtx sync.RWMutex
logger *zap.Logger
}
func (m *mockFirewallCreator) newMockFirewall() *mockFirewall {
m.mtx.RLock()
defer m.mtx.RUnlock()
newFirewall := &mockFirewall{
logger: m.logger.Sugar(),
tables: clone(m.baseFirewall.tables),
chains: clone(m.baseFirewall.chains),
bf: m,
}
initTables(newFirewall)
return newFirewall
}
func initTables(m *mockFirewall) {
for _, t := range m.tables {
t.newAnonSets = make(map[string]bool)
}
}
func (m *mockFirewallCreator) readBaseFirewall(f func(base *mockFirewall)) {
m.mtx.RLock()
f(m.baseFirewall)
m.mtx.RUnlock()
}
func (m *mockFirewallCreator) writeBaseFirewall(f func(base *mockFirewall)) {
m.mtx.Lock()
f(m.baseFirewall)
m.mtx.Unlock()
}
func (m *mockFirewall) AddTable(t *nftables.Table) *nftables.Table {
m.changed = true
if _, ok := m.tables[t.Name]; !ok {
m.tables[t.Name] = &table{
Sets: make(setMap),
newAnonSets: make(map[string]bool),
}
}
return t
}
func (m *mockFirewall) AddChain(c *nftables.Chain) *nftables.Chain {
m.changed = true
if _, ok := m.chains[c.Name]; !ok {
m.chains[c.Name] = chain{
Chain: c,
}
}
return c
}
func (m *mockFirewall) DelChain(c *nftables.Chain) {
m.changed = true
chain, ok := m.chains[c.Name]
if !ok {
m.logger.Errorf("chain %q not found", c.Name)
m.flushErr = syscall.ENOENT
return
}
// delete rules so anonymous sets have a chance to get cleaned up
for _, rule := range chain.Rules {
m.delRule(rule, true)
}
delete(m.chains, c.Name)
}
func (m *mockFirewall) ListChainsOfTableFamily(family nftables.TableFamily) ([]*nftables.Chain, error) {
var chains []*nftables.Chain
m.bf.readBaseFirewall(func(base *mockFirewall) {
for _, c := range base.chains {
if c.Chain.Table.Family == family {
chains = append(chains, c.Chain)
}
}
})
return chains, nil
}
func (m *mockFirewall) AddSet(s *nftables.Set, vals []nftables.SetElement) error {
m.changed = true
t, ok := m.tables[s.Table.Name]
if !ok {
m.logger.Errorf("table %q not found", s.Table.Name)
m.flushErr = syscall.ENOENT
return nil
}
setName := s.Name
if s.Anonymous {
setName = fmt.Sprintf(anonSetName, setAllocNum)
s.ID = uint32(setAllocNum)
s.Name = anonSetName
setAllocNum++
t.newAnonSets[setName] = false
}
if _, ok := t.Sets[setName]; ok {
// TODO: return error if set already exists?
return nil
}
t.Sets[setName] = vals
m.tables[s.Table.Name] = t
return nil
}
func (m *mockFirewall) DelSet(s *nftables.Set) {
m.changed = true
t, ok := m.tables[s.Table.Name]
if !ok {
m.logger.Errorf("table %q not found", s.Table.Name)
m.flushErr = syscall.ENOENT
return
}
delete(t.Sets, s.Name)
m.tables[s.Table.Name] = t
}
func (m *mockFirewall) SetAddElements(s *nftables.Set, vals []nftables.SetElement) error {
m.changed = true
t, ok := m.tables[s.Table.Name]
if !ok {
m.logger.Errorf("table %q not found", s.Table.Name)
m.flushErr = syscall.ENOENT
return nil
}
elements, ok := t.Sets[s.Name]
if !ok {
m.logger.Errorf("set %q not found", s.Name)
m.flushErr = syscall.ENOENT
return nil
}
// don't add elements already present in set
for _, val := range vals {
if !slices.ContainsFunc(elements, func(e nftables.SetElement) bool {
if !bytes.Equal(e.Key, val.Key) {
return false
}
if !bytes.Equal(e.Val, val.Val) {
return false
}
if !bytes.Equal(e.KeyEnd, val.KeyEnd) {
return false
}
if e.IntervalEnd != val.IntervalEnd {
return false
}
if (e.VerdictData != nil) != (val.VerdictData != nil) {
return false
}
if e.VerdictData != nil {
if e.VerdictData.Kind != val.VerdictData.Kind {
return false
}
if e.VerdictData.Chain != val.VerdictData.Chain {
return false
}
}
if e.Timeout != val.Timeout {
return false
}
return true
}) {
elements = append(elements, val)
}
}
t.Sets[s.Name] = elements
m.tables[s.Table.Name] = t
return nil
}
func (m *mockFirewall) SetDeleteElements(s *nftables.Set, vals []nftables.SetElement) error {
m.changed = true
t, ok := m.tables[s.Table.Name]
if !ok {
m.logger.Errorf("table %q not found", s.Table.Name)
m.flushErr = syscall.ENOENT
return nil
}
elements, ok := t.Sets[s.Name]
if !ok {
m.logger.Errorf("set %q not found", s.Name)
m.flushErr = syscall.ENOENT
return nil
}
for _, v := range vals {
i := slices.IndexFunc(elements, func(e nftables.SetElement) bool {
if !bytes.Equal(e.Key, v.Key) {
return false
}
if !bytes.Equal(e.KeyEnd, v.KeyEnd) {
return false
}
if !bytes.Equal(e.Val, v.Val) {
return false
}
return e.IntervalEnd == v.IntervalEnd
})
if i == -1 {
m.logger.Errorf("set element with key %v not found", v.Key)
m.flushErr = syscall.ENOENT
continue
}
elements = slices.Delete(elements, i, i+1)
}
t.Sets[s.Name] = elements
m.tables[s.Table.Name] = t
return nil
}
func (m *mockFirewall) AddRule(r *nftables.Rule) *nftables.Rule {
m.changed = true
t, ok := m.tables[r.Table.Name]
if !ok {
m.logger.Errorf("table %q not found", r.Table.Name)
m.flushErr = syscall.ENOENT
return r
}
c, ok := m.chains[r.Chain.Name]
if !ok {
m.logger.Errorf("chain %q not found", r.Chain.Name)
m.flushErr = syscall.ENOENT
return r
}
// copy this rule so if we update it after flush the caller's rule
// won't be updated
rCopy := clone(r)
m.checkRule(rCopy, t)
c.Rules = append(c.Rules, rCopy)
m.chains[r.Chain.Name] = c
return r
}
func (m *mockFirewall) DelRule(r *nftables.Rule) error {
m.changed = true
m.delRule(r, false)
return nil
}
func (m *mockFirewall) delRule(r *nftables.Rule, softDel bool) {
if _, ok := m.tables[r.Table.Name]; !ok {
m.logger.Errorf("table %q not found", r.Table.Name)
m.flushErr = syscall.ENOENT
return
}
c, ok := m.chains[r.Chain.Name]
if !ok {
m.logger.Errorf("chain %q not found", r.Chain.Name)
m.flushErr = syscall.ENOENT
return
}
i := slices.IndexFunc(c.Rules, func(r2 *nftables.Rule) bool {
return rulesEqual(m.logger.Desugar(), r, r2)
})
if i == -1 {
m.logger.Error("rule not found")
m.flushErr = syscall.ENOENT
return
}
// delete any anonymous sets associated with this rule
for _, ruleExpr := range c.Rules[i].Exprs {
lookupExpr, ok := ruleExpr.(*expr.Lookup)
if !ok || !strings.HasPrefix(lookupExpr.SetName, "__set") {
continue
}
m.DelSet(&nftables.Set{
Table: c.Rules[i].Table,
Name: lookupExpr.SetName,
})
}
if !softDel {
c.Rules = slices.Delete(c.Rules, i, i+1)
m.chains[r.Chain.Name] = c
}
}
func (m *mockFirewall) InsertRule(r *nftables.Rule) *nftables.Rule {
m.changed = true
t, ok := m.tables[r.Table.Name]
if !ok {
m.logger.Errorf("table %q not found", r.Table.Name)
m.flushErr = syscall.ENOENT
return r
}
c, ok := m.chains[r.Chain.Name]
if !ok {
m.logger.Errorf("chain %q not found", r.Chain.Name)
m.flushErr = syscall.ENOENT
return r
}
// copy this rule so if we update it after flush the caller's rule
// won't be updated
rCopy := clone(r)
m.checkRule(rCopy, t)
c.Rules = slices.Insert(c.Rules, 0, rCopy)
m.chains[r.Chain.Name] = c
return r
}
func (m *mockFirewall) checkRule(r *nftables.Rule, t *table) {
for _, ruleExpr := range r.Exprs {
lookup, ok := ruleExpr.(*expr.Lookup)
if ok && lookup.SetName == anonSetName {
if lookup.SetID == 0 {
m.flushErr = syscall.EINVAL
break
}
// mark this expression to be updated after flush
m.unsetLookupExprs = append(m.unsetLookupExprs, lookup)
setName := fmt.Sprintf(anonSetName, lookup.SetID)
if _, ok := t.newAnonSets[setName]; ok {
// mark this anonymous set as valid now that a rule has
// been added that uses it
t.newAnonSets[setName] = true
}
}
}
}
func (m *mockFirewall) GetRules(t *nftables.Table, c *nftables.Chain) ([]*nftables.Rule, error) {
var rules []*nftables.Rule
var err error
m.bf.readBaseFirewall(func(base *mockFirewall) {
ch, ok := base.chains[c.Name]
if !ok {
err = syscall.ENOENT
return
}
rules = clone(ch.Rules)
})
return rules, err
}
func (m *mockFirewall) Flush() error {
defer func() {
m.changed = false
m.bf.readBaseFirewall(func(base *mockFirewall) {
m.tables = clone(base.tables)
initTables(m)
m.chains = clone(base.chains)
})
m.flushErr = nil
}()
if m.flushErr != nil {
return m.flushErr
}
// update lookup expressions
for _, lookupExpr := range m.unsetLookupExprs {
lookupExpr.SetName = fmt.Sprintf(lookupExpr.SetName, lookupExpr.SetID)
lookupExpr.SetID = 0
}
m.unsetLookupExprs = nil
// delete unused anonymous sets
for _, t := range m.tables {
for newAnonSet, used := range t.newAnonSets {
if !used {
delete(t.Sets, newAnonSet)
}
}
}
// only propagate changes if there were changes made
if m.changed {
m.bf.writeBaseFirewall(func(base *mockFirewall) {
base.tables = m.tables
base.chains = m.chains
})
}
return nil
}
func clone[T any](t T) T {
//nolint: forcetypeassert
return copystructure.Must(copystructure.Copy(t)).(T)
}