a06d097c38b5fb20532ad2fd2bac27359e8481d5
[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 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 b = max(-1, b);
842 }
843
844 return [{
845 family: (length(a) == 16) ? 6 : 4,
846 addr: arrtoip(a),
847 mask: m,
848 bits: b
849 }];
850
851 case 1:
852 parts = split(parts[0], "-");
853
854 switch (length(parts)) {
855 case 2:
856 a = iptoarr(parts[0]);
857 b = iptoarr(parts[1]);
858
859 if (a && b && length(a) == length(b)) {
860 return [{
861 family: (length(a) == 16) ? 6 : 4,
862 addr: arrtoip(a),
863 addr2: arrtoip(b),
864 range: true
865 }];
866 }
867
868 break;
869
870 case 1:
871 a = iptoarr(parts[0]);
872
873 if (a) {
874 return [{
875 family: (length(a) == 16) ? 6 : 4,
876 addr: arrtoip(a),
877 mask: to_mask(length(a) * 8, length(a) == 16),
878 bits: length(a) * 8
879 }];
880 }
881
882 n = this.state.networks[parts[0]];
883
884 if (n)
885 return [ ...(n.ipaddrs || []) ];
886 }
887 }
888
889 return null;
890 },
891
892 parse_enum: function(val, choices) {
893 if (type(val) == "string") {
894 val = lc(val);
895
896 for (let i = 0; i < length(choices); i++)
897 if (lc(substr(choices[i], 0, length(val))) == val)
898 return choices[i];
899 }
900
901 return null;
902 },
903
904 section_id: function(sid) {
905 let s = this.get_all(sid);
906
907 if (!s)
908 return null;
909
910 if (s[".anonymous"]) {
911 let c = 0;
912
913 this.cursor.foreach("firewall", s[".type"], function(ss) {
914 if (ss[".name"] == s[".name"])
915 return false;
916
917 c++;
918 });
919
920 return `@${s['.type']}[${c}]`;
921 }
922
923 return s[".name"];
924 },
925
926 warn_section: function(s, msg) {
927 if (s[".name"]) {
928 if (s.name)
929 this.warn("Section %s (%s) %s", this.section_id(s[".name"]), s.name, msg);
930 else
931 this.warn("Section %s %s", this.section_id(s[".name"]), msg);
932 }
933 else {
934 if (s.name)
935 this.warn("ubus %s (%s) %s", s.type || "rule", s.name, msg);
936 else
937 this.warn("ubus %s %s", s.type || "rule", msg);
938 }
939 },
940
941 parse_policy: function(val) {
942 return this.parse_enum(val, [
943 "accept",
944 "reject",
945 "drop"
946 ]);
947 },
948
949 parse_bool: function(val) {
950 if (val == "1" || val == "on" || val == "true" || val == "yes")
951 return true;
952 else if (val == "0" || val == "off" || val == "false" || val == "no")
953 return false;
954 else
955 return null;
956 },
957
958 parse_family: function(val) {
959 if (val == 'any' || val == 'all' || val == '*')
960 return 0;
961 else if (val == 'inet' || index(val, '4') > -1)
962 return 4;
963 else if (index(val, '6') > -1)
964 return 6;
965
966 return null;
967 },
968
969 parse_zone_ref: function(val) {
970 if (val == null)
971 return null;
972
973 if (val == '*')
974 return { any: true };
975
976 for (let zone in this.state.zones) {
977 if (zone.name == val) {
978 return {
979 any: false,
980 zone: zone
981 };
982 }
983 }
984
985 return null;
986 },
987
988 parse_device: function(val) {
989 let rv = this.parse_invert(val);
990
991 if (!rv)
992 return null;
993
994 if (rv.val == '*')
995 rv.any = true;
996 else
997 rv.device = rv.val;
998
999 return rv;
1000 },
1001
1002 parse_direction: function(val) {
1003 if (val == 'in' || val == 'ingress')
1004 return false;
1005 else if (val == 'out' || val == 'egress')
1006 return true;
1007
1008 return null;
1009 },
1010
1011 parse_setmatch: function(val) {
1012 let rv = this.parse_invert(val);
1013
1014 if (!rv)
1015 return null;
1016
1017 rv.val = trim(replace(rv.val, /^[^ \t]+/, function(m) {
1018 rv.name = m;
1019 return '';
1020 }));
1021
1022 let dir = split(rv.val, /[ \t,]/);
1023
1024 for (let i = 0; i < 3 && i < length(dir); i++) {
1025 if (dir[i] == "dst" || dir[i] == "dest")
1026 (rv.dir ||= [])[i] = "dst";
1027 else if (dir[i] == "src")
1028 (rv.dir ||= [])[i] = "src";
1029 }
1030
1031 return length(rv.name) ? rv : null;
1032 },
1033
1034 parse_cthelper: function(val) {
1035 let rv = this.parse_invert(val);
1036
1037 if (!rv)
1038 return null;
1039
1040 let helper = filter(this.state.helpers, h => (h.name == rv.val))[0];
1041
1042 return helper ? { ...rv, ...helper } : null;
1043 },
1044
1045 parse_protocol: function(val) {
1046 let p = this.parse_invert(val);
1047
1048 if (!p)
1049 return null;
1050
1051 p.val = lc(p.val);
1052
1053 switch (p.val) {
1054 case 'all':
1055 case 'any':
1056 case '*':
1057 p.any = true;
1058 break;
1059
1060 case '1':
1061 case 'icmp':
1062 p.name = 'icmp';
1063 break;
1064
1065 case '58':
1066 case 'icmpv6':
1067 case 'ipv6-icmp':
1068 p.name = 'ipv6-icmp';
1069 break;
1070
1071 case 'tcpudp':
1072 return [
1073 { invert: p.invert, name: 'tcp' },
1074 { invert: p.invert, name: 'udp' }
1075 ];
1076
1077 case '6':
1078 p.name = 'tcp';
1079 break;
1080
1081 case '17':
1082 p.name = 'udp';
1083 break;
1084
1085 default:
1086 p.name = p.val;
1087 }
1088
1089 return (p.any || length(p.name)) ? p : null;
1090 },
1091
1092 parse_mac: function(val) {
1093 let mac = this.parse_invert(val);
1094 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;
1095
1096 if (!m)
1097 return null;
1098
1099 mac.mac = sprintf('%02x:%02x:%02x:%02x:%02x:%02x',
1100 hex(m[1]), hex(m[2]), hex(m[3]),
1101 hex(m[4]), hex(m[5]), hex(m[6]));
1102
1103 return mac;
1104 },
1105
1106 parse_port: function(val) {
1107 let port = this.parse_invert(val);
1108 let m = port ? match(port.val, /^([0-9]{1,5})([-:]([0-9]{1,5}))?$/i) : null;
1109
1110 if (!m)
1111 return null;
1112
1113 if (m[3]) {
1114 let min_port = +m[1];
1115 let max_port = +m[3];
1116
1117 if (min_port > max_port ||
1118 min_port < 0 || max_port < 0 ||
1119 min_port > 65535 || max_port > 65535)
1120 return null;
1121
1122 port.min = min_port;
1123 port.max = max_port;
1124 }
1125 else {
1126 let pn = +m[1];
1127
1128 if (pn != pn || pn < 0 || pn > 65535)
1129 return null;
1130
1131 port.min = pn;
1132 port.max = pn;
1133 }
1134
1135 return port;
1136 },
1137
1138 parse_network: function(val) {
1139 let rv = this.parse_invert(val);
1140
1141 if (!rv)
1142 return null;
1143
1144 let nets = this.parse_subnet(rv.val);
1145
1146 if (nets === null)
1147 return null;
1148
1149 if (length(nets))
1150 rv.addrs = [ ...nets ];
1151
1152 return rv;
1153 },
1154
1155 parse_icmptype: function(val) {
1156 let rv = {};
1157
1158 if (exists(ipv4_icmptypes, val)) {
1159 rv.family = 4;
1160
1161 rv.type = ipv4_icmptypes[val][0];
1162 rv.code_min = ipv4_icmptypes[val][1];
1163 rv.code_max = ipv4_icmptypes[val][2];
1164 }
1165
1166 if (exists(ipv6_icmptypes, val)) {
1167 rv.family = rv.family ? 0 : 6;
1168
1169 rv.type6 = ipv6_icmptypes[val][0];
1170 rv.code6_min = ipv6_icmptypes[val][1];
1171 rv.code6_max = ipv6_icmptypes[val][2];
1172 }
1173
1174 if (!exists(rv, "family")) {
1175 let m = match(val, /^([0-9]+)(\/([0-9]+))?$/);
1176
1177 if (!m)
1178 return null;
1179
1180 if (m[3]) {
1181 rv.type = +m[1];
1182 rv.code_min = +m[3];
1183 rv.code_max = rv.code_min;
1184 }
1185 else {
1186 rv.type = +m[1];
1187 rv.code_min = 0;
1188 rv.code_max = 0xFF;
1189 }
1190
1191 if (rv.type > 0xFF || rv.code_min > 0xFF || rv.code_max > 0xFF)
1192 return null;
1193
1194 rv.family = 0;
1195
1196 rv.type6 = rv.type;
1197 rv.code6_min = rv.code_min;
1198 rv.code6_max = rv.code_max;
1199 }
1200
1201 return rv;
1202 },
1203
1204 parse_invert: function(val) {
1205 if (val == null)
1206 return null;
1207
1208 let rv = { invert: false };
1209
1210 rv.val = trim(replace(val, /^[ \t]*!/, () => (rv.invert = true, '')));
1211
1212 return length(rv.val) ? rv : null;
1213 },
1214
1215 parse_limit: function(val) {
1216 let rv = this.parse_invert(val);
1217 let m = rv ? match(rv.val, /^([0-9]+)(\/([a-z]+))?$/) : null;
1218
1219 if (!m)
1220 return null;
1221
1222 let n = +m[1];
1223 let u = m[3] ? this.parse_enum(m[3], [ "second", "minute", "hour", "day" ]) : "second";
1224
1225 if (!u)
1226 return null;
1227
1228 rv.rate = n;
1229 rv.unit = u;
1230
1231 return rv;
1232 },
1233
1234 parse_int: function(val) {
1235 let n = +val;
1236
1237 return (n == n) ? n : null;
1238 },
1239
1240 parse_date: function(val) {
1241 let d = match(val, /^([0-9]{4})(-([0-9]{1,2})(-([0-9]{1,2})(T([0-9:]+))?)?)?$/);
1242
1243 if (d == null || d[1] < 1970 || d[1] > 2038 || d[3] > 12 || d[5] > 31)
1244 return null;
1245
1246 let t = this.parse_time(d[7] ?? "0");
1247
1248 if (t == null)
1249 return null;
1250
1251 return {
1252 year: +d[1],
1253 month: +d[3] || 1,
1254 day: +d[5] || 1,
1255 ...t
1256 };
1257 },
1258
1259 parse_time: function(val) {
1260 let t = match(val, /^([0-9]{1,2})(:([0-9]{1,2})(:([0-9]{1,2}))?)?$/);
1261
1262 if (t == null || t[1] > 23 || t[3] > 59 || t[5] > 59)
1263 return null;
1264
1265 return {
1266 hour: +t[1],
1267 min: +t[3],
1268 sec: +t[5]
1269 };
1270 },
1271
1272 parse_weekdays: function(val) {
1273 let rv = this.parse_invert(val);
1274
1275 if (!rv)
1276 return null;
1277
1278 for (let day in to_array(rv.val)) {
1279 day = this.parse_enum(day, [
1280 "Monday",
1281 "Tuesday",
1282 "Wednesday",
1283 "Thursday",
1284 "Friday",
1285 "Saturday",
1286 "Sunday"
1287 ]);
1288
1289 if (!day)
1290 return null;
1291
1292 (rv.days ||= {})[day] = true;
1293 }
1294
1295 rv.days = keys(rv.days);
1296
1297 return rv.days ? rv : null;
1298 },
1299
1300 parse_monthdays: function(val) {
1301 let rv = this.parse_invert(val);
1302
1303 if (!rv)
1304 return null;
1305
1306 for (let day in to_array(rv.val)) {
1307 day = +day;
1308
1309 if (day < 1 || day > 31)
1310 return null;
1311
1312 (rv.days ||= [])[day] = true;
1313 }
1314
1315 return rv.days ? rv : null;
1316 },
1317
1318 parse_mark: function(val) {
1319 let rv = this.parse_invert(val);
1320 let m = rv ? match(rv.val, /^(0?x?[0-9a-f]+)(\/(0?x?[0-9a-f]+))?$/i) : null;
1321
1322 if (!m)
1323 return null;
1324
1325 let n = +m[1];
1326
1327 if (n != n || n > 0xFFFFFFFF)
1328 return null;
1329
1330 rv.mark = n;
1331 rv.mask = 0xFFFFFFFF;
1332
1333 if (m[3]) {
1334 n = +m[3];
1335
1336 if (n != n || n > 0xFFFFFFFF)
1337 return null;
1338
1339 rv.mask = n;
1340 }
1341
1342 return rv;
1343 },
1344
1345 parse_dscp: function(val) {
1346 let rv = this.parse_invert(val);
1347
1348 if (!rv)
1349 return null;
1350
1351 rv.val = uc(rv.val);
1352
1353 if (exists(dscp_classes, rv.val)) {
1354 rv.dscp = dscp_classes[rv.val];
1355 }
1356 else {
1357 let n = +rv.val;
1358
1359 if (n != n || n < 0 || n > 0x3F)
1360 return null;
1361
1362 rv.dscp = n;
1363 }
1364
1365 return rv;
1366 },
1367
1368 parse_target: function(val) {
1369 return this.parse_enum(val, [
1370 "accept",
1371 "reject",
1372 "drop",
1373 "notrack",
1374 "helper",
1375 "mark",
1376 "dscp",
1377 "dnat",
1378 "snat",
1379 "masquerade",
1380 "accept",
1381 "reject",
1382 "drop"
1383 ]);
1384 },
1385
1386 parse_reject_code: function(val) {
1387 return this.parse_enum(val, [
1388 "tcp-reset",
1389 "port-unreachable",
1390 "admin-prohibited",
1391 "host-unreachable",
1392 "no-route"
1393 ]);
1394 },
1395
1396 parse_reflection_source: function(val) {
1397 return this.parse_enum(val, [
1398 "internal",
1399 "external"
1400 ]);
1401 },
1402
1403 parse_ipsettype: function(val) {
1404 let m = match(val, /^(src|dst|dest)_(.+)$/);
1405 let t = this.parse_enum(m ? m[2] : val, [
1406 "ip",
1407 "port",
1408 "mac",
1409 "net",
1410 "set"
1411 ]);
1412
1413 return t ? [ (!m || m[1] == 'src') ? 'src' : 'dst', t ] : null;
1414 },
1415
1416 parse_ipsetentry: function(val, set) {
1417 let values = split(val, /[ \t]+/);
1418
1419 if (length(values) != length(set.types))
1420 return null;
1421
1422 let rv = [];
1423 let ip, mac, port;
1424
1425 for (let i, t in set.types) {
1426 switch (t) {
1427 case 'ipv4_addr':
1428 ip = filter(this.parse_subnet(values[i]), a => (a.family == 4));
1429
1430 switch (length(ip) ?? 0) {
1431 case 0: return null;
1432 case 1: break;
1433 default: this.warn("Set entry '%s' resolves to multiple addresses, using first one", values[i]);
1434 }
1435
1436 rv[i] = ("net" in set.fw4types) ? `${ip[0].addr}/${ip[0].bits}` : ip[0].addr;
1437 break;
1438
1439 case 'ipv6_addr':
1440 ip = filter(this.parse_subnet(values[i]), a => (a.family == 6));
1441
1442 switch(length(ip)) {
1443 case 0: return null;
1444 case 1: break;
1445 case 2: this.warn("Set entry '%s' resolves to multiple addresses, using first one", values[i]);
1446 }
1447
1448 rv[i] = ("net" in set.fw4types) ? `${ip[0].addr}/${ip[0].bits}` : ip[0].addr;
1449
1450 break;
1451
1452 case 'ether_addr':
1453 mac = this.parse_mac(values[i]);
1454
1455 if (!mac || mac.invert)
1456 return null;
1457
1458 rv[i] = mac.mac;
1459 break;
1460
1461 case 'inet_service':
1462 port = this.parse_port(values[i]);
1463
1464 if (!port || port.invert || port.min != port.max)
1465 return null;
1466
1467 rv[i] = port.min;
1468 break;
1469
1470 default:
1471 rv[i] = values[i];
1472 }
1473 }
1474
1475 return length(rv) ? rv : null;
1476 },
1477
1478 parse_string: function(val) {
1479 return "" + val;
1480 },
1481
1482 parse_opt: function(s, opt, fn, defval, flags) {
1483 let val = s[opt];
1484
1485 if (val === null) {
1486 if (flags & REQUIRED) {
1487 this.warn_section(s, `option '${opt}' is mandatory but not set`);
1488 return NaN;
1489 }
1490
1491 val = defval;
1492 }
1493
1494 if (type(val) == "array") {
1495 this.warn_section(s, `option '${opt}' must not be a list`);
1496 return NaN;
1497 }
1498 else if (val == null) {
1499 return null;
1500 }
1501
1502 let res = this[fn](val);
1503
1504 if (res === null) {
1505 this.warn_section(s, `option '${opt}' specifies invalid value '${val}'`);
1506 return NaN;
1507 }
1508
1509 return res;
1510 },
1511
1512 parse_list: function(s, opt, fn, defval, flags) {
1513 let val = s[opt];
1514 let rv = [];
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 for (val in to_array(val)) {
1526 let res = this[fn](val);
1527
1528 if (res === null) {
1529 this.warn_section(s, `option '${opt}' specifies invalid value '${val}'`);
1530 return NaN;
1531 }
1532
1533 if (flags & FLATTEN_LIST)
1534 push(rv, ...to_array(res));
1535 else
1536 push(rv, res);
1537 }
1538
1539 return length(rv) ? rv : null;
1540 },
1541
1542 quote: function(s, force) {
1543 if (force === true || !match(s, /^([0-9A-Fa-f:.\/-]+)( \. [0-9A-Fa-f:.\/-]+)*$/))
1544 return `"${replace(s + "", /(["\\])/g, '\\$1')}"`;
1545
1546 return s;
1547 },
1548
1549 cidr: function(a) {
1550 if (a.range)
1551 return `${a.addr}-${a.addr2}`;
1552
1553 if ((a.family == 4 && a.bits == 32) ||
1554 (a.family == 6 && a.bits == 128))
1555 return a.addr;
1556
1557 if (a.bits >= 0)
1558 return `${apply_mask(a.addr, a.bits)}/${a.bits}`;
1559
1560 return `${a.addr}/${a.mask}`;
1561 },
1562
1563 host: function(a, v6brackets) {
1564 return a.range
1565 ? `${a.addr}-${a.addr2}`
1566 : (a.family == 6 && v6brackets)
1567 ? `[${apply_mask(a.addr, a.bits)}]` : apply_mask(a.addr, a.bits);
1568 },
1569
1570 port: function(p) {
1571 if (p.min == p.max)
1572 return `${p.min}`;
1573
1574 return `${p.min}-${p.max}`;
1575 },
1576
1577 set: function(v, force) {
1578 let seen = {};
1579
1580 v = filter(to_array(v), item => !seen[item]++);
1581
1582 if (force || length(v) != 1)
1583 return `{ ${join(', ', map(v, this.quote))} }`;
1584
1585 return this.quote(v[0]);
1586 },
1587
1588 concat: function(v) {
1589 return join(' . ', to_array(v));
1590 },
1591
1592 ipproto: function(family) {
1593 switch (family) {
1594 case 4:
1595 return "ip";
1596
1597 case 6:
1598 return "ip6";
1599 }
1600 },
1601
1602 nfproto: function(family, human_readable) {
1603 switch (family) {
1604 case 4:
1605 return human_readable ? "IPv4" : "ipv4";
1606
1607 case 6:
1608 return human_readable ? "IPv6" : "ipv6";
1609
1610 default:
1611 return human_readable ? "IPv4/IPv6" : null;
1612 }
1613 },
1614
1615 l4proto: function(family, proto) {
1616 switch (proto.name) {
1617 case 'icmp':
1618 switch (family ?? 0) {
1619 case 0:
1620 return this.set(['icmp', 'ipv6-icmp']);
1621
1622 case 6:
1623 return 'ipv6-icmp';
1624 }
1625
1626 default:
1627 return proto.name;
1628 }
1629 },
1630
1631 datetime: function(stamp) {
1632 return sprintf('"%04d-%02d-%02d %02d:%02d:%02d"',
1633 stamp.year, stamp.month, stamp.day,
1634 stamp.hour, stamp.min, stamp.sec);
1635 },
1636
1637 date: function(stamp) {
1638 return sprintf('"%04d-%02d-%02d"', stamp.year, stamp.month, stamp.day);
1639 },
1640
1641 datestamp: function(stamp) {
1642 return exists(stamp, 'hour') ? this.datetime(stamp) : this.date(stamp);
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 zone.network = [ ...to_array(zone.network), ...related_ubus_networks ];
1909
1910 for (let e in zone.network) {
1911 if (exists(this.state.networks, e.device)) {
1912 let net = this.state.networks[e.device];
1913
1914 if (net.device) {
1915 push(match_devices, {
1916 invert: e.invert,
1917 device: net.device
1918 });
1919 }
1920
1921 if (net.physdev && !e.invert)
1922 push(related_physdevs, net.physdev);
1923
1924 push(related_subnets, ...(net.ipaddrs || []));
1925 }
1926 }
1927
1928 push(match_devices, ...to_array(zone.device));
1929
1930 match_subnets = subnets_split_af(zone.subnet);
1931 masq_src_subnets = subnets_split_af(zone.masq_src);
1932 masq_dest_subnets = subnets_split_af(zone.masq_dest);
1933
1934 push(related_subnets, ...(match_subnets[0] || []), ...(match_subnets[1] || []));
1935
1936 let match_rules = [];
1937
1938 let add_rule = (family, devices, subnets, zone) => {
1939 let r = {};
1940
1941 r.family = family;
1942
1943 r.devices_pos = null_if_empty(devices[0]);
1944 r.devices_neg = null_if_empty(devices[1]);
1945 r.devices_neg_wildcard = null_if_empty(devices[2]);
1946
1947 r.subnets_pos = map(subnets[0], this.cidr);
1948 r.subnets_neg = map(subnets[1], this.cidr);
1949 r.subnets_masked = subnets[2];
1950
1951 push(match_rules, r);
1952 };
1953
1954 let family = infer_family(zone.family, [
1955 zone.helper, "ct helper",
1956 match_subnets, "subnet list"
1957 ]);
1958
1959 if (type(family) == "string") {
1960 this.warn_section(data, `${family}, skipping`);
1961 return;
1962 }
1963
1964 // group non-inverted device matches into wildcard and non-wildcard ones
1965 let devices = [], plain_devices = [], plain_invert_devices = [], wildcard_invert_devices = [];
1966
1967 for (let device in match_devices) {
1968 let m = match(device.device, /^([^+]*)(\+)?$/);
1969
1970 if (!m) {
1971 this.warn_section(data, `skipping invalid wildcard pattern '${device.device}'`);
1972 continue;
1973 }
1974
1975 // filter `+` (match any device) since nftables does not support
1976 // wildcard only matches
1977 if (!device.invert && m[0] == '+')
1978 continue;
1979
1980 // replace inverted `+` (match no device) with invalid pattern
1981 if (device.invert && m[0] == '+') {
1982 device.device = '/never/';
1983 device.invert = false;
1984 }
1985
1986 // replace "name+" matches with "name*"
1987 else if (m[2] == '+')
1988 device.device = m[1] + '*';
1989
1990 device.wildcard = !!m[2];
1991
1992 if (!device.invert && device.wildcard)
1993 push(devices, [ [ device.device ], plain_invert_devices, wildcard_invert_devices ]);
1994 else if (!device.invert)
1995 push(plain_devices, device.device);
1996 else if (device.wildcard)
1997 push(wildcard_invert_devices, device.device);
1998 else
1999 push(plain_invert_devices, device.device);
2000 }
2001
2002 if (length(plain_devices))
2003 push(devices, [
2004 plain_devices,
2005 plain_invert_devices,
2006 wildcard_invert_devices
2007 ]);
2008 else if (!length(devices))
2009 push(devices, [
2010 null,
2011 plain_invert_devices,
2012 wildcard_invert_devices
2013 ]);
2014
2015 // emit zone jump rules for each device group
2016 if (length(match_devices) || length(match_subnets[0]) || length(match_subnets[1])) {
2017 for (let devgroup in devices) {
2018 // check if there's no AF specific bits, in this case we can do AF agnostic matching
2019 if (!family && !length(match_subnets[0]) && !length(match_subnets[1])) {
2020 add_rule(0, devgroup, [], zone);
2021 }
2022
2023 // we need to emit one or two AF specific rules
2024 else {
2025 if (!family || family == 4)
2026 for (let subnets in subnets_group_by_masking(match_subnets[0]))
2027 add_rule(4, devgroup, subnets, zone);
2028
2029 if (!family || family == 6)
2030 for (let subnets in subnets_group_by_masking(match_subnets[1]))
2031 add_rule(6, devgroup, subnets, zone);
2032 }
2033 }
2034 }
2035
2036 zone.family = family;
2037
2038 zone.match_rules = match_rules;
2039
2040 zone.masq4_src_subnets = subnets_group_by_masking(masq_src_subnets[0]);
2041 zone.masq4_dest_subnets = subnets_group_by_masking(masq_dest_subnets[0]);
2042
2043 zone.masq6_src_subnets = subnets_group_by_masking(masq_src_subnets[1]);
2044 zone.masq6_dest_subnets = subnets_group_by_masking(masq_dest_subnets[1]);
2045
2046 zone.sflags = {};
2047 zone.sflags[zone.input] = true;
2048
2049 zone.dflags = {};
2050 zone.dflags[zone.output] = true;
2051 zone.dflags[zone.forward] = true;
2052
2053 zone.match_devices = map(filter(match_devices, d => !d.invert), d => d.device);
2054 zone.match_subnets = map(filter(related_subnets, s => !s.invert && s.bits != -1), this.cidr);
2055
2056 zone.related_subnets = related_subnets;
2057 zone.related_physdevs = related_physdevs;
2058
2059 if (zone.masq || zone.masq6)
2060 zone.dflags.snat = true;
2061
2062 if ((zone.auto_helper && !(zone.masq || zone.masq6)) || length(zone.helper)) {
2063 zone.dflags.helper = true;
2064
2065 for (let helper in (length(zone.helper) ? zone.helper : this.state.helpers)) {
2066 if (!helper.available)
2067 continue;
2068
2069 for (let proto in helper.proto) {
2070 push(this.state.rules ||= [], {
2071 chain: `helper_${zone.name}`,
2072 family: helper.family,
2073 name: helper.description || helper.name,
2074 proto: proto,
2075 src: zone,
2076 dports_pos: [ this.port(helper.port) ],
2077 target: "helper",
2078 set_helper: helper
2079 });
2080 }
2081 }
2082 }
2083
2084 push(this.state.zones ||= [], zone);
2085 },
2086
2087 parse_forwarding: function(data) {
2088 let fwd = this.parse_options(data, {
2089 enabled: [ "bool", "1" ],
2090
2091 name: [ "string" ],
2092 family: [ "family" ],
2093
2094 src: [ "zone_ref", null, REQUIRED ],
2095 dest: [ "zone_ref", null, REQUIRED ]
2096 });
2097
2098 if (fwd === false) {
2099 this.warn_section(data, "skipped due to invalid options");
2100 return;
2101 }
2102 else if (!fwd.enabled) {
2103 this.warn_section(data, "is disabled, ignoring section");
2104 return;
2105 }
2106
2107 let add_rule = (family, fwd) => {
2108 let f = {
2109 ...fwd,
2110
2111 family: family,
2112 proto: { any: true }
2113 };
2114
2115 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`;
2116 f.chain = fwd.src.any ? "forward" : `forward_${fwd.src.zone.name}`;
2117
2118 if (fwd.dest.any)
2119 f.target = "accept";
2120 else
2121 f.jump_chain = `accept_to_${fwd.dest.zone.name}`;
2122
2123 push(this.state.rules ||= [], f);
2124 };
2125
2126
2127 /* inherit family restrictions from related zones */
2128 let family = infer_family(fwd.family, [
2129 fwd.src?.zone, "source zone",
2130 fwd.dest?.zone, "destination zone"
2131 ]);
2132
2133 if (type(family) == "string") {
2134 this.warn_section(data, `${family}, skipping`);
2135 return;
2136 }
2137
2138 add_rule(family, fwd);
2139
2140 if (fwd.dest.zone)
2141 fwd.dest.zone.dflags.accept = true;
2142 },
2143
2144 parse_rule: function(data) {
2145 let rule = this.parse_options(data, {
2146 enabled: [ "bool", "1" ],
2147
2148 name: [ "string", this.section_id(data[".name"]) ],
2149 _name: [ "string", null, DEPRECATED ],
2150 family: [ "family" ],
2151
2152 src: [ "zone_ref" ],
2153 dest: [ "zone_ref" ],
2154
2155 device: [ "device", null, NO_INVERT ],
2156 direction: [ "direction" ],
2157
2158 ipset: [ "setmatch" ],
2159 helper: [ "cthelper" ],
2160 set_helper: [ "cthelper", null, NO_INVERT ],
2161
2162 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2163
2164 src_ip: [ "network", null, PARSE_LIST ],
2165 src_mac: [ "mac", null, PARSE_LIST ],
2166 src_port: [ "port", null, PARSE_LIST ],
2167
2168 dest_ip: [ "network", null, PARSE_LIST ],
2169 dest_port: [ "port", null, PARSE_LIST ],
2170
2171 icmp_type: [ "icmptype", null, PARSE_LIST ],
2172 extra: [ "string", null, UNSUPPORTED ],
2173
2174 limit: [ "limit" ],
2175 limit_burst: [ "int" ],
2176
2177 utc_time: [ "bool" ],
2178 start_date: [ "date" ],
2179 stop_date: [ "date" ],
2180 start_time: [ "time" ],
2181 stop_time: [ "time" ],
2182 weekdays: [ "weekdays" ],
2183 monthdays: [ "monthdays", null, UNSUPPORTED ],
2184
2185 mark: [ "mark" ],
2186 set_mark: [ "mark", null, NO_INVERT ],
2187 set_xmark: [ "mark", null, NO_INVERT ],
2188
2189 dscp: [ "dscp" ],
2190 set_dscp: [ "dscp", null, NO_INVERT ],
2191
2192 counter: [ "bool", "1" ],
2193
2194 target: [ "target" ]
2195 });
2196
2197 if (rule === false) {
2198 this.warn_section(data, "skipped due to invalid options");
2199 return;
2200 }
2201 else if (!rule.enabled) {
2202 this.warn_section(data, "is disabled, ignoring section");
2203 return;
2204 }
2205
2206 if (rule.target in ["helper", "notrack"] && (!rule.src || !rule.src.zone)) {
2207 this.warn_section(data, `must specify a source zone for target '${rule.target}'`);
2208 return;
2209 }
2210 else if (rule.target == "dscp" && !rule.set_dscp) {
2211 this.warn_section(data, "must specify option 'set_dscp' for target 'dscp'");
2212 return;
2213 }
2214 else if (rule.target == "mark" && !rule.set_mark && !rule.set_xmark) {
2215 this.warn_section(data, "must specify option 'set_mark' or 'set_xmark' for target 'mark'");
2216 return;
2217 }
2218 else if (rule.target == "helper" && !rule.set_helper) {
2219 this.warn_section(data, "must specify option 'set_helper' for target 'helper'");
2220 return;
2221 }
2222 else if (rule.device?.any) {
2223 this.warn_section(data, "must not specify '*' as device");
2224 return;
2225 }
2226
2227 let ipset;
2228
2229 if (rule.ipset) {
2230 ipset = filter(this.state.ipsets, s => (s.name == rule.ipset.name))[0];
2231
2232 if (!ipset) {
2233 this.warn_section(data, `references unknown set '${rule.ipset.name}'`);
2234 return;
2235 }
2236
2237 if (('inet_service' in ipset.types) && !ensure_tcpudp(rule.proto)) {
2238 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2239 return;
2240 }
2241 }
2242
2243 let need_src_action_chain = (rule) => (rule.src?.zone?.log && rule.target != "accept");
2244
2245 let add_rule = (family, proto, saddrs, daddrs, sports, dports, icmptypes, icmpcodes, ipset, rule) => {
2246 let r = {
2247 ...rule,
2248
2249 family: family,
2250 proto: proto,
2251 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2252 has_ports: !!(length(sports) || length(dports)),
2253 saddrs_pos: map(saddrs[0], this.cidr),
2254 saddrs_neg: map(saddrs[1], this.cidr),
2255 saddrs_masked: saddrs[2],
2256 daddrs_pos: map(daddrs[0], this.cidr),
2257 daddrs_neg: map(daddrs[1], this.cidr),
2258 daddrs_masked: daddrs[2],
2259 sports_pos: map(filter_pos(sports), this.port),
2260 sports_neg: map(filter_neg(sports), this.port),
2261 dports_pos: map(filter_pos(dports), this.port),
2262 dports_neg: map(filter_neg(dports), this.port),
2263 smacs_pos: map(filter_pos(rule.src_mac), m => m.mac),
2264 smacs_neg: map(filter_neg(rule.src_mac), m => m.mac),
2265 icmp_types: map(icmptypes, i => (family == 4 ? i.type : i.type6)),
2266 icmp_codes: map(icmpcodes, ic => `${(family == 4) ? ic.type : ic.type6} . ${(family == 4) ? ic.code_min : ic.code6_min}`)
2267 };
2268
2269 if (!length(r.icmp_types))
2270 delete r.icmp_types;
2271
2272 if (!length(r.icmp_codes))
2273 delete r.icmp_codes;
2274
2275 if (r.set_mark) {
2276 r.set_xmark = {
2277 invert: r.set_mark.invert,
2278 mark: r.set_mark.mark,
2279 mask: r.set_mark.mark | r.set_mark.mask
2280 };
2281
2282 delete r.set_mark;
2283 }
2284
2285 let set_types = map_setmatch(ipset, rule.ipset, proto.name);
2286
2287 if (set_types !== set_types) {
2288 this.warn_section(data, "destination MAC address matching not supported");
2289 return;
2290 } else if (set_types) {
2291 r.ipset = { ...r.ipset, fields: set_types };
2292 }
2293
2294 if (r.target == "notrack") {
2295 r.chain = `notrack_${r.src.zone.name}`;
2296 r.src.zone.dflags.notrack = true;
2297 }
2298 else if (r.target == "helper") {
2299 r.chain = `helper_${r.src.zone.name}`;
2300 r.src.zone.dflags.helper = true;
2301 }
2302 else if (r.target == "mark" || r.target == "dscp") {
2303 if ((r.src?.any && r.dest?.any) || (r.src?.zone && r.dest?.zone))
2304 r.chain = "mangle_forward";
2305 else if (r.src?.any && r.dest?.zone)
2306 r.chain = "mangle_postrouting";
2307 else if (r.src?.zone && r.dest?.any)
2308 r.chain = "mangle_prerouting";
2309 else if (r.src && !r.dest)
2310 r.chain = "mangle_input";
2311 else
2312 r.chain = "mangle_output";
2313
2314 if (r.src?.zone) {
2315 r.src.zone.dflags[r.target] = true;
2316 r.iifnames = null_if_empty(r.src.zone.match_devices);
2317 }
2318
2319 if (r.dest?.zone) {
2320 r.dest.zone.dflags[r.target] = true;
2321 r.oifnames = null_if_empty(r.dest.zone.match_devices);
2322 }
2323 }
2324 else {
2325 r.chain = "output";
2326
2327 if (r.src) {
2328 if (!r.src.any)
2329 r.chain = `${r.dest ? "forward" : "input"}_${r.src.zone.name}`;
2330 else
2331 r.chain = r.dest ? "forward" : "input";
2332 }
2333
2334 if (r.dest && !r.src) {
2335 if (!r.dest.any)
2336 r.chain = sprintf("output_%s", r.dest.zone.name);
2337 else
2338 r.chain = "output";
2339 }
2340
2341 if (r.dest && !r.dest.any) {
2342 r.jump_chain = `${r.target}_to_${r.dest.zone.name}`;
2343 r.dest.zone.dflags[r.target] = true;
2344 }
2345 else if (need_src_action_chain(r)) {
2346 r.jump_chain = `${r.target}_from_${r.src.zone.name}`;
2347 r.src.zone.sflags[r.target] = true;
2348 }
2349 else if (r.target == "reject")
2350 r.jump_chain = "handle_reject";
2351 }
2352
2353 if (r.device)
2354 r[r.direction ? "oifnames" : "iifnames"] = [ r.device.device ];
2355
2356 push(this.state.rules ||= [], r);
2357 };
2358
2359 for (let proto in rule.proto) {
2360 let sip, dip, sports, dports, itypes4, itypes6;
2361 let family = rule.family;
2362
2363 switch (proto.name) {
2364 case "icmp":
2365 itypes4 = filter(rule.icmp_type || [], family_is_ipv4);
2366 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2367 break;
2368
2369 case "ipv6-icmp":
2370 family = 6;
2371 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2372 break;
2373
2374 case "tcp":
2375 case "udp":
2376 sports = rule.src_port;
2377 dports = rule.dest_port;
2378 break;
2379 }
2380
2381 sip = subnets_split_af(rule.src_ip);
2382 dip = subnets_split_af(rule.dest_ip);
2383
2384 family = infer_family(family, [
2385 ipset, "set match",
2386 sip, "source IP",
2387 dip, "destination IP",
2388 rule.src?.zone, "source zone",
2389 rule.dest?.zone, "destination zone",
2390 rule.helper, "helper match",
2391 rule.set_helper, "helper to set"
2392 ]);
2393
2394 if (type(family) == "string") {
2395 this.warn_section(data, `${family}, skipping`);
2396 continue;
2397 }
2398
2399 let has_ipv4_specifics = (length(sip[0]) || length(dip[0]) || length(itypes4) || rule.dscp !== null);
2400 let has_ipv6_specifics = (length(sip[1]) || length(dip[1]) || length(itypes6) || rule.dscp !== null);
2401
2402 /* if no family was configured, infer target family from IP addresses */
2403 if (family === null) {
2404 if (has_ipv4_specifics && !has_ipv6_specifics)
2405 family = 4;
2406 else if (has_ipv6_specifics && !has_ipv4_specifics)
2407 family = 6;
2408 else
2409 family = 0;
2410 }
2411
2412 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2413 if (!family && rule.target != "dscp" && !has_ipv4_specifics && !has_ipv6_specifics) {
2414 add_rule(0, proto, [], [], sports, dports, null, null, null, rule);
2415 }
2416
2417 /* we need to emit one or two AF specific rules */
2418 else {
2419 if (family == 0 || family == 4) {
2420 let icmp_types = filter(itypes4, i => (i.code_min == 0 && i.code_max == 0xFF));
2421 let icmp_codes = filter(itypes4, i => (i.code_min != 0 || i.code_max != 0xFF));
2422
2423 for (let saddrs in subnets_group_by_masking(sip[0])) {
2424 for (let daddrs in subnets_group_by_masking(dip[0])) {
2425 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2426 add_rule(4, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2427
2428 if (length(icmp_codes))
2429 add_rule(4, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2430 }
2431 }
2432 }
2433
2434 if (family == 0 || family == 6) {
2435 let icmp_types = filter(itypes6, i => (i.code_min == 0 && i.code_max == 0xFF));
2436 let icmp_codes = filter(itypes6, i => (i.code_min != 0 || i.code_max != 0xFF));
2437
2438 for (let saddrs in subnets_group_by_masking(sip[1])) {
2439 for (let daddrs in subnets_group_by_masking(dip[1])) {
2440 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2441 add_rule(6, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2442
2443 if (length(icmp_codes))
2444 add_rule(6, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2445 }
2446 }
2447 }
2448 }
2449 }
2450 },
2451
2452 parse_redirect: function(data) {
2453 let redir = this.parse_options(data, {
2454 enabled: [ "bool", "1" ],
2455
2456 name: [ "string", this.section_id(data[".name"]) ],
2457 _name: [ "string", null, DEPRECATED ],
2458 family: [ "family" ],
2459
2460 src: [ "zone_ref" ],
2461 dest: [ "zone_ref" ],
2462
2463 ipset: [ "setmatch" ],
2464 helper: [ "cthelper", null, NO_INVERT ],
2465
2466 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2467
2468 src_ip: [ "network" ],
2469 src_mac: [ "mac", null, PARSE_LIST ],
2470 src_port: [ "port" ],
2471
2472 src_dip: [ "network" ],
2473 src_dport: [ "port" ],
2474
2475 dest_ip: [ "network" ],
2476 dest_port: [ "port" ],
2477
2478 extra: [ "string", null, UNSUPPORTED ],
2479
2480 limit: [ "limit" ],
2481 limit_burst: [ "int" ],
2482
2483 utc_time: [ "bool" ],
2484 start_date: [ "date" ],
2485 stop_date: [ "date" ],
2486 start_time: [ "time" ],
2487 stop_time: [ "time" ],
2488 weekdays: [ "weekdays" ],
2489 monthdays: [ "monthdays", null, UNSUPPORTED ],
2490
2491 mark: [ "mark" ],
2492
2493 reflection: [ "bool", "1" ],
2494 reflection_src: [ "reflection_source", "internal" ],
2495
2496 reflection_zone: [ "zone_ref", null, PARSE_LIST ],
2497
2498 counter: [ "bool", "1" ],
2499
2500 target: [ "target", "dnat" ]
2501 });
2502
2503 if (redir === false) {
2504 this.warn_section(data, "skipped due to invalid options");
2505 return;
2506 }
2507 else if (!redir.enabled) {
2508 this.warn_section(data, "is disabled, ignoring section");
2509 return;
2510 }
2511
2512 if (!(redir.target in ["dnat", "snat"])) {
2513 this.warn_section(data, "has invalid target specified, defaulting to dnat");
2514 redir.target = "dnat";
2515 }
2516
2517 let ipset;
2518
2519 if (redir.ipset) {
2520 ipset = filter(this.state.ipsets, s => (s.name == redir.ipset.name))[0];
2521
2522 if (!ipset) {
2523 this.warn_section(data, `references unknown set '${redir.ipset.name}'`);
2524 return;
2525 }
2526
2527 if (('inet_service' in ipset.types) && !ensure_tcpudp(redir.proto)) {
2528 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2529 return;
2530 }
2531 }
2532
2533 let resolve_dest = (redir) => {
2534 for (let zone in this.state.zones) {
2535 for (let zone_addr in zone.related_subnets) {
2536 for (let dest_addr in redir.dest_ip.addrs) {
2537 if (dest_addr.family != zone_addr.family)
2538 continue;
2539
2540 let a = apply_mask(dest_addr.addr, zone_addr.mask);
2541 let b = apply_mask(zone_addr.addr, zone_addr.mask);
2542
2543 if (a != b)
2544 continue;
2545
2546 redir.dest = {
2547 any: false,
2548 zone: zone
2549 };
2550
2551 return true;
2552 }
2553 }
2554 }
2555
2556 return false;
2557 };
2558
2559 if (redir.target == "dnat") {
2560 if (!redir.src)
2561 return this.warn_section(data, "has no source specified");
2562 else if (redir.src.any)
2563 return this.warn_section(data, "must not have source '*' for dnat target");
2564 else if (redir.dest_ip && redir.dest_ip.invert)
2565 return this.warn_section(data, "must not specify a negated 'dest_ip' value");
2566 else if (redir.dest_ip && length(filter(redir.dest_ip.addrs, a => a.bits == -1)))
2567 return this.warn_section(data, "must not use non-contiguous masks in 'dest_ip'");
2568
2569 if (!redir.dest && redir.dest_ip && resolve_dest(redir))
2570 this.warn_section(data, `does not specify a destination, assuming '${redir.dest.zone.name}'`);
2571
2572 if (!redir.dest_port)
2573 redir.dest_port = redir.src_dport;
2574
2575 if (redir.reflection && redir.dest?.zone && redir.src.zone.masq) {
2576 redir.dest.zone.dflags.accept = true;
2577 redir.dest.zone.dflags.dnat = true;
2578 redir.dest.zone.dflags.snat = true;
2579 }
2580
2581 if (redir.helper)
2582 redir.src.zone.dflags.helper = true;
2583
2584 redir.src.zone.dflags[redir.target] = true;
2585 }
2586 else {
2587 if (!redir.dest)
2588 return this.warn_section(data, "has no destination specified");
2589 else if (redir.dest.any)
2590 return this.warn_section(data, "must not have destination '*' for snat target");
2591 else if (!redir.src_dip)
2592 return this.warn_section(data, "has no 'src_dip' option specified");
2593 else if (redir.src_dip.invert)
2594 return this.warn_section(data, "must not specify a negated 'src_dip' value");
2595 else if (length(filter(redir.src_dip.addrs, a => a.bits == -1)))
2596 return this.warn_section(data, "must not use non-contiguous masks in 'src_dip'");
2597 else if (redir.src_mac)
2598 return this.warn_section(data, "must not use 'src_mac' option for snat target");
2599 else if (redir.helper)
2600 return this.warn_section(data, "must not use 'helper' option for snat target");
2601
2602 redir.dest.zone.dflags[redir.target] = true;
2603 }
2604
2605
2606 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, ipset, redir) => {
2607 let r = {
2608 ...redir,
2609
2610 family: family,
2611 proto: proto,
2612 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2613 has_ports: !!(sport || dport || rport),
2614 saddrs_pos: map(saddrs[0], this.cidr),
2615 saddrs_neg: map(saddrs[1], this.cidr),
2616 saddrs_masked: saddrs[2],
2617 daddrs_pos: map(daddrs[0], this.cidr),
2618 daddrs_neg: map(daddrs[1], this.cidr),
2619 daddrs_masked: daddrs[2],
2620 sports_pos: map(filter_pos(to_array(sport)), this.port),
2621 sports_neg: map(filter_neg(to_array(sport)), this.port),
2622 dports_pos: map(filter_pos(to_array(dport)), this.port),
2623 dports_neg: map(filter_neg(to_array(dport)), this.port),
2624 smacs_pos: map(filter_pos(redir.src_mac), m => m.mac),
2625 smacs_neg: map(filter_neg(redir.src_mac), m => m.mac),
2626
2627 raddr: raddrs ? raddrs[0] : null,
2628 rport: rport
2629 };
2630
2631 let set_types = map_setmatch(ipset, redir.ipset, proto.name);
2632
2633 if (set_types !== set_types) {
2634 this.warn_section(data, "destination MAC address matching not supported");
2635 return;
2636 } else if (set_types) {
2637 r.ipset = { ...r.ipset, fields: set_types };
2638 }
2639
2640 switch (r.target) {
2641 case "dnat":
2642 r.chain = `dstnat_${r.src.zone.name}`;
2643 r.src.zone.dflags.dnat = true;
2644
2645 if (!r.raddr)
2646 r.target = "redirect";
2647
2648 break;
2649
2650 case "snat":
2651 r.chain = `srcnat_${r.dest.zone.name}`;
2652 r.dest.zone.dflags.snat = true;
2653 break;
2654 }
2655
2656 push(this.state.redirects ||= [], r);
2657 };
2658
2659 let to_hostaddr = (a) => {
2660 let bits = (a.family == 4) ? 32 : 128;
2661
2662 return {
2663 family: a.family,
2664 addr: apply_mask(a.addr, bits),
2665 bits: bits
2666 };
2667 };
2668
2669 for (let proto in redir.proto) {
2670 let sip, dip, rip, iip, eip, refip, sport, dport, rport;
2671 let family = redir.family;
2672
2673 if (proto.name == "ipv6-icmp")
2674 family = 6;
2675
2676 switch (redir.target) {
2677 case "dnat":
2678 sip = subnets_split_af(redir.src_ip);
2679 dip = subnets_split_af(redir.src_dip);
2680 rip = subnets_split_af(redir.dest_ip);
2681
2682 switch (proto.name) {
2683 case "tcp":
2684 case "udp":
2685 sport = redir.src_port;
2686 dport = redir.src_dport;
2687 rport = redir.dest_port;
2688 break;
2689 }
2690
2691 break;
2692
2693 case "snat":
2694 sip = subnets_split_af(redir.src_ip);
2695 dip = subnets_split_af(redir.dest_ip);
2696 rip = subnets_split_af(redir.src_dip);
2697
2698 switch (proto.name) {
2699 case "tcp":
2700 case "udp":
2701 sport = redir.src_port;
2702 dport = redir.dest_port;
2703 rport = redir.src_dport;
2704 break;
2705 }
2706
2707 break;
2708 }
2709
2710 family = infer_family(family, [
2711 ipset, "set match",
2712 sip, "source IP",
2713 dip, "destination IP",
2714 rip, "rewrite IP",
2715 redir.src?.zone, "source zone",
2716 redir.dest?.zone, "destination zone",
2717 redir.helper, "helper match"
2718 ]);
2719
2720 if (type(family) == "string") {
2721 this.warn_section(data, `${family}, skipping`);
2722 continue;
2723 }
2724
2725 /* build reflection rules */
2726 if (redir.target == "dnat" && redir.reflection &&
2727 (length(rip[0]) || length(rip[1])) && redir.src?.zone && redir.dest?.zone) {
2728 let refredir = {
2729 name: `${redir.name} (reflection)`,
2730
2731 helper: redir.helper,
2732
2733 // XXX: this likely makes no sense for reflection rules
2734 //src_mac: redir.src_mac,
2735
2736 limit: redir.limit,
2737 limit_burst: redir.limit_burst,
2738
2739 start_date: redir.start_date,
2740 stop_date: redir.stop_date,
2741 start_time: redir.start_time,
2742 stop_time: redir.stop_time,
2743 weekdays: redir.weekdays,
2744
2745 mark: redir.mark
2746 };
2747
2748 let eaddrs = length(dip) ? dip : subnets_split_af({ addrs: map(redir.src.zone.related_subnets, to_hostaddr) });
2749 let rzones = length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
2750
2751 for (let rzone in rzones) {
2752 if (!is_family(rzone, family)) {
2753 this.warn_section(data,
2754 `is restricted to IPv${family} but referenced reflection zone is IPv${rzone.family} only, skipping`);
2755 continue;
2756 }
2757
2758 let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
2759 let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
2760
2761 for (let i = 0; i <= 1; i++) {
2762 if (redir.src.zone[i ? "masq6" : "masq"] && length(rip[i])) {
2763 let snat_addr = refaddrs[i]?.[0];
2764
2765 /* For internal reflection sources try to find a suitable candiate IP
2766 * among the reflection zone subnets which is within the same subnet
2767 * as the original DNAT destination. If we can't find any matching
2768 * one then simply take the first candidate. */
2769 if (redir.reflection_src == "internal") {
2770 for (let zone_addr in rzone.zone.related_subnets) {
2771 if (zone_addr.family != rip[i][0].family)
2772 continue;
2773
2774 let r = apply_mask(rip[i][0].addr, zone_addr.mask);
2775 let a = apply_mask(zone_addr.addr, zone_addr.mask);
2776
2777 if (r != a)
2778 continue;
2779
2780 snat_addr = zone_addr;
2781 break;
2782 }
2783 }
2784
2785 if (!snat_addr) {
2786 this.warn_section(data, `${redir.reflection_src || "external"} rewrite IP cannot be determined, disabling reflection`);
2787 }
2788 else if (!length(iaddrs[i])) {
2789 this.warn_section(data, "internal address range cannot be determined, disabling reflection");
2790 }
2791 else if (!length(eaddrs[i])) {
2792 this.warn_section(data, "external address range cannot be determined, disabling reflection");
2793 }
2794 else {
2795 refredir.src = rzone;
2796 refredir.dest = null;
2797 refredir.target = "dnat";
2798
2799 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2800 for (let daddrs in subnets_group_by_masking(eaddrs[i]))
2801 add_rule(i ? 6 : 4, proto, saddrs, daddrs, rip[i], sport, dport, rport, null, refredir);
2802
2803 refredir.src = null;
2804 refredir.dest = rzone;
2805 refredir.target = "snat";
2806
2807 for (let daddrs in subnets_group_by_masking(rip[i]))
2808 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2809 add_rule(i ? 6 : 4, proto, saddrs, daddrs, [ to_hostaddr(snat_addr) ], null, rport, null, null, refredir);
2810 }
2811 }
2812 }
2813 }
2814 }
2815
2816 if (length(rip[0]) > 1 || length(rip[1]) > 1)
2817 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
2818
2819 let has_ip4_addr = length(sip[0]) || length(dip[0]) || length(rip[0]),
2820 has_ip6_addr = length(sip[1]) || length(dip[1]) || length(rip[1]),
2821 has_any_addr = has_ip4_addr || has_ip6_addr;
2822
2823 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2824 if (!family && !has_any_addr) {
2825 /* for backwards compatibility, treat unspecified family as IPv4 unless user explicitly requested any (0) */
2826 if (family == null)
2827 family = 4;
2828
2829 add_rule(family, proto, [], [], null, sport, dport, rport, null, redir);
2830 }
2831
2832 /* we need to emit one or two AF specific rules */
2833 else {
2834 if ((!family || family == 4) && (!has_any_addr || has_ip4_addr)) {
2835 for (let saddrs in subnets_group_by_masking(sip[0]))
2836 for (let daddrs in subnets_group_by_masking(dip[0]))
2837 add_rule(4, proto, saddrs, daddrs, rip[0], sport, dport, rport, ipset, redir);
2838 }
2839
2840 if ((!family || family == 6) && (!has_any_addr || has_ip6_addr)) {
2841 for (let saddrs in subnets_group_by_masking(sip[1]))
2842 for (let daddrs in subnets_group_by_masking(dip[1]))
2843 add_rule(6, proto, saddrs, daddrs, rip[1], sport, dport, rport, ipset, redir);
2844 }
2845 }
2846 }
2847 },
2848
2849 parse_nat: function(data) {
2850 let snat = this.parse_options(data, {
2851 enabled: [ "bool", "1" ],
2852
2853 name: [ "string", this.section_id(data[".name"]) ],
2854 family: [ "family" ],
2855
2856 src: [ "zone_ref" ],
2857 device: [ "string" ],
2858
2859 ipset: [ "setmatch", null, UNSUPPORTED ],
2860
2861 proto: [ "protocol", "all", PARSE_LIST | FLATTEN_LIST ],
2862
2863 src_ip: [ "network" ],
2864 src_port: [ "port" ],
2865
2866 snat_ip: [ "network", null, NO_INVERT ],
2867 snat_port: [ "port", null, NO_INVERT ],
2868
2869 dest_ip: [ "network" ],
2870 dest_port: [ "port" ],
2871
2872 extra: [ "string", null, UNSUPPORTED ],
2873
2874 limit: [ "limit" ],
2875 limit_burst: [ "int" ],
2876
2877 connlimit_ports: [ "bool" ],
2878
2879 utc_time: [ "bool" ],
2880 start_date: [ "date" ],
2881 stop_date: [ "date" ],
2882 start_time: [ "time" ],
2883 stop_time: [ "time" ],
2884 weekdays: [ "weekdays" ],
2885 monthdays: [ "monthdays", null, UNSUPPORTED ],
2886
2887 mark: [ "mark" ],
2888
2889 target: [ "target", "masquerade" ]
2890 });
2891
2892 if (snat === false) {
2893 this.warn_section(data, "skipped due to invalid options");
2894 return;
2895 }
2896 else if (!snat.enabled) {
2897 this.warn_section(data, "is disabled, ignoring section");
2898 return;
2899 }
2900
2901 if (!(snat.target in ["accept", "snat", "masquerade"])) {
2902 this.warn_section(data, "has invalid target specified, defaulting to masquerade");
2903 snat.target = "masquerade";
2904 }
2905
2906 if (snat.target == "snat" && !snat.snat_ip && !snat.snat_port) {
2907 this.warn_section(data, "needs either 'snat_ip' or 'snat_port' for target snat, ignoring section");
2908 return;
2909 }
2910 else if (snat.target != "snat" && snat.snat_ip) {
2911 this.warn_section(data, "must not use 'snat_ip' for non-snat target, ignoring section");
2912 return;
2913 }
2914 else if (snat.target != "snat" && snat.snat_port) {
2915 this.warn_section(data, "must not use 'snat_port' for non-snat target, ignoring section");
2916 return;
2917 }
2918
2919 if ((snat.snat_port || snat.src_port || snat.dest_port) && !ensure_tcpudp(snat.proto)) {
2920 this.warn_section(data, "specifies ports but no UDP/TCP protocol, ignoring section");
2921 return;
2922 }
2923
2924 if (snat.snat_ip && length(filter(snat.snat_ip.addrs, a => a.bits == -1 || a.invert))) {
2925 this.warn_section(data, "must not use inversion or non-contiguous masks in 'snat_ip', ignoring section");
2926 return;
2927 }
2928
2929 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, snat) => {
2930 let n = {
2931 ...snat,
2932
2933 family: family,
2934 proto: proto,
2935 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2936 has_ports: !!(sport || dport),
2937 saddrs_pos: map(saddrs[0], this.cidr),
2938 saddrs_neg: map(saddrs[1], this.cidr),
2939 saddrs_masked: saddrs[2],
2940 daddrs_pos: map(daddrs[0], this.cidr),
2941 daddrs_neg: map(daddrs[1], this.cidr),
2942 daddrs_masked: daddrs[2],
2943 sports_pos: map(filter_pos(to_array(sport)), this.port),
2944 sports_neg: map(filter_neg(to_array(sport)), this.port),
2945 dports_pos: map(filter_pos(to_array(dport)), this.port),
2946 dports_neg: map(filter_neg(to_array(dport)), this.port),
2947
2948 raddr: raddrs ? raddrs[0] : null,
2949 rport: rport,
2950
2951 chain: snat.src?.zone ? `srcnat_${snat.src.zone.name}` : "srcnat"
2952 };
2953
2954 push(this.state.redirects ||= [], n);
2955 };
2956
2957 for (let proto in snat.proto) {
2958 let sip, dip, rip, sport, dport, rport;
2959 let family = snat.family;
2960
2961 sip = subnets_split_af(snat.src_ip);
2962 dip = subnets_split_af(snat.dest_ip);
2963 rip = subnets_split_af(snat.snat_ip);
2964
2965 switch (proto.name) {
2966 case "tcp":
2967 case "udp":
2968 sport = snat.src_port;
2969 dport = snat.dest_port;
2970 rport = snat.snat_port;
2971 break;
2972 }
2973
2974 if (length(rip[0]) > 1 || length(rip[1]) > 1)
2975 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
2976
2977 family = infer_family(family, [
2978 sip, "source IP",
2979 dip, "destination IP",
2980 rip, "rewrite IP",
2981 snat.src?.zone, "source zone"
2982 ]);
2983
2984 if (type(family) == "string") {
2985 this.warn_section(data, `${family}, skipping`);
2986 continue;
2987 }
2988
2989 if (snat.src?.zone)
2990 snat.src.zone.dflags.snat = true;
2991
2992 /* if no family was configured, infer target family from IP addresses */
2993 if (family === null) {
2994 if ((length(sip[0]) || length(dip[0]) || length(rip[0])) && !length(sip[1]) && !length(dip[1]) && !length(rip[1]))
2995 family = 4;
2996 else if ((length(sip[1]) || length(dip[1]) || length(rip[1])) && !length(sip[0]) && !length(dip[0]) && !length(rip[0]))
2997 family = 6;
2998 else
2999 family = 4; /* default to IPv4 only for backwards compatibility, unless an explict family any was configured */
3000 }
3001
3002 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
3003 if (!family && !length(sip[0]) && !length(sip[1]) && !length(dip[0]) && !length(dip[1]) && !length(rip[0]) && !length(rip[1])) {
3004 add_rule(0, proto, [], [], null, sport, dport, rport, snat);
3005 }
3006
3007 /* we need to emit one or two AF specific rules */
3008 else {
3009 if (family == 0 || family == 4)
3010 for (let saddr in subnets_group_by_masking(sip[0]))
3011 for (let daddr in subnets_group_by_masking(dip[0]))
3012 add_rule(4, proto, saddr, daddr, rip[0], sport, dport, rport, snat);
3013
3014 if (family == 0 || family == 6)
3015 for (let saddr in subnets_group_by_masking(sip[1]))
3016 for (let daddr in subnets_group_by_masking(dip[1]))
3017 add_rule(6, proto, saddr, daddr, rip[1], sport, dport, rport, snat);
3018 }
3019 }
3020 },
3021
3022 parse_ipset: function(data) {
3023 let ipset = this.parse_options(data, {
3024 enabled: [ "bool", "1" ],
3025 reload_set: [ "bool" ],
3026 counters: [ "bool" ],
3027 comment: [ "bool" ],
3028
3029 name: [ "string", null, REQUIRED ],
3030 family: [ "family", "4" ],
3031
3032 storage: [ "string", null, UNSUPPORTED ],
3033 match: [ "ipsettype", null, PARSE_LIST ],
3034
3035 iprange: [ "string", null, UNSUPPORTED ],
3036 portrange: [ "string", null, UNSUPPORTED ],
3037
3038 netmask: [ "int", null, UNSUPPORTED ],
3039 maxelem: [ "int" ],
3040 hashsize: [ "int", null, UNSUPPORTED ],
3041 timeout: [ "int", "-1" ],
3042
3043 external: [ "string", null, UNSUPPORTED ],
3044
3045 entry: [ "string", null, PARSE_LIST ],
3046 loadfile: [ "string" ]
3047 });
3048
3049 if (ipset === false) {
3050 this.warn_section(data, "skipped due to invalid options");
3051 return;
3052 }
3053 else if (!ipset.enabled) {
3054 this.warn_section(data, "is disabled, ignoring section");
3055 return;
3056 }
3057
3058 if (ipset.family == 0) {
3059 this.warn_section(data, "must not specify family 'any'");
3060 return;
3061 }
3062 else if (!length(ipset.match)) {
3063 this.warn_section(data, "has no datatypes assigned");
3064 return;
3065 }
3066
3067 let dirs = map(ipset.match, m => m[0]),
3068 types = map(ipset.match, m => m[1]),
3069 interval = false;
3070
3071 if ("set" in types) {
3072 this.warn_section(data, "match type 'set' is not supported");
3073 return;
3074 }
3075
3076 if ("net" in types) {
3077 if (this.kernel < 0x05060000) {
3078 this.warn_section(data, "match type 'net' requires kernel 5.6 or later");
3079 return;
3080 }
3081
3082 interval = true;
3083 }
3084
3085 let s = {
3086 ...ipset,
3087
3088 fw4types: types,
3089
3090 types: map(types, (t) => {
3091 switch (t) {
3092 case 'ip':
3093 case 'net':
3094 return (ipset.family == 4) ? 'ipv4_addr' : 'ipv6_addr';
3095
3096 case 'mac':
3097 return 'ether_addr';
3098
3099 case 'port':
3100 return 'inet_service';
3101 }
3102 }),
3103
3104 directions: dirs,
3105 interval: interval
3106 };
3107
3108 s.entries = filter(map(ipset.entry, (e) => {
3109 let v = this.parse_ipsetentry(e, s);
3110
3111 if (!v)
3112 this.warn_section(data, `ignoring invalid ipset entry '${e}'`);
3113
3114 return v;
3115 }), (e) => (e != null));
3116
3117 push(this.state.ipsets ||= [], s);
3118 }
3119 };