-
Notifications
You must be signed in to change notification settings - Fork 26
/
policy_linux.go
678 lines (608 loc) · 27.2 KB
/
policy_linux.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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
package nexodus
import (
"encoding/json"
"fmt"
"github.com/nexodus-io/nexodus/internal/client"
"os/exec"
"strings"
"github.com/nexodus-io/nexodus/internal/util"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
// Nftables keywords
sgTableName = "nexodus"
tableFamily = "inet"
ingressChain = "nexodus-inbound"
egressChain = "nexodus-outbound"
destPort = "dport"
destAddr = "daddr"
srcAddr = "saddr"
actionAccept = "accept"
actionDrop = "drop"
counter = "counter"
// Protocols
protoIPv4 = "ipv4"
protoIPv6 = "ipv6"
protoICMPv4 = "icmpv4"
protoICMP = "icmp"
protoICMPv6 = "icmpv6"
protoTCP = "tcp"
protoUDP = "udp"
// Network router keywords
rtrTableName = "nexodus-net-router"
chainPrerouting = "prerouting"
chainPostrouting = "postrouting"
chainForward = "forward"
chainTypeNAT = "nat"
chainTypeFilter = "filter"
priorityDstNAT = "dstnat"
prioritySrcNAT = "srcnat"
priorityFilter = "filter"
)
var (
ruleInterface string
)
// processSecurityGroupRules processes a security group for a Linux node
func (nx *Nexodus) processSecurityGroupRules() error {
// Delete the table if the security group is empty and attempt to drop a table if one exists
if nx.securityGroup == nil {
// Drop the existing table and return nil if a group was not found to drop
_ = nx.policyTableDrop(sgTableName)
return nil
}
ruleInterface = fmt.Sprintf("iifname %s", wgIface)
inboundRules := nx.securityGroup.InboundRules
outboundRules := nx.securityGroup.OutboundRules
// Enable rule debugging to print rules via debug logging as they are processed
if nx.logger.Level().Enabled(zapcore.DebugLevel) {
err := debugSecurityGroupRules(nx.logger, inboundRules, outboundRules)
if err != nil {
nx.logger.Debug(err)
}
}
// Drop the existing table
if err := nx.policyTableDrop(sgTableName); err != nil {
return fmt.Errorf("nftables setup error, failed to flush nftables: %w", err)
}
// Create the nftables table
if err := nx.nfCreateTable(sgTableName); err != nil {
return fmt.Errorf("nftables setup error, failed to create nftables inet table: %w", err)
}
// Create the ingress nftables chains
if err := nx.nfCreateChain(ingressChain); err != nil {
return fmt.Errorf("nftables setup error, failed to create nftables chain %s: %w", ingressChain, err)
}
// Create the egress nftables chains
if err := nx.nfCreateChain(egressChain); err != nil {
return fmt.Errorf("nftables setup error, failed to create nftables chain %s: %w", egressChain, err)
}
// Process the inbound rules
for _, rule := range inboundRules {
if len(rule.IpRanges) == 0 { // If the ip range is empty, add one
rule.IpRanges = append(rule.IpRanges, "")
}
if util.ContainsValidCustomIPv4Ranges(rule.IpRanges) {
// if the rule is a L3 addresses in v4 family, with or without L4 port(s)
if err := nx.nfPermitProtoPortAddrV4(ingressChain, rule); err != nil {
return fmt.Errorf("nftables setup error, failed to process inbound v4 rule: %w", err)
}
} else if util.ContainsValidCustomIPv6Ranges(rule.IpRanges) {
// if the rule is a L3 addresses in v6 family, with or without L4 port(s)
if err := nx.nfPermitProtoPortAddrV6(ingressChain, rule); err != nil {
return fmt.Errorf("nftables setup error, failed to process inbound v6 rule: %w", err)
}
} else if rule.GetFromPort() != 0 && rule.GetToPort() != 0 {
// if the rule is L4 port(s) range with no l3 addresses
if err := nx.nfPermitProtoPort(ingressChain, rule); err != nil {
return fmt.Errorf("nftables setup error, failed to process inbound destination port rule: %w", err)
}
} else {
// if the rule is only protocol to permit (no L4 ports or L3 addresses)
if err := nx.nfPermitProtoAny(ingressChain, rule); err != nil {
return fmt.Errorf("nftables setup error, failed to process inbound destination port rule: %w", err)
}
}
}
// Process the outbound rules
for _, rule := range outboundRules {
if len(rule.IpRanges) == 0 { // If the ip range is empty, add one
rule.IpRanges = append(rule.IpRanges, "")
}
if util.ContainsValidCustomIPv4Ranges(rule.IpRanges) {
// if the rule is a L3 addresses in v4 family, with or without L4 port(s)
if err := nx.nfPermitProtoPortAddrV4(egressChain, rule); err != nil {
return fmt.Errorf("nftables setup error, failed to process outbound v4 rule: %w", err)
}
} else if util.ContainsValidCustomIPv6Ranges(rule.IpRanges) {
// if the rule is a L3 addresses in v6 family, with or without L4 port(s)
if err := nx.nfPermitProtoPortAddrV6(egressChain, rule); err != nil {
return fmt.Errorf("nftables setup error, failed to process outbound v6 rule: %w", err)
}
} else if rule.GetFromPort() != 0 && rule.GetToPort() != 0 {
// if the rule is L4 port(s) range with no l3 addresses
if err := nx.nfPermitProtoPort(egressChain, rule); err != nil {
return fmt.Errorf("nftables setup error, failed to process inbound destination port rule: %w", err)
}
} else {
// if the rule is only protocol to permit (no L4 ports or L3 addresses)
if err := nx.nfPermitProtoAny(egressChain, rule); err != nil {
return fmt.Errorf("nftables setup error, failed to process inbound destination port rule: %w", err)
}
}
}
// the ct module provides access to the connection tracking subsystem, which tracks the state of network
// connections. The state keyword is used to match traffic based on its connection state, in this case as
// established. The established state refers to traffic that is part of an existing connection that has
// already been established, and where both endpoints have exchanged packets.
nft := []string{"insert", "rule", tableFamily, sgTableName, ingressChain, "ct", "state", "established,related", ruleInterface, "counter", "accept"}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
// append a default drop that appears implicit to the user only if there are any rules in the egress chain
if nx.securityGroup.InboundRules != nil && len(nx.securityGroup.InboundRules) != 0 {
if err := nx.nfIngressRuleDrop(); err != nil {
return fmt.Errorf("nftables setup error, failed to add ingress drop rule: %w", err)
}
}
// append a drop that appears implicit to the user only if there are any user defined rules in the egress chain
if nx.securityGroup.OutboundRules != nil && len(nx.securityGroup.OutboundRules) != 0 {
if err := nx.nfEgressRuleDrop(); err != nil {
return fmt.Errorf("nftables setup error, failed to add egress drop rule: %w", err)
}
}
return nil
}
// nfPermitProtoPortAddrV4 creates a nftables rule that permits the specified rule. Example Rules handled by this method:
// nft add rule inet nexodus nexodus-inbound meta nfproto ipv4 ip protocol icmp ip saddr 100.100.0.0/20 counter accept
// nft add rule inet nexodus nexodus-outbound meta nfproto ipv4 ip daddr 100.100.0.1-100.100.0.100 iifname wg0 accept
// nft add rule inet nexodus nexodus-outbound meta nfproto ipv4 ip daddr 8.8.8.8 udp dport 53 iifname "wg0" accept
func (nx *Nexodus) nfPermitProtoPortAddrV4(chain string, rule client.ModelsSecurityRule) error {
var dportOption, srcOrDst string
var nft []string
dportOption = nx.nftPortOption(rule)
if chain == ingressChain {
srcOrDst = srcAddr
} else {
srcOrDst = destAddr
}
switch rule.GetIpProtocol() {
case protoIPv4:
// if the specified proto is ipv4 that specifies an L3 address and does not specify ports.
if rule.GetFromPort() == 0 && rule.GetToPort() == 0 {
for _, ipRange := range rule.IpRanges {
srcOrDstOption := fmt.Sprintf("ip %s %s", srcOrDst, ipRange)
// v4 permits for L3 src or dst
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv4, srcOrDstOption, ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
} else if rule.GetFromPort() != 0 && rule.GetToPort() != 0 {
// if the specified proto is ipv4 that specifies an L3 address and does specify ports.
ports := fmt.Sprintf("%d-%d", rule.GetFromPort(), rule.GetToPort())
if len(rule.IpRanges) > 0 {
for _, ipRange := range rule.IpRanges {
srcOrDstOption := fmt.Sprintf("ip %s %s", srcOrDst, ipRange)
// v4 permits for L3 src or dst with specific ports
nft := []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv4, srcOrDstOption, "th", "dport", ports, ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
}
}
case protoTCP:
// permit ipv4 tcp to src/dst L3 to any destination port
if rule.GetFromPort() == 0 && rule.GetToPort() == 0 {
for _, ipRange := range rule.IpRanges {
srcOrDstOption := fmt.Sprintf("ip %s %s", srcOrDst, ipRange)
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv4, srcOrDstOption, protoTCP, destPort, "0-65535", ruleInterface, "counter", actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
}
// permit ipv4 tcp to L3 src/dst to specified destination port or port range
if rule.GetFromPort() != 0 && rule.GetToPort() != 0 {
for _, ipRange := range rule.IpRanges {
srcOrDstOption := fmt.Sprintf("ip %s %s", srcOrDst, ipRange)
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv4, srcOrDstOption, protoTCP, dportOption, ruleInterface, "counter", actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
}
case protoUDP:
// permit ipv4 udp to src/dst L3 to any destination port
if rule.GetFromPort() == 0 && rule.GetToPort() == 0 {
for _, ipRange := range rule.IpRanges {
srcOrDstOption := fmt.Sprintf("ip %s %s", srcOrDst, ipRange)
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv4, srcOrDstOption, protoUDP, destPort, "0-65535", ruleInterface, "counter", actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
}
// permit ipv4 udp to L3 src/dst to specified destination port or port range
if rule.GetFromPort() != 0 && rule.GetToPort() != 0 {
for _, ipRange := range rule.IpRanges {
srcOrDstOption := fmt.Sprintf("ip %s %s", srcOrDst, ipRange)
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv4, srcOrDstOption, rule.GetIpProtocol(), dportOption, ruleInterface, "counter", actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
}
case protoICMP, protoICMPv4:
// icmpv4 permits to L3 src or dst
for _, ipRange := range rule.IpRanges {
srcOrDstOption := fmt.Sprintf("ip %s %s", srcOrDst, ipRange)
nft = []string{"insert", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv4, "ip", "protocol", protoICMP, srcOrDstOption, ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
default:
nx.logger.Debugf("no match for permit proto dport rule: %v", rule)
return nil
}
return nil
}
// nfPermitProtoPortAddrV6 creates a nftables rule that permits the specified rule. Example Rules handled by this method:
// nft add rule inet nexodus nexodus-outbound meta nfproto ipv6 ip6 daddr 2001:4860:4860::8888-2001:4860:4860::8889 udp dport 0-65535 iifname "wg0" accept
// nft add rule inet nexodus nexodus-outbound meta nfproto ipv6 ip6 daddr 2001:4860:4860::8888-2001:4860:4860::8889 iifname "wg0" accept
// nft add rule inet nexodus nexodus-outbound meta nfproto ipv6 ip6 daddr 2001:4860:4860::8888-2001:4860:4860::8889 udp dport 53 iifname "wg0" accept
// nft add rule inet nexodus nexodus-inbound meta nfproto ipv6 ip6 nexthdr ipv6-icmp ip6 saddr 200::/64 counter accept
func (nx *Nexodus) nfPermitProtoPortAddrV6(chain string, rule client.ModelsSecurityRule) error {
var dportOption, srcOrDst string
var nft []string
dportOption = nx.nftPortOption(rule)
if chain == ingressChain {
srcOrDst = srcAddr
} else {
srcOrDst = destAddr
}
switch rule.GetIpProtocol() {
case protoIPv6:
// nft add rule inet nexodus nexodus-outbound meta nfproto ipv6 ip6 daddr 2001:4860:4860::8888-2001:4860:4860::8889 iifname "wg0" accept
// ipv6 that specifies an L3 src/dst and does not specify ports.
if rule.GetFromPort() == 0 && rule.GetToPort() == 0 {
for _, ipRange := range rule.IpRanges {
srcOrDstIpAddrOption := fmt.Sprintf("ip6 %s %s", srcOrDst, ipRange)
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv6, srcOrDstIpAddrOption, ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
} else if rule.GetFromPort() > 0 && rule.GetToPort() > 0 {
// ipv6 that specifies an L3 src/dst and specifies ports.
ports := fmt.Sprintf("%d-%d", rule.GetFromPort(), rule.GetToPort())
if len(rule.IpRanges) > 0 {
for _, ipRange := range rule.IpRanges {
srcOrDstIpAddrOption := fmt.Sprintf("ip6 %s %s", srcOrDst, ipRange)
// IPv6 permits for L3 with specified ports
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv6, srcOrDstIpAddrOption, "th", "dport", ports, ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
}
}
case protoTCP:
// permit ipv4 tcp to src/dst L3 to any destination port
if rule.GetFromPort() == 0 && rule.GetToPort() == 0 {
for _, ipRange := range rule.IpRanges {
srcOrDstOption := fmt.Sprintf("ip6 %s %s", srcOrDst, ipRange)
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv6, srcOrDstOption, protoTCP, destPort, "0-65535", ruleInterface, "counter", actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
}
// permit ipv6 udp to L3 src/dst to specified destination port or port range
if rule.GetFromPort() != 0 && rule.GetToPort() != 0 {
for _, ipRange := range rule.IpRanges {
srcOrDstIpAddrOption := fmt.Sprintf("ip6 %s %s", srcOrDst, ipRange)
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv6, srcOrDstIpAddrOption, rule.GetIpProtocol(), dportOption, ruleInterface, "counter", actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
}
case protoUDP:
// permit ipv4 udp to src/dst L3 to any destination port
if rule.GetFromPort() == 0 && rule.GetToPort() == 0 {
for _, ipRange := range rule.IpRanges {
srcOrDstOption := fmt.Sprintf("ip6 %s %s", srcOrDst, ipRange)
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv6, srcOrDstOption, protoUDP, destPort, "0-65535", ruleInterface, "counter", actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
}
// permit ipv4 udp to L3 src/dst to specified destination port or port range
if rule.GetFromPort() != 0 && rule.GetToPort() != 0 {
for _, ipRange := range rule.IpRanges {
srcOrDstIpAddrOption := fmt.Sprintf("ip6 %s %s", srcOrDst, ipRange)
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv6, srcOrDstIpAddrOption, protoUDP, dportOption, ruleInterface, "counter", actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
}
case protoICMP, protoICMPv6:
// icmpv4 permits to L3 src or dst
for _, ipRange := range rule.IpRanges {
srcOrDstIpAddrOption := fmt.Sprintf("ip6 %s %s", srcOrDst, ipRange)
nft = []string{"insert", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv6, "ip6", "nexthdr", "ipv6-icmp", srcOrDstIpAddrOption, ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
default:
nx.logger.Debugf("no match for permit proto dport rule: %v", rule)
return nil
}
return nil
}
// nfPermitProtoPort creates a nftables rule that permits the specified rule. Example Rules handled by this method:
// nft add rule inet nexodus nexodus-inbound meta nfproto ipv4 iifname "wg0" tcp dport 1-80 counter accept
// nft add rule inet nexodus nexodus-inbound meta nfproto ipv6 iifname "wg0" tcp dport 1-80 counter accept
func (nx *Nexodus) nfPermitProtoPort(chain string, rule client.ModelsSecurityRule) error {
var dportOption string
var nft []string
dportOption = nx.nftPortOption(rule)
switch rule.GetIpProtocol() {
case protoIPv4:
// if the specified proto is ipv4, add rules for both tcp and udp to the chain with the specified dport
if dportOption == "" {
return nil
}
// tcp permits for ports to the specified dport for v4/v6
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv4, protoTCP, dportOption, ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
// udp permits for ports to the specified dport for v4/v6
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv4, protoUDP, dportOption, ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
case protoIPv6:
// if the specified proto is ipv6, add rules for both tcp and udp to the chain with the specified dport
if dportOption == "" {
return nil
}
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv6, protoTCP, dportOption, ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv6, protoUDP, dportOption, ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
case protoUDP, protoTCP:
// if the specified proto is tcp or udp, add rules for both ipv4 and ipv6 to the chain with the specified dport
if dportOption == "" {
return nil
}
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv4, rule.GetIpProtocol(), dportOption, ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv6, rule.GetIpProtocol(), dportOption, ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
default:
nx.logger.Debugf("no match for permit proto dport rule: %v", rule)
return nil
}
return nil
}
// nfPermitProtoAny creates a nftables rule that permits the specified rule. Example Rules handled by this method:
// nft insert rule inet nexodus nexodus-outbound meta nfproto ipv4 iifname "wg0" counter accept
// nft insert rule inet nexodus nexodus-outbound meta nfproto ipv6 iifname "wg0" counter accept
// nft add rule inet nexodus nexodus-inbound meta nfproto ipv4 tcp dport 0-65535 iifname "wg0" counter accept
// nft add rule inet nexodus nexodus-inbound meta nfproto ipv6 tcp dport 0-65535 iifname "wg0" counter accept
func (nx *Nexodus) nfPermitProtoAny(chain string, rule client.ModelsSecurityRule) error {
var nft []string
switch rule.GetIpProtocol() {
case protoIPv4, protoIPv6:
// permit ipv4 any
if rule.GetIpProtocol() == protoIPv4 {
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", rule.GetIpProtocol(), ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
// permit ipv6 any
if rule.GetIpProtocol() == protoIPv6 {
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", rule.GetIpProtocol(), ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
case "icmp", protoICMPv4, protoICMPv6:
// permit icmpv4 any
if rule.GetIpProtocol() == protoICMPv4 || rule.GetIpProtocol() == "icmp" {
nft = []string{"insert", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv4, "ip", "protocol", protoICMP, ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
// permit icmpv6 any
if rule.GetIpProtocol() == protoICMPv6 {
// ip6 nexthdr is used instead of ip6 protocol for IPv6, because the protocol field is not directly in the IPv6 header.
nft = []string{"insert", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv6, "ip6", "nexthdr", "ipv6-icmp", ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
case protoTCP, protoUDP:
// permit ip/ip6 tcp or udp any to all ports
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv4, rule.GetIpProtocol(), destPort, "0-65535", ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
// permit ipv6 tcp or udp any
nft = []string{"add", "rule", tableFamily, sgTableName, chain, "meta", "nfproto", protoIPv6, rule.GetIpProtocol(), destPort, "0-65535", ruleInterface, counter, actionAccept}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
default:
nx.logger.Debugf("no match for permit proto any dport rule: %v", rule)
return nil
}
return nil
}
// nftPortOption returns the nftables port option for the specified rule.
func (nx *Nexodus) nftPortOption(rule client.ModelsSecurityRule) string {
var portOption string
var portRange string
if rule.GetFromPort() == 0 && rule.GetToPort() == 0 {
portRange = fmt.Sprintf("%d-%d", 0, 65535)
} else if rule.GetFromPort() == rule.GetToPort() {
portRange = fmt.Sprintf("%d", rule.GetFromPort())
} else {
portRange = fmt.Sprintf("%d-%d", rule.GetFromPort(), rule.GetToPort())
}
portOption = fmt.Sprintf("%s %s", destPort, portRange)
return portOption
}
// nfIngressRuleDrop is used to append a drop rule to the ingress chain. Example rule handled by this method:
func (nx *Nexodus) nfIngressRuleDrop() error {
nft := []string{"add", "rule", tableFamily, sgTableName, ingressChain, ruleInterface, "counter", actionDrop}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
return nil
}
// nfEgressRuleDrop is used to append a drop rule to the egress chain
func (nx *Nexodus) nfEgressRuleDrop() error {
nft := []string{"add", "rule", tableFamily, sgTableName, egressChain, ruleInterface, "counter", actionDrop}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
return nil
}
// policyTableDrop is used to delete the nftables table if it exists
func (nx *Nexodus) policyTableDrop(table string) error {
// First, check if the table exists
exists, err := nx.nfTableExists(table)
if err != nil {
return err
}
if !exists {
return nil
}
// If the table exists, proceed with deletion
nft := []string{"delete", "table", tableFamily, table}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
return nil
}
func (nx *Nexodus) nfTableExists(table string) (bool, error) {
args := []string{"list", "tables"}
output, err := policyCmd(nx.logger, args)
if err != nil {
return false, err
}
tableFullName := fmt.Sprintf("table %s %s", tableFamily, table)
// Split the output into lines
lines := strings.Split(output, "\n")
for _, line := range lines {
// Trim spaces and check for an exact match
if strings.TrimSpace(line) == tableFullName {
return true, nil
}
}
return false, nil
}
// nfCreateTable is used to create the nftables table
func (nx *Nexodus) nfCreateTable(table string) error {
if _, err := policyCmd(nx.logger, []string{"add", "table", tableFamily, table}); err != nil {
return err
}
return nil
}
// nfCreateChain is used to create the nftables chain in the nf table
func (nx *Nexodus) nfCreateChain(chainName string) error {
if _, err := policyCmd(nx.logger, []string{"add", "chain", tableFamily, sgTableName, chainName, "{", "type", "filter", "hook", "input", "priority", "0", ";", "policy", "accept", ";", "}"}); err != nil {
return err
}
return nil
}
// policyCmd is used to execute nft commands
func policyCmd(logger *zap.SugaredLogger, cmd []string) (string, error) {
nft := exec.Command("nft", cmd...)
output, err := nft.CombinedOutput()
if err != nil {
return "", fmt.Errorf("nft command: nft %q failed: %w\n", strings.Join(cmd, " "), err)
}
logger.Debugf("nft command: nft %s", strings.Join(cmd, " "))
return string(output), nil
}
func debugSecurityGroupRules(logger *zap.SugaredLogger, inboundRules, outboundRules []client.ModelsSecurityRule) error {
inJson, err := json.MarshalIndent(inboundRules, "", " ")
if err != nil {
return fmt.Errorf("failed to print debug json inbound rules: %w", err)
}
logger.Debugf("\nInboundRules:\n %s\n", inJson)
outJson, err := json.MarshalIndent(outboundRules, "", " ")
if err != nil {
return fmt.Errorf("failed to print debug json inbound rules: %w", err)
}
logger.Debugf("\nOutboundRules:\n %s\n", outJson)
return nil
}
// networkRouterSetup set up the v4/v6 nftables rules for a network router node
func (nx *Nexodus) networkRouterSetup() error {
// Drop the existing table if one exists from previous runs
if err := nx.policyTableDrop(rtrTableName); err != nil {
return fmt.Errorf("nftables router setup error, failed to flush nftables: %w", err)
}
// Create the net router table
if err := nx.nfCreateTable(rtrTableName); err != nil {
return fmt.Errorf("nftables setup error, failed to create nftables inet table: %w", err)
}
// Create the prerouting nftables chain
if err := nx.rtrCreateChain(chainPrerouting, chainTypeNAT, priorityDstNAT); err != nil {
return fmt.Errorf("nftables setup error, failed to create network router nftables chain %s: %w", chainPrerouting, err)
}
// Create the postrouting nftables chain
if err := nx.rtrCreateChain(chainPostrouting, chainTypeNAT, prioritySrcNAT); err != nil {
return fmt.Errorf("nftables setup error, failed to create network router nftables chain %s: %w", chainTypeNAT, err)
}
// Create the forward nftables chain
if err := nx.rtrCreateChain(chainForward, chainTypeFilter, priorityFilter); err != nil {
return fmt.Errorf("nftables setup error, failed to create network router nftables chain %s: %w", chainTypeFilter, err)
}
// Create the forwarding rule with a prefix and oifname interface for each destination prefix
for prefix, iface := range nx.netRouterInterfaceMap {
nx.logger.Debugf("Adding nftables forwarding rule for prefix: %s on interface: %s", prefix, iface.Name)
nft := []string{"add", "rule", tableFamily, rtrTableName, chainForward, "oifname", iface.Name, "ip", destAddr, prefix, counter, "accept"}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
// If --disable-snat was not passed, add a masquerade rule to the postrouting chain,
if !nx.networkRouterDisableNAT {
for _, iface := range nx.netRouterInterfaceMap {
nft := []string{"add", "rule", tableFamily, rtrTableName, chainPostrouting, "oifname", iface.Name, counter, "masquerade"}
if _, err := policyCmd(nx.logger, nft); err != nil {
return err
}
}
}
return nil
}
// rtrCreateChain is used to create the nftables net-router chain in the nf table
func (nx *Nexodus) rtrCreateChain(chainName, chainType, chainPriority string) error {
if _, err := policyCmd(nx.logger, []string{"add", "chain", tableFamily, rtrTableName, chainName, "{", "type", chainType, "hook", chainName, "priority", chainPriority, ";", "}"}); err != nil {
return err
}
return nil
}