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