e6bd3652141f835763e18abf6932ff80aca23a89
[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
2248 target: [ "target" ]
2249 });
2250
2251 if (rule === false) {
2252 this.warn_section(data, "skipped due to invalid options");
2253 return;
2254 }
2255 else if (!rule.enabled) {
2256 this.warn_section(data, "is disabled, ignoring section");
2257 return;
2258 }
2259
2260 if (rule.target in ["helper", "notrack"] && (!rule.src || !rule.src.zone)) {
2261 this.warn_section(data, `must specify a source zone for target '${rule.target}'`);
2262 return;
2263 }
2264 else if (rule.target == "dscp" && !rule.set_dscp) {
2265 this.warn_section(data, "must specify option 'set_dscp' for target 'dscp'");
2266 return;
2267 }
2268 else if (rule.target == "mark" && !rule.set_mark && !rule.set_xmark) {
2269 this.warn_section(data, "must specify option 'set_mark' or 'set_xmark' for target 'mark'");
2270 return;
2271 }
2272 else if (rule.target == "helper" && !rule.set_helper) {
2273 this.warn_section(data, "must specify option 'set_helper' for target 'helper'");
2274 return;
2275 }
2276 else if (rule.device?.any) {
2277 this.warn_section(data, "must not specify '*' as device");
2278 return;
2279 }
2280
2281 let ipset;
2282
2283 if (rule.ipset) {
2284 ipset = filter(this.state.ipsets, s => (s.name == rule.ipset.name))[0];
2285
2286 if (!ipset) {
2287 this.warn_section(data, `references unknown set '${rule.ipset.name}'`);
2288 return;
2289 }
2290
2291 if (('inet_service' in ipset.types) && !ensure_tcpudp(rule.proto)) {
2292 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2293 return;
2294 }
2295 }
2296
2297 let need_src_action_chain = (rule) => (rule.src?.zone?.log && rule.target != "accept");
2298
2299 let add_rule = (family, proto, saddrs, daddrs, sports, dports, icmptypes, icmpcodes, ipset, rule) => {
2300 let r = {
2301 ...rule,
2302
2303 family: family,
2304 proto: proto,
2305 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2306 has_ports: !!(length(sports) || length(dports)),
2307 saddrs_pos: map(saddrs[0], this.cidr),
2308 saddrs_neg: map(saddrs[1], this.cidr),
2309 saddrs_masked: saddrs[2],
2310 daddrs_pos: map(daddrs[0], this.cidr),
2311 daddrs_neg: map(daddrs[1], this.cidr),
2312 daddrs_masked: daddrs[2],
2313 sports_pos: map(filter_pos(sports), this.port),
2314 sports_neg: map(filter_neg(sports), this.port),
2315 dports_pos: map(filter_pos(dports), this.port),
2316 dports_neg: map(filter_neg(dports), this.port),
2317 smacs_pos: map(filter_pos(rule.src_mac), m => m.mac),
2318 smacs_neg: map(filter_neg(rule.src_mac), m => m.mac),
2319 icmp_types: map(icmptypes, i => (family == 4 ? i.type : i.type6)),
2320 icmp_codes: map(icmpcodes, ic => `${(family == 4) ? ic.type : ic.type6} . ${(family == 4) ? ic.code_min : ic.code6_min}`)
2321 };
2322
2323 if (!length(r.icmp_types))
2324 delete r.icmp_types;
2325
2326 if (!length(r.icmp_codes))
2327 delete r.icmp_codes;
2328
2329 if (r.set_mark) {
2330 r.set_xmark = {
2331 invert: r.set_mark.invert,
2332 mark: r.set_mark.mark,
2333 mask: r.set_mark.mark | r.set_mark.mask
2334 };
2335
2336 delete r.set_mark;
2337 }
2338
2339 let set_types = map_setmatch(ipset, rule.ipset, proto.name);
2340
2341 if (set_types !== set_types) {
2342 this.warn_section(data, "destination MAC address matching not supported");
2343 return;
2344 } else if (set_types) {
2345 r.ipset = { ...r.ipset, fields: set_types };
2346 }
2347
2348 if (r.target == "notrack") {
2349 r.chain = `notrack_${r.src.zone.name}`;
2350 r.src.zone.dflags.notrack = true;
2351 }
2352 else if (r.target == "helper") {
2353 r.chain = `helper_${r.src.zone.name}`;
2354 r.src.zone.dflags.helper = true;
2355 }
2356 else if (r.target == "mark" || r.target == "dscp") {
2357 if ((r.src?.any && r.dest?.any) || (r.src?.zone && r.dest?.zone))
2358 r.chain = "mangle_forward";
2359 else if (r.src?.any && r.dest?.zone)
2360 r.chain = "mangle_postrouting";
2361 else if (r.src?.zone && r.dest?.any)
2362 r.chain = "mangle_prerouting";
2363 else if (r.src && !r.dest)
2364 r.chain = "mangle_input";
2365 else
2366 r.chain = "mangle_output";
2367
2368 if (r.src?.zone) {
2369 r.src.zone.dflags[r.target] = true;
2370 r.iifnames = null_if_empty(r.src.zone.match_devices);
2371 }
2372
2373 if (r.dest?.zone) {
2374 r.dest.zone.dflags[r.target] = true;
2375 r.oifnames = null_if_empty(r.dest.zone.match_devices);
2376 }
2377 }
2378 else {
2379 r.chain = "output";
2380
2381 if (r.src) {
2382 if (!r.src.any)
2383 r.chain = `${r.dest ? "forward" : "input"}_${r.src.zone.name}`;
2384 else
2385 r.chain = r.dest ? "forward" : "input";
2386 }
2387
2388 if (r.dest && !r.src) {
2389 if (!r.dest.any)
2390 r.chain = sprintf("output_%s", r.dest.zone.name);
2391 else
2392 r.chain = "output";
2393 }
2394
2395 if (r.dest && !r.dest.any) {
2396 r.jump_chain = `${r.target}_to_${r.dest.zone.name}`;
2397 r.dest.zone.dflags[r.target] = true;
2398 }
2399 else if (need_src_action_chain(r)) {
2400 r.jump_chain = `${r.target}_from_${r.src.zone.name}`;
2401 r.src.zone.sflags[r.target] = true;
2402 }
2403 else if (r.target == "reject")
2404 r.jump_chain = "handle_reject";
2405 }
2406
2407 if (r.device)
2408 r[r.direction ? "oifnames" : "iifnames"] = [ r.device.device ];
2409
2410 push(this.state.rules ||= [], r);
2411 };
2412
2413 for (let proto in rule.proto) {
2414 let sip, dip, sports, dports, itypes4, itypes6;
2415 let family = rule.family;
2416
2417 switch (proto.name) {
2418 case "icmp":
2419 itypes4 = filter(rule.icmp_type || [], family_is_ipv4);
2420 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2421 break;
2422
2423 case "ipv6-icmp":
2424 family = 6;
2425 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2426 break;
2427
2428 case "tcp":
2429 case "udp":
2430 sports = rule.src_port;
2431 dports = rule.dest_port;
2432 break;
2433 }
2434
2435 sip = subnets_split_af(rule.src_ip);
2436 dip = subnets_split_af(rule.dest_ip);
2437
2438 family = infer_family(family, [
2439 ipset, "set match",
2440 sip, "source IP",
2441 dip, "destination IP",
2442 rule.src?.zone, "source zone",
2443 rule.dest?.zone, "destination zone",
2444 rule.helper, "helper match",
2445 rule.set_helper, "helper to set"
2446 ]);
2447
2448 if (type(family) == "string") {
2449 this.warn_section(data, `${family}, skipping`);
2450 continue;
2451 }
2452
2453 let has_ipv4_specifics = (length(sip[0]) || length(dip[0]) || length(itypes4) || rule.dscp !== null);
2454 let has_ipv6_specifics = (length(sip[1]) || length(dip[1]) || length(itypes6) || rule.dscp !== null);
2455
2456 /* if no family was configured, infer target family from IP addresses */
2457 if (family === null) {
2458 if (has_ipv4_specifics && !has_ipv6_specifics)
2459 family = 4;
2460 else if (has_ipv6_specifics && !has_ipv4_specifics)
2461 family = 6;
2462 else
2463 family = 0;
2464 }
2465
2466 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2467 if (!family && rule.target != "dscp" && !has_ipv4_specifics && !has_ipv6_specifics) {
2468 add_rule(0, proto, [], [], sports, dports, null, null, null, rule);
2469 }
2470
2471 /* we need to emit one or two AF specific rules */
2472 else {
2473 if (family == 0 || family == 4) {
2474 let icmp_types = filter(itypes4, i => (i.code_min == 0 && i.code_max == 0xFF));
2475 let icmp_codes = filter(itypes4, i => (i.code_min != 0 || i.code_max != 0xFF));
2476
2477 for (let saddrs in subnets_group_by_masking(sip[0])) {
2478 for (let daddrs in subnets_group_by_masking(dip[0])) {
2479 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2480 add_rule(4, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2481
2482 if (length(icmp_codes))
2483 add_rule(4, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2484 }
2485 }
2486 }
2487
2488 if (family == 0 || family == 6) {
2489 let icmp_types = filter(itypes6, i => (i.code_min == 0 && i.code_max == 0xFF));
2490 let icmp_codes = filter(itypes6, i => (i.code_min != 0 || i.code_max != 0xFF));
2491
2492 for (let saddrs in subnets_group_by_masking(sip[1])) {
2493 for (let daddrs in subnets_group_by_masking(dip[1])) {
2494 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2495 add_rule(6, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2496
2497 if (length(icmp_codes))
2498 add_rule(6, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2499 }
2500 }
2501 }
2502 }
2503 }
2504 },
2505
2506 parse_redirect: function(data) {
2507 let redir = this.parse_options(data, {
2508 enabled: [ "bool", "1" ],
2509
2510 name: [ "string", this.section_id(data[".name"]) ],
2511 _name: [ "string", null, DEPRECATED ],
2512 family: [ "family" ],
2513
2514 src: [ "zone_ref" ],
2515 dest: [ "zone_ref" ],
2516
2517 ipset: [ "setmatch" ],
2518 helper: [ "cthelper", null, NO_INVERT ],
2519
2520 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2521
2522 src_ip: [ "network" ],
2523 src_mac: [ "mac", null, PARSE_LIST ],
2524 src_port: [ "port" ],
2525
2526 src_dip: [ "network" ],
2527 src_dport: [ "port" ],
2528
2529 dest_ip: [ "network" ],
2530 dest_port: [ "port" ],
2531
2532 extra: [ "string", null, UNSUPPORTED ],
2533
2534 limit: [ "limit" ],
2535 limit_burst: [ "int" ],
2536
2537 utc_time: [ "bool" ],
2538 start_date: [ "date" ],
2539 stop_date: [ "date" ],
2540 start_time: [ "time" ],
2541 stop_time: [ "time" ],
2542 weekdays: [ "weekdays" ],
2543 monthdays: [ "monthdays", null, UNSUPPORTED ],
2544
2545 mark: [ "mark" ],
2546
2547 reflection: [ "bool", "1" ],
2548 reflection_src: [ "reflection_source", "internal" ],
2549
2550 reflection_zone: [ "zone_ref", null, PARSE_LIST ],
2551
2552 counter: [ "bool", "1" ],
2553
2554 target: [ "target", "dnat" ]
2555 });
2556
2557 if (redir === false) {
2558 this.warn_section(data, "skipped due to invalid options");
2559 return;
2560 }
2561 else if (!redir.enabled) {
2562 this.warn_section(data, "is disabled, ignoring section");
2563 return;
2564 }
2565
2566 if (!(redir.target in ["dnat", "snat"])) {
2567 this.warn_section(data, "has invalid target specified, defaulting to dnat");
2568 redir.target = "dnat";
2569 }
2570
2571 let ipset;
2572
2573 if (redir.ipset) {
2574 ipset = filter(this.state.ipsets, s => (s.name == redir.ipset.name))[0];
2575
2576 if (!ipset) {
2577 this.warn_section(data, `references unknown set '${redir.ipset.name}'`);
2578 return;
2579 }
2580
2581 if (('inet_service' in ipset.types) && !ensure_tcpudp(redir.proto)) {
2582 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2583 return;
2584 }
2585 }
2586
2587 let resolve_dest = (redir) => {
2588 for (let zone in this.state.zones) {
2589 for (let zone_addr in zone.related_subnets) {
2590 for (let dest_addr in redir.dest_ip.addrs) {
2591 if (dest_addr.family != zone_addr.family)
2592 continue;
2593
2594 let a = apply_mask(dest_addr.addr, zone_addr.mask);
2595 let b = apply_mask(zone_addr.addr, zone_addr.mask);
2596
2597 if (a != b)
2598 continue;
2599
2600 redir.dest = {
2601 any: false,
2602 zone: zone
2603 };
2604
2605 return true;
2606 }
2607 }
2608 }
2609
2610 return false;
2611 };
2612
2613 if (redir.target == "dnat") {
2614 if (!redir.src)
2615 return this.warn_section(data, "has no source specified");
2616 else if (redir.src.any)
2617 return this.warn_section(data, "must not have source '*' for dnat target");
2618 else if (redir.dest_ip && redir.dest_ip.invert)
2619 return this.warn_section(data, "must not specify a negated 'dest_ip' value");
2620 else if (redir.dest_ip && length(filter(redir.dest_ip.addrs, a => a.bits == -1)))
2621 return this.warn_section(data, "must not use non-contiguous masks in 'dest_ip'");
2622
2623 if (!redir.dest && redir.dest_ip && resolve_dest(redir))
2624 this.warn_section(data, `does not specify a destination, assuming '${redir.dest.zone.name}'`);
2625
2626 if (!redir.dest_port)
2627 redir.dest_port = redir.src_dport;
2628
2629 if (redir.reflection && redir.dest?.zone && redir.src.zone.masq) {
2630 redir.dest.zone.dflags.accept = true;
2631 redir.dest.zone.dflags.dnat = true;
2632 redir.dest.zone.dflags.snat = true;
2633 }
2634
2635 if (redir.helper)
2636 redir.src.zone.dflags.helper = true;
2637
2638 redir.src.zone.dflags[redir.target] = true;
2639 }
2640 else {
2641 if (!redir.dest)
2642 return this.warn_section(data, "has no destination specified");
2643 else if (redir.dest.any)
2644 return this.warn_section(data, "must not have destination '*' for snat target");
2645 else if (!redir.src_dip)
2646 return this.warn_section(data, "has no 'src_dip' option specified");
2647 else if (redir.src_dip.invert)
2648 return this.warn_section(data, "must not specify a negated 'src_dip' value");
2649 else if (length(filter(redir.src_dip.addrs, a => a.bits == -1)))
2650 return this.warn_section(data, "must not use non-contiguous masks in 'src_dip'");
2651 else if (redir.src_mac)
2652 return this.warn_section(data, "must not use 'src_mac' option for snat target");
2653 else if (redir.helper)
2654 return this.warn_section(data, "must not use 'helper' option for snat target");
2655
2656 redir.dest.zone.dflags[redir.target] = true;
2657 }
2658
2659
2660 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, ipset, redir) => {
2661 let r = {
2662 ...redir,
2663
2664 family: family,
2665 proto: proto,
2666 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2667 has_ports: !!(sport || dport || rport),
2668 saddrs_pos: map(saddrs[0], this.cidr),
2669 saddrs_neg: map(saddrs[1], this.cidr),
2670 saddrs_masked: saddrs[2],
2671 daddrs_pos: map(daddrs[0], this.cidr),
2672 daddrs_neg: map(daddrs[1], this.cidr),
2673 daddrs_masked: daddrs[2],
2674 sports_pos: map(filter_pos(to_array(sport)), this.port),
2675 sports_neg: map(filter_neg(to_array(sport)), this.port),
2676 dports_pos: map(filter_pos(to_array(dport)), this.port),
2677 dports_neg: map(filter_neg(to_array(dport)), this.port),
2678 smacs_pos: map(filter_pos(redir.src_mac), m => m.mac),
2679 smacs_neg: map(filter_neg(redir.src_mac), m => m.mac),
2680
2681 raddr: raddrs ? raddrs[0] : null,
2682 rport: rport
2683 };
2684
2685 let set_types = map_setmatch(ipset, redir.ipset, proto.name);
2686
2687 if (set_types !== set_types) {
2688 this.warn_section(data, "destination MAC address matching not supported");
2689 return;
2690 } else if (set_types) {
2691 r.ipset = { ...r.ipset, fields: set_types };
2692 }
2693
2694 switch (r.target) {
2695 case "dnat":
2696 r.chain = `dstnat_${r.src.zone.name}`;
2697 r.src.zone.dflags.dnat = true;
2698
2699 if (!r.raddr)
2700 r.target = "redirect";
2701
2702 break;
2703
2704 case "snat":
2705 r.chain = `srcnat_${r.dest.zone.name}`;
2706 r.dest.zone.dflags.snat = true;
2707 break;
2708 }
2709
2710 push(this.state.redirects ||= [], r);
2711 };
2712
2713 let to_hostaddr = (a) => {
2714 let bits = (a.family == 4) ? 32 : 128;
2715
2716 return {
2717 family: a.family,
2718 addr: apply_mask(a.addr, bits),
2719 bits: bits
2720 };
2721 };
2722
2723 for (let proto in redir.proto) {
2724 let sip, dip, rip, iip, eip, refip, sport, dport, rport;
2725 let family = redir.family;
2726
2727 if (proto.name == "ipv6-icmp")
2728 family = 6;
2729
2730 switch (redir.target) {
2731 case "dnat":
2732 sip = subnets_split_af(redir.src_ip);
2733 dip = subnets_split_af(redir.src_dip);
2734 rip = subnets_split_af(redir.dest_ip);
2735
2736 switch (proto.name) {
2737 case "tcp":
2738 case "udp":
2739 sport = redir.src_port;
2740 dport = redir.src_dport;
2741 rport = redir.dest_port;
2742 break;
2743 }
2744
2745 break;
2746
2747 case "snat":
2748 sip = subnets_split_af(redir.src_ip);
2749 dip = subnets_split_af(redir.dest_ip);
2750 rip = subnets_split_af(redir.src_dip);
2751
2752 switch (proto.name) {
2753 case "tcp":
2754 case "udp":
2755 sport = redir.src_port;
2756 dport = redir.dest_port;
2757 rport = redir.src_dport;
2758 break;
2759 }
2760
2761 break;
2762 }
2763
2764 family = infer_family(family, [
2765 ipset, "set match",
2766 sip, "source IP",
2767 dip, "destination IP",
2768 rip, "rewrite IP",
2769 redir.src?.zone, "source zone",
2770 redir.dest?.zone, "destination zone",
2771 redir.helper, "helper match"
2772 ]);
2773
2774 if (type(family) == "string") {
2775 this.warn_section(data, `${family}, skipping`);
2776 continue;
2777 }
2778
2779 /* build reflection rules */
2780 if (redir.target == "dnat" && redir.reflection &&
2781 (length(rip[0]) || length(rip[1])) && redir.src?.zone && redir.dest?.zone) {
2782 let refredir = {
2783 name: `${redir.name} (reflection)`,
2784
2785 helper: redir.helper,
2786
2787 // XXX: this likely makes no sense for reflection rules
2788 //src_mac: redir.src_mac,
2789
2790 limit: redir.limit,
2791 limit_burst: redir.limit_burst,
2792
2793 start_date: redir.start_date,
2794 stop_date: redir.stop_date,
2795 start_time: redir.start_time,
2796 stop_time: redir.stop_time,
2797 weekdays: redir.weekdays,
2798
2799 mark: redir.mark
2800 };
2801
2802 let eaddrs = length(dip) ? dip : subnets_split_af({ addrs: map(redir.src.zone.related_subnets, to_hostaddr) });
2803 let rzones = length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
2804
2805 for (let rzone in rzones) {
2806 if (!is_family(rzone, family)) {
2807 this.warn_section(data,
2808 `is restricted to IPv${family} but referenced reflection zone is IPv${rzone.family} only, skipping`);
2809 continue;
2810 }
2811
2812 let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
2813 let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
2814
2815 for (let i = 0; i <= 1; i++) {
2816 if (redir.src.zone[i ? "masq6" : "masq"] && length(rip[i])) {
2817 let snat_addr = refaddrs[i]?.[0];
2818
2819 /* For internal reflection sources try to find a suitable candiate IP
2820 * among the reflection zone subnets which is within the same subnet
2821 * as the original DNAT destination. If we can't find any matching
2822 * one then simply take the first candidate. */
2823 if (redir.reflection_src == "internal") {
2824 for (let zone_addr in rzone.zone.related_subnets) {
2825 if (zone_addr.family != rip[i][0].family)
2826 continue;
2827
2828 let r = apply_mask(rip[i][0].addr, zone_addr.mask);
2829 let a = apply_mask(zone_addr.addr, zone_addr.mask);
2830
2831 if (r != a)
2832 continue;
2833
2834 snat_addr = zone_addr;
2835 break;
2836 }
2837 }
2838
2839 if (!snat_addr) {
2840 this.warn_section(data, `${redir.reflection_src || "external"} rewrite IP cannot be determined, disabling reflection`);
2841 }
2842 else if (!length(iaddrs[i])) {
2843 this.warn_section(data, "internal address range cannot be determined, disabling reflection");
2844 }
2845 else if (!length(eaddrs[i])) {
2846 this.warn_section(data, "external address range cannot be determined, disabling reflection");
2847 }
2848 else {
2849 refredir.src = rzone;
2850 refredir.dest = null;
2851 refredir.target = "dnat";
2852
2853 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2854 for (let daddrs in subnets_group_by_masking(eaddrs[i]))
2855 add_rule(i ? 6 : 4, proto, saddrs, daddrs, rip[i], sport, dport, rport, null, refredir);
2856
2857 refredir.src = null;
2858 refredir.dest = rzone;
2859 refredir.target = "snat";
2860
2861 for (let daddrs in subnets_group_by_masking(rip[i]))
2862 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2863 add_rule(i ? 6 : 4, proto, saddrs, daddrs, [ to_hostaddr(snat_addr) ], null, rport, null, null, refredir);
2864 }
2865 }
2866 }
2867 }
2868 }
2869
2870 if (length(rip[0]) > 1 || length(rip[1]) > 1)
2871 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
2872
2873 let has_ip4_addr = length(sip[0]) || length(dip[0]) || length(rip[0]),
2874 has_ip6_addr = length(sip[1]) || length(dip[1]) || length(rip[1]),
2875 has_any_addr = has_ip4_addr || has_ip6_addr;
2876
2877 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2878 if (!family && !has_any_addr) {
2879 /* for backwards compatibility, treat unspecified family as IPv4 unless user explicitly requested any (0) */
2880 if (family == null)
2881 family = 4;
2882
2883 add_rule(family, proto, [], [], null, sport, dport, rport, null, redir);
2884 }
2885
2886 /* we need to emit one or two AF specific rules */
2887 else {
2888 if ((!family || family == 4) && (!has_any_addr || has_ip4_addr)) {
2889 for (let saddrs in subnets_group_by_masking(sip[0]))
2890 for (let daddrs in subnets_group_by_masking(dip[0]))
2891 add_rule(4, proto, saddrs, daddrs, rip[0], sport, dport, rport, ipset, redir);
2892 }
2893
2894 if ((!family || family == 6) && (!has_any_addr || has_ip6_addr)) {
2895 for (let saddrs in subnets_group_by_masking(sip[1]))
2896 for (let daddrs in subnets_group_by_masking(dip[1]))
2897 add_rule(6, proto, saddrs, daddrs, rip[1], sport, dport, rport, ipset, redir);
2898 }
2899 }
2900 }
2901 },
2902
2903 parse_nat: function(data) {
2904 let snat = this.parse_options(data, {
2905 enabled: [ "bool", "1" ],
2906
2907 name: [ "string", this.section_id(data[".name"]) ],
2908 family: [ "family" ],
2909
2910 src: [ "zone_ref" ],
2911 device: [ "string" ],
2912
2913 ipset: [ "setmatch", null, UNSUPPORTED ],
2914
2915 proto: [ "protocol", "all", PARSE_LIST | FLATTEN_LIST ],
2916
2917 src_ip: [ "network" ],
2918 src_port: [ "port" ],
2919
2920 snat_ip: [ "network", null, NO_INVERT ],
2921 snat_port: [ "port", null, NO_INVERT ],
2922
2923 dest_ip: [ "network" ],
2924 dest_port: [ "port" ],
2925
2926 extra: [ "string", null, UNSUPPORTED ],
2927
2928 limit: [ "limit" ],
2929 limit_burst: [ "int" ],
2930
2931 connlimit_ports: [ "bool" ],
2932
2933 utc_time: [ "bool" ],
2934 start_date: [ "date" ],
2935 stop_date: [ "date" ],
2936 start_time: [ "time" ],
2937 stop_time: [ "time" ],
2938 weekdays: [ "weekdays" ],
2939 monthdays: [ "monthdays", null, UNSUPPORTED ],
2940
2941 mark: [ "mark" ],
2942
2943 target: [ "target", "masquerade" ]
2944 });
2945
2946 if (snat === false) {
2947 this.warn_section(data, "skipped due to invalid options");
2948 return;
2949 }
2950 else if (!snat.enabled) {
2951 this.warn_section(data, "is disabled, ignoring section");
2952 return;
2953 }
2954
2955 if (!(snat.target in ["accept", "snat", "masquerade"])) {
2956 this.warn_section(data, "has invalid target specified, defaulting to masquerade");
2957 snat.target = "masquerade";
2958 }
2959
2960 if (snat.target == "snat" && !snat.snat_ip && !snat.snat_port) {
2961 this.warn_section(data, "needs either 'snat_ip' or 'snat_port' for target snat, ignoring section");
2962 return;
2963 }
2964 else if (snat.target != "snat" && snat.snat_ip) {
2965 this.warn_section(data, "must not use 'snat_ip' for non-snat target, ignoring section");
2966 return;
2967 }
2968 else if (snat.target != "snat" && snat.snat_port) {
2969 this.warn_section(data, "must not use 'snat_port' for non-snat target, ignoring section");
2970 return;
2971 }
2972
2973 if ((snat.snat_port || snat.src_port || snat.dest_port) && !ensure_tcpudp(snat.proto)) {
2974 this.warn_section(data, "specifies ports but no UDP/TCP protocol, ignoring section");
2975 return;
2976 }
2977
2978 if (snat.snat_ip && length(filter(snat.snat_ip.addrs, a => a.bits == -1 || a.invert))) {
2979 this.warn_section(data, "must not use inversion or non-contiguous masks in 'snat_ip', ignoring section");
2980 return;
2981 }
2982
2983 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, snat) => {
2984 let n = {
2985 ...snat,
2986
2987 family: family,
2988 proto: proto,
2989 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2990 has_ports: !!(sport || dport),
2991 saddrs_pos: map(saddrs[0], this.cidr),
2992 saddrs_neg: map(saddrs[1], this.cidr),
2993 saddrs_masked: saddrs[2],
2994 daddrs_pos: map(daddrs[0], this.cidr),
2995 daddrs_neg: map(daddrs[1], this.cidr),
2996 daddrs_masked: daddrs[2],
2997 sports_pos: map(filter_pos(to_array(sport)), this.port),
2998 sports_neg: map(filter_neg(to_array(sport)), this.port),
2999 dports_pos: map(filter_pos(to_array(dport)), this.port),
3000 dports_neg: map(filter_neg(to_array(dport)), this.port),
3001
3002 raddr: raddrs ? raddrs[0] : null,
3003 rport: rport,
3004
3005 chain: snat.src?.zone ? `srcnat_${snat.src.zone.name}` : "srcnat"
3006 };
3007
3008 push(this.state.redirects ||= [], n);
3009 };
3010
3011 for (let proto in snat.proto) {
3012 let sip, dip, rip, sport, dport, rport;
3013 let family = snat.family;
3014
3015 sip = subnets_split_af(snat.src_ip);
3016 dip = subnets_split_af(snat.dest_ip);
3017 rip = subnets_split_af(snat.snat_ip);
3018
3019 switch (proto.name) {
3020 case "tcp":
3021 case "udp":
3022 sport = snat.src_port;
3023 dport = snat.dest_port;
3024 rport = snat.snat_port;
3025 break;
3026 }
3027
3028 if (length(rip[0]) > 1 || length(rip[1]) > 1)
3029 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
3030
3031 family = infer_family(family, [
3032 sip, "source IP",
3033 dip, "destination IP",
3034 rip, "rewrite IP",
3035 snat.src?.zone, "source zone"
3036 ]);
3037
3038 if (type(family) == "string") {
3039 this.warn_section(data, `${family}, skipping`);
3040 continue;
3041 }
3042
3043 if (snat.src?.zone)
3044 snat.src.zone.dflags.snat = true;
3045
3046 /* if no family was configured, infer target family from IP addresses */
3047 if (family === null) {
3048 if ((length(sip[0]) || length(dip[0]) || length(rip[0])) && !length(sip[1]) && !length(dip[1]) && !length(rip[1]))
3049 family = 4;
3050 else if ((length(sip[1]) || length(dip[1]) || length(rip[1])) && !length(sip[0]) && !length(dip[0]) && !length(rip[0]))
3051 family = 6;
3052 else
3053 family = 4; /* default to IPv4 only for backwards compatibility, unless an explict family any was configured */
3054 }
3055
3056 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
3057 if (!family && !length(sip[0]) && !length(sip[1]) && !length(dip[0]) && !length(dip[1]) && !length(rip[0]) && !length(rip[1])) {
3058 add_rule(0, proto, [], [], null, sport, dport, rport, snat);
3059 }
3060
3061 /* we need to emit one or two AF specific rules */
3062 else {
3063 if (family == 0 || family == 4)
3064 for (let saddr in subnets_group_by_masking(sip[0]))
3065 for (let daddr in subnets_group_by_masking(dip[0]))
3066 add_rule(4, proto, saddr, daddr, rip[0], sport, dport, rport, snat);
3067
3068 if (family == 0 || family == 6)
3069 for (let saddr in subnets_group_by_masking(sip[1]))
3070 for (let daddr in subnets_group_by_masking(dip[1]))
3071 add_rule(6, proto, saddr, daddr, rip[1], sport, dport, rport, snat);
3072 }
3073 }
3074 },
3075
3076 parse_include: function(data) {
3077 let inc = this.parse_options(data, {
3078 enabled: [ "bool", "1" ],
3079
3080 path: [ "string", null, REQUIRED ],
3081 type: [ "includetype", "script" ],
3082
3083 fw4_compatible: [ "bool", data.path != "/etc/firewall.user" ],
3084
3085 family: [ "family", null, UNSUPPORTED ],
3086 reload: [ "bool", null, UNSUPPORTED ],
3087
3088 position: [ "includeposition" ],
3089 chain: [ "string" ]
3090 });
3091
3092 if (inc.type == "script" && !inc.fw4_compatible) {
3093 this.warn_section(data, "is not marked as compatible with fw4, ignoring section");
3094 this.warn_section(data, "requires 'option fw4_compatible 1' to be considered compatible");
3095 return;
3096 }
3097
3098 for (let opt in [ "table", "chain", "position" ]) {
3099 if (inc.type != "nftables" && inc[opt]) {
3100 this.warn_section(data, `must not specify '${opt}' for non-nftables includes, ignoring section`);
3101 return;
3102 }
3103 }
3104
3105 switch (inc.position ??= 'table-append') {
3106 case 'ruleset-prepend':
3107 case 'ruleset-append':
3108 case 'table-prepend':
3109 case 'table-append':
3110 if (inc.chain)
3111 this.warn_section(data, `specifies 'chain' which has no effect for position ${inc.position}`);
3112
3113 delete inc.chain;
3114 break;
3115
3116 case 'chain-prepend':
3117 case 'chain-append':
3118 if (!inc.chain) {
3119 this.warn_section(data, `must specify 'chain' for position ${inc.position}, ignoring section`);
3120 return;
3121 }
3122
3123 break;
3124 }
3125
3126 let path = fs.readlink(inc.path) ?? inc.path;
3127
3128 if (!fs.access(path)) {
3129 this.warn_section(data, `specifies unreachable path '${path}', ignoring section`);
3130 return;
3131 }
3132
3133 push(this.state.includes ||= [], { ...inc, path });
3134 },
3135
3136 parse_ipset: function(data) {
3137 let ipset = this.parse_options(data, {
3138 enabled: [ "bool", "1" ],
3139 reload_set: [ "bool" ],
3140 counters: [ "bool" ],
3141 comment: [ "bool" ],
3142
3143 name: [ "string", null, REQUIRED ],
3144 family: [ "family", "4" ],
3145
3146 storage: [ "string", null, UNSUPPORTED ],
3147 match: [ "ipsettype", null, PARSE_LIST ],
3148
3149 iprange: [ "string", null, UNSUPPORTED ],
3150 portrange: [ "string", null, UNSUPPORTED ],
3151
3152 netmask: [ "int", null, UNSUPPORTED ],
3153 maxelem: [ "int" ],
3154 hashsize: [ "int", null, UNSUPPORTED ],
3155 timeout: [ "int", "-1" ],
3156
3157 external: [ "string", null, UNSUPPORTED ],
3158
3159 entry: [ "string", null, PARSE_LIST ],
3160 loadfile: [ "string" ]
3161 });
3162
3163 if (ipset === false) {
3164 this.warn_section(data, "skipped due to invalid options");
3165 return;
3166 }
3167 else if (!ipset.enabled) {
3168 this.warn_section(data, "is disabled, ignoring section");
3169 return;
3170 }
3171
3172 if (ipset.family == 0) {
3173 this.warn_section(data, "must not specify family 'any'");
3174 return;
3175 }
3176 else if (!length(ipset.match)) {
3177 this.warn_section(data, "has no datatypes assigned");
3178 return;
3179 }
3180
3181 let dirs = map(ipset.match, m => m[0]),
3182 types = map(ipset.match, m => m[1]),
3183 interval = false;
3184
3185 if ("set" in types) {
3186 this.warn_section(data, "match type 'set' is not supported");
3187 return;
3188 }
3189
3190 if ("net" in types) {
3191 if (this.kernel < 0x05060000) {
3192 this.warn_section(data, "match type 'net' requires kernel 5.6 or later");
3193 return;
3194 }
3195
3196 interval = true;
3197 }
3198
3199 let s = {
3200 ...ipset,
3201
3202 fw4types: types,
3203
3204 types: map(types, (t) => {
3205 switch (t) {
3206 case 'ip':
3207 case 'net':
3208 return (ipset.family == 4) ? 'ipv4_addr' : 'ipv6_addr';
3209
3210 case 'mac':
3211 return 'ether_addr';
3212
3213 case 'port':
3214 return 'inet_service';
3215 }
3216 }),
3217
3218 directions: dirs,
3219 interval: interval
3220 };
3221
3222 if (s.interval)
3223 push(s.flags ??= [], 'interval');
3224
3225 if (s.timeout >= 0)
3226 push(s.flags ??= [], 'timeout');
3227
3228 s.entries = filter(map(ipset.entry, (e) => {
3229 let v = this.parse_ipsetentry(e, s);
3230
3231 if (!v)
3232 this.warn_section(data, `ignoring invalid ipset entry '${e}'`);
3233
3234 return v;
3235 }), (e) => (e != null));
3236
3237 push(this.state.ipsets ||= [], s);
3238 }
3239 };