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