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