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