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