fw4: add support for zone log_limit
[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
2321 target: [ "target" ]
2322 });
2323
2324 if (rule === false) {
2325 this.warn_section(data, "skipped due to invalid options");
2326 return;
2327 }
2328 else if (!rule.enabled) {
2329 this.warn_section(data, "is disabled, ignoring section");
2330 return;
2331 }
2332
2333 if (rule.target in ["helper", "notrack"] && (!rule.src || !rule.src.zone)) {
2334 this.warn_section(data, `must specify a source zone for target '${rule.target}'`);
2335 return;
2336 }
2337 else if (rule.target == "dscp" && !rule.set_dscp) {
2338 this.warn_section(data, "must specify option 'set_dscp' for target 'dscp'");
2339 return;
2340 }
2341 else if (rule.target == "mark" && !rule.set_mark && !rule.set_xmark) {
2342 this.warn_section(data, "must specify option 'set_mark' or 'set_xmark' for target 'mark'");
2343 return;
2344 }
2345 else if (rule.target == "helper" && !rule.set_helper) {
2346 this.warn_section(data, "must specify option 'set_helper' for target 'helper'");
2347 return;
2348 }
2349 else if (rule.device?.any) {
2350 this.warn_section(data, "must not specify '*' as device");
2351 return;
2352 }
2353
2354 switch (this.parse_bool(rule.log)) {
2355 case true:
2356 rule.log = `${rule.name}: `;
2357 break;
2358
2359 case false:
2360 delete rule.log;
2361 }
2362
2363 let ipset;
2364
2365 if (rule.ipset) {
2366 ipset = filter(this.state.ipsets, s => (s.name == rule.ipset.name))?.[0];
2367
2368 if (!ipset) {
2369 this.warn_section(data, `references unknown set '${rule.ipset.name}'`);
2370 return;
2371 }
2372
2373 if (('inet_service' in ipset.types) && !ensure_tcpudp(rule.proto)) {
2374 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2375 return;
2376 }
2377 }
2378
2379 let need_src_action_chain = (rule) => (rule.src?.zone?.log && rule.target != "accept");
2380
2381 let add_rule = (family, proto, saddrs, daddrs, sports, dports, icmptypes, icmpcodes, ipset, rule) => {
2382 let r = {
2383 ...rule,
2384
2385 family: family,
2386 proto: proto,
2387 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2388 has_ports: !!(length(sports) || length(dports)),
2389 saddrs_pos: map(saddrs[0], this.cidr),
2390 saddrs_neg: map(saddrs[1], this.cidr),
2391 saddrs_masked: saddrs[2],
2392 daddrs_pos: map(daddrs[0], this.cidr),
2393 daddrs_neg: map(daddrs[1], this.cidr),
2394 daddrs_masked: daddrs[2],
2395 sports_pos: map(filter_pos(sports), this.port),
2396 sports_neg: map(filter_neg(sports), this.port),
2397 dports_pos: map(filter_pos(dports), this.port),
2398 dports_neg: map(filter_neg(dports), this.port),
2399 smacs_pos: map(filter_pos(rule.src_mac), m => m.mac),
2400 smacs_neg: map(filter_neg(rule.src_mac), m => m.mac),
2401 icmp_types: map(icmptypes, i => (family == 4 ? i.type : i.type6)),
2402 icmp_codes: map(icmpcodes, ic => `${(family == 4) ? ic.type : ic.type6} . ${(family == 4) ? ic.code_min : ic.code6_min}`)
2403 };
2404
2405 if (!length(r.icmp_types))
2406 delete r.icmp_types;
2407
2408 if (!length(r.icmp_codes))
2409 delete r.icmp_codes;
2410
2411 if (r.set_mark) {
2412 r.set_xmark = {
2413 invert: r.set_mark.invert,
2414 mark: r.set_mark.mark,
2415 mask: r.set_mark.mark | r.set_mark.mask
2416 };
2417
2418 delete r.set_mark;
2419 }
2420
2421 let set_types = map_setmatch(ipset, rule.ipset, proto.name);
2422
2423 if (set_types !== set_types) {
2424 this.warn_section(data, "destination MAC address matching not supported");
2425 return;
2426 } else if (set_types) {
2427 r.ipset = { ...r.ipset, fields: set_types };
2428 }
2429
2430 if (r.target == "notrack") {
2431 r.chain = `notrack_${r.src.zone.name}`;
2432 r.src.zone.dflags.notrack = true;
2433 }
2434 else if (r.target == "helper") {
2435 r.chain = `helper_${r.src.zone.name}`;
2436 r.src.zone.dflags.helper = true;
2437 }
2438 else if (r.target == "mark" || r.target == "dscp") {
2439 if ((r.src?.any && r.dest?.any) || (r.src?.zone && r.dest?.zone))
2440 r.chain = "mangle_forward";
2441 else if (r.src?.any && r.dest?.zone)
2442 r.chain = "mangle_postrouting";
2443 else if (r.src?.zone && r.dest?.any)
2444 r.chain = "mangle_prerouting";
2445 else if (r.src && !r.dest)
2446 r.chain = "mangle_input";
2447 else
2448 r.chain = "mangle_output";
2449
2450 if (r.src?.zone) {
2451 r.src.zone.dflags[r.target] = true;
2452 r.iifnames = null_if_empty(r.src.zone.match_devices);
2453 }
2454
2455 if (r.dest?.zone) {
2456 r.dest.zone.dflags[r.target] = true;
2457 r.oifnames = null_if_empty(r.dest.zone.match_devices);
2458 }
2459 }
2460 else {
2461 r.chain = "output";
2462
2463 if (r.src) {
2464 if (!r.src.any)
2465 r.chain = `${r.dest ? "forward" : "input"}_${r.src.zone.name}`;
2466 else
2467 r.chain = r.dest ? "forward" : "input";
2468 }
2469
2470 if (r.dest && !r.src) {
2471 if (!r.dest.any)
2472 r.chain = sprintf("output_%s", r.dest.zone.name);
2473 else
2474 r.chain = "output";
2475 }
2476
2477 if (r.target && r.dest && !r.dest.any) {
2478 r.jump_chain = `${r.target}_to_${r.dest.zone.name}`;
2479 r.dest.zone.dflags[r.target] = true;
2480 }
2481 else if (r.target && need_src_action_chain(r)) {
2482 r.jump_chain = `${r.target}_from_${r.src.zone.name}`;
2483 r.src.zone.sflags[r.target] = true;
2484 }
2485 else if (r.target == "reject")
2486 r.jump_chain = "handle_reject";
2487 }
2488
2489 if (r.device)
2490 r[r.direction ? "oifnames" : "iifnames"] = [ r.device.device ];
2491
2492 push(this.state.rules ||= [], r);
2493 };
2494
2495 for (let proto in rule.proto) {
2496 let sip, dip, sports, dports, itypes4, itypes6;
2497 let family = rule.family;
2498
2499 switch (proto.name) {
2500 case "icmp":
2501 itypes4 = filter(rule.icmp_type || [], family_is_ipv4);
2502 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2503 break;
2504
2505 case "ipv6-icmp":
2506 family = 6;
2507 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2508 break;
2509
2510 case "tcp":
2511 case "udp":
2512 sports = rule.src_port;
2513 dports = rule.dest_port;
2514 break;
2515 }
2516
2517 sip = subnets_split_af(rule.src_ip);
2518 dip = subnets_split_af(rule.dest_ip);
2519
2520 family = infer_family(family, [
2521 ipset, "set match",
2522 sip, "source IP",
2523 dip, "destination IP",
2524 rule.src?.zone, "source zone",
2525 rule.dest?.zone, "destination zone",
2526 rule.helper, "helper match",
2527 rule.set_helper, "helper to set"
2528 ]);
2529
2530 if (type(family) == "string") {
2531 this.warn_section(data, `${family}, skipping`);
2532 continue;
2533 }
2534
2535 let has_ipv4_specifics = (length(sip[0]) || length(dip[0]) || length(itypes4) || rule.dscp !== null);
2536 let has_ipv6_specifics = (length(sip[1]) || length(dip[1]) || length(itypes6) || rule.dscp !== null);
2537
2538 /* if no family was configured, infer target family from IP addresses */
2539 if (family === null) {
2540 if (has_ipv4_specifics && !has_ipv6_specifics)
2541 family = 4;
2542 else if (has_ipv6_specifics && !has_ipv4_specifics)
2543 family = 6;
2544 else
2545 family = 0;
2546 }
2547
2548 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2549 if (!family && rule.target != "dscp" && !has_ipv4_specifics && !has_ipv6_specifics) {
2550 add_rule(0, proto, [], [], sports, dports, null, null, null, rule);
2551 }
2552
2553 /* we need to emit one or two AF specific rules */
2554 else {
2555 if (family == 0 || family == 4) {
2556 let icmp_types = filter(itypes4, i => (i.code_min == 0 && i.code_max == 0xFF));
2557 let icmp_codes = filter(itypes4, i => (i.code_min != 0 || i.code_max != 0xFF));
2558
2559 for (let saddrs in subnets_group_by_masking(sip[0])) {
2560 for (let daddrs in subnets_group_by_masking(dip[0])) {
2561 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2562 add_rule(4, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2563
2564 if (length(icmp_codes))
2565 add_rule(4, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2566 }
2567 }
2568 }
2569
2570 if (family == 0 || family == 6) {
2571 let icmp_types = filter(itypes6, i => (i.code_min == 0 && i.code_max == 0xFF));
2572 let icmp_codes = filter(itypes6, i => (i.code_min != 0 || i.code_max != 0xFF));
2573
2574 for (let saddrs in subnets_group_by_masking(sip[1])) {
2575 for (let daddrs in subnets_group_by_masking(dip[1])) {
2576 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2577 add_rule(6, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2578
2579 if (length(icmp_codes))
2580 add_rule(6, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2581 }
2582 }
2583 }
2584 }
2585 }
2586 },
2587
2588 parse_redirect: function(data) {
2589 let redir = this.parse_options(data, {
2590 enabled: [ "bool", "1" ],
2591
2592 name: [ "string", this.section_id(data[".name"]) ],
2593 _name: [ "string", null, DEPRECATED ],
2594 family: [ "family" ],
2595
2596 src: [ "zone_ref" ],
2597 dest: [ "zone_ref" ],
2598
2599 ipset: [ "setmatch" ],
2600 helper: [ "cthelper", null, NO_INVERT ],
2601
2602 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2603
2604 src_ip: [ "network" ],
2605 src_mac: [ "mac", null, PARSE_LIST ],
2606 src_port: [ "port" ],
2607
2608 src_dip: [ "network" ],
2609 src_dport: [ "port" ],
2610
2611 dest_ip: [ "network" ],
2612 dest_port: [ "port" ],
2613
2614 extra: [ "string", null, UNSUPPORTED ],
2615
2616 limit: [ "limit" ],
2617 limit_burst: [ "int" ],
2618
2619 utc_time: [ "bool" ],
2620 start_date: [ "date" ],
2621 stop_date: [ "date" ],
2622 start_time: [ "time" ],
2623 stop_time: [ "time" ],
2624 weekdays: [ "weekdays" ],
2625 monthdays: [ "monthdays", null, UNSUPPORTED ],
2626
2627 mark: [ "mark" ],
2628
2629 reflection: [ "bool", "1" ],
2630 reflection_src: [ "reflection_source", "internal" ],
2631
2632 reflection_zone: [ "zone_ref", null, PARSE_LIST ],
2633
2634 counter: [ "bool", "1" ],
2635 log: [ "string" ],
2636
2637 target: [ "target", "dnat" ]
2638 });
2639
2640 if (redir === false) {
2641 this.warn_section(data, "skipped due to invalid options");
2642 return;
2643 }
2644 else if (!redir.enabled) {
2645 this.warn_section(data, "is disabled, ignoring section");
2646 return;
2647 }
2648
2649 if (!(redir.target in ["dnat", "snat"])) {
2650 this.warn_section(data, "has invalid target specified, defaulting to dnat");
2651 redir.target = "dnat";
2652 }
2653
2654 switch (this.parse_bool(redir.log)) {
2655 case true:
2656 redir.log = `${redir.name}: `;
2657 break;
2658
2659 case false:
2660 delete redir.log;
2661 }
2662
2663 let ipset;
2664
2665 if (redir.ipset) {
2666 ipset = filter(this.state.ipsets, s => (s.name == redir.ipset.name))?.[0];
2667
2668 if (!ipset) {
2669 this.warn_section(data, `references unknown set '${redir.ipset.name}'`);
2670 return;
2671 }
2672
2673 if (('inet_service' in ipset.types) && !ensure_tcpudp(redir.proto)) {
2674 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2675 return;
2676 }
2677 }
2678
2679 let resolve_dest = (redir) => {
2680 for (let zone in this.state.zones) {
2681 for (let zone_addr in zone.related_subnets) {
2682 for (let dest_addr in redir.dest_ip.addrs) {
2683 if (dest_addr.family != zone_addr.family)
2684 continue;
2685
2686 let a = apply_mask(dest_addr.addr, zone_addr.mask);
2687 let b = apply_mask(zone_addr.addr, zone_addr.mask);
2688
2689 if (a != b)
2690 continue;
2691
2692 redir.dest = {
2693 any: false,
2694 zone: zone
2695 };
2696
2697 return true;
2698 }
2699 }
2700 }
2701
2702 return false;
2703 };
2704
2705 if (redir.target == "dnat") {
2706 if (!redir.src)
2707 return this.warn_section(data, "has no source specified");
2708 else if (redir.src.any)
2709 return this.warn_section(data, "must not have source '*' for dnat target");
2710 else if (redir.dest_ip && redir.dest_ip.invert)
2711 return this.warn_section(data, "must not specify a negated 'dest_ip' value");
2712 else if (redir.dest_ip && length(filter(redir.dest_ip.addrs, a => a.bits == -1)))
2713 return this.warn_section(data, "must not use non-contiguous masks in 'dest_ip'");
2714
2715 if (!redir.dest && redir.dest_ip && resolve_dest(redir))
2716 this.warn_section(data, `does not specify a destination, assuming '${redir.dest.zone.name}'`);
2717
2718 if (!redir.dest_port)
2719 redir.dest_port = redir.src_dport;
2720
2721 if (redir.reflection && redir.dest?.zone && redir.src.zone.masq) {
2722 redir.dest.zone.dflags.accept = true;
2723 redir.dest.zone.dflags.dnat = true;
2724 redir.dest.zone.dflags.snat = true;
2725 }
2726
2727 if (redir.helper)
2728 redir.src.zone.dflags.helper = true;
2729
2730 redir.src.zone.dflags[redir.target] = true;
2731 }
2732 else {
2733 if (!redir.dest)
2734 return this.warn_section(data, "has no destination specified");
2735 else if (redir.dest.any)
2736 return this.warn_section(data, "must not have destination '*' for snat target");
2737 else if (!redir.src_dip)
2738 return this.warn_section(data, "has no 'src_dip' option specified");
2739 else if (redir.src_dip.invert)
2740 return this.warn_section(data, "must not specify a negated 'src_dip' value");
2741 else if (length(filter(redir.src_dip.addrs, a => a.bits == -1)))
2742 return this.warn_section(data, "must not use non-contiguous masks in 'src_dip'");
2743 else if (redir.src_mac)
2744 return this.warn_section(data, "must not use 'src_mac' option for snat target");
2745 else if (redir.helper)
2746 return this.warn_section(data, "must not use 'helper' option for snat target");
2747
2748 redir.dest.zone.dflags[redir.target] = true;
2749 }
2750
2751 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, ipset, redir) => {
2752 let r = {
2753 ...redir,
2754
2755 family: family,
2756 proto: proto,
2757 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2758 has_ports: !!(sport || dport || rport),
2759 saddrs_pos: map(saddrs[0], this.cidr),
2760 saddrs_neg: map(saddrs[1], this.cidr),
2761 saddrs_masked: saddrs[2],
2762 daddrs_pos: map(daddrs[0], this.cidr),
2763 daddrs_neg: map(daddrs[1], this.cidr),
2764 daddrs_masked: daddrs[2],
2765 sports_pos: map(filter_pos(to_array(sport)), this.port),
2766 sports_neg: map(filter_neg(to_array(sport)), this.port),
2767 dports_pos: map(filter_pos(to_array(dport)), this.port),
2768 dports_neg: map(filter_neg(to_array(dport)), this.port),
2769 smacs_pos: map(filter_pos(redir.src_mac), m => m.mac),
2770 smacs_neg: map(filter_neg(redir.src_mac), m => m.mac),
2771
2772 raddr: raddrs ? raddrs[0] : null,
2773 rport: rport
2774 };
2775
2776 let set_types = map_setmatch(ipset, redir.ipset, proto.name);
2777
2778 if (set_types !== set_types) {
2779 this.warn_section(data, "destination MAC address matching not supported");
2780 return;
2781 } else if (set_types) {
2782 r.ipset = { ...r.ipset, fields: set_types };
2783 }
2784
2785 switch (r.target) {
2786 case "dnat":
2787 r.chain = `dstnat_${r.src.zone.name}`;
2788 r.src.zone.dflags.dnat = true;
2789
2790 if (!r.raddr)
2791 r.target = "redirect";
2792
2793 break;
2794
2795 case "snat":
2796 r.chain = `srcnat_${r.dest.zone.name}`;
2797 r.dest.zone.dflags.snat = true;
2798 break;
2799 }
2800
2801 push(this.state.redirects ||= [], r);
2802 };
2803
2804 let to_hostaddr = (a) => {
2805 let bits = (a.family == 4) ? 32 : 128;
2806
2807 return {
2808 family: a.family,
2809 addr: apply_mask(a.addr, bits),
2810 bits: bits
2811 };
2812 };
2813
2814 for (let proto in redir.proto) {
2815 let sip, dip, rip, iip, eip, refip, sport, dport, rport;
2816 let family = redir.family;
2817
2818 if (proto.name == "ipv6-icmp")
2819 family = 6;
2820
2821 switch (redir.target) {
2822 case "dnat":
2823 sip = subnets_split_af(redir.src_ip);
2824 dip = subnets_split_af(redir.src_dip);
2825 rip = subnets_split_af(redir.dest_ip);
2826
2827 switch (proto.name) {
2828 case "tcp":
2829 case "udp":
2830 sport = redir.src_port;
2831 dport = redir.src_dport;
2832 rport = redir.dest_port;
2833 break;
2834 }
2835
2836 break;
2837
2838 case "snat":
2839 sip = subnets_split_af(redir.src_ip);
2840 dip = subnets_split_af(redir.dest_ip);
2841 rip = subnets_split_af(redir.src_dip);
2842
2843 switch (proto.name) {
2844 case "tcp":
2845 case "udp":
2846 sport = redir.src_port;
2847 dport = redir.dest_port;
2848 rport = redir.src_dport;
2849 break;
2850 }
2851
2852 break;
2853 }
2854
2855 family = infer_family(family, [
2856 ipset, "set match",
2857 sip, "source IP",
2858 dip, "destination IP",
2859 rip, "rewrite IP",
2860 redir.src?.zone, "source zone",
2861 redir.dest?.zone, "destination zone",
2862 redir.helper, "helper match"
2863 ]);
2864
2865 if (type(family) == "string") {
2866 this.warn_section(data, `${family}, skipping`);
2867 continue;
2868 }
2869
2870 /* build reflection rules */
2871 if (redir.target == "dnat" && redir.reflection &&
2872 (length(rip[0]) || length(rip[1])) && redir.src?.zone && redir.dest?.zone) {
2873 let refredir = {
2874 name: `${redir.name} (reflection)`,
2875
2876 helper: redir.helper,
2877
2878 // XXX: this likely makes no sense for reflection rules
2879 //src_mac: redir.src_mac,
2880
2881 limit: redir.limit,
2882 limit_burst: redir.limit_burst,
2883
2884 start_date: redir.start_date,
2885 stop_date: redir.stop_date,
2886 start_time: redir.start_time,
2887 stop_time: redir.stop_time,
2888 weekdays: redir.weekdays,
2889
2890 mark: redir.mark
2891 };
2892
2893 let eaddrs = length(dip) ? dip : subnets_split_af({ addrs: map(redir.src.zone.related_subnets, to_hostaddr) });
2894 let rzones = length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
2895
2896 for (let rzone in rzones) {
2897 if (!is_family(rzone, family)) {
2898 this.warn_section(data,
2899 `is restricted to IPv${family} but referenced reflection zone is IPv${rzone.family} only, skipping`);
2900 continue;
2901 }
2902
2903 let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
2904 let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
2905
2906 for (let i = 0; i <= 1; i++) {
2907 if (redir.src.zone[i ? "masq6" : "masq"] && length(rip[i])) {
2908 let snat_addr = refaddrs[i]?.[0];
2909
2910 /* For internal reflection sources try to find a suitable candiate IP
2911 * among the reflection zone subnets which is within the same subnet
2912 * as the original DNAT destination. If we can't find any matching
2913 * one then simply take the first candidate. */
2914 if (redir.reflection_src == "internal") {
2915 for (let zone_addr in rzone.zone.related_subnets) {
2916 if (zone_addr.family != rip[i][0].family)
2917 continue;
2918
2919 let r = apply_mask(rip[i][0].addr, zone_addr.mask);
2920 let a = apply_mask(zone_addr.addr, zone_addr.mask);
2921
2922 if (r != a)
2923 continue;
2924
2925 snat_addr = zone_addr;
2926 break;
2927 }
2928 }
2929
2930 if (!snat_addr) {
2931 this.warn_section(data, `${redir.reflection_src || "external"} rewrite IP cannot be determined, disabling reflection`);
2932 }
2933 else if (!length(iaddrs[i])) {
2934 this.warn_section(data, "internal address range cannot be determined, disabling reflection");
2935 }
2936 else if (!length(eaddrs[i])) {
2937 this.warn_section(data, "external address range cannot be determined, disabling reflection");
2938 }
2939 else {
2940 refredir.src = rzone;
2941 refredir.dest = null;
2942 refredir.target = "dnat";
2943
2944 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2945 for (let daddrs in subnets_group_by_masking(eaddrs[i]))
2946 add_rule(i ? 6 : 4, proto, saddrs, daddrs, rip[i], sport, dport, rport, null, refredir);
2947
2948 refredir.src = null;
2949 refredir.dest = rzone;
2950 refredir.target = "snat";
2951
2952 for (let daddrs in subnets_group_by_masking(rip[i]))
2953 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2954 add_rule(i ? 6 : 4, proto, saddrs, daddrs, [ to_hostaddr(snat_addr) ], null, rport, null, null, refredir);
2955 }
2956 }
2957 }
2958 }
2959 }
2960
2961 if (length(rip[0]) > 1 || length(rip[1]) > 1)
2962 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
2963
2964 let has_ip4_addr = length(sip[0]) || length(dip[0]) || length(rip[0]),
2965 has_ip6_addr = length(sip[1]) || length(dip[1]) || length(rip[1]),
2966 has_any_addr = has_ip4_addr || has_ip6_addr;
2967
2968 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2969 if (!family && !has_any_addr) {
2970 /* for backwards compatibility, treat unspecified family as IPv4 unless user explicitly requested any (0) */
2971 if (family == null)
2972 family = 4;
2973
2974 add_rule(family, proto, [], [], null, sport, dport, rport, null, redir);
2975 }
2976
2977 /* we need to emit one or two AF specific rules */
2978 else {
2979 if ((!family || family == 4) && (!has_any_addr || has_ip4_addr)) {
2980 for (let saddrs in subnets_group_by_masking(sip[0]))
2981 for (let daddrs in subnets_group_by_masking(dip[0]))
2982 add_rule(4, proto, saddrs, daddrs, rip[0], sport, dport, rport, ipset, redir);
2983 }
2984
2985 if ((!family || family == 6) && (!has_any_addr || has_ip6_addr)) {
2986 for (let saddrs in subnets_group_by_masking(sip[1]))
2987 for (let daddrs in subnets_group_by_masking(dip[1]))
2988 add_rule(6, proto, saddrs, daddrs, rip[1], sport, dport, rport, ipset, redir);
2989 }
2990 }
2991 }
2992 },
2993
2994 parse_nat: function(data) {
2995 let snat = this.parse_options(data, {
2996 enabled: [ "bool", "1" ],
2997
2998 name: [ "string", this.section_id(data[".name"]) ],
2999 family: [ "family" ],
3000
3001 src: [ "zone_ref" ],
3002 device: [ "string" ],
3003
3004 ipset: [ "setmatch", null, UNSUPPORTED ],
3005
3006 proto: [ "protocol", "all", PARSE_LIST | FLATTEN_LIST ],
3007
3008 src_ip: [ "network" ],
3009 src_port: [ "port" ],
3010
3011 snat_ip: [ "network", null, NO_INVERT ],
3012 snat_port: [ "port", null, NO_INVERT ],
3013
3014 dest_ip: [ "network" ],
3015 dest_port: [ "port" ],
3016
3017 extra: [ "string", null, UNSUPPORTED ],
3018
3019 limit: [ "limit" ],
3020 limit_burst: [ "int" ],
3021
3022 connlimit_ports: [ "bool" ],
3023
3024 utc_time: [ "bool" ],
3025 start_date: [ "date" ],
3026 stop_date: [ "date" ],
3027 start_time: [ "time" ],
3028 stop_time: [ "time" ],
3029 weekdays: [ "weekdays" ],
3030 monthdays: [ "monthdays", null, UNSUPPORTED ],
3031
3032 mark: [ "mark" ],
3033
3034 counter: [ "bool", "1" ],
3035 log: [ "string" ],
3036
3037 target: [ "target", "masquerade" ]
3038 });
3039
3040 if (snat === false) {
3041 this.warn_section(data, "skipped due to invalid options");
3042 return;
3043 }
3044 else if (!snat.enabled) {
3045 this.warn_section(data, "is disabled, ignoring section");
3046 return;
3047 }
3048
3049 if (!(snat.target in ["accept", "snat", "masquerade"])) {
3050 this.warn_section(data, "has invalid target specified, defaulting to masquerade");
3051 snat.target = "masquerade";
3052 }
3053
3054 if (snat.target == "snat" && !snat.snat_ip && !snat.snat_port) {
3055 this.warn_section(data, "needs either 'snat_ip' or 'snat_port' for target snat, ignoring section");
3056 return;
3057 }
3058 else if (snat.target != "snat" && snat.snat_ip) {
3059 this.warn_section(data, "must not use 'snat_ip' for non-snat target, ignoring section");
3060 return;
3061 }
3062 else if (snat.target != "snat" && snat.snat_port) {
3063 this.warn_section(data, "must not use 'snat_port' for non-snat target, ignoring section");
3064 return;
3065 }
3066
3067 if ((snat.snat_port || snat.src_port || snat.dest_port) && !ensure_tcpudp(snat.proto)) {
3068 this.warn_section(data, "specifies ports but no UDP/TCP protocol, ignoring section");
3069 return;
3070 }
3071
3072 if (snat.snat_ip && length(filter(snat.snat_ip.addrs, a => a.bits == -1 || a.invert))) {
3073 this.warn_section(data, "must not use inversion or non-contiguous masks in 'snat_ip', ignoring section");
3074 return;
3075 }
3076
3077 switch (this.parse_bool(snat.log)) {
3078 case true:
3079 snat.log = `${snat.name}: `;
3080 break;
3081
3082 case false:
3083 delete snat.log;
3084 }
3085
3086 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, snat) => {
3087 let n = {
3088 ...snat,
3089
3090 family: family,
3091 proto: proto,
3092 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
3093 has_ports: !!(sport || dport),
3094 saddrs_pos: map(saddrs[0], this.cidr),
3095 saddrs_neg: map(saddrs[1], this.cidr),
3096 saddrs_masked: saddrs[2],
3097 daddrs_pos: map(daddrs[0], this.cidr),
3098 daddrs_neg: map(daddrs[1], this.cidr),
3099 daddrs_masked: daddrs[2],
3100 sports_pos: map(filter_pos(to_array(sport)), this.port),
3101 sports_neg: map(filter_neg(to_array(sport)), this.port),
3102 dports_pos: map(filter_pos(to_array(dport)), this.port),
3103 dports_neg: map(filter_neg(to_array(dport)), this.port),
3104
3105 raddr: raddrs ? raddrs[0] : null,
3106 rport: rport,
3107
3108 chain: snat.src?.zone ? `srcnat_${snat.src.zone.name}` : "srcnat"
3109 };
3110
3111 push(this.state.redirects ||= [], n);
3112 };
3113
3114 for (let proto in snat.proto) {
3115 let sip, dip, rip, sport, dport, rport;
3116 let family = snat.family;
3117
3118 sip = subnets_split_af(snat.src_ip);
3119 dip = subnets_split_af(snat.dest_ip);
3120 rip = subnets_split_af(snat.snat_ip);
3121
3122 switch (proto.name) {
3123 case "tcp":
3124 case "udp":
3125 sport = snat.src_port;
3126 dport = snat.dest_port;
3127 rport = snat.snat_port;
3128 break;
3129 }
3130
3131 if (length(rip[0]) > 1 || length(rip[1]) > 1)
3132 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
3133
3134 family = infer_family(family, [
3135 sip, "source IP",
3136 dip, "destination IP",
3137 rip, "rewrite IP",
3138 snat.src?.zone, "source zone"
3139 ]);
3140
3141 if (type(family) == "string") {
3142 this.warn_section(data, `${family}, skipping`);
3143 continue;
3144 }
3145
3146 if (snat.src?.zone)
3147 snat.src.zone.dflags.snat = true;
3148
3149 /* if no family was configured, infer target family from IP addresses */
3150 if (family === null) {
3151 if ((length(sip[0]) || length(dip[0]) || length(rip[0])) && !length(sip[1]) && !length(dip[1]) && !length(rip[1]))
3152 family = 4;
3153 else if ((length(sip[1]) || length(dip[1]) || length(rip[1])) && !length(sip[0]) && !length(dip[0]) && !length(rip[0]))
3154 family = 6;
3155 else
3156 family = 4; /* default to IPv4 only for backwards compatibility, unless an explict family any was configured */
3157 }
3158
3159 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
3160 if (!family && !length(sip[0]) && !length(sip[1]) && !length(dip[0]) && !length(dip[1]) && !length(rip[0]) && !length(rip[1])) {
3161 add_rule(0, proto, [], [], null, sport, dport, rport, snat);
3162 }
3163
3164 /* we need to emit one or two AF specific rules */
3165 else {
3166 if (family == 0 || family == 4)
3167 for (let saddr in subnets_group_by_masking(sip[0]))
3168 for (let daddr in subnets_group_by_masking(dip[0]))
3169 add_rule(4, proto, saddr, daddr, rip[0], sport, dport, rport, snat);
3170
3171 if (family == 0 || family == 6)
3172 for (let saddr in subnets_group_by_masking(sip[1]))
3173 for (let daddr in subnets_group_by_masking(dip[1]))
3174 add_rule(6, proto, saddr, daddr, rip[1], sport, dport, rport, snat);
3175 }
3176 }
3177 },
3178
3179 parse_include: function(data) {
3180 let inc = this.parse_options(data, {
3181 enabled: [ "bool", "1" ],
3182
3183 path: [ "string", null, REQUIRED ],
3184 type: [ "includetype", "script" ],
3185
3186 fw4_compatible: [ "bool", data.path != "/etc/firewall.user" ],
3187
3188 family: [ "family", null, UNSUPPORTED ],
3189 reload: [ "bool", null, UNSUPPORTED ],
3190
3191 position: [ "includeposition" ],
3192 chain: [ "identifier" ]
3193 });
3194
3195 if (!inc.enabled) {
3196 this.warn_section(data, "is disabled, ignoring section");
3197 return;
3198 }
3199
3200 if (inc.type == "script" && !inc.fw4_compatible) {
3201 this.warn_section(data, "is not marked as compatible with fw4, ignoring section");
3202 this.warn_section(data, "requires 'option fw4_compatible 1' to be considered compatible");
3203 return;
3204 }
3205
3206 for (let opt in [ "table", "chain", "position" ]) {
3207 if (inc.type != "nftables" && inc[opt]) {
3208 this.warn_section(data, `must not specify '${opt}' for non-nftables includes, ignoring section`);
3209 return;
3210 }
3211 }
3212
3213 switch (inc.position ??= 'table-append') {
3214 case 'ruleset-prepend':
3215 case 'ruleset-append':
3216 case 'table-prepend':
3217 case 'table-append':
3218 if (inc.chain)
3219 this.warn_section(data, `specifies 'chain' which has no effect for position ${inc.position}`);
3220
3221 delete inc.chain;
3222 break;
3223
3224 case 'chain-prepend':
3225 case 'chain-append':
3226 if (!inc.chain) {
3227 this.warn_section(data, `must specify 'chain' for position ${inc.position}, ignoring section`);
3228 return;
3229 }
3230
3231 break;
3232 }
3233
3234 let path = fs.readlink(inc.path) ?? inc.path;
3235
3236 if (!fs.access(path)) {
3237 this.warn_section(data, `specifies unreachable path '${path}', ignoring section`);
3238 return;
3239 }
3240
3241 if (!data['.name'])
3242 this.warn(`Automatically including '${path}'`);
3243
3244 push(this.state.includes ||= [], { ...inc, path });
3245 },
3246
3247 parse_ipset: function(data) {
3248 let ipset = this.parse_options(data, {
3249 enabled: [ "bool", "1" ],
3250 reload_set: [ "bool" ],
3251 counters: [ "bool" ],
3252 comment: [ "string" ],
3253
3254 name: [ "identifier", null, REQUIRED ],
3255 family: [ "family", "4" ],
3256
3257 storage: [ "string", null, UNSUPPORTED ],
3258 match: [ "ipsettype", null, PARSE_LIST ],
3259
3260 iprange: [ "string", null, UNSUPPORTED ],
3261 portrange: [ "string", null, UNSUPPORTED ],
3262
3263 netmask: [ "int", null, UNSUPPORTED ],
3264 maxelem: [ "int" ],
3265 hashsize: [ "int", null, UNSUPPORTED ],
3266 timeout: [ "int", "-1" ],
3267
3268 external: [ "string", null, UNSUPPORTED ],
3269
3270 entry: [ "string", null, PARSE_LIST ],
3271 loadfile: [ "string" ]
3272 });
3273
3274 if (ipset === false) {
3275 this.warn_section(data, "skipped due to invalid options");
3276 return;
3277 }
3278 else if (!ipset.enabled) {
3279 this.warn_section(data, "is disabled, ignoring section");
3280 return;
3281 }
3282
3283 if (ipset.family == 0) {
3284 this.warn_section(data, "must not specify family 'any'");
3285 return;
3286 }
3287 else if (!length(ipset.match)) {
3288 this.warn_section(data, "has no datatypes assigned");
3289 return;
3290 }
3291
3292 let dirs = map(ipset.match, m => m[0]),
3293 types = map(ipset.match, m => m[1]),
3294 interval = false;
3295
3296 if ("set" in types) {
3297 this.warn_section(data, "match type 'set' is not supported");
3298 return;
3299 }
3300
3301 if ("net" in types) {
3302 if (this.kernel < 0x05060000) {
3303 this.warn_section(data, "match type 'net' requires kernel 5.6 or later");
3304 return;
3305 }
3306
3307 interval = true;
3308 }
3309
3310 let s = {
3311 ...ipset,
3312
3313 fw4types: types,
3314
3315 types: map(types, (t) => {
3316 switch (t) {
3317 case 'ip':
3318 case 'net':
3319 return (ipset.family == 4) ? 'ipv4_addr' : 'ipv6_addr';
3320
3321 case 'mac':
3322 return 'ether_addr';
3323
3324 case 'port':
3325 return 'inet_service';
3326 }
3327 }),
3328
3329 directions: dirs,
3330 interval: interval
3331 };
3332
3333 if (s.interval)
3334 push(s.flags ??= [], 'interval');
3335
3336 if (s.timeout >= 0)
3337 push(s.flags ??= [], 'timeout');
3338
3339 s.entries = filter(map(ipset.entry, (e) => {
3340 let v = this.parse_ipsetentry(e, s);
3341
3342 if (!v)
3343 this.warn_section(data, `ignoring invalid ipset entry '${e}'`);
3344
3345 return v;
3346 }), (e) => (e != null));
3347
3348 push(this.state.ipsets ||= [], s);
3349 }
3350 };