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