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