033083505a03126505cc9123bb49d842cf12d975
[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_string: function(val) {
1577 return "" + val;
1578 },
1579
1580 parse_opt: function(s, opt, fn, defval, flags) {
1581 let val = s[opt];
1582
1583 if (val === null) {
1584 if (flags & REQUIRED) {
1585 this.warn_section(s, `option '${opt}' is mandatory but not set`);
1586 return NaN;
1587 }
1588
1589 val = defval;
1590 }
1591
1592 if (type(val) == "array") {
1593 this.warn_section(s, `option '${opt}' must not be a list`);
1594 return NaN;
1595 }
1596 else if (val == null) {
1597 return null;
1598 }
1599
1600 let res = this[fn](val);
1601
1602 if (res === null) {
1603 this.warn_section(s, `option '${opt}' specifies invalid value '${val}'`);
1604 return NaN;
1605 }
1606
1607 return res;
1608 },
1609
1610 parse_list: function(s, opt, fn, defval, flags) {
1611 let val = s[opt];
1612 let rv = [];
1613
1614 if (val == null) {
1615 if (flags & REQUIRED) {
1616 this.warn_section(s, `option '${opt}' is mandatory but not set`);
1617 return NaN;
1618 }
1619
1620 val = defval;
1621 }
1622
1623 for (val in to_array(val)) {
1624 let res = this[fn](val);
1625
1626 if (res === null) {
1627 this.warn_section(s, `option '${opt}' specifies invalid value '${val}'`);
1628 return NaN;
1629 }
1630
1631 if (flags & FLATTEN_LIST)
1632 push(rv, ...to_array(res));
1633 else
1634 push(rv, res);
1635 }
1636
1637 return length(rv) ? rv : null;
1638 },
1639
1640 quote: function(s, force) {
1641 if (force === true || !match(s, /^([0-9A-Fa-f:.\/-]+)( \. [0-9A-Fa-f:.\/-]+)*$/))
1642 return `"${replace(s + "", /(["\\])/g, '\\$1')}"`;
1643
1644 return s;
1645 },
1646
1647 cidr: function(a) {
1648 if (a.range)
1649 return `${a.addr}-${a.addr2}`;
1650
1651 if ((a.family == 4 && a.bits == 32) ||
1652 (a.family == 6 && a.bits == 128))
1653 return a.addr;
1654
1655 if (a.bits >= 0)
1656 return `${apply_mask(a.addr, a.bits)}/${a.bits}`;
1657
1658 return `${a.addr}/${a.mask}`;
1659 },
1660
1661 host: function(a, v6brackets) {
1662 return a.range
1663 ? `${a.addr}-${a.addr2}`
1664 : (a.family == 6 && v6brackets)
1665 ? `[${apply_mask(a.addr, a.bits)}]` : apply_mask(a.addr, a.bits);
1666 },
1667
1668 port: function(p) {
1669 if (p.min == p.max)
1670 return `${p.min}`;
1671
1672 return `${p.min}-${p.max}`;
1673 },
1674
1675 set: function(v, force) {
1676 let seen = {};
1677
1678 v = filter(to_array(v), item => !seen[item]++);
1679
1680 if (force || length(v) != 1)
1681 return `{ ${join(', ', map(v, this.quote))} }`;
1682
1683 return this.quote(v[0]);
1684 },
1685
1686 concat: function(v) {
1687 return join(' . ', to_array(v));
1688 },
1689
1690 ipproto: function(family) {
1691 switch (family) {
1692 case 4:
1693 return "ip";
1694
1695 case 6:
1696 return "ip6";
1697 }
1698 },
1699
1700 nfproto: function(family, human_readable) {
1701 switch (family) {
1702 case 4:
1703 return human_readable ? "IPv4" : "ipv4";
1704
1705 case 6:
1706 return human_readable ? "IPv6" : "ipv6";
1707
1708 default:
1709 return human_readable ? "IPv4/IPv6" : null;
1710 }
1711 },
1712
1713 l4proto: function(family, proto) {
1714 switch (proto.name) {
1715 case 'icmp':
1716 switch (family ?? 0) {
1717 case 0:
1718 return this.set(['icmp', 'ipv6-icmp']);
1719
1720 case 6:
1721 return 'ipv6-icmp';
1722 }
1723
1724 default:
1725 return proto.name;
1726 }
1727 },
1728
1729 datetime: function(stamp) {
1730 return sprintf('"%04d-%02d-%02d %02d:%02d:%02d"',
1731 stamp.year, stamp.month, stamp.day,
1732 stamp.hour, stamp.min, stamp.sec);
1733 },
1734
1735 date: function(stamp) {
1736 return sprintf('"%04d-%02d-%02d"', stamp.year, stamp.month, stamp.day);
1737 },
1738
1739 datestamp: function(stamp) {
1740 return exists(stamp, 'hour') ? this.datetime(stamp) : this.date(stamp);
1741 },
1742
1743 time: function(stamp) {
1744 return sprintf('"%02d:%02d:%02d"', stamp.hour, stamp.min, stamp.sec);
1745 },
1746
1747 hex: function(n) {
1748 return sprintf('0x%x', n);
1749 },
1750
1751 is_loopback_dev: function(dev) {
1752 return !!(+fs.readfile(`/sys/class/net/${dev}/flags`) & 0x8);
1753 },
1754
1755 is_loopback_addr: function(addr) {
1756 return (index(addr, "127.") == 0 || addr == "::1" || addr == "::1/128");
1757 },
1758
1759 filter_loopback_devs: function(devs, invert) {
1760 return null_if_empty(filter(devs, d => (this.is_loopback_dev(d) == invert)));
1761 },
1762
1763 filter_loopback_addrs: function(addrs, invert) {
1764 return null_if_empty(filter(addrs, a => (this.is_loopback_addr(a) == invert)));
1765 },
1766
1767
1768 input_policy: function(reject_as_drop) {
1769 return (!reject_as_drop || this.state.defaults.input != 'reject') ? this.state.defaults.input : 'drop';
1770 },
1771
1772 output_policy: function(reject_as_drop) {
1773 return (!reject_as_drop || this.state.defaults.output != 'reject') ? this.state.defaults.output : 'drop';
1774 },
1775
1776 forward_policy: function(reject_as_drop) {
1777 return (!reject_as_drop || this.state.defaults.forward != 'reject') ? this.state.defaults.forward : 'drop';
1778 },
1779
1780 default_option: function(flag) {
1781 return this.state.defaults[flag];
1782 },
1783
1784 helpers: function() {
1785 return this.state.helpers;
1786 },
1787
1788 zones: function() {
1789 return this.state.zones;
1790 },
1791
1792 rules: function(chain) {
1793 return filter(this.state.rules, r => (r.chain == chain));
1794 },
1795
1796 redirects: function(chain) {
1797 return filter(this.state.redirects, r => (r.chain == chain));
1798 },
1799
1800 ipsets: function() {
1801 return this.state.ipsets;
1802 },
1803
1804 includes: function(position, chain) {
1805 let stmts = [];
1806 let pad = '';
1807 let pre = '';
1808
1809 switch (position) {
1810 case 'table-prepend':
1811 case 'table-append':
1812 pad = '\t';
1813 pre = '\n';
1814 break;
1815
1816 case 'chain-prepend':
1817 case 'chain-append':
1818 pad = '\t\t';
1819 break;
1820
1821 default:
1822 pre = '\n';
1823 }
1824
1825 push(stmts, pre);
1826
1827 for (let inc in this.state.includes)
1828 if (inc.type == 'nftables' && inc.position == position && (!chain || inc.chain == chain))
1829 push(stmts, `${pad}include "${inc.path}"\n`);
1830
1831 print(length(stmts) > 1 ? join('', stmts) : '');
1832 },
1833
1834 parse_setfile: function(set, cb) {
1835 let fd = fs.open(set.loadfile, "r");
1836
1837 if (!fd) {
1838 warn(`Unable to load file '${set.loadfile}' for set '${set.name}': ${fs.error()}\n`);
1839 return;
1840 }
1841
1842 let count = 0;
1843
1844 for (let line = fd.read("line"); length(line); line = fd.read("line")) {
1845 line = trim(line);
1846
1847 if (length(line) == 0 || ord(line) == 35)
1848 continue;
1849
1850 let v = this.parse_ipsetentry(line, set);
1851
1852 if (!v) {
1853 this.warn(`Skipping invalid entry '${line}' in file '${set.loadfile}' for set '${set.name}'`);
1854 continue;
1855 }
1856
1857 cb(v);
1858
1859 count++;
1860 }
1861
1862 fd.close();
1863
1864 return count;
1865 },
1866
1867 print_setentries: function(set) {
1868 let first = true;
1869 let printer = (entry) => {
1870 if (first) {
1871 print("\t\telements = {\n");
1872 first = false;
1873 }
1874
1875 print("\t\t\t", join(" . ", entry), ",\n");
1876 };
1877
1878 map(set.entries, printer);
1879
1880 if (set.loadfile)
1881 this.parse_setfile(set, printer);
1882
1883 if (!first)
1884 print("\t\t}\n");
1885 },
1886
1887 parse_helper: function(data) {
1888 let helper = this.parse_options(data, {
1889 name: [ "string", null, REQUIRED ],
1890 description: [ "string" ],
1891 module: [ "string" ],
1892 family: [ "family" ],
1893 proto: [ "protocol", null, PARSE_LIST | FLATTEN_LIST | NO_INVERT ],
1894 port: [ "port", null, NO_INVERT ]
1895 });
1896
1897 if (helper === false) {
1898 this.warn("Helper definition '%s' skipped due to invalid options", data.name || data['.name']);
1899 return;
1900 }
1901 else if (helper.proto.any) {
1902 this.warn("Helper definition '%s' must not specify wildcard protocol", data.name || data['.name']);
1903 return;
1904 }
1905 else if (length(helper.proto) > 1) {
1906 this.warn("Helper definition '%s' must not specify multiple protocols", data.name || data['.name']);
1907 return;
1908 }
1909
1910 helper.available = (fs.stat(`/sys/module/${helper.module}`)?.type == "directory");
1911
1912 push(this.state.helpers ||= [], helper);
1913 },
1914
1915 parse_defaults: function(data) {
1916 if (this.state.defaults) {
1917 this.warn_section(data, ": ignoring duplicate defaults section");
1918 return;
1919 }
1920
1921 let defs = this.parse_options(data, {
1922 input: [ "policy", "drop" ],
1923 output: [ "policy", "drop" ],
1924 forward: [ "policy", "drop" ],
1925
1926 drop_invalid: [ "bool" ],
1927 tcp_reject_code: [ "reject_code", "tcp-reset" ],
1928 any_reject_code: [ "reject_code", "port-unreachable" ],
1929
1930 syn_flood: [ "bool" ],
1931 synflood_protect: [ "bool" ],
1932 synflood_rate: [ "limit", "25/second" ],
1933 synflood_burst: [ "int", "50" ],
1934
1935 tcp_syncookies: [ "bool", "1" ],
1936 tcp_ecn: [ "int" ],
1937 tcp_window_scaling: [ "bool", "1" ],
1938
1939 accept_redirects: [ "bool" ],
1940 accept_source_route: [ "bool" ],
1941
1942 auto_helper: [ "bool", "1" ],
1943 custom_chains: [ "bool", null, UNSUPPORTED ],
1944 disable_ipv6: [ "bool", null, UNSUPPORTED ],
1945 flow_offloading: [ "bool", "0" ],
1946 flow_offloading_hw: [ "bool", "0" ],
1947
1948 auto_includes: [ "bool", "1" ]
1949 });
1950
1951 if (defs.synflood_protect === null)
1952 defs.synflood_protect = defs.syn_flood;
1953
1954 delete defs.syn_flood;
1955
1956 this.state.defaults = defs;
1957 },
1958
1959 parse_zone: function(data) {
1960 let zone = this.parse_options(data, {
1961 enabled: [ "bool", "1" ],
1962
1963 name: [ "string", null, REQUIRED ],
1964 family: [ "family" ],
1965
1966 network: [ "device", null, PARSE_LIST ],
1967 device: [ "device", null, PARSE_LIST ],
1968 subnet: [ "network", null, PARSE_LIST ],
1969
1970 input: [ "policy", this.state.defaults ? this.state.defaults.input : "drop" ],
1971 output: [ "policy", this.state.defaults ? this.state.defaults.output : "drop" ],
1972 forward: [ "policy", this.state.defaults ? this.state.defaults.forward : "drop" ],
1973
1974 masq: [ "bool" ],
1975 masq_allow_invalid: [ "bool" ],
1976 masq_src: [ "network", null, PARSE_LIST ],
1977 masq_dest: [ "network", null, PARSE_LIST ],
1978
1979 masq6: [ "bool" ],
1980
1981 extra: [ "string", null, UNSUPPORTED ],
1982 extra_src: [ "string", null, UNSUPPORTED ],
1983 extra_dest: [ "string", null, UNSUPPORTED ],
1984
1985 mtu_fix: [ "bool" ],
1986 custom_chains: [ "bool", null, UNSUPPORTED ],
1987
1988 log: [ "int" ],
1989 log_limit: [ "limit", null, UNSUPPORTED ],
1990
1991 auto_helper: [ "bool", "1" ],
1992 helper: [ "cthelper", null, PARSE_LIST ],
1993
1994 counter: [ "bool", "1" ]
1995 });
1996
1997 if (zone === false) {
1998 this.warn_section(data, "skipped due to invalid options");
1999 return;
2000 }
2001 else if (!zone.enabled) {
2002 this.warn_section(data, "is disabled, ignoring section");
2003 return;
2004 }
2005
2006 for (let helper in zone.helper) {
2007 if (!helper.available) {
2008 this.warn_section(data, `uses unavailable ct helper '${zone.helper.name}'`);
2009 }
2010 }
2011
2012 if (zone.mtu_fix && this.kernel < 0x040a0000) {
2013 this.warn_section(data, "option 'mtu_fix' requires kernel 4.10 or later");
2014 return;
2015 }
2016
2017 if (this.state.defaults?.auto_helper === false)
2018 zone.auto_helper = false;
2019
2020 let match_devices = [];
2021 let related_physdevs = [];
2022 let related_subnets = [];
2023 let related_ubus_networks = [];
2024 let match_subnets, masq_src_subnets, masq_dest_subnets;
2025
2026 for (let name, net in this.state.networks) {
2027 if (net.zone === zone.name)
2028 push(related_ubus_networks, { invert: false, device: name });
2029 }
2030
2031 zone.network = [ ...to_array(zone.network), ...related_ubus_networks ];
2032
2033 for (let e in zone.network) {
2034 if (exists(this.state.networks, e.device)) {
2035 let net = this.state.networks[e.device];
2036
2037 if (net.device) {
2038 push(match_devices, {
2039 invert: e.invert,
2040 device: net.device
2041 });
2042 }
2043
2044 if (net.physdev && !e.invert)
2045 push(related_physdevs, net.physdev);
2046
2047 push(related_subnets, ...(net.ipaddrs || []));
2048 }
2049 }
2050
2051 push(match_devices, ...to_array(zone.device));
2052
2053 match_subnets = subnets_split_af(zone.subnet);
2054 masq_src_subnets = subnets_split_af(zone.masq_src);
2055 masq_dest_subnets = subnets_split_af(zone.masq_dest);
2056
2057 push(related_subnets, ...(match_subnets[0] || []), ...(match_subnets[1] || []));
2058
2059 let match_rules = [];
2060
2061 let add_rule = (family, devices, subnets, zone) => {
2062 let r = {};
2063
2064 r.family = family;
2065
2066 r.devices_pos = null_if_empty(devices[0]);
2067 r.devices_neg = null_if_empty(devices[1]);
2068 r.devices_neg_wildcard = null_if_empty(devices[2]);
2069
2070 r.subnets_pos = map(subnets[0], this.cidr);
2071 r.subnets_neg = map(subnets[1], this.cidr);
2072 r.subnets_masked = subnets[2];
2073
2074 push(match_rules, r);
2075 };
2076
2077 let family = infer_family(zone.family, [
2078 match_subnets, "subnet list"
2079 ]);
2080
2081 if (type(family) == "string") {
2082 this.warn_section(data, `${family}, skipping`);
2083 return;
2084 }
2085
2086 // group non-inverted device matches into wildcard and non-wildcard ones
2087 let devices = [], plain_devices = [], plain_invert_devices = [], wildcard_invert_devices = [];
2088
2089 for (let device in match_devices) {
2090 let m = match(device.device, /^([^+]*)(\+)?$/);
2091
2092 if (!m) {
2093 this.warn_section(data, `skipping invalid wildcard pattern '${device.device}'`);
2094 continue;
2095 }
2096
2097 // filter `+` (match any device) since nftables does not support
2098 // wildcard only matches
2099 if (!device.invert && m[0] == '+')
2100 continue;
2101
2102 // replace inverted `+` (match no device) with invalid pattern
2103 if (device.invert && m[0] == '+') {
2104 device.device = '/never/';
2105 device.invert = false;
2106 }
2107
2108 // replace "name+" matches with "name*"
2109 else if (m[2] == '+')
2110 device.device = m[1] + '*';
2111
2112 device.wildcard = !!m[2];
2113
2114 if (!device.invert && device.wildcard)
2115 push(devices, [ [ device.device ], plain_invert_devices, wildcard_invert_devices ]);
2116 else if (!device.invert)
2117 push(plain_devices, device.device);
2118 else if (device.wildcard)
2119 push(wildcard_invert_devices, device.device);
2120 else
2121 push(plain_invert_devices, device.device);
2122 }
2123
2124 if (length(plain_devices))
2125 push(devices, [
2126 plain_devices,
2127 plain_invert_devices,
2128 wildcard_invert_devices
2129 ]);
2130 else if (!length(devices))
2131 push(devices, [
2132 null,
2133 plain_invert_devices,
2134 wildcard_invert_devices
2135 ]);
2136
2137 // emit zone jump rules for each device group
2138 if (length(match_devices) || length(match_subnets[0]) || length(match_subnets[1])) {
2139 for (let devgroup in devices) {
2140 // check if there's no AF specific bits, in this case we can do AF agnostic matching
2141 if (!family && !length(match_subnets[0]) && !length(match_subnets[1])) {
2142 add_rule(0, devgroup, [], zone);
2143 }
2144
2145 // we need to emit one or two AF specific rules
2146 else {
2147 if (!family || family == 4)
2148 for (let subnets in subnets_group_by_masking(match_subnets[0]))
2149 add_rule(4, devgroup, subnets, zone);
2150
2151 if (!family || family == 6)
2152 for (let subnets in subnets_group_by_masking(match_subnets[1]))
2153 add_rule(6, devgroup, subnets, zone);
2154 }
2155 }
2156 }
2157
2158 zone.family = family;
2159
2160 zone.match_rules = match_rules;
2161
2162 zone.masq4_src_subnets = subnets_group_by_masking(masq_src_subnets[0]);
2163 zone.masq4_dest_subnets = subnets_group_by_masking(masq_dest_subnets[0]);
2164
2165 zone.masq6_src_subnets = subnets_group_by_masking(masq_src_subnets[1]);
2166 zone.masq6_dest_subnets = subnets_group_by_masking(masq_dest_subnets[1]);
2167
2168 zone.sflags = {};
2169 zone.sflags[zone.input] = true;
2170
2171 zone.dflags = {};
2172 zone.dflags[zone.output] = true;
2173 zone.dflags[zone.forward] = true;
2174
2175 zone.match_devices = map(filter(match_devices, d => !d.invert), d => d.device);
2176 zone.match_subnets = map(filter(related_subnets, s => !s.invert && s.bits != -1), this.cidr);
2177
2178 zone.related_subnets = related_subnets;
2179 zone.related_physdevs = related_physdevs;
2180
2181 if (zone.masq || zone.masq6)
2182 zone.dflags.snat = true;
2183
2184 if ((zone.auto_helper && !(zone.masq || zone.masq6)) || length(zone.helper)) {
2185 zone.dflags.helper = true;
2186
2187 for (let helper in (length(zone.helper) ? zone.helper : this.state.helpers)) {
2188 if (!helper.available)
2189 continue;
2190
2191 for (let proto in helper.proto) {
2192 push(this.state.rules ||= [], {
2193 chain: `helper_${zone.name}`,
2194 family: helper.family,
2195 name: helper.description || helper.name,
2196 proto: proto,
2197 src: zone,
2198 dports_pos: [ this.port(helper.port) ],
2199 target: "helper",
2200 set_helper: helper
2201 });
2202 }
2203 }
2204 }
2205
2206 push(this.state.zones ||= [], zone);
2207 },
2208
2209 parse_forwarding: function(data) {
2210 let fwd = this.parse_options(data, {
2211 enabled: [ "bool", "1" ],
2212
2213 name: [ "string" ],
2214 family: [ "family" ],
2215
2216 src: [ "zone_ref", null, REQUIRED ],
2217 dest: [ "zone_ref", null, REQUIRED ]
2218 });
2219
2220 if (fwd === false) {
2221 this.warn_section(data, "skipped due to invalid options");
2222 return;
2223 }
2224 else if (!fwd.enabled) {
2225 this.warn_section(data, "is disabled, ignoring section");
2226 return;
2227 }
2228
2229 let add_rule = (family, fwd) => {
2230 let f = {
2231 ...fwd,
2232
2233 family: family,
2234 proto: { any: true }
2235 };
2236
2237 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`;
2238 f.chain = fwd.src.any ? "forward" : `forward_${fwd.src.zone.name}`;
2239
2240 if (fwd.dest.any)
2241 f.target = "accept";
2242 else
2243 f.jump_chain = `accept_to_${fwd.dest.zone.name}`;
2244
2245 push(this.state.rules ||= [], f);
2246 };
2247
2248
2249 /* inherit family restrictions from related zones */
2250 let family = infer_family(fwd.family, [
2251 fwd.src?.zone, "source zone",
2252 fwd.dest?.zone, "destination zone"
2253 ]);
2254
2255 if (type(family) == "string") {
2256 this.warn_section(data, `${family}, skipping`);
2257 return;
2258 }
2259
2260 add_rule(family, fwd);
2261
2262 if (fwd.dest.zone)
2263 fwd.dest.zone.dflags.accept = true;
2264 },
2265
2266 parse_rule: function(data) {
2267 let rule = this.parse_options(data, {
2268 enabled: [ "bool", "1" ],
2269
2270 name: [ "string", this.section_id(data[".name"]) ],
2271 _name: [ "string", null, DEPRECATED ],
2272 family: [ "family" ],
2273
2274 src: [ "zone_ref" ],
2275 dest: [ "zone_ref" ],
2276
2277 device: [ "device", null, NO_INVERT ],
2278 direction: [ "direction" ],
2279
2280 ipset: [ "setmatch" ],
2281 helper: [ "cthelper" ],
2282 set_helper: [ "cthelper", null, NO_INVERT ],
2283
2284 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2285
2286 src_ip: [ "network", null, PARSE_LIST ],
2287 src_mac: [ "mac", null, PARSE_LIST ],
2288 src_port: [ "port", null, PARSE_LIST ],
2289
2290 dest_ip: [ "network", null, PARSE_LIST ],
2291 dest_port: [ "port", null, PARSE_LIST ],
2292
2293 icmp_type: [ "icmptype", null, PARSE_LIST ],
2294 extra: [ "string", null, UNSUPPORTED ],
2295
2296 limit: [ "limit" ],
2297 limit_burst: [ "int" ],
2298
2299 utc_time: [ "bool" ],
2300 start_date: [ "date" ],
2301 stop_date: [ "date" ],
2302 start_time: [ "time" ],
2303 stop_time: [ "time" ],
2304 weekdays: [ "weekdays" ],
2305 monthdays: [ "monthdays", null, UNSUPPORTED ],
2306
2307 mark: [ "mark" ],
2308 set_mark: [ "mark", null, NO_INVERT ],
2309 set_xmark: [ "mark", null, NO_INVERT ],
2310
2311 dscp: [ "dscp" ],
2312 set_dscp: [ "dscp", null, NO_INVERT ],
2313
2314 counter: [ "bool", "1" ],
2315 log: [ "string" ],
2316
2317 target: [ "target" ]
2318 });
2319
2320 if (rule === false) {
2321 this.warn_section(data, "skipped due to invalid options");
2322 return;
2323 }
2324 else if (!rule.enabled) {
2325 this.warn_section(data, "is disabled, ignoring section");
2326 return;
2327 }
2328
2329 if (rule.target in ["helper", "notrack"] && (!rule.src || !rule.src.zone)) {
2330 this.warn_section(data, `must specify a source zone for target '${rule.target}'`);
2331 return;
2332 }
2333 else if (rule.target == "dscp" && !rule.set_dscp) {
2334 this.warn_section(data, "must specify option 'set_dscp' for target 'dscp'");
2335 return;
2336 }
2337 else if (rule.target == "mark" && !rule.set_mark && !rule.set_xmark) {
2338 this.warn_section(data, "must specify option 'set_mark' or 'set_xmark' for target 'mark'");
2339 return;
2340 }
2341 else if (rule.target == "helper" && !rule.set_helper) {
2342 this.warn_section(data, "must specify option 'set_helper' for target 'helper'");
2343 return;
2344 }
2345 else if (rule.device?.any) {
2346 this.warn_section(data, "must not specify '*' as device");
2347 return;
2348 }
2349
2350 switch (this.parse_bool(rule.log)) {
2351 case true:
2352 rule.log = `${rule.name}: `;
2353 break;
2354
2355 case false:
2356 delete rule.log;
2357 }
2358
2359 let ipset;
2360
2361 if (rule.ipset) {
2362 ipset = filter(this.state.ipsets, s => (s.name == rule.ipset.name))?.[0];
2363
2364 if (!ipset) {
2365 this.warn_section(data, `references unknown set '${rule.ipset.name}'`);
2366 return;
2367 }
2368
2369 if (('inet_service' in ipset.types) && !ensure_tcpudp(rule.proto)) {
2370 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2371 return;
2372 }
2373 }
2374
2375 let need_src_action_chain = (rule) => (rule.src?.zone?.log && rule.target != "accept");
2376
2377 let add_rule = (family, proto, saddrs, daddrs, sports, dports, icmptypes, icmpcodes, ipset, rule) => {
2378 let r = {
2379 ...rule,
2380
2381 family: family,
2382 proto: proto,
2383 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2384 has_ports: !!(length(sports) || length(dports)),
2385 saddrs_pos: map(saddrs[0], this.cidr),
2386 saddrs_neg: map(saddrs[1], this.cidr),
2387 saddrs_masked: saddrs[2],
2388 daddrs_pos: map(daddrs[0], this.cidr),
2389 daddrs_neg: map(daddrs[1], this.cidr),
2390 daddrs_masked: daddrs[2],
2391 sports_pos: map(filter_pos(sports), this.port),
2392 sports_neg: map(filter_neg(sports), this.port),
2393 dports_pos: map(filter_pos(dports), this.port),
2394 dports_neg: map(filter_neg(dports), this.port),
2395 smacs_pos: map(filter_pos(rule.src_mac), m => m.mac),
2396 smacs_neg: map(filter_neg(rule.src_mac), m => m.mac),
2397 icmp_types: map(icmptypes, i => (family == 4 ? i.type : i.type6)),
2398 icmp_codes: map(icmpcodes, ic => `${(family == 4) ? ic.type : ic.type6} . ${(family == 4) ? ic.code_min : ic.code6_min}`)
2399 };
2400
2401 if (!length(r.icmp_types))
2402 delete r.icmp_types;
2403
2404 if (!length(r.icmp_codes))
2405 delete r.icmp_codes;
2406
2407 if (r.set_mark) {
2408 r.set_xmark = {
2409 invert: r.set_mark.invert,
2410 mark: r.set_mark.mark,
2411 mask: r.set_mark.mark | r.set_mark.mask
2412 };
2413
2414 delete r.set_mark;
2415 }
2416
2417 let set_types = map_setmatch(ipset, rule.ipset, proto.name);
2418
2419 if (set_types !== set_types) {
2420 this.warn_section(data, "destination MAC address matching not supported");
2421 return;
2422 } else if (set_types) {
2423 r.ipset = { ...r.ipset, fields: set_types };
2424 }
2425
2426 if (r.target == "notrack") {
2427 r.chain = `notrack_${r.src.zone.name}`;
2428 r.src.zone.dflags.notrack = true;
2429 }
2430 else if (r.target == "helper") {
2431 r.chain = `helper_${r.src.zone.name}`;
2432 r.src.zone.dflags.helper = true;
2433 }
2434 else if (r.target == "mark" || r.target == "dscp") {
2435 if ((r.src?.any && r.dest?.any) || (r.src?.zone && r.dest?.zone))
2436 r.chain = "mangle_forward";
2437 else if (r.src?.any && r.dest?.zone)
2438 r.chain = "mangle_postrouting";
2439 else if (r.src?.zone && r.dest?.any)
2440 r.chain = "mangle_prerouting";
2441 else if (r.src && !r.dest)
2442 r.chain = "mangle_input";
2443 else
2444 r.chain = "mangle_output";
2445
2446 if (r.src?.zone) {
2447 r.src.zone.dflags[r.target] = true;
2448 r.iifnames = null_if_empty(r.src.zone.match_devices);
2449 }
2450
2451 if (r.dest?.zone) {
2452 r.dest.zone.dflags[r.target] = true;
2453 r.oifnames = null_if_empty(r.dest.zone.match_devices);
2454 }
2455 }
2456 else {
2457 r.chain = "output";
2458
2459 if (r.src) {
2460 if (!r.src.any)
2461 r.chain = `${r.dest ? "forward" : "input"}_${r.src.zone.name}`;
2462 else
2463 r.chain = r.dest ? "forward" : "input";
2464 }
2465
2466 if (r.dest && !r.src) {
2467 if (!r.dest.any)
2468 r.chain = sprintf("output_%s", r.dest.zone.name);
2469 else
2470 r.chain = "output";
2471 }
2472
2473 if (r.target && r.dest && !r.dest.any) {
2474 r.jump_chain = `${r.target}_to_${r.dest.zone.name}`;
2475 r.dest.zone.dflags[r.target] = true;
2476 }
2477 else if (r.target && need_src_action_chain(r)) {
2478 r.jump_chain = `${r.target}_from_${r.src.zone.name}`;
2479 r.src.zone.sflags[r.target] = true;
2480 }
2481 else if (r.target == "reject")
2482 r.jump_chain = "handle_reject";
2483 }
2484
2485 if (r.device)
2486 r[r.direction ? "oifnames" : "iifnames"] = [ r.device.device ];
2487
2488 push(this.state.rules ||= [], r);
2489 };
2490
2491 for (let proto in rule.proto) {
2492 let sip, dip, sports, dports, itypes4, itypes6;
2493 let family = rule.family;
2494
2495 switch (proto.name) {
2496 case "icmp":
2497 itypes4 = filter(rule.icmp_type || [], family_is_ipv4);
2498 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2499 break;
2500
2501 case "ipv6-icmp":
2502 family = 6;
2503 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2504 break;
2505
2506 case "tcp":
2507 case "udp":
2508 sports = rule.src_port;
2509 dports = rule.dest_port;
2510 break;
2511 }
2512
2513 sip = subnets_split_af(rule.src_ip);
2514 dip = subnets_split_af(rule.dest_ip);
2515
2516 family = infer_family(family, [
2517 ipset, "set match",
2518 sip, "source IP",
2519 dip, "destination IP",
2520 rule.src?.zone, "source zone",
2521 rule.dest?.zone, "destination zone",
2522 rule.helper, "helper match",
2523 rule.set_helper, "helper to set"
2524 ]);
2525
2526 if (type(family) == "string") {
2527 this.warn_section(data, `${family}, skipping`);
2528 continue;
2529 }
2530
2531 let has_ipv4_specifics = (length(sip[0]) || length(dip[0]) || length(itypes4) || rule.dscp !== null);
2532 let has_ipv6_specifics = (length(sip[1]) || length(dip[1]) || length(itypes6) || rule.dscp !== null);
2533
2534 /* if no family was configured, infer target family from IP addresses */
2535 if (family === null) {
2536 if (has_ipv4_specifics && !has_ipv6_specifics)
2537 family = 4;
2538 else if (has_ipv6_specifics && !has_ipv4_specifics)
2539 family = 6;
2540 else
2541 family = 0;
2542 }
2543
2544 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2545 if (!family && rule.target != "dscp" && !has_ipv4_specifics && !has_ipv6_specifics) {
2546 add_rule(0, proto, [], [], sports, dports, null, null, null, rule);
2547 }
2548
2549 /* we need to emit one or two AF specific rules */
2550 else {
2551 if (family == 0 || family == 4) {
2552 let icmp_types = filter(itypes4, i => (i.code_min == 0 && i.code_max == 0xFF));
2553 let icmp_codes = filter(itypes4, i => (i.code_min != 0 || i.code_max != 0xFF));
2554
2555 for (let saddrs in subnets_group_by_masking(sip[0])) {
2556 for (let daddrs in subnets_group_by_masking(dip[0])) {
2557 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2558 add_rule(4, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2559
2560 if (length(icmp_codes))
2561 add_rule(4, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2562 }
2563 }
2564 }
2565
2566 if (family == 0 || family == 6) {
2567 let icmp_types = filter(itypes6, i => (i.code_min == 0 && i.code_max == 0xFF));
2568 let icmp_codes = filter(itypes6, i => (i.code_min != 0 || i.code_max != 0xFF));
2569
2570 for (let saddrs in subnets_group_by_masking(sip[1])) {
2571 for (let daddrs in subnets_group_by_masking(dip[1])) {
2572 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2573 add_rule(6, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2574
2575 if (length(icmp_codes))
2576 add_rule(6, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2577 }
2578 }
2579 }
2580 }
2581 }
2582 },
2583
2584 parse_redirect: function(data) {
2585 let redir = this.parse_options(data, {
2586 enabled: [ "bool", "1" ],
2587
2588 name: [ "string", this.section_id(data[".name"]) ],
2589 _name: [ "string", null, DEPRECATED ],
2590 family: [ "family" ],
2591
2592 src: [ "zone_ref" ],
2593 dest: [ "zone_ref" ],
2594
2595 ipset: [ "setmatch" ],
2596 helper: [ "cthelper", null, NO_INVERT ],
2597
2598 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2599
2600 src_ip: [ "network" ],
2601 src_mac: [ "mac", null, PARSE_LIST ],
2602 src_port: [ "port" ],
2603
2604 src_dip: [ "network" ],
2605 src_dport: [ "port" ],
2606
2607 dest_ip: [ "network" ],
2608 dest_port: [ "port" ],
2609
2610 extra: [ "string", null, UNSUPPORTED ],
2611
2612 limit: [ "limit" ],
2613 limit_burst: [ "int" ],
2614
2615 utc_time: [ "bool" ],
2616 start_date: [ "date" ],
2617 stop_date: [ "date" ],
2618 start_time: [ "time" ],
2619 stop_time: [ "time" ],
2620 weekdays: [ "weekdays" ],
2621 monthdays: [ "monthdays", null, UNSUPPORTED ],
2622
2623 mark: [ "mark" ],
2624
2625 reflection: [ "bool", "1" ],
2626 reflection_src: [ "reflection_source", "internal" ],
2627
2628 reflection_zone: [ "zone_ref", null, PARSE_LIST ],
2629
2630 counter: [ "bool", "1" ],
2631 log: [ "string" ],
2632
2633 target: [ "target", "dnat" ]
2634 });
2635
2636 if (redir === false) {
2637 this.warn_section(data, "skipped due to invalid options");
2638 return;
2639 }
2640 else if (!redir.enabled) {
2641 this.warn_section(data, "is disabled, ignoring section");
2642 return;
2643 }
2644
2645 if (!(redir.target in ["dnat", "snat"])) {
2646 this.warn_section(data, "has invalid target specified, defaulting to dnat");
2647 redir.target = "dnat";
2648 }
2649
2650 switch (this.parse_bool(redir.log)) {
2651 case true:
2652 redir.log = `${redir.name}: `;
2653 break;
2654
2655 case false:
2656 delete redir.log;
2657 }
2658
2659 let ipset;
2660
2661 if (redir.ipset) {
2662 ipset = filter(this.state.ipsets, s => (s.name == redir.ipset.name))?.[0];
2663
2664 if (!ipset) {
2665 this.warn_section(data, `references unknown set '${redir.ipset.name}'`);
2666 return;
2667 }
2668
2669 if (('inet_service' in ipset.types) && !ensure_tcpudp(redir.proto)) {
2670 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2671 return;
2672 }
2673 }
2674
2675 let resolve_dest = (redir) => {
2676 for (let zone in this.state.zones) {
2677 for (let zone_addr in zone.related_subnets) {
2678 for (let dest_addr in redir.dest_ip.addrs) {
2679 if (dest_addr.family != zone_addr.family)
2680 continue;
2681
2682 let a = apply_mask(dest_addr.addr, zone_addr.mask);
2683 let b = apply_mask(zone_addr.addr, zone_addr.mask);
2684
2685 if (a != b)
2686 continue;
2687
2688 redir.dest = {
2689 any: false,
2690 zone: zone
2691 };
2692
2693 return true;
2694 }
2695 }
2696 }
2697
2698 return false;
2699 };
2700
2701 if (redir.target == "dnat") {
2702 if (!redir.src)
2703 return this.warn_section(data, "has no source specified");
2704 else if (redir.src.any)
2705 return this.warn_section(data, "must not have source '*' for dnat target");
2706 else if (redir.dest_ip && redir.dest_ip.invert)
2707 return this.warn_section(data, "must not specify a negated 'dest_ip' value");
2708 else if (redir.dest_ip && length(filter(redir.dest_ip.addrs, a => a.bits == -1)))
2709 return this.warn_section(data, "must not use non-contiguous masks in 'dest_ip'");
2710
2711 if (!redir.dest && redir.dest_ip && resolve_dest(redir))
2712 this.warn_section(data, `does not specify a destination, assuming '${redir.dest.zone.name}'`);
2713
2714 if (!redir.dest_port)
2715 redir.dest_port = redir.src_dport;
2716
2717 if (redir.reflection && redir.dest?.zone && redir.src.zone.masq) {
2718 redir.dest.zone.dflags.accept = true;
2719 redir.dest.zone.dflags.dnat = true;
2720 redir.dest.zone.dflags.snat = true;
2721 }
2722
2723 if (redir.helper)
2724 redir.src.zone.dflags.helper = true;
2725
2726 redir.src.zone.dflags[redir.target] = true;
2727 }
2728 else {
2729 if (!redir.dest)
2730 return this.warn_section(data, "has no destination specified");
2731 else if (redir.dest.any)
2732 return this.warn_section(data, "must not have destination '*' for snat target");
2733 else if (!redir.src_dip)
2734 return this.warn_section(data, "has no 'src_dip' option specified");
2735 else if (redir.src_dip.invert)
2736 return this.warn_section(data, "must not specify a negated 'src_dip' value");
2737 else if (length(filter(redir.src_dip.addrs, a => a.bits == -1)))
2738 return this.warn_section(data, "must not use non-contiguous masks in 'src_dip'");
2739 else if (redir.src_mac)
2740 return this.warn_section(data, "must not use 'src_mac' option for snat target");
2741 else if (redir.helper)
2742 return this.warn_section(data, "must not use 'helper' option for snat target");
2743
2744 redir.dest.zone.dflags[redir.target] = true;
2745 }
2746
2747 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, ipset, redir) => {
2748 let r = {
2749 ...redir,
2750
2751 family: family,
2752 proto: proto,
2753 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2754 has_ports: !!(sport || dport || rport),
2755 saddrs_pos: map(saddrs[0], this.cidr),
2756 saddrs_neg: map(saddrs[1], this.cidr),
2757 saddrs_masked: saddrs[2],
2758 daddrs_pos: map(daddrs[0], this.cidr),
2759 daddrs_neg: map(daddrs[1], this.cidr),
2760 daddrs_masked: daddrs[2],
2761 sports_pos: map(filter_pos(to_array(sport)), this.port),
2762 sports_neg: map(filter_neg(to_array(sport)), this.port),
2763 dports_pos: map(filter_pos(to_array(dport)), this.port),
2764 dports_neg: map(filter_neg(to_array(dport)), this.port),
2765 smacs_pos: map(filter_pos(redir.src_mac), m => m.mac),
2766 smacs_neg: map(filter_neg(redir.src_mac), m => m.mac),
2767
2768 raddr: raddrs ? raddrs[0] : null,
2769 rport: rport
2770 };
2771
2772 let set_types = map_setmatch(ipset, redir.ipset, proto.name);
2773
2774 if (set_types !== set_types) {
2775 this.warn_section(data, "destination MAC address matching not supported");
2776 return;
2777 } else if (set_types) {
2778 r.ipset = { ...r.ipset, fields: set_types };
2779 }
2780
2781 switch (r.target) {
2782 case "dnat":
2783 r.chain = `dstnat_${r.src.zone.name}`;
2784 r.src.zone.dflags.dnat = true;
2785
2786 if (!r.raddr)
2787 r.target = "redirect";
2788
2789 break;
2790
2791 case "snat":
2792 r.chain = `srcnat_${r.dest.zone.name}`;
2793 r.dest.zone.dflags.snat = true;
2794 break;
2795 }
2796
2797 push(this.state.redirects ||= [], r);
2798 };
2799
2800 let to_hostaddr = (a) => {
2801 let bits = (a.family == 4) ? 32 : 128;
2802
2803 return {
2804 family: a.family,
2805 addr: apply_mask(a.addr, bits),
2806 bits: bits
2807 };
2808 };
2809
2810 for (let proto in redir.proto) {
2811 let sip, dip, rip, iip, eip, refip, sport, dport, rport;
2812 let family = redir.family;
2813
2814 if (proto.name == "ipv6-icmp")
2815 family = 6;
2816
2817 switch (redir.target) {
2818 case "dnat":
2819 sip = subnets_split_af(redir.src_ip);
2820 dip = subnets_split_af(redir.src_dip);
2821 rip = subnets_split_af(redir.dest_ip);
2822
2823 switch (proto.name) {
2824 case "tcp":
2825 case "udp":
2826 sport = redir.src_port;
2827 dport = redir.src_dport;
2828 rport = redir.dest_port;
2829 break;
2830 }
2831
2832 break;
2833
2834 case "snat":
2835 sip = subnets_split_af(redir.src_ip);
2836 dip = subnets_split_af(redir.dest_ip);
2837 rip = subnets_split_af(redir.src_dip);
2838
2839 switch (proto.name) {
2840 case "tcp":
2841 case "udp":
2842 sport = redir.src_port;
2843 dport = redir.dest_port;
2844 rport = redir.src_dport;
2845 break;
2846 }
2847
2848 break;
2849 }
2850
2851 family = infer_family(family, [
2852 ipset, "set match",
2853 sip, "source IP",
2854 dip, "destination IP",
2855 rip, "rewrite IP",
2856 redir.src?.zone, "source zone",
2857 redir.dest?.zone, "destination zone",
2858 redir.helper, "helper match"
2859 ]);
2860
2861 if (type(family) == "string") {
2862 this.warn_section(data, `${family}, skipping`);
2863 continue;
2864 }
2865
2866 /* build reflection rules */
2867 if (redir.target == "dnat" && redir.reflection &&
2868 (length(rip[0]) || length(rip[1])) && redir.src?.zone && redir.dest?.zone) {
2869 let refredir = {
2870 name: `${redir.name} (reflection)`,
2871
2872 helper: redir.helper,
2873
2874 // XXX: this likely makes no sense for reflection rules
2875 //src_mac: redir.src_mac,
2876
2877 limit: redir.limit,
2878 limit_burst: redir.limit_burst,
2879
2880 start_date: redir.start_date,
2881 stop_date: redir.stop_date,
2882 start_time: redir.start_time,
2883 stop_time: redir.stop_time,
2884 weekdays: redir.weekdays,
2885
2886 mark: redir.mark
2887 };
2888
2889 let eaddrs = length(dip) ? dip : subnets_split_af({ addrs: map(redir.src.zone.related_subnets, to_hostaddr) });
2890 let rzones = length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
2891
2892 for (let rzone in rzones) {
2893 if (!is_family(rzone, family)) {
2894 this.warn_section(data,
2895 `is restricted to IPv${family} but referenced reflection zone is IPv${rzone.family} only, skipping`);
2896 continue;
2897 }
2898
2899 let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
2900 let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
2901
2902 for (let i = 0; i <= 1; i++) {
2903 if (redir.src.zone[i ? "masq6" : "masq"] && length(rip[i])) {
2904 let snat_addr = refaddrs[i]?.[0];
2905
2906 /* For internal reflection sources try to find a suitable candiate IP
2907 * among the reflection zone subnets which is within the same subnet
2908 * as the original DNAT destination. If we can't find any matching
2909 * one then simply take the first candidate. */
2910 if (redir.reflection_src == "internal") {
2911 for (let zone_addr in rzone.zone.related_subnets) {
2912 if (zone_addr.family != rip[i][0].family)
2913 continue;
2914
2915 let r = apply_mask(rip[i][0].addr, zone_addr.mask);
2916 let a = apply_mask(zone_addr.addr, zone_addr.mask);
2917
2918 if (r != a)
2919 continue;
2920
2921 snat_addr = zone_addr;
2922 break;
2923 }
2924 }
2925
2926 if (!snat_addr) {
2927 this.warn_section(data, `${redir.reflection_src || "external"} rewrite IP cannot be determined, disabling reflection`);
2928 }
2929 else if (!length(iaddrs[i])) {
2930 this.warn_section(data, "internal address range cannot be determined, disabling reflection");
2931 }
2932 else if (!length(eaddrs[i])) {
2933 this.warn_section(data, "external address range cannot be determined, disabling reflection");
2934 }
2935 else {
2936 refredir.src = rzone;
2937 refredir.dest = null;
2938 refredir.target = "dnat";
2939
2940 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2941 for (let daddrs in subnets_group_by_masking(eaddrs[i]))
2942 add_rule(i ? 6 : 4, proto, saddrs, daddrs, rip[i], sport, dport, rport, null, refredir);
2943
2944 refredir.src = null;
2945 refredir.dest = rzone;
2946 refredir.target = "snat";
2947
2948 for (let daddrs in subnets_group_by_masking(rip[i]))
2949 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2950 add_rule(i ? 6 : 4, proto, saddrs, daddrs, [ to_hostaddr(snat_addr) ], null, rport, null, null, refredir);
2951 }
2952 }
2953 }
2954 }
2955 }
2956
2957 if (length(rip[0]) > 1 || length(rip[1]) > 1)
2958 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
2959
2960 let has_ip4_addr = length(sip[0]) || length(dip[0]) || length(rip[0]),
2961 has_ip6_addr = length(sip[1]) || length(dip[1]) || length(rip[1]),
2962 has_any_addr = has_ip4_addr || has_ip6_addr;
2963
2964 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2965 if (!family && !has_any_addr) {
2966 /* for backwards compatibility, treat unspecified family as IPv4 unless user explicitly requested any (0) */
2967 if (family == null)
2968 family = 4;
2969
2970 add_rule(family, proto, [], [], null, sport, dport, rport, null, redir);
2971 }
2972
2973 /* we need to emit one or two AF specific rules */
2974 else {
2975 if ((!family || family == 4) && (!has_any_addr || has_ip4_addr)) {
2976 for (let saddrs in subnets_group_by_masking(sip[0]))
2977 for (let daddrs in subnets_group_by_masking(dip[0]))
2978 add_rule(4, proto, saddrs, daddrs, rip[0], sport, dport, rport, ipset, redir);
2979 }
2980
2981 if ((!family || family == 6) && (!has_any_addr || has_ip6_addr)) {
2982 for (let saddrs in subnets_group_by_masking(sip[1]))
2983 for (let daddrs in subnets_group_by_masking(dip[1]))
2984 add_rule(6, proto, saddrs, daddrs, rip[1], sport, dport, rport, ipset, redir);
2985 }
2986 }
2987 }
2988 },
2989
2990 parse_nat: function(data) {
2991 let snat = this.parse_options(data, {
2992 enabled: [ "bool", "1" ],
2993
2994 name: [ "string", this.section_id(data[".name"]) ],
2995 family: [ "family" ],
2996
2997 src: [ "zone_ref" ],
2998 device: [ "string" ],
2999
3000 ipset: [ "setmatch", null, UNSUPPORTED ],
3001
3002 proto: [ "protocol", "all", PARSE_LIST | FLATTEN_LIST ],
3003
3004 src_ip: [ "network" ],
3005 src_port: [ "port" ],
3006
3007 snat_ip: [ "network", null, NO_INVERT ],
3008 snat_port: [ "port", null, NO_INVERT ],
3009
3010 dest_ip: [ "network" ],
3011 dest_port: [ "port" ],
3012
3013 extra: [ "string", null, UNSUPPORTED ],
3014
3015 limit: [ "limit" ],
3016 limit_burst: [ "int" ],
3017
3018 connlimit_ports: [ "bool" ],
3019
3020 utc_time: [ "bool" ],
3021 start_date: [ "date" ],
3022 stop_date: [ "date" ],
3023 start_time: [ "time" ],
3024 stop_time: [ "time" ],
3025 weekdays: [ "weekdays" ],
3026 monthdays: [ "monthdays", null, UNSUPPORTED ],
3027
3028 mark: [ "mark" ],
3029
3030 counter: [ "bool", "1" ],
3031 log: [ "string" ],
3032
3033 target: [ "target", "masquerade" ]
3034 });
3035
3036 if (snat === false) {
3037 this.warn_section(data, "skipped due to invalid options");
3038 return;
3039 }
3040 else if (!snat.enabled) {
3041 this.warn_section(data, "is disabled, ignoring section");
3042 return;
3043 }
3044
3045 if (!(snat.target in ["accept", "snat", "masquerade"])) {
3046 this.warn_section(data, "has invalid target specified, defaulting to masquerade");
3047 snat.target = "masquerade";
3048 }
3049
3050 if (snat.target == "snat" && !snat.snat_ip && !snat.snat_port) {
3051 this.warn_section(data, "needs either 'snat_ip' or 'snat_port' for target snat, ignoring section");
3052 return;
3053 }
3054 else if (snat.target != "snat" && snat.snat_ip) {
3055 this.warn_section(data, "must not use 'snat_ip' for non-snat target, ignoring section");
3056 return;
3057 }
3058 else if (snat.target != "snat" && snat.snat_port) {
3059 this.warn_section(data, "must not use 'snat_port' for non-snat target, ignoring section");
3060 return;
3061 }
3062
3063 if ((snat.snat_port || snat.src_port || snat.dest_port) && !ensure_tcpudp(snat.proto)) {
3064 this.warn_section(data, "specifies ports but no UDP/TCP protocol, ignoring section");
3065 return;
3066 }
3067
3068 if (snat.snat_ip && length(filter(snat.snat_ip.addrs, a => a.bits == -1 || a.invert))) {
3069 this.warn_section(data, "must not use inversion or non-contiguous masks in 'snat_ip', ignoring section");
3070 return;
3071 }
3072
3073 switch (this.parse_bool(snat.log)) {
3074 case true:
3075 snat.log = `${snat.name}: `;
3076 break;
3077
3078 case false:
3079 delete snat.log;
3080 }
3081
3082 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, snat) => {
3083 let n = {
3084 ...snat,
3085
3086 family: family,
3087 proto: proto,
3088 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
3089 has_ports: !!(sport || dport),
3090 saddrs_pos: map(saddrs[0], this.cidr),
3091 saddrs_neg: map(saddrs[1], this.cidr),
3092 saddrs_masked: saddrs[2],
3093 daddrs_pos: map(daddrs[0], this.cidr),
3094 daddrs_neg: map(daddrs[1], this.cidr),
3095 daddrs_masked: daddrs[2],
3096 sports_pos: map(filter_pos(to_array(sport)), this.port),
3097 sports_neg: map(filter_neg(to_array(sport)), this.port),
3098 dports_pos: map(filter_pos(to_array(dport)), this.port),
3099 dports_neg: map(filter_neg(to_array(dport)), this.port),
3100
3101 raddr: raddrs ? raddrs[0] : null,
3102 rport: rport,
3103
3104 chain: snat.src?.zone ? `srcnat_${snat.src.zone.name}` : "srcnat"
3105 };
3106
3107 push(this.state.redirects ||= [], n);
3108 };
3109
3110 for (let proto in snat.proto) {
3111 let sip, dip, rip, sport, dport, rport;
3112 let family = snat.family;
3113
3114 sip = subnets_split_af(snat.src_ip);
3115 dip = subnets_split_af(snat.dest_ip);
3116 rip = subnets_split_af(snat.snat_ip);
3117
3118 switch (proto.name) {
3119 case "tcp":
3120 case "udp":
3121 sport = snat.src_port;
3122 dport = snat.dest_port;
3123 rport = snat.snat_port;
3124 break;
3125 }
3126
3127 if (length(rip[0]) > 1 || length(rip[1]) > 1)
3128 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
3129
3130 family = infer_family(family, [
3131 sip, "source IP",
3132 dip, "destination IP",
3133 rip, "rewrite IP",
3134 snat.src?.zone, "source zone"
3135 ]);
3136
3137 if (type(family) == "string") {
3138 this.warn_section(data, `${family}, skipping`);
3139 continue;
3140 }
3141
3142 if (snat.src?.zone)
3143 snat.src.zone.dflags.snat = true;
3144
3145 /* if no family was configured, infer target family from IP addresses */
3146 if (family === null) {
3147 if ((length(sip[0]) || length(dip[0]) || length(rip[0])) && !length(sip[1]) && !length(dip[1]) && !length(rip[1]))
3148 family = 4;
3149 else if ((length(sip[1]) || length(dip[1]) || length(rip[1])) && !length(sip[0]) && !length(dip[0]) && !length(rip[0]))
3150 family = 6;
3151 else
3152 family = 4; /* default to IPv4 only for backwards compatibility, unless an explict family any was configured */
3153 }
3154
3155 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
3156 if (!family && !length(sip[0]) && !length(sip[1]) && !length(dip[0]) && !length(dip[1]) && !length(rip[0]) && !length(rip[1])) {
3157 add_rule(0, proto, [], [], null, sport, dport, rport, snat);
3158 }
3159
3160 /* we need to emit one or two AF specific rules */
3161 else {
3162 if (family == 0 || family == 4)
3163 for (let saddr in subnets_group_by_masking(sip[0]))
3164 for (let daddr in subnets_group_by_masking(dip[0]))
3165 add_rule(4, proto, saddr, daddr, rip[0], sport, dport, rport, snat);
3166
3167 if (family == 0 || family == 6)
3168 for (let saddr in subnets_group_by_masking(sip[1]))
3169 for (let daddr in subnets_group_by_masking(dip[1]))
3170 add_rule(6, proto, saddr, daddr, rip[1], sport, dport, rport, snat);
3171 }
3172 }
3173 },
3174
3175 parse_include: function(data) {
3176 let inc = this.parse_options(data, {
3177 enabled: [ "bool", "1" ],
3178
3179 path: [ "string", null, REQUIRED ],
3180 type: [ "includetype", "script" ],
3181
3182 fw4_compatible: [ "bool", data.path != "/etc/firewall.user" ],
3183
3184 family: [ "family", null, UNSUPPORTED ],
3185 reload: [ "bool", null, UNSUPPORTED ],
3186
3187 position: [ "includeposition" ],
3188 chain: [ "string" ]
3189 });
3190
3191 if (!inc.enabled) {
3192 this.warn_section(data, "is disabled, ignoring section");
3193 return;
3194 }
3195
3196 if (inc.type == "script" && !inc.fw4_compatible) {
3197 this.warn_section(data, "is not marked as compatible with fw4, ignoring section");
3198 this.warn_section(data, "requires 'option fw4_compatible 1' to be considered compatible");
3199 return;
3200 }
3201
3202 for (let opt in [ "table", "chain", "position" ]) {
3203 if (inc.type != "nftables" && inc[opt]) {
3204 this.warn_section(data, `must not specify '${opt}' for non-nftables includes, ignoring section`);
3205 return;
3206 }
3207 }
3208
3209 switch (inc.position ??= 'table-append') {
3210 case 'ruleset-prepend':
3211 case 'ruleset-append':
3212 case 'table-prepend':
3213 case 'table-append':
3214 if (inc.chain)
3215 this.warn_section(data, `specifies 'chain' which has no effect for position ${inc.position}`);
3216
3217 delete inc.chain;
3218 break;
3219
3220 case 'chain-prepend':
3221 case 'chain-append':
3222 if (!inc.chain) {
3223 this.warn_section(data, `must specify 'chain' for position ${inc.position}, ignoring section`);
3224 return;
3225 }
3226
3227 break;
3228 }
3229
3230 let path = fs.readlink(inc.path) ?? inc.path;
3231
3232 if (!fs.access(path)) {
3233 this.warn_section(data, `specifies unreachable path '${path}', ignoring section`);
3234 return;
3235 }
3236
3237 if (!data['.name'])
3238 this.warn(`Automatically including '${path}'`);
3239
3240 push(this.state.includes ||= [], { ...inc, path });
3241 },
3242
3243 parse_ipset: function(data) {
3244 let ipset = this.parse_options(data, {
3245 enabled: [ "bool", "1" ],
3246 reload_set: [ "bool" ],
3247 counters: [ "bool" ],
3248 comment: [ "string" ],
3249
3250 name: [ "string", null, REQUIRED ],
3251 family: [ "family", "4" ],
3252
3253 storage: [ "string", null, UNSUPPORTED ],
3254 match: [ "ipsettype", null, PARSE_LIST ],
3255
3256 iprange: [ "string", null, UNSUPPORTED ],
3257 portrange: [ "string", null, UNSUPPORTED ],
3258
3259 netmask: [ "int", null, UNSUPPORTED ],
3260 maxelem: [ "int" ],
3261 hashsize: [ "int", null, UNSUPPORTED ],
3262 timeout: [ "int", "-1" ],
3263
3264 external: [ "string", null, UNSUPPORTED ],
3265
3266 entry: [ "string", null, PARSE_LIST ],
3267 loadfile: [ "string" ]
3268 });
3269
3270 if (ipset === false) {
3271 this.warn_section(data, "skipped due to invalid options");
3272 return;
3273 }
3274 else if (!ipset.enabled) {
3275 this.warn_section(data, "is disabled, ignoring section");
3276 return;
3277 }
3278
3279 if (ipset.family == 0) {
3280 this.warn_section(data, "must not specify family 'any'");
3281 return;
3282 }
3283 else if (!length(ipset.match)) {
3284 this.warn_section(data, "has no datatypes assigned");
3285 return;
3286 }
3287
3288 let dirs = map(ipset.match, m => m[0]),
3289 types = map(ipset.match, m => m[1]),
3290 interval = false;
3291
3292 if ("set" in types) {
3293 this.warn_section(data, "match type 'set' is not supported");
3294 return;
3295 }
3296
3297 if ("net" in types) {
3298 if (this.kernel < 0x05060000) {
3299 this.warn_section(data, "match type 'net' requires kernel 5.6 or later");
3300 return;
3301 }
3302
3303 interval = true;
3304 }
3305
3306 let s = {
3307 ...ipset,
3308
3309 fw4types: types,
3310
3311 types: map(types, (t) => {
3312 switch (t) {
3313 case 'ip':
3314 case 'net':
3315 return (ipset.family == 4) ? 'ipv4_addr' : 'ipv6_addr';
3316
3317 case 'mac':
3318 return 'ether_addr';
3319
3320 case 'port':
3321 return 'inet_service';
3322 }
3323 }),
3324
3325 directions: dirs,
3326 interval: interval
3327 };
3328
3329 if (s.interval)
3330 push(s.flags ??= [], 'interval');
3331
3332 if (s.timeout >= 0)
3333 push(s.flags ??= [], 'timeout');
3334
3335 s.entries = filter(map(ipset.entry, (e) => {
3336 let v = this.parse_ipsetentry(e, s);
3337
3338 if (!v)
3339 this.warn_section(data, `ignoring invalid ipset entry '${e}'`);
3340
3341 return v;
3342 }), (e) => (e != null));
3343
3344 push(this.state.ipsets ||= [], s);
3345 }
3346 };