fw4: add support for `option log` in rule and redirect sections
[project/firewall4.git] / root / usr / share / ucode / fw4.uc
1 const fs = require("fs");
2 const uci = require("uci");
3 const ubus = require("ubus");
4
5 const STATEFILE = "/var/run/fw4.state";
6
7 const PARSE_LIST = 0x01;
8 const FLATTEN_LIST = 0x02;
9 const NO_INVERT = 0x04;
10 const UNSUPPORTED = 0x08;
11 const REQUIRED = 0x10;
12 const DEPRECATED = 0x20;
13
14 const ipv4_icmptypes = {
15 "any": [ 0xFF, 0, 0xFF ],
16 "echo-reply": [ 0, 0, 0xFF ],
17 "pong": [ 0, 0, 0xFF ], /* Alias */
18
19 "destination-unreachable": [ 3, 0, 0xFF ],
20 "network-unreachable": [ 3, 0, 0 ],
21 "host-unreachable": [ 3, 1, 1 ],
22 "protocol-unreachable": [ 3, 2, 2 ],
23 "port-unreachable": [ 3, 3, 3 ],
24 "fragmentation-needed": [ 3, 4, 4 ],
25 "source-route-failed": [ 3, 5, 5 ],
26 "network-unknown": [ 3, 6, 6 ],
27 "host-unknown": [ 3, 7, 7 ],
28 "network-prohibited": [ 3, 9, 9 ],
29 "host-prohibited": [ 3, 10, 10 ],
30 "TOS-network-unreachable": [ 3, 11, 11 ],
31 "TOS-host-unreachable": [ 3, 12, 12 ],
32 "communication-prohibited": [ 3, 13, 13 ],
33 "host-precedence-violation": [ 3, 14, 14 ],
34 "precedence-cutoff": [ 3, 15, 15 ],
35
36 "source-quench": [ 4, 0, 0xFF ],
37
38 "redirect": [ 5, 0, 0xFF ],
39 "network-redirect": [ 5, 0, 0 ],
40 "host-redirect": [ 5, 1, 1 ],
41 "TOS-network-redirect": [ 5, 2, 2 ],
42 "TOS-host-redirect": [ 5, 3, 3 ],
43
44 "echo-request": [ 8, 0, 0xFF ],
45 "ping": [ 8, 0, 0xFF ], /* Alias */
46
47 "router-advertisement": [ 9, 0, 0xFF ],
48
49 "router-solicitation": [ 10, 0, 0xFF ],
50
51 "time-exceeded": [ 11, 0, 0xFF ],
52 "ttl-exceeded": [ 11, 0, 0xFF ], /* Alias */
53 "ttl-zero-during-transit": [ 11, 0, 0 ],
54 "ttl-zero-during-reassembly": [ 11, 1, 1 ],
55
56 "parameter-problem": [ 12, 0, 0xFF ],
57 "ip-header-bad": [ 12, 0, 0 ],
58 "required-option-missing": [ 12, 1, 1 ],
59
60 "timestamp-request": [ 13, 0, 0xFF ],
61
62 "timestamp-reply": [ 14, 0, 0xFF ],
63
64 "address-mask-request": [ 17, 0, 0xFF ],
65
66 "address-mask-reply": [ 18, 0, 0xFF ]
67 };
68
69 const ipv6_icmptypes = {
70 "destination-unreachable": [ 1, 0, 0xFF ],
71 "no-route": [ 1, 0, 0 ],
72 "communication-prohibited": [ 1, 1, 1 ],
73 "address-unreachable": [ 1, 3, 3 ],
74 "port-unreachable": [ 1, 4, 4 ],
75
76 "packet-too-big": [ 2, 0, 0xFF ],
77
78 "time-exceeded": [ 3, 0, 0xFF ],
79 "ttl-exceeded": [ 3, 0, 0xFF ], /* Alias */
80 "ttl-zero-during-transit": [ 3, 0, 0 ],
81 "ttl-zero-during-reassembly": [ 3, 1, 1 ],
82
83 "parameter-problem": [ 4, 0, 0xFF ],
84 "bad-header": [ 4, 0, 0 ],
85 "unknown-header-type": [ 4, 1, 1 ],
86 "unknown-option": [ 4, 2, 2 ],
87
88 "echo-request": [ 128, 0, 0xFF ],
89 "ping": [ 128, 0, 0xFF ], /* Alias */
90
91 "echo-reply": [ 129, 0, 0xFF ],
92 "pong": [ 129, 0, 0xFF ], /* Alias */
93
94 "router-solicitation": [ 133, 0, 0xFF ],
95
96 "router-advertisement": [ 134, 0, 0xFF ],
97
98 "neighbour-solicitation": [ 135, 0, 0xFF ],
99 "neighbor-solicitation": [ 135, 0, 0xFF ], /* Alias */
100
101 "neighbour-advertisement": [ 136, 0, 0xFF ],
102 "neighbor-advertisement": [ 136, 0, 0xFF ], /* Alias */
103
104 "redirect": [ 137, 0, 0xFF ]
105 };
106
107 const dscp_classes = {
108 "CS0": 0x00,
109 "CS1": 0x08,
110 "CS2": 0x10,
111 "CS3": 0x18,
112 "CS4": 0x20,
113 "CS5": 0x28,
114 "CS6": 0x30,
115 "CS7": 0x38,
116 "BE": 0x00,
117 "LE": 0x01,
118 "AF11": 0x0a,
119 "AF12": 0x0c,
120 "AF13": 0x0e,
121 "AF21": 0x12,
122 "AF22": 0x14,
123 "AF23": 0x16,
124 "AF31": 0x1a,
125 "AF32": 0x1c,
126 "AF33": 0x1e,
127 "AF41": 0x22,
128 "AF42": 0x24,
129 "AF43": 0x26,
130 "EF": 0x2e
131 };
132
133 function to_mask(bits, v6) {
134 let m = [], n = false;
135
136 if (bits < 0) {
137 n = true;
138 bits = -bits;
139 }
140
141 if (bits > (v6 ? 128 : 32))
142 return null;
143
144 for (let i = 0; i < (v6 ? 16 : 4); i++) {
145 let b = (bits < 8) ? bits : 8;
146 m[i] = (n ? ~(0xff << (8 - b)) : (0xff << (8 - b))) & 0xff;
147 bits -= b;
148 }
149
150 return arrtoip(m);
151 }
152
153 function to_bits(mask) {
154 let a = iptoarr(mask);
155
156 if (!a)
157 return null;
158
159 let bits = 0;
160
161 for (let i = 0, z = false; i < length(a); i++) {
162 z ||= !a[i];
163
164 while (!z && (a[i] & 0x80)) {
165 a[i] = (a[i] << 1) & 0xff;
166 bits++;
167 }
168
169 if (a[i])
170 return null;
171 }
172
173 return bits;
174 }
175
176 function apply_mask(addr, mask) {
177 let a = iptoarr(addr);
178
179 if (!a)
180 return null;
181
182 if (type(mask) == "int") {
183 for (let i = 0; i < length(a); i++) {
184 let b = (mask < 8) ? mask : 8;
185 a[i] &= (0xff << (8 - b)) & 0xff;
186 mask -= b;
187 }
188 }
189 else {
190 let m = iptoarr(mask);
191
192 if (!m || length(a) != length(m))
193 return null;
194
195 for (let i = 0; i < length(a); i++)
196 a[i] &= m[i];
197 }
198
199 return arrtoip(a);
200 }
201
202 function to_array(x) {
203 if (type(x) == "array")
204 return x;
205
206 if (x == null)
207 return [];
208
209 if (type(x) == "object")
210 return [ x ];
211
212 x = trim("" + x);
213
214 return (x == "") ? [] : split(x, /[ \t]+/);
215 }
216
217 function filter_pos(x) {
218 let rv = filter(x, e => !e.invert);
219 return length(rv) ? rv : null;
220 }
221
222 function filter_neg(x) {
223 let rv = filter(x, e => e.invert);
224 return length(rv) ? rv : null;
225 }
226
227 function null_if_empty(x) {
228 return length(x) ? x : null;
229 }
230
231 function subnets_split_af(x) {
232 let rv = {};
233
234 for (let ag in to_array(x)) {
235 for (let a in filter(ag.addrs, a => (a.family == 4)))
236 push(rv[0] ||= [], { ...a, invert: ag.invert });
237
238 for (let a in filter(ag.addrs, a => (a.family == 6)))
239 push(rv[1] ||= [], { ...a, invert: ag.invert });
240 }
241
242 if (rv[0] || rv[1])
243 rv.family = (!rv[0] ^ !rv[1]) ? (rv[0] ? 4 : 6) : 0;
244
245 return rv;
246 }
247
248 function subnets_group_by_masking(x) {
249 let groups = [], plain = [], nc = [], invert_plain = [], invert_masked = [];
250
251 for (let a in to_array(x)) {
252 if (a.bits == -1 && !a.invert)
253 push(nc, a);
254 else if (!a.invert)
255 push(plain, a);
256 else if (a.bits == -1)
257 push(invert_masked, a);
258 else
259 push(invert_plain, a);
260 }
261
262 for (let a in nc)
263 push(groups, [ null, null_if_empty(invert_plain), [ a, ...invert_masked ] ]);
264
265 if (length(plain)) {
266 push(groups, [
267 plain,
268 null_if_empty(invert_plain),
269 null_if_empty(invert_masked)
270 ]);
271 }
272 else if (!length(groups)) {
273 push(groups, [
274 null,
275 null_if_empty(invert_plain),
276 null_if_empty(invert_masked)
277 ]);
278 }
279
280 return groups;
281 }
282
283 function ensure_tcpudp(x) {
284 if (length(filter(x, p => (p.name == "tcp" || p.name == "udp"))))
285 return true;
286
287 let rest = filter(x, p => !p.any),
288 any = filter(x, p => p.any);
289
290 if (length(any) && !length(rest)) {
291 splice(x, 0);
292 push(x, { name: "tcp" }, { name: "udp" });
293 return true;
294 }
295
296 return false;
297 }
298
299 let is_family = (x, v) => (!x.family || x.family == v);
300 let family_is_ipv4 = (x) => (!x.family || x.family == 4);
301 let family_is_ipv6 = (x) => (!x.family || x.family == 6);
302
303 function infer_family(f, objects) {
304 let res = f;
305 let by = null;
306
307 for (let i = 0; i < length(objects); i += 2) {
308 let objs = to_array(objects[i]),
309 desc = objects[i + 1];
310
311 for (let obj in objs) {
312 if (!obj || !obj.family || obj.family == res)
313 continue;
314
315 if (!res) {
316 res = obj.family;
317 by = obj.desc;
318 continue;
319 }
320
321 return by
322 ? `references IPv${obj.family} only ${desc} but is restricted to IPv${res} by ${by}`
323 : `is restricted to IPv${res} but referenced ${desc} is IPv${obj.family} only`;
324 }
325 }
326
327 return res;
328 }
329
330 function map_setmatch(set, match, proto) {
331 if (!set || (('inet_service' in set.types) && proto != 'tcp' && proto != 'udp'))
332 return null;
333
334 let fields = [];
335
336 for (let i, t in set.types) {
337 let dir = ((match.dir?.[i] || set.directions[i] || 'src') == 'src' ? 's' : 'd');
338
339 switch (t) {
340 case 'ipv4_addr':
341 fields[i] = `ip ${dir}addr`;
342 break;
343
344 case 'ipv6_addr':
345 fields[i] = `ip6 ${dir}addr`;
346 break;
347
348 case 'ether_addr':
349 if (dir != 's')
350 return NaN;
351
352 fields[i] = 'ether saddr';
353 break;
354
355 case 'inet_service':
356 fields[i] = `${proto} ${dir}port`;
357 break;
358 }
359 }
360
361 return fields;
362 }
363
364 function resolve_lower_devices(devstatus, devname, require_hwoffload) {
365 let dir = fs.opendir(`/sys/class/net/${devname}`);
366 let devs = [];
367
368 if (dir) {
369 switch (devstatus[devname]?.devtype) {
370 case 'vlan':
371 case 'bridge':
372 let e;
373
374 while ((e = dir.read()) != null)
375 if (index(e, "lower_") === 0)
376 push(devs, ...resolve_lower_devices(devstatus, substr(e, 6), require_hwoffload));
377
378 break;
379
380 default:
381 if (!require_hwoffload || devstatus[devname]?.["hw-tc-offload"])
382 push(devs, devname);
383
384 break;
385 }
386
387 dir.close();
388 }
389
390 return devs;
391 }
392
393 function nft_json_command(...args) {
394 let cmd = [ "/usr/sbin/nft", "--terse", "--json", ...args ];
395 let nft = fs.popen(join(" ", cmd), "r");
396 let info;
397
398 if (nft) {
399 try {
400 info = filter(json(nft.read("all"))?.nftables,
401 item => (type(item) == "object" && !item.metainfo));
402 }
403 catch (e) {
404 warn(`Unable to parse nftables JSON output: ${e}\n`);
405 }
406
407 nft.close();
408 }
409 else {
410 warn(`Unable to popen() ${cmd}: ${fs.error()}\n`);
411 }
412
413 return info || [];
414 }
415
416 function nft_try_hw_offload(devices) {
417 let nft_test = `
418 add table inet fw4-hw-offload-test;
419 add flowtable inet fw4-hw-offload-test ft {
420 hook ingress priority 0;
421 devices = { "${join('", "', devices)}" };
422 flags offload;
423 }
424 `;
425
426 let rc = system(`/usr/sbin/nft -c '${replace(nft_test, "'", "'\\''")}' 2>/dev/null`);
427
428 return (rc == 0);
429 }
430
431
432 return {
433 read_kernel_version: function() {
434 let fd = fs.open("/proc/version", "r"),
435 v = 0;
436
437 if (fd) {
438 let m = match(fd.read("line"), /^Linux version ([0-9]+)\.([0-9]+)\.([0-9]+)/);
439
440 v = m ? (+m[1] << 24) | (+m[2] << 16) | (+m[3] << 8) : 0;
441 fd.close();
442 }
443
444 return v;
445 },
446
447 resolve_offload_devices: function() {
448 if (!this.default_option("flow_offloading"))
449 return [];
450
451 let devstatus = null;
452 let devices = [];
453 let bus = ubus.connect();
454
455 if (bus) {
456 devstatus = bus.call("network.device", "status") || {};
457 bus.disconnect();
458 }
459
460 if (this.default_option("flow_offloading_hw")) {
461 for (let zone in this.zones())
462 for (let device in zone.related_physdevs)
463 push(devices, ...resolve_lower_devices(devstatus, device, true));
464
465 devices = sort(uniq(devices));
466
467 if (length(devices) && nft_try_hw_offload(devices))
468 return devices;
469
470 this.warn('Hardware flow offloading unavailable, falling back to software offloading');
471 this.state.defaults.flow_offloading_hw = false;
472
473 devices = [];
474 }
475
476 for (let zone in this.zones())
477 for (let device in zone.related_physdevs)
478 push(devices, ...resolve_lower_devices(devstatus, device, false));
479
480 return sort(uniq(devices));
481 },
482
483 check_set_types: function() {
484 let sets = {};
485
486 for (let item in nft_json_command("list", "sets", "inet"))
487 if (item.set?.table == "fw4")
488 sets[item.set.name] = (type(item.set.type) == "array") ? item.set.type : [ item.set.type ];
489
490 return sets;
491 },
492
493 check_flowtable: function() {
494 for (let item in nft_json_command("list", "flowtables", "inet"))
495 if (item.flowtable?.table == "fw4" && item.flowtable?.name == "ft")
496 return true;
497
498 return false;
499 },
500
501 read_state: function() {
502 let fd = fs.open(STATEFILE, "r");
503 let state = null;
504
505 if (fd) {
506 try {
507 state = json(fd.read("all"));
508 }
509 catch (e) {
510 warn(`Unable to parse '${STATEFILE}': ${e}\n`);
511 }
512
513 fd.close();
514 }
515
516 return state;
517 },
518
519 read_ubus: function() {
520 let self = this,
521 ifaces, services,
522 rules = [], networks = {},
523 bus = ubus.connect();
524
525 if (bus) {
526 ifaces = bus.call("network.interface", "dump");
527 services = bus.call("service", "get_data", { "type": "firewall" });
528
529 bus.disconnect();
530 }
531 else {
532 warn(`Unable to connect to ubus: ${ubus.error()}\n`);
533 }
534
535
536 //
537 // Gather logical network information from ubus
538 //
539
540 if (type(ifaces?.interface) == "array") {
541 for (let ifc in ifaces.interface) {
542 let net = {
543 up: ifc.up,
544 device: ifc.l3_device,
545 physdev: ifc.device,
546 zone: ifc.data?.zone
547 };
548
549 if (type(ifc["ipv4-address"]) == "array") {
550 for (let addr in ifc["ipv4-address"]) {
551 push(net.ipaddrs ||= [], {
552 family: 4,
553 addr: addr.address,
554 mask: to_mask(addr.mask, false),
555 bits: addr.mask
556 });
557 }
558 }
559
560 if (type(ifc["ipv6-address"]) == "array") {
561 for (let addr in ifc["ipv6-address"]) {
562 push(net.ipaddrs ||= [], {
563 family: 6,
564 addr: addr.address,
565 mask: to_mask(addr.mask, true),
566 bits: addr.mask
567 });
568 }
569 }
570
571 if (type(ifc["ipv6-prefix-assignment"]) == "array") {
572 for (let addr in ifc["ipv6-prefix-assignment"]) {
573 if (addr["local-address"]) {
574 push(net.ipaddrs ||= [], {
575 family: 6,
576 addr: addr["local-address"].address,
577 mask: to_mask(addr["local-address"].mask, true),
578 bits: addr["local-address"].mask
579 });
580 }
581 }
582 }
583
584 if (type(ifc.data?.firewall) == "array") {
585 let n = 0;
586
587 for (let rulespec in ifc.data.firewall) {
588 push(rules, {
589 ...rulespec,
590
591 name: (rulespec.type != 'ipset') ? `ubus:${ifc.interface}[${ifc.proto}] ${rulespec.type || 'rule'} ${n}` : rulespec.name,
592 device: rulespec.device || ifc.l3_device
593 });
594
595 n++;
596 }
597 }
598
599 networks[ifc.interface] = net;
600 }
601 }
602
603
604 //
605 // Gather firewall rule definitions from ubus services
606 //
607
608 if (type(services) == "object") {
609 for (let svcname, service in services) {
610 if (type(service?.firewall) == "array") {
611 let n = 0;
612
613 for (let rulespec in services[svcname].firewall) {
614 push(rules, {
615 ...rulespec,
616
617 name: (rulespec.type != 'ipset') ? `ubus:${svcname} ${rulespec.type || 'rule'} ${n}` : rulespec.name
618 });
619
620 n++;
621 }
622 }
623
624 for (let svcinst, instance in service) {
625 if (type(instance?.firewall) == "array") {
626 let n = 0;
627
628 for (let rulespec in instance.firewall) {
629 push(rules, {
630 ...rulespec,
631
632 name: (rulespec.type != 'ipset') ? `ubus:${svcname}[${svcinst}] ${rulespec.type || 'rule'} ${n}` : rulespec.name
633 });
634
635 n++;
636 }
637 }
638 }
639 }
640 }
641
642 return {
643 networks: networks,
644 ubus_rules: rules
645 };
646 },
647
648 load: function(use_statefile) {
649 let self = this;
650
651 this.state = use_statefile ? this.read_state() : null;
652
653 this.cursor = uci.cursor();
654 this.cursor.load("firewall");
655 this.cursor.load("/usr/share/firewall4/helpers");
656
657 if (!this.state)
658 this.state = this.read_ubus();
659
660 this.kernel = this.read_kernel_version();
661
662
663 //
664 // Read helper mapping
665 //
666
667 this.cursor.foreach("helpers", "helper", h => self.parse_helper(h));
668
669
670 //
671 // Read default policies
672 //
673
674 this.cursor.foreach("firewall", "defaults", d => self.parse_defaults(d));
675
676 if (!this.state.defaults)
677 this.parse_defaults({});
678
679
680 //
681 // Build list of ipsets
682 //
683
684 if (!this.state.ipsets) {
685 map(filter(this.state.ubus_rules, n => (n.type == "ipset")), s => self.parse_ipset(s));
686 this.cursor.foreach("firewall", "ipset", s => self.parse_ipset(s));
687 }
688
689
690 //
691 // Build list of logical zones
692 //
693
694 if (!this.state.zones)
695 this.cursor.foreach("firewall", "zone", z => self.parse_zone(z));
696
697
698 //
699 // Build list of rules
700 //
701
702 map(filter(this.state.ubus_rules, r => (r.type == "rule")), r => self.parse_rule(r));
703 this.cursor.foreach("firewall", "rule", r => self.parse_rule(r));
704
705
706 //
707 // Build list of forwardings
708 //
709
710 this.cursor.foreach("firewall", "forwarding", f => self.parse_forwarding(f));
711
712
713 //
714 // Build list of redirects
715 //
716
717 map(filter(this.state.ubus_rules, r => (r.type == "redirect")), r => self.parse_redirect(r));
718 this.cursor.foreach("firewall", "redirect", r => self.parse_redirect(r));
719
720
721 //
722 // Build list of snats
723 //
724
725 map(filter(this.state.ubus_rules, n => (n.type == "nat")), n => self.parse_nat(n));
726 this.cursor.foreach("firewall", "nat", n => self.parse_nat(n));
727
728
729 //
730 // Build list of includes
731 //
732
733 this.cursor.foreach("firewall", "include", i => self.parse_include(i));
734
735
736 if (use_statefile) {
737 let fd = fs.open(STATEFILE, "w");
738
739 if (fd) {
740 fd.write({
741 zones: this.state.zones,
742 ipsets: this.state.ipsets,
743 networks: this.state.networks,
744 ubus_rules: this.state.ubus_rules,
745 includes: this.state.includes
746 });
747
748 fd.close();
749 }
750 else {
751 warn(`Unable to write '${STATEFILE}': ${fs.error()}\n`);
752 }
753 }
754 },
755
756 warn: function(fmt, ...args) {
757 if (getenv("QUIET"))
758 return;
759
760 let msg = sprintf(fmt, ...args);
761
762 if (getenv("TTY"))
763 warn(`\033[33m${msg}\033[m\n`);
764 else
765 warn(`[!] ${msg}\n`);
766 },
767
768 get: function(sid, opt) {
769 return this.cursor.get("firewall", sid, opt);
770 },
771
772 get_all: function(sid) {
773 return this.cursor.get_all("firewall", sid);
774 },
775
776 parse_options: function(s, spec) {
777 let rv = {};
778
779 for (let key, val in spec) {
780 let datatype = `parse_${val[0]}`,
781 defval = val[1],
782 flags = val[2] || 0,
783 parsefn = (flags & PARSE_LIST) ? "parse_list" : "parse_opt";
784
785 let res = this[parsefn](s, key, datatype, defval, flags);
786
787 if (res !== res)
788 return false;
789
790 if (type(res) == "object" && res.invert && (flags & NO_INVERT)) {
791 this.warn_section(s, `option '${key}' must not be negated`);
792 return false;
793 }
794
795 if (res != null) {
796 if (flags & DEPRECATED)
797 this.warn_section(s, `option '${key}' is deprecated by fw4`);
798 else if (flags & UNSUPPORTED)
799 this.warn_section(s, `option '${key}' is not supported by fw4`);
800 else
801 rv[key] = res;
802 }
803 }
804
805 for (let opt in s) {
806 if (index(opt, '.') != 0 && opt != 'type' && !exists(spec, opt)) {
807 this.warn_section(s, `specifies unknown option '${opt}'`);
808 }
809 }
810
811 return rv;
812 },
813
814 parse_subnet: function(subnet) {
815 let parts = split(subnet, "/");
816 let a, b, m, n;
817
818 switch (length(parts)) {
819 case 2:
820 a = iptoarr(parts[0]);
821 m = iptoarr(parts[1]);
822
823 if (!a)
824 return null;
825
826 if (m) {
827 if (length(a) != length(m))
828 return null;
829
830 b = to_bits(parts[1]);
831
832 /* allow non-contiguous masks such as `::ffff:ffff:ffff:ffff` */
833 if (b == null) {
834 b = -1;
835
836 for (let i, x in m)
837 a[i] &= x;
838 }
839
840 m = arrtoip(m);
841 }
842 else {
843 b = +parts[1];
844
845 if (type(b) != "int")
846 return null;
847
848 m = to_mask(b, length(a) == 16);
849 b = max(-1, b);
850 }
851
852 return [{
853 family: (length(a) == 16) ? 6 : 4,
854 addr: arrtoip(a),
855 mask: m,
856 bits: b
857 }];
858
859 case 1:
860 parts = split(parts[0], "-");
861
862 switch (length(parts)) {
863 case 2:
864 a = iptoarr(parts[0]);
865 b = iptoarr(parts[1]);
866
867 if (a && b && length(a) == length(b)) {
868 return [{
869 family: (length(a) == 16) ? 6 : 4,
870 addr: arrtoip(a),
871 addr2: arrtoip(b),
872 range: true
873 }];
874 }
875
876 break;
877
878 case 1:
879 a = iptoarr(parts[0]);
880
881 if (a) {
882 return [{
883 family: (length(a) == 16) ? 6 : 4,
884 addr: arrtoip(a),
885 mask: to_mask(length(a) * 8, length(a) == 16),
886 bits: length(a) * 8
887 }];
888 }
889
890 n = this.state.networks[parts[0]];
891
892 if (n)
893 return [ ...(n.ipaddrs || []) ];
894 }
895 }
896
897 return null;
898 },
899
900 parse_enum: function(val, choices) {
901 if (type(val) == "string") {
902 val = lc(val);
903
904 for (let i = 0; i < length(choices); i++)
905 if (lc(substr(choices[i], 0, length(val))) == val)
906 return choices[i];
907 }
908
909 return null;
910 },
911
912 section_id: function(sid) {
913 let s = this.get_all(sid);
914
915 if (!s)
916 return null;
917
918 if (s[".anonymous"]) {
919 let c = 0;
920
921 this.cursor.foreach("firewall", s[".type"], function(ss) {
922 if (ss[".name"] == s[".name"])
923 return false;
924
925 c++;
926 });
927
928 return `@${s['.type']}[${c}]`;
929 }
930
931 return s[".name"];
932 },
933
934 warn_section: function(s, msg) {
935 if (s[".name"]) {
936 if (s.name)
937 this.warn("Section %s (%s) %s", this.section_id(s[".name"]), s.name, msg);
938 else
939 this.warn("Section %s %s", this.section_id(s[".name"]), msg);
940 }
941 else {
942 if (s.name)
943 this.warn("ubus %s (%s) %s", s.type || "rule", s.name, msg);
944 else
945 this.warn("ubus %s %s", s.type || "rule", msg);
946 }
947 },
948
949 parse_policy: function(val) {
950 return this.parse_enum(val, [
951 "accept",
952 "reject",
953 "drop"
954 ]);
955 },
956
957 parse_bool: function(val) {
958 if (val == "1" || val == "on" || val == "true" || val == "yes")
959 return true;
960 else if (val == "0" || val == "off" || val == "false" || val == "no")
961 return false;
962 else
963 return null;
964 },
965
966 parse_family: function(val) {
967 if (val == 'any' || val == 'all' || val == '*')
968 return 0;
969 else if (val == 'inet' || index(val, '4') > -1)
970 return 4;
971 else if (index(val, '6') > -1)
972 return 6;
973
974 return null;
975 },
976
977 parse_zone_ref: function(val) {
978 if (val == null)
979 return null;
980
981 if (val == '*')
982 return { any: true };
983
984 for (let zone in this.state.zones) {
985 if (zone.name == val) {
986 return {
987 any: false,
988 zone: zone
989 };
990 }
991 }
992
993 return null;
994 },
995
996 parse_device: function(val) {
997 let rv = this.parse_invert(val);
998
999 if (!rv)
1000 return null;
1001
1002 if (rv.val == '*')
1003 rv.any = true;
1004 else
1005 rv.device = rv.val;
1006
1007 return rv;
1008 },
1009
1010 parse_direction: function(val) {
1011 if (val == 'in' || val == 'ingress')
1012 return false;
1013 else if (val == 'out' || val == 'egress')
1014 return true;
1015
1016 return null;
1017 },
1018
1019 parse_setmatch: function(val) {
1020 let rv = this.parse_invert(val);
1021
1022 if (!rv)
1023 return null;
1024
1025 rv.val = trim(replace(rv.val, /^[^ \t]+/, function(m) {
1026 rv.name = m;
1027 return '';
1028 }));
1029
1030 let dir = split(rv.val, /[ \t,]/);
1031
1032 for (let i = 0; i < 3 && i < length(dir); i++) {
1033 if (dir[i] == "dst" || dir[i] == "dest")
1034 (rv.dir ||= [])[i] = "dst";
1035 else if (dir[i] == "src")
1036 (rv.dir ||= [])[i] = "src";
1037 }
1038
1039 return length(rv.name) ? rv : null;
1040 },
1041
1042 parse_cthelper: function(val) {
1043 let rv = this.parse_invert(val);
1044
1045 if (!rv)
1046 return null;
1047
1048 let helper = filter(this.state.helpers, h => (h.name == rv.val))?.[0];
1049
1050 return helper ? { ...rv, ...helper } : null;
1051 },
1052
1053 parse_protocol: function(val) {
1054 let p = this.parse_invert(val);
1055
1056 if (!p)
1057 return null;
1058
1059 p.val = lc(p.val);
1060
1061 switch (p.val) {
1062 case 'all':
1063 case 'any':
1064 case '*':
1065 p.any = true;
1066 break;
1067
1068 case '1':
1069 case 'icmp':
1070 p.name = 'icmp';
1071 break;
1072
1073 case '58':
1074 case 'icmpv6':
1075 case 'ipv6-icmp':
1076 p.name = 'ipv6-icmp';
1077 break;
1078
1079 case 'tcpudp':
1080 return [
1081 { invert: p.invert, name: 'tcp' },
1082 { invert: p.invert, name: 'udp' }
1083 ];
1084
1085 case '6':
1086 p.name = 'tcp';
1087 break;
1088
1089 case '17':
1090 p.name = 'udp';
1091 break;
1092
1093 default:
1094 p.name = p.val;
1095 }
1096
1097 return (p.any || length(p.name)) ? p : null;
1098 },
1099
1100 parse_mac: function(val) {
1101 let mac = this.parse_invert(val);
1102 let m = mac ? match(mac.val, /^([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})$/i) : null;
1103
1104 if (!m)
1105 return null;
1106
1107 mac.mac = sprintf('%02x:%02x:%02x:%02x:%02x:%02x',
1108 hex(m[1]), hex(m[2]), hex(m[3]),
1109 hex(m[4]), hex(m[5]), hex(m[6]));
1110
1111 return mac;
1112 },
1113
1114 parse_port: function(val) {
1115 let port = this.parse_invert(val);
1116 let m = port ? match(port.val, /^([0-9]{1,5})([-:]([0-9]{1,5}))?$/i) : null;
1117
1118 if (!m)
1119 return null;
1120
1121 if (m[3]) {
1122 let min_port = +m[1];
1123 let max_port = +m[3];
1124
1125 if (min_port > max_port ||
1126 min_port < 0 || max_port < 0 ||
1127 min_port > 65535 || max_port > 65535)
1128 return null;
1129
1130 port.min = min_port;
1131 port.max = max_port;
1132 }
1133 else {
1134 let pn = +m[1];
1135
1136 if (pn != pn || pn < 0 || pn > 65535)
1137 return null;
1138
1139 port.min = pn;
1140 port.max = pn;
1141 }
1142
1143 return port;
1144 },
1145
1146 parse_network: function(val) {
1147 let rv = this.parse_invert(val);
1148
1149 if (!rv)
1150 return null;
1151
1152 let nets = this.parse_subnet(rv.val);
1153
1154 if (nets === null)
1155 return null;
1156
1157 if (length(nets))
1158 rv.addrs = [ ...nets ];
1159
1160 return rv;
1161 },
1162
1163 parse_icmptype: function(val) {
1164 let rv = {};
1165
1166 if (exists(ipv4_icmptypes, val)) {
1167 rv.family = 4;
1168
1169 rv.type = ipv4_icmptypes[val][0];
1170 rv.code_min = ipv4_icmptypes[val][1];
1171 rv.code_max = ipv4_icmptypes[val][2];
1172 }
1173
1174 if (exists(ipv6_icmptypes, val)) {
1175 rv.family = rv.family ? 0 : 6;
1176
1177 rv.type6 = ipv6_icmptypes[val][0];
1178 rv.code6_min = ipv6_icmptypes[val][1];
1179 rv.code6_max = ipv6_icmptypes[val][2];
1180 }
1181
1182 if (!exists(rv, "family")) {
1183 let m = match(val, /^([0-9]+)(\/([0-9]+))?$/);
1184
1185 if (!m)
1186 return null;
1187
1188 if (m[3]) {
1189 rv.type = +m[1];
1190 rv.code_min = +m[3];
1191 rv.code_max = rv.code_min;
1192 }
1193 else {
1194 rv.type = +m[1];
1195 rv.code_min = 0;
1196 rv.code_max = 0xFF;
1197 }
1198
1199 if (rv.type > 0xFF || rv.code_min > 0xFF || rv.code_max > 0xFF)
1200 return null;
1201
1202 rv.family = 0;
1203
1204 rv.type6 = rv.type;
1205 rv.code6_min = rv.code_min;
1206 rv.code6_max = rv.code_max;
1207 }
1208
1209 return rv;
1210 },
1211
1212 parse_invert: function(val) {
1213 if (val == null)
1214 return null;
1215
1216 let rv = { invert: false };
1217
1218 rv.val = trim(replace(val, /^[ \t]*!/, () => (rv.invert = true, '')));
1219
1220 return length(rv.val) ? rv : null;
1221 },
1222
1223 parse_limit: function(val) {
1224 let rv = this.parse_invert(val);
1225 let m = rv ? match(rv.val, /^([0-9]+)(\/([a-z]+))?$/) : null;
1226
1227 if (!m)
1228 return null;
1229
1230 let n = +m[1];
1231 let u = m[3] ? this.parse_enum(m[3], [ "second", "minute", "hour", "day" ]) : "second";
1232
1233 if (!u)
1234 return null;
1235
1236 rv.rate = n;
1237 rv.unit = u;
1238
1239 return rv;
1240 },
1241
1242 parse_int: function(val) {
1243 let n = +val;
1244
1245 return (n == n) ? n : null;
1246 },
1247
1248 parse_date: function(val) {
1249 let d = match(val, /^([0-9]{4})(-([0-9]{1,2})(-([0-9]{1,2})(T([0-9:]+))?)?)?$/);
1250
1251 if (d == null || d[1] < 1970 || d[1] > 2038 || d[3] > 12 || d[5] > 31)
1252 return null;
1253
1254 let t = this.parse_time(d[7] ?? "0");
1255
1256 if (t == null)
1257 return null;
1258
1259 return {
1260 year: +d[1],
1261 month: +d[3] || 1,
1262 day: +d[5] || 1,
1263 ...t
1264 };
1265 },
1266
1267 parse_time: function(val) {
1268 let t = match(val, /^([0-9]{1,2})(:([0-9]{1,2})(:([0-9]{1,2}))?)?$/);
1269
1270 if (t == null || t[1] > 23 || t[3] > 59 || t[5] > 59)
1271 return null;
1272
1273 return {
1274 hour: +t[1],
1275 min: +t[3],
1276 sec: +t[5]
1277 };
1278 },
1279
1280 parse_weekdays: function(val) {
1281 let rv = this.parse_invert(val);
1282
1283 if (!rv)
1284 return null;
1285
1286 for (let day in to_array(rv.val)) {
1287 day = this.parse_enum(day, [
1288 "Monday",
1289 "Tuesday",
1290 "Wednesday",
1291 "Thursday",
1292 "Friday",
1293 "Saturday",
1294 "Sunday"
1295 ]);
1296
1297 if (!day)
1298 return null;
1299
1300 (rv.days ||= {})[day] = true;
1301 }
1302
1303 rv.days = keys(rv.days);
1304
1305 return rv.days ? rv : null;
1306 },
1307
1308 parse_monthdays: function(val) {
1309 let rv = this.parse_invert(val);
1310
1311 if (!rv)
1312 return null;
1313
1314 for (let day in to_array(rv.val)) {
1315 day = +day;
1316
1317 if (day < 1 || day > 31)
1318 return null;
1319
1320 (rv.days ||= [])[day] = true;
1321 }
1322
1323 return rv.days ? rv : null;
1324 },
1325
1326 parse_mark: function(val) {
1327 let rv = this.parse_invert(val);
1328 let m = rv ? match(rv.val, /^(0?x?[0-9a-f]+)(\/(0?x?[0-9a-f]+))?$/i) : null;
1329
1330 if (!m)
1331 return null;
1332
1333 let n = +m[1];
1334
1335 if (n != n || n > 0xFFFFFFFF)
1336 return null;
1337
1338 rv.mark = n;
1339 rv.mask = 0xFFFFFFFF;
1340
1341 if (m[3]) {
1342 n = +m[3];
1343
1344 if (n != n || n > 0xFFFFFFFF)
1345 return null;
1346
1347 rv.mask = n;
1348 }
1349
1350 return rv;
1351 },
1352
1353 parse_dscp: function(val) {
1354 let rv = this.parse_invert(val);
1355
1356 if (!rv)
1357 return null;
1358
1359 rv.val = uc(rv.val);
1360
1361 if (exists(dscp_classes, rv.val)) {
1362 rv.dscp = dscp_classes[rv.val];
1363 }
1364 else {
1365 let n = +rv.val;
1366
1367 if (n != n || n < 0 || n > 0x3F)
1368 return null;
1369
1370 rv.dscp = n;
1371 }
1372
1373 return rv;
1374 },
1375
1376 parse_target: function(val) {
1377 return this.parse_enum(val, [
1378 "accept",
1379 "reject",
1380 "drop",
1381 "notrack",
1382 "helper",
1383 "mark",
1384 "dscp",
1385 "dnat",
1386 "snat",
1387 "masquerade",
1388 "accept",
1389 "reject",
1390 "drop"
1391 ]);
1392 },
1393
1394 parse_reject_code: function(val) {
1395 return this.parse_enum(val, [
1396 "tcp-reset",
1397 "port-unreachable",
1398 "admin-prohibited",
1399 "host-unreachable",
1400 "no-route"
1401 ]);
1402 },
1403
1404 parse_reflection_source: function(val) {
1405 return this.parse_enum(val, [
1406 "internal",
1407 "external"
1408 ]);
1409 },
1410
1411 parse_ipsettype: function(val) {
1412 let m = match(val, /^(src|dst|dest)_(.+)$/);
1413 let t = this.parse_enum(m ? m[2] : val, [
1414 "ip",
1415 "port",
1416 "mac",
1417 "net",
1418 "set"
1419 ]);
1420
1421 return t ? [ (!m || m[1] == 'src') ? 'src' : 'dst', t ] : null;
1422 },
1423
1424 parse_ipsetentry: function(val, set) {
1425 let values = split(val, /[ \t]+/);
1426
1427 if (length(values) != length(set.types))
1428 return null;
1429
1430 let rv = [];
1431 let ip, mac, port;
1432
1433 for (let i, t in set.types) {
1434 switch (t) {
1435 case 'ipv4_addr':
1436 ip = filter(this.parse_subnet(values[i]), a => (a.family == 4));
1437
1438 switch (length(ip) ?? 0) {
1439 case 0: return null;
1440 case 1: break;
1441 default: this.warn("Set entry '%s' resolves to multiple addresses, using first one", values[i]);
1442 }
1443
1444 rv[i] = ("net" in set.fw4types) ? `${ip[0].addr}/${ip[0].bits}` : ip[0].addr;
1445 break;
1446
1447 case 'ipv6_addr':
1448 ip = filter(this.parse_subnet(values[i]), a => (a.family == 6));
1449
1450 switch (length(ip) ?? 0) {
1451 case 0: return null;
1452 case 1: break;
1453 case 2: this.warn("Set entry '%s' resolves to multiple addresses, using first one", values[i]);
1454 }
1455
1456 rv[i] = ("net" in set.fw4types) ? `${ip[0].addr}/${ip[0].bits}` : ip[0].addr;
1457
1458 break;
1459
1460 case 'ether_addr':
1461 mac = this.parse_mac(values[i]);
1462
1463 if (!mac || mac.invert)
1464 return null;
1465
1466 rv[i] = mac.mac;
1467 break;
1468
1469 case 'inet_service':
1470 port = this.parse_port(values[i]);
1471
1472 if (!port || port.invert || port.min != port.max)
1473 return null;
1474
1475 rv[i] = port.min;
1476 break;
1477
1478 default:
1479 rv[i] = values[i];
1480 }
1481 }
1482
1483 return length(rv) ? rv : null;
1484 },
1485
1486 parse_includetype: function(val) {
1487 return this.parse_enum(val, [
1488 "script",
1489 "nftables"
1490 ]);
1491 },
1492
1493 parse_includeposition: function(val) {
1494 return replace(this.parse_enum(val, [
1495 "ruleset-prepend",
1496 "ruleset-postpend",
1497 "ruleset-append",
1498
1499 "table-prepend",
1500 "table-postpend",
1501 "table-append",
1502
1503 "chain-prepend",
1504 "chain-postpend",
1505 "chain-append"
1506 ]), "postpend", "append");
1507 },
1508
1509 parse_string: function(val) {
1510 return "" + val;
1511 },
1512
1513 parse_opt: function(s, opt, fn, defval, flags) {
1514 let val = s[opt];
1515
1516 if (val === null) {
1517 if (flags & REQUIRED) {
1518 this.warn_section(s, `option '${opt}' is mandatory but not set`);
1519 return NaN;
1520 }
1521
1522 val = defval;
1523 }
1524
1525 if (type(val) == "array") {
1526 this.warn_section(s, `option '${opt}' must not be a list`);
1527 return NaN;
1528 }
1529 else if (val == null) {
1530 return null;
1531 }
1532
1533 let res = this[fn](val);
1534
1535 if (res === null) {
1536 this.warn_section(s, `option '${opt}' specifies invalid value '${val}'`);
1537 return NaN;
1538 }
1539
1540 return res;
1541 },
1542
1543 parse_list: function(s, opt, fn, defval, flags) {
1544 let val = s[opt];
1545 let rv = [];
1546
1547 if (val == null) {
1548 if (flags & REQUIRED) {
1549 this.warn_section(s, `option '${opt}' is mandatory but not set`);
1550 return NaN;
1551 }
1552
1553 val = defval;
1554 }
1555
1556 for (val in to_array(val)) {
1557 let res = this[fn](val);
1558
1559 if (res === null) {
1560 this.warn_section(s, `option '${opt}' specifies invalid value '${val}'`);
1561 return NaN;
1562 }
1563
1564 if (flags & FLATTEN_LIST)
1565 push(rv, ...to_array(res));
1566 else
1567 push(rv, res);
1568 }
1569
1570 return length(rv) ? rv : null;
1571 },
1572
1573 quote: function(s, force) {
1574 if (force === true || !match(s, /^([0-9A-Fa-f:.\/-]+)( \. [0-9A-Fa-f:.\/-]+)*$/))
1575 return `"${replace(s + "", /(["\\])/g, '\\$1')}"`;
1576
1577 return s;
1578 },
1579
1580 cidr: function(a) {
1581 if (a.range)
1582 return `${a.addr}-${a.addr2}`;
1583
1584 if ((a.family == 4 && a.bits == 32) ||
1585 (a.family == 6 && a.bits == 128))
1586 return a.addr;
1587
1588 if (a.bits >= 0)
1589 return `${apply_mask(a.addr, a.bits)}/${a.bits}`;
1590
1591 return `${a.addr}/${a.mask}`;
1592 },
1593
1594 host: function(a, v6brackets) {
1595 return a.range
1596 ? `${a.addr}-${a.addr2}`
1597 : (a.family == 6 && v6brackets)
1598 ? `[${apply_mask(a.addr, a.bits)}]` : apply_mask(a.addr, a.bits);
1599 },
1600
1601 port: function(p) {
1602 if (p.min == p.max)
1603 return `${p.min}`;
1604
1605 return `${p.min}-${p.max}`;
1606 },
1607
1608 set: function(v, force) {
1609 let seen = {};
1610
1611 v = filter(to_array(v), item => !seen[item]++);
1612
1613 if (force || length(v) != 1)
1614 return `{ ${join(', ', map(v, this.quote))} }`;
1615
1616 return this.quote(v[0]);
1617 },
1618
1619 concat: function(v) {
1620 return join(' . ', to_array(v));
1621 },
1622
1623 ipproto: function(family) {
1624 switch (family) {
1625 case 4:
1626 return "ip";
1627
1628 case 6:
1629 return "ip6";
1630 }
1631 },
1632
1633 nfproto: function(family, human_readable) {
1634 switch (family) {
1635 case 4:
1636 return human_readable ? "IPv4" : "ipv4";
1637
1638 case 6:
1639 return human_readable ? "IPv6" : "ipv6";
1640
1641 default:
1642 return human_readable ? "IPv4/IPv6" : null;
1643 }
1644 },
1645
1646 l4proto: function(family, proto) {
1647 switch (proto.name) {
1648 case 'icmp':
1649 switch (family ?? 0) {
1650 case 0:
1651 return this.set(['icmp', 'ipv6-icmp']);
1652
1653 case 6:
1654 return 'ipv6-icmp';
1655 }
1656
1657 default:
1658 return proto.name;
1659 }
1660 },
1661
1662 datetime: function(stamp) {
1663 return sprintf('"%04d-%02d-%02d %02d:%02d:%02d"',
1664 stamp.year, stamp.month, stamp.day,
1665 stamp.hour, stamp.min, stamp.sec);
1666 },
1667
1668 date: function(stamp) {
1669 return sprintf('"%04d-%02d-%02d"', stamp.year, stamp.month, stamp.day);
1670 },
1671
1672 datestamp: function(stamp) {
1673 return exists(stamp, 'hour') ? this.datetime(stamp) : this.date(stamp);
1674 },
1675
1676 time: function(stamp) {
1677 return sprintf('"%02d:%02d:%02d"', stamp.hour, stamp.min, stamp.sec);
1678 },
1679
1680 hex: function(n) {
1681 return sprintf('0x%x', n);
1682 },
1683
1684 is_loopback_dev: function(dev) {
1685 return !!(+fs.readfile(`/sys/class/net/${dev}/flags`) & 0x8);
1686 },
1687
1688 is_loopback_addr: function(addr) {
1689 return (index(addr, "127.") == 0 || addr == "::1" || addr == "::1/128");
1690 },
1691
1692 filter_loopback_devs: function(devs, invert) {
1693 return null_if_empty(filter(devs, d => (this.is_loopback_dev(d) == invert)));
1694 },
1695
1696 filter_loopback_addrs: function(addrs, invert) {
1697 return null_if_empty(filter(addrs, a => (this.is_loopback_addr(a) == invert)));
1698 },
1699
1700
1701 input_policy: function(reject_as_drop) {
1702 return (!reject_as_drop || this.state.defaults.input != 'reject') ? this.state.defaults.input : 'drop';
1703 },
1704
1705 output_policy: function(reject_as_drop) {
1706 return (!reject_as_drop || this.state.defaults.output != 'reject') ? this.state.defaults.output : 'drop';
1707 },
1708
1709 forward_policy: function(reject_as_drop) {
1710 return (!reject_as_drop || this.state.defaults.forward != 'reject') ? this.state.defaults.forward : 'drop';
1711 },
1712
1713 default_option: function(flag) {
1714 return this.state.defaults[flag];
1715 },
1716
1717 helpers: function() {
1718 return this.state.helpers;
1719 },
1720
1721 zones: function() {
1722 return this.state.zones;
1723 },
1724
1725 rules: function(chain) {
1726 return filter(this.state.rules, r => (r.chain == chain));
1727 },
1728
1729 redirects: function(chain) {
1730 return filter(this.state.redirects, r => (r.chain == chain));
1731 },
1732
1733 ipsets: function() {
1734 return this.state.ipsets;
1735 },
1736
1737 includes: function(position, chain) {
1738 let stmts = [];
1739 let pad = '';
1740 let pre = '';
1741
1742 switch (position) {
1743 case 'table-prepend':
1744 case 'table-append':
1745 pad = '\t';
1746 pre = '\n';
1747 break;
1748
1749 case 'chain-prepend':
1750 case 'chain-append':
1751 pad = '\t\t';
1752 break;
1753
1754 default:
1755 pre = '\n';
1756 }
1757
1758 push(stmts, pre);
1759
1760 for (let inc in this.state.includes)
1761 if (inc.type == 'nftables' && inc.position == position && (!chain || inc.chain == chain))
1762 push(stmts, `${pad}include "${inc.path}"\n`);
1763
1764 print(length(stmts) > 1 ? join('', stmts) : '');
1765 },
1766
1767 parse_setfile: function(set, cb) {
1768 let fd = fs.open(set.loadfile, "r");
1769
1770 if (!fd) {
1771 warn(`Unable to load file '${set.loadfile}' for set '${set.name}': ${fs.error()}\n`);
1772 return;
1773 }
1774
1775 let line = null, count = 0;
1776
1777 while ((line = fd.read("line")) !== "") {
1778 line = trim(line);
1779
1780 if (length(line) == 0 || ord(line) == 35)
1781 continue;
1782
1783 let v = this.parse_ipsetentry(line, set);
1784
1785 if (!v) {
1786 this.warn(`Skipping invalid entry '${line}' in file '${set.loadfile}' for set '${set.name}'`);
1787 continue;
1788 }
1789
1790 cb(v);
1791
1792 count++;
1793 }
1794
1795 fd.close();
1796
1797 return count;
1798 },
1799
1800 print_setentries: function(set) {
1801 let first = true;
1802 let printer = (entry) => {
1803 if (first) {
1804 print("\t\telements = {\n");
1805 first = false;
1806 }
1807
1808 print("\t\t\t", join(" . ", entry), ",\n");
1809 };
1810
1811 map(set.entries, printer);
1812
1813 if (set.loadfile)
1814 this.parse_setfile(set, printer);
1815
1816 if (!first)
1817 print("\t\t}\n");
1818 },
1819
1820 parse_helper: function(data) {
1821 let helper = this.parse_options(data, {
1822 name: [ "string", null, REQUIRED ],
1823 description: [ "string" ],
1824 module: [ "string" ],
1825 family: [ "family" ],
1826 proto: [ "protocol", null, PARSE_LIST | FLATTEN_LIST | NO_INVERT ],
1827 port: [ "port", null, NO_INVERT ]
1828 });
1829
1830 if (helper === false) {
1831 this.warn("Helper definition '%s' skipped due to invalid options", data.name || data['.name']);
1832 return;
1833 }
1834 else if (helper.proto.any) {
1835 this.warn("Helper definition '%s' must not specify wildcard protocol", data.name || data['.name']);
1836 return;
1837 }
1838 else if (length(helper.proto) > 1) {
1839 this.warn("Helper definition '%s' must not specify multiple protocols", data.name || data['.name']);
1840 return;
1841 }
1842
1843 helper.available = (fs.stat(`/sys/module/${helper.module}`)?.type == "directory");
1844
1845 push(this.state.helpers ||= [], helper);
1846 },
1847
1848 parse_defaults: function(data) {
1849 if (this.state.defaults) {
1850 this.warn_section(data, ": ignoring duplicate defaults section");
1851 return;
1852 }
1853
1854 let defs = this.parse_options(data, {
1855 input: [ "policy", "drop" ],
1856 output: [ "policy", "drop" ],
1857 forward: [ "policy", "drop" ],
1858
1859 drop_invalid: [ "bool" ],
1860 tcp_reject_code: [ "reject_code", "tcp-reset" ],
1861 any_reject_code: [ "reject_code", "port-unreachable" ],
1862
1863 syn_flood: [ "bool" ],
1864 synflood_protect: [ "bool" ],
1865 synflood_rate: [ "limit", "25/second" ],
1866 synflood_burst: [ "int", "50" ],
1867
1868 tcp_syncookies: [ "bool", "1" ],
1869 tcp_ecn: [ "int" ],
1870 tcp_window_scaling: [ "bool", "1" ],
1871
1872 accept_redirects: [ "bool" ],
1873 accept_source_route: [ "bool" ],
1874
1875 auto_helper: [ "bool", "1" ],
1876 custom_chains: [ "bool", null, UNSUPPORTED ],
1877 disable_ipv6: [ "bool", null, UNSUPPORTED ],
1878 flow_offloading: [ "bool", "0" ],
1879 flow_offloading_hw: [ "bool", "0" ]
1880 });
1881
1882 if (defs.synflood_protect === null)
1883 defs.synflood_protect = defs.syn_flood;
1884
1885 delete defs.syn_flood;
1886
1887 this.state.defaults = defs;
1888 },
1889
1890 parse_zone: function(data) {
1891 let zone = this.parse_options(data, {
1892 enabled: [ "bool", "1" ],
1893
1894 name: [ "string", null, REQUIRED ],
1895 family: [ "family" ],
1896
1897 network: [ "device", null, PARSE_LIST ],
1898 device: [ "device", null, PARSE_LIST ],
1899 subnet: [ "network", null, PARSE_LIST ],
1900
1901 input: [ "policy", this.state.defaults ? this.state.defaults.input : "drop" ],
1902 output: [ "policy", this.state.defaults ? this.state.defaults.output : "drop" ],
1903 forward: [ "policy", this.state.defaults ? this.state.defaults.forward : "drop" ],
1904
1905 masq: [ "bool" ],
1906 masq_allow_invalid: [ "bool" ],
1907 masq_src: [ "network", null, PARSE_LIST ],
1908 masq_dest: [ "network", null, PARSE_LIST ],
1909
1910 masq6: [ "bool" ],
1911
1912 extra: [ "string", null, UNSUPPORTED ],
1913 extra_src: [ "string", null, UNSUPPORTED ],
1914 extra_dest: [ "string", null, UNSUPPORTED ],
1915
1916 mtu_fix: [ "bool" ],
1917 custom_chains: [ "bool", null, UNSUPPORTED ],
1918
1919 log: [ "int" ],
1920 log_limit: [ "limit", null, UNSUPPORTED ],
1921
1922 auto_helper: [ "bool", "1" ],
1923 helper: [ "cthelper", null, PARSE_LIST ],
1924
1925 counter: [ "bool", "1" ]
1926 });
1927
1928 if (zone === false) {
1929 this.warn_section(data, "skipped due to invalid options");
1930 return;
1931 }
1932 else if (!zone.enabled) {
1933 this.warn_section(data, "is disabled, ignoring section");
1934 return;
1935 }
1936
1937 for (let helper in zone.helper) {
1938 if (!helper.available) {
1939 this.warn_section(data, `uses unavailable ct helper '${zone.helper.name}'`);
1940 }
1941 }
1942
1943 if (zone.mtu_fix && this.kernel < 0x040a0000) {
1944 this.warn_section(data, "option 'mtu_fix' requires kernel 4.10 or later");
1945 return;
1946 }
1947
1948 if (this.state.defaults?.auto_helper === false)
1949 zone.auto_helper = false;
1950
1951 let match_devices = [];
1952 let related_physdevs = [];
1953 let related_subnets = [];
1954 let related_ubus_networks = [];
1955 let match_subnets, masq_src_subnets, masq_dest_subnets;
1956
1957 for (let name, net in this.state.networks) {
1958 if (net.zone === zone.name)
1959 push(related_ubus_networks, { invert: false, device: name });
1960 }
1961
1962 zone.network = [ ...to_array(zone.network), ...related_ubus_networks ];
1963
1964 for (let e in zone.network) {
1965 if (exists(this.state.networks, e.device)) {
1966 let net = this.state.networks[e.device];
1967
1968 if (net.device) {
1969 push(match_devices, {
1970 invert: e.invert,
1971 device: net.device
1972 });
1973 }
1974
1975 if (net.physdev && !e.invert)
1976 push(related_physdevs, net.physdev);
1977
1978 push(related_subnets, ...(net.ipaddrs || []));
1979 }
1980 }
1981
1982 push(match_devices, ...to_array(zone.device));
1983
1984 match_subnets = subnets_split_af(zone.subnet);
1985 masq_src_subnets = subnets_split_af(zone.masq_src);
1986 masq_dest_subnets = subnets_split_af(zone.masq_dest);
1987
1988 push(related_subnets, ...(match_subnets[0] || []), ...(match_subnets[1] || []));
1989
1990 let match_rules = [];
1991
1992 let add_rule = (family, devices, subnets, zone) => {
1993 let r = {};
1994
1995 r.family = family;
1996
1997 r.devices_pos = null_if_empty(devices[0]);
1998 r.devices_neg = null_if_empty(devices[1]);
1999 r.devices_neg_wildcard = null_if_empty(devices[2]);
2000
2001 r.subnets_pos = map(subnets[0], this.cidr);
2002 r.subnets_neg = map(subnets[1], this.cidr);
2003 r.subnets_masked = subnets[2];
2004
2005 push(match_rules, r);
2006 };
2007
2008 let family = infer_family(zone.family, [
2009 zone.helper, "ct helper",
2010 match_subnets, "subnet list"
2011 ]);
2012
2013 if (type(family) == "string") {
2014 this.warn_section(data, `${family}, skipping`);
2015 return;
2016 }
2017
2018 // group non-inverted device matches into wildcard and non-wildcard ones
2019 let devices = [], plain_devices = [], plain_invert_devices = [], wildcard_invert_devices = [];
2020
2021 for (let device in match_devices) {
2022 let m = match(device.device, /^([^+]*)(\+)?$/);
2023
2024 if (!m) {
2025 this.warn_section(data, `skipping invalid wildcard pattern '${device.device}'`);
2026 continue;
2027 }
2028
2029 // filter `+` (match any device) since nftables does not support
2030 // wildcard only matches
2031 if (!device.invert && m[0] == '+')
2032 continue;
2033
2034 // replace inverted `+` (match no device) with invalid pattern
2035 if (device.invert && m[0] == '+') {
2036 device.device = '/never/';
2037 device.invert = false;
2038 }
2039
2040 // replace "name+" matches with "name*"
2041 else if (m[2] == '+')
2042 device.device = m[1] + '*';
2043
2044 device.wildcard = !!m[2];
2045
2046 if (!device.invert && device.wildcard)
2047 push(devices, [ [ device.device ], plain_invert_devices, wildcard_invert_devices ]);
2048 else if (!device.invert)
2049 push(plain_devices, device.device);
2050 else if (device.wildcard)
2051 push(wildcard_invert_devices, device.device);
2052 else
2053 push(plain_invert_devices, device.device);
2054 }
2055
2056 if (length(plain_devices))
2057 push(devices, [
2058 plain_devices,
2059 plain_invert_devices,
2060 wildcard_invert_devices
2061 ]);
2062 else if (!length(devices))
2063 push(devices, [
2064 null,
2065 plain_invert_devices,
2066 wildcard_invert_devices
2067 ]);
2068
2069 // emit zone jump rules for each device group
2070 if (length(match_devices) || length(match_subnets[0]) || length(match_subnets[1])) {
2071 for (let devgroup in devices) {
2072 // check if there's no AF specific bits, in this case we can do AF agnostic matching
2073 if (!family && !length(match_subnets[0]) && !length(match_subnets[1])) {
2074 add_rule(0, devgroup, [], zone);
2075 }
2076
2077 // we need to emit one or two AF specific rules
2078 else {
2079 if (!family || family == 4)
2080 for (let subnets in subnets_group_by_masking(match_subnets[0]))
2081 add_rule(4, devgroup, subnets, zone);
2082
2083 if (!family || family == 6)
2084 for (let subnets in subnets_group_by_masking(match_subnets[1]))
2085 add_rule(6, devgroup, subnets, zone);
2086 }
2087 }
2088 }
2089
2090 zone.family = family;
2091
2092 zone.match_rules = match_rules;
2093
2094 zone.masq4_src_subnets = subnets_group_by_masking(masq_src_subnets[0]);
2095 zone.masq4_dest_subnets = subnets_group_by_masking(masq_dest_subnets[0]);
2096
2097 zone.masq6_src_subnets = subnets_group_by_masking(masq_src_subnets[1]);
2098 zone.masq6_dest_subnets = subnets_group_by_masking(masq_dest_subnets[1]);
2099
2100 zone.sflags = {};
2101 zone.sflags[zone.input] = true;
2102
2103 zone.dflags = {};
2104 zone.dflags[zone.output] = true;
2105 zone.dflags[zone.forward] = true;
2106
2107 zone.match_devices = map(filter(match_devices, d => !d.invert), d => d.device);
2108 zone.match_subnets = map(filter(related_subnets, s => !s.invert && s.bits != -1), this.cidr);
2109
2110 zone.related_subnets = related_subnets;
2111 zone.related_physdevs = related_physdevs;
2112
2113 if (zone.masq || zone.masq6)
2114 zone.dflags.snat = true;
2115
2116 if ((zone.auto_helper && !(zone.masq || zone.masq6)) || length(zone.helper)) {
2117 zone.dflags.helper = true;
2118
2119 for (let helper in (length(zone.helper) ? zone.helper : this.state.helpers)) {
2120 if (!helper.available)
2121 continue;
2122
2123 for (let proto in helper.proto) {
2124 push(this.state.rules ||= [], {
2125 chain: `helper_${zone.name}`,
2126 family: helper.family,
2127 name: helper.description || helper.name,
2128 proto: proto,
2129 src: zone,
2130 dports_pos: [ this.port(helper.port) ],
2131 target: "helper",
2132 set_helper: helper
2133 });
2134 }
2135 }
2136 }
2137
2138 push(this.state.zones ||= [], zone);
2139 },
2140
2141 parse_forwarding: function(data) {
2142 let fwd = this.parse_options(data, {
2143 enabled: [ "bool", "1" ],
2144
2145 name: [ "string" ],
2146 family: [ "family" ],
2147
2148 src: [ "zone_ref", null, REQUIRED ],
2149 dest: [ "zone_ref", null, REQUIRED ]
2150 });
2151
2152 if (fwd === false) {
2153 this.warn_section(data, "skipped due to invalid options");
2154 return;
2155 }
2156 else if (!fwd.enabled) {
2157 this.warn_section(data, "is disabled, ignoring section");
2158 return;
2159 }
2160
2161 let add_rule = (family, fwd) => {
2162 let f = {
2163 ...fwd,
2164
2165 family: family,
2166 proto: { any: true }
2167 };
2168
2169 f.name ||= `Accept ${fwd.src.any ? "any" : fwd.src.zone.name} to ${fwd.dest.any ? "any" : fwd.dest.zone.name} ${family ? `${this.nfproto(family, true)} ` : ''}forwarding`;
2170 f.chain = fwd.src.any ? "forward" : `forward_${fwd.src.zone.name}`;
2171
2172 if (fwd.dest.any)
2173 f.target = "accept";
2174 else
2175 f.jump_chain = `accept_to_${fwd.dest.zone.name}`;
2176
2177 push(this.state.rules ||= [], f);
2178 };
2179
2180
2181 /* inherit family restrictions from related zones */
2182 let family = infer_family(fwd.family, [
2183 fwd.src?.zone, "source zone",
2184 fwd.dest?.zone, "destination zone"
2185 ]);
2186
2187 if (type(family) == "string") {
2188 this.warn_section(data, `${family}, skipping`);
2189 return;
2190 }
2191
2192 add_rule(family, fwd);
2193
2194 if (fwd.dest.zone)
2195 fwd.dest.zone.dflags.accept = true;
2196 },
2197
2198 parse_rule: function(data) {
2199 let rule = this.parse_options(data, {
2200 enabled: [ "bool", "1" ],
2201
2202 name: [ "string", this.section_id(data[".name"]) ],
2203 _name: [ "string", null, DEPRECATED ],
2204 family: [ "family" ],
2205
2206 src: [ "zone_ref" ],
2207 dest: [ "zone_ref" ],
2208
2209 device: [ "device", null, NO_INVERT ],
2210 direction: [ "direction" ],
2211
2212 ipset: [ "setmatch" ],
2213 helper: [ "cthelper" ],
2214 set_helper: [ "cthelper", null, NO_INVERT ],
2215
2216 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2217
2218 src_ip: [ "network", null, PARSE_LIST ],
2219 src_mac: [ "mac", null, PARSE_LIST ],
2220 src_port: [ "port", null, PARSE_LIST ],
2221
2222 dest_ip: [ "network", null, PARSE_LIST ],
2223 dest_port: [ "port", null, PARSE_LIST ],
2224
2225 icmp_type: [ "icmptype", null, PARSE_LIST ],
2226 extra: [ "string", null, UNSUPPORTED ],
2227
2228 limit: [ "limit" ],
2229 limit_burst: [ "int" ],
2230
2231 utc_time: [ "bool" ],
2232 start_date: [ "date" ],
2233 stop_date: [ "date" ],
2234 start_time: [ "time" ],
2235 stop_time: [ "time" ],
2236 weekdays: [ "weekdays" ],
2237 monthdays: [ "monthdays", null, UNSUPPORTED ],
2238
2239 mark: [ "mark" ],
2240 set_mark: [ "mark", null, NO_INVERT ],
2241 set_xmark: [ "mark", null, NO_INVERT ],
2242
2243 dscp: [ "dscp" ],
2244 set_dscp: [ "dscp", null, NO_INVERT ],
2245
2246 counter: [ "bool", "1" ],
2247 log: [ "string" ],
2248
2249 target: [ "target" ]
2250 });
2251
2252 if (rule === false) {
2253 this.warn_section(data, "skipped due to invalid options");
2254 return;
2255 }
2256 else if (!rule.enabled) {
2257 this.warn_section(data, "is disabled, ignoring section");
2258 return;
2259 }
2260
2261 if (rule.target in ["helper", "notrack"] && (!rule.src || !rule.src.zone)) {
2262 this.warn_section(data, `must specify a source zone for target '${rule.target}'`);
2263 return;
2264 }
2265 else if (rule.target == "dscp" && !rule.set_dscp) {
2266 this.warn_section(data, "must specify option 'set_dscp' for target 'dscp'");
2267 return;
2268 }
2269 else if (rule.target == "mark" && !rule.set_mark && !rule.set_xmark) {
2270 this.warn_section(data, "must specify option 'set_mark' or 'set_xmark' for target 'mark'");
2271 return;
2272 }
2273 else if (rule.target == "helper" && !rule.set_helper) {
2274 this.warn_section(data, "must specify option 'set_helper' for target 'helper'");
2275 return;
2276 }
2277 else if (rule.device?.any) {
2278 this.warn_section(data, "must not specify '*' as device");
2279 return;
2280 }
2281
2282 switch (this.parse_bool(rule.log)) {
2283 case true:
2284 rule.log = rule.name;
2285 break;
2286
2287 case false:
2288 delete rule.log;
2289 }
2290
2291 let ipset;
2292
2293 if (rule.ipset) {
2294 ipset = filter(this.state.ipsets, s => (s.name == rule.ipset.name))[0];
2295
2296 if (!ipset) {
2297 this.warn_section(data, `references unknown set '${rule.ipset.name}'`);
2298 return;
2299 }
2300
2301 if (('inet_service' in ipset.types) && !ensure_tcpudp(rule.proto)) {
2302 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2303 return;
2304 }
2305 }
2306
2307 let need_src_action_chain = (rule) => (rule.src?.zone?.log && rule.target != "accept");
2308
2309 let add_rule = (family, proto, saddrs, daddrs, sports, dports, icmptypes, icmpcodes, ipset, rule) => {
2310 let r = {
2311 ...rule,
2312
2313 family: family,
2314 proto: proto,
2315 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2316 has_ports: !!(length(sports) || length(dports)),
2317 saddrs_pos: map(saddrs[0], this.cidr),
2318 saddrs_neg: map(saddrs[1], this.cidr),
2319 saddrs_masked: saddrs[2],
2320 daddrs_pos: map(daddrs[0], this.cidr),
2321 daddrs_neg: map(daddrs[1], this.cidr),
2322 daddrs_masked: daddrs[2],
2323 sports_pos: map(filter_pos(sports), this.port),
2324 sports_neg: map(filter_neg(sports), this.port),
2325 dports_pos: map(filter_pos(dports), this.port),
2326 dports_neg: map(filter_neg(dports), this.port),
2327 smacs_pos: map(filter_pos(rule.src_mac), m => m.mac),
2328 smacs_neg: map(filter_neg(rule.src_mac), m => m.mac),
2329 icmp_types: map(icmptypes, i => (family == 4 ? i.type : i.type6)),
2330 icmp_codes: map(icmpcodes, ic => `${(family == 4) ? ic.type : ic.type6} . ${(family == 4) ? ic.code_min : ic.code6_min}`)
2331 };
2332
2333 if (!length(r.icmp_types))
2334 delete r.icmp_types;
2335
2336 if (!length(r.icmp_codes))
2337 delete r.icmp_codes;
2338
2339 if (r.set_mark) {
2340 r.set_xmark = {
2341 invert: r.set_mark.invert,
2342 mark: r.set_mark.mark,
2343 mask: r.set_mark.mark | r.set_mark.mask
2344 };
2345
2346 delete r.set_mark;
2347 }
2348
2349 let set_types = map_setmatch(ipset, rule.ipset, proto.name);
2350
2351 if (set_types !== set_types) {
2352 this.warn_section(data, "destination MAC address matching not supported");
2353 return;
2354 } else if (set_types) {
2355 r.ipset = { ...r.ipset, fields: set_types };
2356 }
2357
2358 if (r.target == "notrack") {
2359 r.chain = `notrack_${r.src.zone.name}`;
2360 r.src.zone.dflags.notrack = true;
2361 }
2362 else if (r.target == "helper") {
2363 r.chain = `helper_${r.src.zone.name}`;
2364 r.src.zone.dflags.helper = true;
2365 }
2366 else if (r.target == "mark" || r.target == "dscp") {
2367 if ((r.src?.any && r.dest?.any) || (r.src?.zone && r.dest?.zone))
2368 r.chain = "mangle_forward";
2369 else if (r.src?.any && r.dest?.zone)
2370 r.chain = "mangle_postrouting";
2371 else if (r.src?.zone && r.dest?.any)
2372 r.chain = "mangle_prerouting";
2373 else if (r.src && !r.dest)
2374 r.chain = "mangle_input";
2375 else
2376 r.chain = "mangle_output";
2377
2378 if (r.src?.zone) {
2379 r.src.zone.dflags[r.target] = true;
2380 r.iifnames = null_if_empty(r.src.zone.match_devices);
2381 }
2382
2383 if (r.dest?.zone) {
2384 r.dest.zone.dflags[r.target] = true;
2385 r.oifnames = null_if_empty(r.dest.zone.match_devices);
2386 }
2387 }
2388 else {
2389 r.chain = "output";
2390
2391 if (r.src) {
2392 if (!r.src.any)
2393 r.chain = `${r.dest ? "forward" : "input"}_${r.src.zone.name}`;
2394 else
2395 r.chain = r.dest ? "forward" : "input";
2396 }
2397
2398 if (r.dest && !r.src) {
2399 if (!r.dest.any)
2400 r.chain = sprintf("output_%s", r.dest.zone.name);
2401 else
2402 r.chain = "output";
2403 }
2404
2405 if (r.dest && !r.dest.any) {
2406 r.jump_chain = `${r.target}_to_${r.dest.zone.name}`;
2407 r.dest.zone.dflags[r.target] = true;
2408 }
2409 else if (need_src_action_chain(r)) {
2410 r.jump_chain = `${r.target}_from_${r.src.zone.name}`;
2411 r.src.zone.sflags[r.target] = true;
2412 }
2413 else if (r.target == "reject")
2414 r.jump_chain = "handle_reject";
2415 }
2416
2417 if (r.device)
2418 r[r.direction ? "oifnames" : "iifnames"] = [ r.device.device ];
2419
2420 push(this.state.rules ||= [], r);
2421 };
2422
2423 for (let proto in rule.proto) {
2424 let sip, dip, sports, dports, itypes4, itypes6;
2425 let family = rule.family;
2426
2427 switch (proto.name) {
2428 case "icmp":
2429 itypes4 = filter(rule.icmp_type || [], family_is_ipv4);
2430 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2431 break;
2432
2433 case "ipv6-icmp":
2434 family = 6;
2435 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2436 break;
2437
2438 case "tcp":
2439 case "udp":
2440 sports = rule.src_port;
2441 dports = rule.dest_port;
2442 break;
2443 }
2444
2445 sip = subnets_split_af(rule.src_ip);
2446 dip = subnets_split_af(rule.dest_ip);
2447
2448 family = infer_family(family, [
2449 ipset, "set match",
2450 sip, "source IP",
2451 dip, "destination IP",
2452 rule.src?.zone, "source zone",
2453 rule.dest?.zone, "destination zone",
2454 rule.helper, "helper match",
2455 rule.set_helper, "helper to set"
2456 ]);
2457
2458 if (type(family) == "string") {
2459 this.warn_section(data, `${family}, skipping`);
2460 continue;
2461 }
2462
2463 let has_ipv4_specifics = (length(sip[0]) || length(dip[0]) || length(itypes4) || rule.dscp !== null);
2464 let has_ipv6_specifics = (length(sip[1]) || length(dip[1]) || length(itypes6) || rule.dscp !== null);
2465
2466 /* if no family was configured, infer target family from IP addresses */
2467 if (family === null) {
2468 if (has_ipv4_specifics && !has_ipv6_specifics)
2469 family = 4;
2470 else if (has_ipv6_specifics && !has_ipv4_specifics)
2471 family = 6;
2472 else
2473 family = 0;
2474 }
2475
2476 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2477 if (!family && rule.target != "dscp" && !has_ipv4_specifics && !has_ipv6_specifics) {
2478 add_rule(0, proto, [], [], sports, dports, null, null, null, rule);
2479 }
2480
2481 /* we need to emit one or two AF specific rules */
2482 else {
2483 if (family == 0 || family == 4) {
2484 let icmp_types = filter(itypes4, i => (i.code_min == 0 && i.code_max == 0xFF));
2485 let icmp_codes = filter(itypes4, i => (i.code_min != 0 || i.code_max != 0xFF));
2486
2487 for (let saddrs in subnets_group_by_masking(sip[0])) {
2488 for (let daddrs in subnets_group_by_masking(dip[0])) {
2489 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2490 add_rule(4, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2491
2492 if (length(icmp_codes))
2493 add_rule(4, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2494 }
2495 }
2496 }
2497
2498 if (family == 0 || family == 6) {
2499 let icmp_types = filter(itypes6, i => (i.code_min == 0 && i.code_max == 0xFF));
2500 let icmp_codes = filter(itypes6, i => (i.code_min != 0 || i.code_max != 0xFF));
2501
2502 for (let saddrs in subnets_group_by_masking(sip[1])) {
2503 for (let daddrs in subnets_group_by_masking(dip[1])) {
2504 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2505 add_rule(6, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2506
2507 if (length(icmp_codes))
2508 add_rule(6, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2509 }
2510 }
2511 }
2512 }
2513 }
2514 },
2515
2516 parse_redirect: function(data) {
2517 let redir = this.parse_options(data, {
2518 enabled: [ "bool", "1" ],
2519
2520 name: [ "string", this.section_id(data[".name"]) ],
2521 _name: [ "string", null, DEPRECATED ],
2522 family: [ "family" ],
2523
2524 src: [ "zone_ref" ],
2525 dest: [ "zone_ref" ],
2526
2527 ipset: [ "setmatch" ],
2528 helper: [ "cthelper", null, NO_INVERT ],
2529
2530 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2531
2532 src_ip: [ "network" ],
2533 src_mac: [ "mac", null, PARSE_LIST ],
2534 src_port: [ "port" ],
2535
2536 src_dip: [ "network" ],
2537 src_dport: [ "port" ],
2538
2539 dest_ip: [ "network" ],
2540 dest_port: [ "port" ],
2541
2542 extra: [ "string", null, UNSUPPORTED ],
2543
2544 limit: [ "limit" ],
2545 limit_burst: [ "int" ],
2546
2547 utc_time: [ "bool" ],
2548 start_date: [ "date" ],
2549 stop_date: [ "date" ],
2550 start_time: [ "time" ],
2551 stop_time: [ "time" ],
2552 weekdays: [ "weekdays" ],
2553 monthdays: [ "monthdays", null, UNSUPPORTED ],
2554
2555 mark: [ "mark" ],
2556
2557 reflection: [ "bool", "1" ],
2558 reflection_src: [ "reflection_source", "internal" ],
2559
2560 reflection_zone: [ "zone_ref", null, PARSE_LIST ],
2561
2562 counter: [ "bool", "1" ],
2563 log: [ "string" ],
2564
2565 target: [ "target", "dnat" ]
2566 });
2567
2568 if (redir === false) {
2569 this.warn_section(data, "skipped due to invalid options");
2570 return;
2571 }
2572 else if (!redir.enabled) {
2573 this.warn_section(data, "is disabled, ignoring section");
2574 return;
2575 }
2576
2577 if (!(redir.target in ["dnat", "snat"])) {
2578 this.warn_section(data, "has invalid target specified, defaulting to dnat");
2579 redir.target = "dnat";
2580 }
2581
2582 switch (this.parse_bool(redir.log)) {
2583 case true:
2584 redir.log = redir.name;
2585 break;
2586
2587 case false:
2588 delete redir.log;
2589 }
2590
2591 let ipset;
2592
2593 if (redir.ipset) {
2594 ipset = filter(this.state.ipsets, s => (s.name == redir.ipset.name))[0];
2595
2596 if (!ipset) {
2597 this.warn_section(data, `references unknown set '${redir.ipset.name}'`);
2598 return;
2599 }
2600
2601 if (('inet_service' in ipset.types) && !ensure_tcpudp(redir.proto)) {
2602 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2603 return;
2604 }
2605 }
2606
2607 let resolve_dest = (redir) => {
2608 for (let zone in this.state.zones) {
2609 for (let zone_addr in zone.related_subnets) {
2610 for (let dest_addr in redir.dest_ip.addrs) {
2611 if (dest_addr.family != zone_addr.family)
2612 continue;
2613
2614 let a = apply_mask(dest_addr.addr, zone_addr.mask);
2615 let b = apply_mask(zone_addr.addr, zone_addr.mask);
2616
2617 if (a != b)
2618 continue;
2619
2620 redir.dest = {
2621 any: false,
2622 zone: zone
2623 };
2624
2625 return true;
2626 }
2627 }
2628 }
2629
2630 return false;
2631 };
2632
2633 if (redir.target == "dnat") {
2634 if (!redir.src)
2635 return this.warn_section(data, "has no source specified");
2636 else if (redir.src.any)
2637 return this.warn_section(data, "must not have source '*' for dnat target");
2638 else if (redir.dest_ip && redir.dest_ip.invert)
2639 return this.warn_section(data, "must not specify a negated 'dest_ip' value");
2640 else if (redir.dest_ip && length(filter(redir.dest_ip.addrs, a => a.bits == -1)))
2641 return this.warn_section(data, "must not use non-contiguous masks in 'dest_ip'");
2642
2643 if (!redir.dest && redir.dest_ip && resolve_dest(redir))
2644 this.warn_section(data, `does not specify a destination, assuming '${redir.dest.zone.name}'`);
2645
2646 if (!redir.dest_port)
2647 redir.dest_port = redir.src_dport;
2648
2649 if (redir.reflection && redir.dest?.zone && redir.src.zone.masq) {
2650 redir.dest.zone.dflags.accept = true;
2651 redir.dest.zone.dflags.dnat = true;
2652 redir.dest.zone.dflags.snat = true;
2653 }
2654
2655 if (redir.helper)
2656 redir.src.zone.dflags.helper = true;
2657
2658 redir.src.zone.dflags[redir.target] = true;
2659 }
2660 else {
2661 if (!redir.dest)
2662 return this.warn_section(data, "has no destination specified");
2663 else if (redir.dest.any)
2664 return this.warn_section(data, "must not have destination '*' for snat target");
2665 else if (!redir.src_dip)
2666 return this.warn_section(data, "has no 'src_dip' option specified");
2667 else if (redir.src_dip.invert)
2668 return this.warn_section(data, "must not specify a negated 'src_dip' value");
2669 else if (length(filter(redir.src_dip.addrs, a => a.bits == -1)))
2670 return this.warn_section(data, "must not use non-contiguous masks in 'src_dip'");
2671 else if (redir.src_mac)
2672 return this.warn_section(data, "must not use 'src_mac' option for snat target");
2673 else if (redir.helper)
2674 return this.warn_section(data, "must not use 'helper' option for snat target");
2675
2676 redir.dest.zone.dflags[redir.target] = true;
2677 }
2678
2679 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, ipset, redir) => {
2680 let r = {
2681 ...redir,
2682
2683 family: family,
2684 proto: proto,
2685 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2686 has_ports: !!(sport || dport || rport),
2687 saddrs_pos: map(saddrs[0], this.cidr),
2688 saddrs_neg: map(saddrs[1], this.cidr),
2689 saddrs_masked: saddrs[2],
2690 daddrs_pos: map(daddrs[0], this.cidr),
2691 daddrs_neg: map(daddrs[1], this.cidr),
2692 daddrs_masked: daddrs[2],
2693 sports_pos: map(filter_pos(to_array(sport)), this.port),
2694 sports_neg: map(filter_neg(to_array(sport)), this.port),
2695 dports_pos: map(filter_pos(to_array(dport)), this.port),
2696 dports_neg: map(filter_neg(to_array(dport)), this.port),
2697 smacs_pos: map(filter_pos(redir.src_mac), m => m.mac),
2698 smacs_neg: map(filter_neg(redir.src_mac), m => m.mac),
2699
2700 raddr: raddrs ? raddrs[0] : null,
2701 rport: rport
2702 };
2703
2704 let set_types = map_setmatch(ipset, redir.ipset, proto.name);
2705
2706 if (set_types !== set_types) {
2707 this.warn_section(data, "destination MAC address matching not supported");
2708 return;
2709 } else if (set_types) {
2710 r.ipset = { ...r.ipset, fields: set_types };
2711 }
2712
2713 switch (r.target) {
2714 case "dnat":
2715 r.chain = `dstnat_${r.src.zone.name}`;
2716 r.src.zone.dflags.dnat = true;
2717
2718 if (!r.raddr)
2719 r.target = "redirect";
2720
2721 break;
2722
2723 case "snat":
2724 r.chain = `srcnat_${r.dest.zone.name}`;
2725 r.dest.zone.dflags.snat = true;
2726 break;
2727 }
2728
2729 push(this.state.redirects ||= [], r);
2730 };
2731
2732 let to_hostaddr = (a) => {
2733 let bits = (a.family == 4) ? 32 : 128;
2734
2735 return {
2736 family: a.family,
2737 addr: apply_mask(a.addr, bits),
2738 bits: bits
2739 };
2740 };
2741
2742 for (let proto in redir.proto) {
2743 let sip, dip, rip, iip, eip, refip, sport, dport, rport;
2744 let family = redir.family;
2745
2746 if (proto.name == "ipv6-icmp")
2747 family = 6;
2748
2749 switch (redir.target) {
2750 case "dnat":
2751 sip = subnets_split_af(redir.src_ip);
2752 dip = subnets_split_af(redir.src_dip);
2753 rip = subnets_split_af(redir.dest_ip);
2754
2755 switch (proto.name) {
2756 case "tcp":
2757 case "udp":
2758 sport = redir.src_port;
2759 dport = redir.src_dport;
2760 rport = redir.dest_port;
2761 break;
2762 }
2763
2764 break;
2765
2766 case "snat":
2767 sip = subnets_split_af(redir.src_ip);
2768 dip = subnets_split_af(redir.dest_ip);
2769 rip = subnets_split_af(redir.src_dip);
2770
2771 switch (proto.name) {
2772 case "tcp":
2773 case "udp":
2774 sport = redir.src_port;
2775 dport = redir.dest_port;
2776 rport = redir.src_dport;
2777 break;
2778 }
2779
2780 break;
2781 }
2782
2783 family = infer_family(family, [
2784 ipset, "set match",
2785 sip, "source IP",
2786 dip, "destination IP",
2787 rip, "rewrite IP",
2788 redir.src?.zone, "source zone",
2789 redir.dest?.zone, "destination zone",
2790 redir.helper, "helper match"
2791 ]);
2792
2793 if (type(family) == "string") {
2794 this.warn_section(data, `${family}, skipping`);
2795 continue;
2796 }
2797
2798 /* build reflection rules */
2799 if (redir.target == "dnat" && redir.reflection &&
2800 (length(rip[0]) || length(rip[1])) && redir.src?.zone && redir.dest?.zone) {
2801 let refredir = {
2802 name: `${redir.name} (reflection)`,
2803
2804 helper: redir.helper,
2805
2806 // XXX: this likely makes no sense for reflection rules
2807 //src_mac: redir.src_mac,
2808
2809 limit: redir.limit,
2810 limit_burst: redir.limit_burst,
2811
2812 start_date: redir.start_date,
2813 stop_date: redir.stop_date,
2814 start_time: redir.start_time,
2815 stop_time: redir.stop_time,
2816 weekdays: redir.weekdays,
2817
2818 mark: redir.mark
2819 };
2820
2821 let eaddrs = length(dip) ? dip : subnets_split_af({ addrs: map(redir.src.zone.related_subnets, to_hostaddr) });
2822 let rzones = length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
2823
2824 for (let rzone in rzones) {
2825 if (!is_family(rzone, family)) {
2826 this.warn_section(data,
2827 `is restricted to IPv${family} but referenced reflection zone is IPv${rzone.family} only, skipping`);
2828 continue;
2829 }
2830
2831 let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
2832 let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
2833
2834 for (let i = 0; i <= 1; i++) {
2835 if (redir.src.zone[i ? "masq6" : "masq"] && length(rip[i])) {
2836 let snat_addr = refaddrs[i]?.[0];
2837
2838 /* For internal reflection sources try to find a suitable candiate IP
2839 * among the reflection zone subnets which is within the same subnet
2840 * as the original DNAT destination. If we can't find any matching
2841 * one then simply take the first candidate. */
2842 if (redir.reflection_src == "internal") {
2843 for (let zone_addr in rzone.zone.related_subnets) {
2844 if (zone_addr.family != rip[i][0].family)
2845 continue;
2846
2847 let r = apply_mask(rip[i][0].addr, zone_addr.mask);
2848 let a = apply_mask(zone_addr.addr, zone_addr.mask);
2849
2850 if (r != a)
2851 continue;
2852
2853 snat_addr = zone_addr;
2854 break;
2855 }
2856 }
2857
2858 if (!snat_addr) {
2859 this.warn_section(data, `${redir.reflection_src || "external"} rewrite IP cannot be determined, disabling reflection`);
2860 }
2861 else if (!length(iaddrs[i])) {
2862 this.warn_section(data, "internal address range cannot be determined, disabling reflection");
2863 }
2864 else if (!length(eaddrs[i])) {
2865 this.warn_section(data, "external address range cannot be determined, disabling reflection");
2866 }
2867 else {
2868 refredir.src = rzone;
2869 refredir.dest = null;
2870 refredir.target = "dnat";
2871
2872 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2873 for (let daddrs in subnets_group_by_masking(eaddrs[i]))
2874 add_rule(i ? 6 : 4, proto, saddrs, daddrs, rip[i], sport, dport, rport, null, refredir);
2875
2876 refredir.src = null;
2877 refredir.dest = rzone;
2878 refredir.target = "snat";
2879
2880 for (let daddrs in subnets_group_by_masking(rip[i]))
2881 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2882 add_rule(i ? 6 : 4, proto, saddrs, daddrs, [ to_hostaddr(snat_addr) ], null, rport, null, null, refredir);
2883 }
2884 }
2885 }
2886 }
2887 }
2888
2889 if (length(rip[0]) > 1 || length(rip[1]) > 1)
2890 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
2891
2892 let has_ip4_addr = length(sip[0]) || length(dip[0]) || length(rip[0]),
2893 has_ip6_addr = length(sip[1]) || length(dip[1]) || length(rip[1]),
2894 has_any_addr = has_ip4_addr || has_ip6_addr;
2895
2896 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2897 if (!family && !has_any_addr) {
2898 /* for backwards compatibility, treat unspecified family as IPv4 unless user explicitly requested any (0) */
2899 if (family == null)
2900 family = 4;
2901
2902 add_rule(family, proto, [], [], null, sport, dport, rport, null, redir);
2903 }
2904
2905 /* we need to emit one or two AF specific rules */
2906 else {
2907 if ((!family || family == 4) && (!has_any_addr || has_ip4_addr)) {
2908 for (let saddrs in subnets_group_by_masking(sip[0]))
2909 for (let daddrs in subnets_group_by_masking(dip[0]))
2910 add_rule(4, proto, saddrs, daddrs, rip[0], sport, dport, rport, ipset, redir);
2911 }
2912
2913 if ((!family || family == 6) && (!has_any_addr || has_ip6_addr)) {
2914 for (let saddrs in subnets_group_by_masking(sip[1]))
2915 for (let daddrs in subnets_group_by_masking(dip[1]))
2916 add_rule(6, proto, saddrs, daddrs, rip[1], sport, dport, rport, ipset, redir);
2917 }
2918 }
2919 }
2920 },
2921
2922 parse_nat: function(data) {
2923 let snat = this.parse_options(data, {
2924 enabled: [ "bool", "1" ],
2925
2926 name: [ "string", this.section_id(data[".name"]) ],
2927 family: [ "family" ],
2928
2929 src: [ "zone_ref" ],
2930 device: [ "string" ],
2931
2932 ipset: [ "setmatch", null, UNSUPPORTED ],
2933
2934 proto: [ "protocol", "all", PARSE_LIST | FLATTEN_LIST ],
2935
2936 src_ip: [ "network" ],
2937 src_port: [ "port" ],
2938
2939 snat_ip: [ "network", null, NO_INVERT ],
2940 snat_port: [ "port", null, NO_INVERT ],
2941
2942 dest_ip: [ "network" ],
2943 dest_port: [ "port" ],
2944
2945 extra: [ "string", null, UNSUPPORTED ],
2946
2947 limit: [ "limit" ],
2948 limit_burst: [ "int" ],
2949
2950 connlimit_ports: [ "bool" ],
2951
2952 utc_time: [ "bool" ],
2953 start_date: [ "date" ],
2954 stop_date: [ "date" ],
2955 start_time: [ "time" ],
2956 stop_time: [ "time" ],
2957 weekdays: [ "weekdays" ],
2958 monthdays: [ "monthdays", null, UNSUPPORTED ],
2959
2960 mark: [ "mark" ],
2961
2962 target: [ "target", "masquerade" ]
2963 });
2964
2965 if (snat === false) {
2966 this.warn_section(data, "skipped due to invalid options");
2967 return;
2968 }
2969 else if (!snat.enabled) {
2970 this.warn_section(data, "is disabled, ignoring section");
2971 return;
2972 }
2973
2974 if (!(snat.target in ["accept", "snat", "masquerade"])) {
2975 this.warn_section(data, "has invalid target specified, defaulting to masquerade");
2976 snat.target = "masquerade";
2977 }
2978
2979 if (snat.target == "snat" && !snat.snat_ip && !snat.snat_port) {
2980 this.warn_section(data, "needs either 'snat_ip' or 'snat_port' for target snat, ignoring section");
2981 return;
2982 }
2983 else if (snat.target != "snat" && snat.snat_ip) {
2984 this.warn_section(data, "must not use 'snat_ip' for non-snat target, ignoring section");
2985 return;
2986 }
2987 else if (snat.target != "snat" && snat.snat_port) {
2988 this.warn_section(data, "must not use 'snat_port' for non-snat target, ignoring section");
2989 return;
2990 }
2991
2992 if ((snat.snat_port || snat.src_port || snat.dest_port) && !ensure_tcpudp(snat.proto)) {
2993 this.warn_section(data, "specifies ports but no UDP/TCP protocol, ignoring section");
2994 return;
2995 }
2996
2997 if (snat.snat_ip && length(filter(snat.snat_ip.addrs, a => a.bits == -1 || a.invert))) {
2998 this.warn_section(data, "must not use inversion or non-contiguous masks in 'snat_ip', ignoring section");
2999 return;
3000 }
3001
3002 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, snat) => {
3003 let n = {
3004 ...snat,
3005
3006 family: family,
3007 proto: proto,
3008 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
3009 has_ports: !!(sport || dport),
3010 saddrs_pos: map(saddrs[0], this.cidr),
3011 saddrs_neg: map(saddrs[1], this.cidr),
3012 saddrs_masked: saddrs[2],
3013 daddrs_pos: map(daddrs[0], this.cidr),
3014 daddrs_neg: map(daddrs[1], this.cidr),
3015 daddrs_masked: daddrs[2],
3016 sports_pos: map(filter_pos(to_array(sport)), this.port),
3017 sports_neg: map(filter_neg(to_array(sport)), this.port),
3018 dports_pos: map(filter_pos(to_array(dport)), this.port),
3019 dports_neg: map(filter_neg(to_array(dport)), this.port),
3020
3021 raddr: raddrs ? raddrs[0] : null,
3022 rport: rport,
3023
3024 chain: snat.src?.zone ? `srcnat_${snat.src.zone.name}` : "srcnat"
3025 };
3026
3027 push(this.state.redirects ||= [], n);
3028 };
3029
3030 for (let proto in snat.proto) {
3031 let sip, dip, rip, sport, dport, rport;
3032 let family = snat.family;
3033
3034 sip = subnets_split_af(snat.src_ip);
3035 dip = subnets_split_af(snat.dest_ip);
3036 rip = subnets_split_af(snat.snat_ip);
3037
3038 switch (proto.name) {
3039 case "tcp":
3040 case "udp":
3041 sport = snat.src_port;
3042 dport = snat.dest_port;
3043 rport = snat.snat_port;
3044 break;
3045 }
3046
3047 if (length(rip[0]) > 1 || length(rip[1]) > 1)
3048 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
3049
3050 family = infer_family(family, [
3051 sip, "source IP",
3052 dip, "destination IP",
3053 rip, "rewrite IP",
3054 snat.src?.zone, "source zone"
3055 ]);
3056
3057 if (type(family) == "string") {
3058 this.warn_section(data, `${family}, skipping`);
3059 continue;
3060 }
3061
3062 if (snat.src?.zone)
3063 snat.src.zone.dflags.snat = true;
3064
3065 /* if no family was configured, infer target family from IP addresses */
3066 if (family === null) {
3067 if ((length(sip[0]) || length(dip[0]) || length(rip[0])) && !length(sip[1]) && !length(dip[1]) && !length(rip[1]))
3068 family = 4;
3069 else if ((length(sip[1]) || length(dip[1]) || length(rip[1])) && !length(sip[0]) && !length(dip[0]) && !length(rip[0]))
3070 family = 6;
3071 else
3072 family = 4; /* default to IPv4 only for backwards compatibility, unless an explict family any was configured */
3073 }
3074
3075 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
3076 if (!family && !length(sip[0]) && !length(sip[1]) && !length(dip[0]) && !length(dip[1]) && !length(rip[0]) && !length(rip[1])) {
3077 add_rule(0, proto, [], [], null, sport, dport, rport, snat);
3078 }
3079
3080 /* we need to emit one or two AF specific rules */
3081 else {
3082 if (family == 0 || family == 4)
3083 for (let saddr in subnets_group_by_masking(sip[0]))
3084 for (let daddr in subnets_group_by_masking(dip[0]))
3085 add_rule(4, proto, saddr, daddr, rip[0], sport, dport, rport, snat);
3086
3087 if (family == 0 || family == 6)
3088 for (let saddr in subnets_group_by_masking(sip[1]))
3089 for (let daddr in subnets_group_by_masking(dip[1]))
3090 add_rule(6, proto, saddr, daddr, rip[1], sport, dport, rport, snat);
3091 }
3092 }
3093 },
3094
3095 parse_include: function(data) {
3096 let inc = this.parse_options(data, {
3097 enabled: [ "bool", "1" ],
3098
3099 path: [ "string", null, REQUIRED ],
3100 type: [ "includetype", "script" ],
3101
3102 fw4_compatible: [ "bool", data.path != "/etc/firewall.user" ],
3103
3104 family: [ "family", null, UNSUPPORTED ],
3105 reload: [ "bool", null, UNSUPPORTED ],
3106
3107 position: [ "includeposition" ],
3108 chain: [ "string" ]
3109 });
3110
3111 if (inc.type == "script" && !inc.fw4_compatible) {
3112 this.warn_section(data, "is not marked as compatible with fw4, ignoring section");
3113 this.warn_section(data, "requires 'option fw4_compatible 1' to be considered compatible");
3114 return;
3115 }
3116
3117 for (let opt in [ "table", "chain", "position" ]) {
3118 if (inc.type != "nftables" && inc[opt]) {
3119 this.warn_section(data, `must not specify '${opt}' for non-nftables includes, ignoring section`);
3120 return;
3121 }
3122 }
3123
3124 switch (inc.position ??= 'table-append') {
3125 case 'ruleset-prepend':
3126 case 'ruleset-append':
3127 case 'table-prepend':
3128 case 'table-append':
3129 if (inc.chain)
3130 this.warn_section(data, `specifies 'chain' which has no effect for position ${inc.position}`);
3131
3132 delete inc.chain;
3133 break;
3134
3135 case 'chain-prepend':
3136 case 'chain-append':
3137 if (!inc.chain) {
3138 this.warn_section(data, `must specify 'chain' for position ${inc.position}, ignoring section`);
3139 return;
3140 }
3141
3142 break;
3143 }
3144
3145 let path = fs.readlink(inc.path) ?? inc.path;
3146
3147 if (!fs.access(path)) {
3148 this.warn_section(data, `specifies unreachable path '${path}', ignoring section`);
3149 return;
3150 }
3151
3152 push(this.state.includes ||= [], { ...inc, path });
3153 },
3154
3155 parse_ipset: function(data) {
3156 let ipset = this.parse_options(data, {
3157 enabled: [ "bool", "1" ],
3158 reload_set: [ "bool" ],
3159 counters: [ "bool" ],
3160 comment: [ "bool" ],
3161
3162 name: [ "string", null, REQUIRED ],
3163 family: [ "family", "4" ],
3164
3165 storage: [ "string", null, UNSUPPORTED ],
3166 match: [ "ipsettype", null, PARSE_LIST ],
3167
3168 iprange: [ "string", null, UNSUPPORTED ],
3169 portrange: [ "string", null, UNSUPPORTED ],
3170
3171 netmask: [ "int", null, UNSUPPORTED ],
3172 maxelem: [ "int" ],
3173 hashsize: [ "int", null, UNSUPPORTED ],
3174 timeout: [ "int", "-1" ],
3175
3176 external: [ "string", null, UNSUPPORTED ],
3177
3178 entry: [ "string", null, PARSE_LIST ],
3179 loadfile: [ "string" ]
3180 });
3181
3182 if (ipset === false) {
3183 this.warn_section(data, "skipped due to invalid options");
3184 return;
3185 }
3186 else if (!ipset.enabled) {
3187 this.warn_section(data, "is disabled, ignoring section");
3188 return;
3189 }
3190
3191 if (ipset.family == 0) {
3192 this.warn_section(data, "must not specify family 'any'");
3193 return;
3194 }
3195 else if (!length(ipset.match)) {
3196 this.warn_section(data, "has no datatypes assigned");
3197 return;
3198 }
3199
3200 let dirs = map(ipset.match, m => m[0]),
3201 types = map(ipset.match, m => m[1]),
3202 interval = false;
3203
3204 if ("set" in types) {
3205 this.warn_section(data, "match type 'set' is not supported");
3206 return;
3207 }
3208
3209 if ("net" in types) {
3210 if (this.kernel < 0x05060000) {
3211 this.warn_section(data, "match type 'net' requires kernel 5.6 or later");
3212 return;
3213 }
3214
3215 interval = true;
3216 }
3217
3218 let s = {
3219 ...ipset,
3220
3221 fw4types: types,
3222
3223 types: map(types, (t) => {
3224 switch (t) {
3225 case 'ip':
3226 case 'net':
3227 return (ipset.family == 4) ? 'ipv4_addr' : 'ipv6_addr';
3228
3229 case 'mac':
3230 return 'ether_addr';
3231
3232 case 'port':
3233 return 'inet_service';
3234 }
3235 }),
3236
3237 directions: dirs,
3238 interval: interval
3239 };
3240
3241 if (s.interval)
3242 push(s.flags ??= [], 'interval');
3243
3244 if (s.timeout >= 0)
3245 push(s.flags ??= [], 'timeout');
3246
3247 s.entries = filter(map(ipset.entry, (e) => {
3248 let v = this.parse_ipsetentry(e, s);
3249
3250 if (!v)
3251 this.warn_section(data, `ignoring invalid ipset entry '${e}'`);
3252
3253 return v;
3254 }), (e) => (e != null));
3255
3256 push(this.state.ipsets ||= [], s);
3257 }
3258 };