1 const fs = require("fs");
2 const uci = require("uci");
3 const ubus = require("ubus");
5 const STATEFILE = "/var/run/fw4.state";
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;
14 const ipv4_icmptypes = {
15 "any": [ 0xFF, 0, 0xFF ],
16 "echo-reply": [ 0, 0, 0xFF ],
17 "pong": [ 0, 0, 0xFF ], /* Alias */
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 ],
36 "source-quench": [ 4, 0, 0xFF ],
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 ],
44 "echo-request": [ 8, 0, 0xFF ],
45 "ping": [ 8, 0, 0xFF ], /* Alias */
47 "router-advertisement": [ 9, 0, 0xFF ],
49 "router-solicitation": [ 10, 0, 0xFF ],
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 ],
56 "parameter-problem": [ 12, 0, 0xFF ],
57 "ip-header-bad": [ 12, 0, 0 ],
58 "required-option-missing": [ 12, 1, 1 ],
60 "timestamp-request": [ 13, 0, 0xFF ],
62 "timestamp-reply": [ 14, 0, 0xFF ],
64 "address-mask-request": [ 17, 0, 0xFF ],
66 "address-mask-reply": [ 18, 0, 0xFF ]
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 ],
77 "packet-too-big": [ 2, 0, 0xFF ],
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 ],
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 ],
89 "echo-request": [ 128, 0, 0xFF ],
90 "ping": [ 128, 0, 0xFF ], /* Alias */
92 "echo-reply": [ 129, 0, 0xFF ],
93 "pong": [ 129, 0, 0xFF ], /* Alias */
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 ],
100 "router-solicitation": [ 133, 0, 0xFF ],
102 "router-advertisement": [ 134, 0, 0xFF ],
104 "neighbour-solicitation": [ 135, 0, 0xFF ],
105 "neighbor-solicitation": [ 135, 0, 0xFF ], /* Alias */
107 "neighbour-advertisement": [ 136, 0, 0xFF ],
108 "neighbor-advertisement": [ 136, 0, 0xFF ], /* Alias */
110 "redirect": [ 137, 0, 0xFF ],
112 /* codes 0, 1, 255 */
113 "router-renumbering": [ 138, 0, 0xFF ],
116 "node-info-query": [ 139, 0, 0xFF ],
118 "node-info-response": [ 140, 0, 0xFF ],
120 "inverse-neighbour-discovery-solicitation-message": [ 141, 0, 0xFF ],
121 "inverse-neighbor-discovery-solicitation-message": [ 141, 0, 0xFF ], /* Alias */
123 "inverse-neighbour-discovery-advertisement-message": [ 142, 0, 0xFF ],
124 "inverse-neighbor-discovery-advertisement-message": [ 142, 0, 0xFF ], /* Alias */
126 "v2-multicast-listener-report": [ 143, 0, 0xFF ],
128 "home-agent-address-discovery-request-message": [ 144, 0, 0xFF ],
129 "home-agent-address-discovery-reply-message": [ 145, 0, 0xFF ],
131 "mobile-prefix-solicitation": [ 146, 0, 0xFF ],
132 "mobile-prefix-advertisement": [ 147, 0, 0xFF ],
135 "certification-path-solicitation-message": [ 148, 0, 0xFF ],
136 "certification-path-advertisement-message": [ 149, 0, 0xFF ],
138 "seamoby-protocol-message": [ 150, 0, 0xFF ],
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 ],
145 /* codes 0-5, 6-255 */
146 "fmipv6-message": [ 154, 0, 0xFF ],
148 "rpl-control-message": [ 155, 0, 0xFF ],
150 "ilnpv6-locator-update-message": [ 156, 0, 0xFF ],
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 ],
157 /* Multicast Protocol for Low-Power */
158 "mpl-control-message": [ 159, 0, 0xFF ],
161 "extended-echo-request": [ 160, 0, 0xFF ],
162 "extended-ping": [ 160, 0, 0xFF ], /* Alias */
164 /* codes 0-4, 5-255 */
165 "extended-echo-reply": [ 161, 0, 0xFF ],
166 "extended-pong": [ 161, 0, 0xFF ] /* Alias */
169 const dscp_classes = {
195 function to_mask(bits, v6) {
196 let m = [], n = false;
203 if (bits > (v6 ? 128 : 32))
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;
215 function to_bits(mask) {
216 let a = iptoarr(mask);
223 for (let i = 0, z = false; i < length(a); i++) {
226 while (!z && (a[i] & 0x80)) {
227 a[i] = (a[i] << 1) & 0xff;
238 function apply_mask(addr, mask) {
239 let a = iptoarr(addr);
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;
252 let m = iptoarr(mask);
254 if (!m || length(a) != length(m))
257 for (let i = 0; i < length(a); i++)
264 function to_array(x) {
265 if (type(x) == "array")
271 if (type(x) == "object")
276 return (x == "") ? [] : split(x, /[ \t]+/);
279 function filter_pos(x) {
280 let rv = filter(x, e => !e.invert);
281 return length(rv) ? rv : null;
284 function filter_neg(x) {
285 let rv = filter(x, e => e.invert);
286 return length(rv) ? rv : null;
289 function null_if_empty(x) {
290 return length(x) ? x : null;
293 function subnets_split_af(x) {
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 });
300 for (let a in filter(ag.addrs, a => (a.family == 6)))
301 push(rv[1] ||= [], { ...a, invert: ag.invert });
305 rv.family = (!rv[0] ^ !rv[1]) ? (rv[0] ? 4 : 6) : 0;
310 function subnets_group_by_masking(x) {
311 let groups = [], plain = [], nc = [], invert_plain = [], invert_masked = [];
313 for (let a in to_array(x)) {
314 if (a.bits == -1 && !a.invert)
318 else if (a.bits == -1)
319 push(invert_masked, a);
321 push(invert_plain, a);
325 push(groups, [ null, null_if_empty(invert_plain), [ a, ...invert_masked ] ]);
330 null_if_empty(invert_plain),
331 null_if_empty(invert_masked)
334 else if (!length(groups)) {
337 null_if_empty(invert_plain),
338 null_if_empty(invert_masked)
345 function ensure_tcpudp(x) {
346 if (length(filter(x, p => (p.name == "tcp" || p.name == "udp"))))
349 let rest = filter(x, p => !p.any),
350 any = filter(x, p => p.any);
352 if (length(any) && !length(rest)) {
354 push(x, { name: "tcp" }, { name: "udp" });
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);
365 function infer_family(f, objects) {
369 for (let i = 0; i < length(objects); i += 2) {
370 let objs = to_array(objects[i]),
371 desc = objects[i + 1];
373 for (let obj in objs) {
374 if (!obj || !obj.family || obj.family == res)
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`;
392 function map_setmatch(set, match, proto) {
393 if (!set || (('inet_service' in set.types) && proto != 'tcp' && proto != 'udp'))
398 for (let i, t in set.types) {
399 let dir = ((match.dir?.[i] || set.directions[i] || 'src') == 'src' ? 's' : 'd');
403 fields[i] = `ip ${dir}addr`;
407 fields[i] = `ip6 ${dir}addr`;
414 fields[i] = 'ether saddr';
418 fields[i] = `${proto} ${dir}port`;
426 function resolve_lower_devices(devstatus, devname, require_hwoffload) {
427 let dir = fs.opendir(`/sys/class/net/${devname}`);
431 switch (devstatus[devname]?.devtype) {
436 while ((e = dir.read()) != null)
437 if (index(e, "lower_") === 0)
438 push(devs, ...resolve_lower_devices(devstatus, substr(e, 6), require_hwoffload));
443 if (!require_hwoffload || devstatus[devname]?.["hw-tc-offload"])
455 function nft_json_command(...args) {
456 let cmd = [ "/usr/sbin/nft", "--terse", "--json", ...args ];
457 let nft = fs.popen(join(" ", cmd), "r");
462 info = filter(json(nft.read("all"))?.nftables,
463 item => (type(item) == "object" && !item.metainfo));
466 warn(`Unable to parse nftables JSON output: ${e}\n`);
472 warn(`Unable to popen() ${cmd}: ${fs.error()}\n`);
478 function nft_try_hw_offload(devices) {
480 add table inet fw4-hw-offload-test;
481 add flowtable inet fw4-hw-offload-test ft {
482 hook ingress priority 0;
483 devices = { "${join('", "', devices)}" };
488 let rc = system(`/usr/sbin/nft -c '${replace(nft_test, "'", "'\\''")}' 2>/dev/null`);
495 read_kernel_version: function() {
496 let fd = fs.open("/proc/version", "r"),
500 let m = match(fd.read("line"), /^Linux version ([0-9]+)\.([0-9]+)\.([0-9]+)/);
502 v = m ? (+m[1] << 24) | (+m[2] << 16) | (+m[3] << 8) : 0;
509 resolve_offload_devices: function() {
510 if (!this.default_option("flow_offloading"))
513 let devstatus = null;
515 let bus = ubus.connect();
518 devstatus = bus.call("network.device", "status") || {};
522 if (this.default_option("flow_offloading_hw")) {
523 for (let zone in this.zones())
524 for (let device in zone.related_physdevs)
525 push(devices, ...resolve_lower_devices(devstatus, device, true));
527 devices = sort(uniq(devices));
529 if (length(devices) && nft_try_hw_offload(devices))
532 this.warn('Hardware flow offloading unavailable, falling back to software offloading');
533 this.state.defaults.flow_offloading_hw = false;
538 for (let zone in this.zones())
539 for (let device in zone.related_physdevs)
540 push(devices, ...resolve_lower_devices(devstatus, device, false));
542 return sort(uniq(devices));
545 check_set_types: function() {
548 for (let item in nft_json_command("list", "sets", "inet"))
549 if (item.set?.table == "fw4")
550 sets[item.set.name] = (type(item.set.type) == "array") ? item.set.type : [ item.set.type ];
555 check_flowtable: function() {
556 for (let item in nft_json_command("list", "flowtables", "inet"))
557 if (item.flowtable?.table == "fw4" && item.flowtable?.name == "ft")
563 read_state: function() {
564 let fd = fs.open(STATEFILE, "r");
569 state = json(fd.read("all"));
572 warn(`Unable to parse '${STATEFILE}': ${e}\n`);
581 read_ubus: function() {
584 rules = [], networks = {},
585 bus = ubus.connect();
588 ifaces = bus.call("network.interface", "dump");
589 services = bus.call("service", "get_data", { "type": "firewall" });
594 warn(`Unable to connect to ubus: ${ubus.error()}\n`);
599 // Gather logical network information from ubus
602 if (type(ifaces?.interface) == "array") {
603 for (let ifc in ifaces.interface) {
606 device: ifc.l3_device ?? ifc.device,
611 if (type(ifc["ipv4-address"]) == "array") {
612 for (let addr in ifc["ipv4-address"]) {
613 push(net.ipaddrs ||= [], {
616 mask: to_mask(addr.mask, false),
622 if (type(ifc["ipv6-address"]) == "array") {
623 for (let addr in ifc["ipv6-address"]) {
624 push(net.ipaddrs ||= [], {
627 mask: to_mask(addr.mask, true),
633 if (type(ifc["ipv6-prefix-assignment"]) == "array") {
634 for (let addr in ifc["ipv6-prefix-assignment"]) {
635 if (addr["local-address"]) {
636 push(net.ipaddrs ||= [], {
638 addr: addr["local-address"].address,
639 mask: to_mask(addr["local-address"].mask, true),
640 bits: addr["local-address"].mask
646 if (type(ifc.data?.firewall) == "array") {
649 for (let rulespec in ifc.data.firewall) {
653 name: (rulespec.type != 'ipset') ? `ubus:${ifc.interface}[${ifc.proto}] ${rulespec.type || 'rule'} ${n}` : rulespec.name,
654 device: rulespec.device ?? ifc.l3_device ?? ifc.device
661 networks[ifc.interface] = net;
667 // Gather firewall rule definitions from ubus services
670 if (type(services) == "object") {
671 for (let svcname, service in services) {
672 if (type(service?.firewall) == "array") {
675 for (let rulespec in services[svcname].firewall) {
679 name: (rulespec.type != 'ipset') ? `ubus:${svcname} ${rulespec.type || 'rule'} ${n}` : rulespec.name
686 for (let svcinst, instance in service) {
687 if (type(instance?.firewall) == "array") {
690 for (let rulespec in instance.firewall) {
694 name: (rulespec.type != 'ipset') ? `ubus:${svcname}[${svcinst}] ${rulespec.type || 'rule'} ${n}` : rulespec.name
710 load: function(use_statefile) {
713 this.state = use_statefile ? this.read_state() : null;
715 this.cursor = uci.cursor();
716 this.cursor.load("firewall");
717 this.cursor.load("/usr/share/firewall4/helpers");
720 this.state = this.read_ubus();
722 this.kernel = this.read_kernel_version();
726 // Read helper mapping
729 this.cursor.foreach("helpers", "helper", h => self.parse_helper(h));
733 // Read default policies
736 this.cursor.foreach("firewall", "defaults", d => self.parse_defaults(d));
738 if (!this.state.defaults)
739 this.parse_defaults({});
743 // Build list of ipsets
746 if (!this.state.ipsets) {
747 map(filter(this.state.ubus_rules, n => (n.type == "ipset")), s => self.parse_ipset(s));
748 this.cursor.foreach("firewall", "ipset", s => self.parse_ipset(s));
753 // Build list of logical zones
756 if (!this.state.zones)
757 this.cursor.foreach("firewall", "zone", z => self.parse_zone(z));
761 // Build list of rules
764 map(filter(this.state.ubus_rules, r => (r.type == "rule")), r => self.parse_rule(r));
765 this.cursor.foreach("firewall", "rule", r => self.parse_rule(r));
769 // Build list of forwardings
772 this.cursor.foreach("firewall", "forwarding", f => self.parse_forwarding(f));
776 // Build list of redirects
779 map(filter(this.state.ubus_rules, r => (r.type == "redirect")), r => self.parse_redirect(r));
780 this.cursor.foreach("firewall", "redirect", r => self.parse_redirect(r));
784 // Build list of snats
787 map(filter(this.state.ubus_rules, n => (n.type == "nat")), n => self.parse_nat(n));
788 this.cursor.foreach("firewall", "nat", n => self.parse_nat(n));
792 // Build list of includes
795 this.cursor.foreach("firewall", "include", i => self.parse_include(i));
799 // Discover automatic includes
802 if (this.default_option("auto_includes")) {
803 for (let position in [ 'ruleset-pre', 'ruleset-post', 'table-pre', 'table-post', 'chain-pre', 'chain-post' ])
804 for (let chain in (position in [ 'chain-pre', 'chain-post' ]) ? fs.lsdir(`/usr/share/nftables.d/${position}`) : [ null ])
805 for (let path in fs.glob(`/usr/share/nftables.d/${position}${chain ? `/${chain}` : ''}/*.nft`))
807 this.parse_include({ type: 'nftables', position, chain, path });
812 let fd = fs.open(STATEFILE, "w");
816 zones: this.state.zones,
817 ipsets: this.state.ipsets,
818 networks: this.state.networks,
819 ubus_rules: this.state.ubus_rules,
820 includes: this.state.includes
826 warn(`Unable to write '${STATEFILE}': ${fs.error()}\n`);
831 warn: function(fmt, ...args) {
835 let msg = sprintf(fmt, ...args);
838 warn(`\033[33m${msg}\033[m\n`);
840 warn(`[!] ${msg}\n`);
843 get: function(sid, opt) {
844 return this.cursor.get("firewall", sid, opt);
847 get_all: function(sid) {
848 return this.cursor.get_all("firewall", sid);
851 parse_options: function(s, spec) {
854 for (let key, val in spec) {
855 let datatype = `parse_${val[0]}`,
858 parsefn = (flags & PARSE_LIST) ? "parse_list" : "parse_opt";
860 let res = this[parsefn](s, key, datatype, defval, flags);
865 if (type(res) == "object" && res.invert && (flags & NO_INVERT)) {
866 this.warn_section(s, `option '${key}' must not be negated`);
871 if (flags & DEPRECATED)
872 this.warn_section(s, `option '${key}' is deprecated by fw4`);
873 else if (flags & UNSUPPORTED)
874 this.warn_section(s, `option '${key}' is not supported by fw4`);
881 if (index(opt, '.') != 0 && opt != 'type' && !exists(spec, opt)) {
882 this.warn_section(s, `specifies unknown option '${opt}'`);
889 parse_subnet: function(subnet) {
890 let parts = split(subnet, "/");
893 switch (length(parts)) {
895 a = iptoarr(parts[0]);
896 m = iptoarr(parts[1]);
902 if (length(a) != length(m))
905 b = to_bits(parts[1]);
907 /* allow non-contiguous masks such as `::ffff:ffff:ffff:ffff` */
920 if (type(b) != "int")
923 m = to_mask(b, length(a) == 16);
928 family: (length(a) == 16) ? 6 : 4,
935 parts = split(parts[0], "-");
937 switch (length(parts)) {
939 a = iptoarr(parts[0]);
940 b = iptoarr(parts[1]);
942 if (a && b && length(a) == length(b)) {
944 family: (length(a) == 16) ? 6 : 4,
954 a = iptoarr(parts[0]);
958 family: (length(a) == 16) ? 6 : 4,
960 mask: to_mask(length(a) * 8, length(a) == 16),
965 n = this.state.networks[parts[0]];
968 return [ ...(n.ipaddrs || []) ];
975 parse_enum: function(val, choices) {
976 if (type(val) == "string") {
979 for (let i = 0; i < length(choices); i++)
980 if (lc(substr(choices[i], 0, length(val))) == val)
987 section_id: function(sid) {
988 let s = this.get_all(sid);
993 if (s[".anonymous"]) {
996 this.cursor.foreach("firewall", s[".type"], function(ss) {
997 if (ss[".name"] == s[".name"])
1003 return `@${s['.type']}[${c}]`;
1009 warn_section: function(s, msg) {
1012 this.warn("Section %s (%s) %s", this.section_id(s[".name"]), s.name, msg);
1014 this.warn("Section %s %s", this.section_id(s[".name"]), msg);
1018 this.warn("ubus %s (%s) %s", s.type || "rule", s.name, msg);
1020 this.warn("ubus %s %s", s.type || "rule", msg);
1024 parse_policy: function(val) {
1025 return this.parse_enum(val, [
1032 parse_bool: function(val) {
1033 if (val == "1" || val == "on" || val == "true" || val == "yes")
1035 else if (val == "0" || val == "off" || val == "false" || val == "no")
1041 parse_family: function(val) {
1042 if (val == 'any' || val == 'all' || val == '*')
1044 else if (val == 'inet' || index(val, '4') > -1)
1046 else if (index(val, '6') > -1)
1052 parse_zone_ref: function(val) {
1057 return { any: true };
1059 for (let zone in this.state.zones) {
1060 if (zone.name == val) {
1071 parse_device: function(val) {
1072 let rv = this.parse_invert(val);
1085 parse_direction: function(val) {
1086 if (val == 'in' || val == 'ingress')
1088 else if (val == 'out' || val == 'egress')
1094 parse_setmatch: function(val) {
1095 let rv = this.parse_invert(val);
1100 rv.val = trim(replace(rv.val, /^[^ \t]+/, function(m) {
1105 let dir = split(rv.val, /[ \t,]/);
1107 for (let i = 0; i < 3 && i < length(dir); i++) {
1108 if (dir[i] == "dst" || dir[i] == "dest")
1109 (rv.dir ||= [])[i] = "dst";
1110 else if (dir[i] == "src")
1111 (rv.dir ||= [])[i] = "src";
1114 return length(rv.name) ? rv : null;
1117 parse_cthelper: function(val) {
1118 let rv = this.parse_invert(val);
1123 let helper = filter(this.state.helpers, h => (h.name == rv.val))?.[0];
1125 return helper ? { ...rv, ...helper } : null;
1128 parse_protocol: function(val) {
1129 let p = this.parse_invert(val);
1151 p.name = 'ipv6-icmp';
1156 { invert: p.invert, name: 'tcp' },
1157 { invert: p.invert, name: 'udp' }
1172 return (p.any || length(p.name)) ? p : null;
1175 parse_mac: function(val) {
1176 let mac = this.parse_invert(val);
1177 let m = mac ? match(mac.val, /^([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})$/i) : null;
1182 mac.mac = sprintf('%02x:%02x:%02x:%02x:%02x:%02x',
1183 hex(m[1]), hex(m[2]), hex(m[3]),
1184 hex(m[4]), hex(m[5]), hex(m[6]));
1189 parse_port: function(val) {
1190 let port = this.parse_invert(val);
1191 let m = port ? match(port.val, /^([0-9]{1,5})([-:]([0-9]{1,5}))?$/i) : null;
1197 let min_port = +m[1];
1198 let max_port = +m[3];
1200 if (min_port > max_port ||
1201 min_port < 0 || max_port < 0 ||
1202 min_port > 65535 || max_port > 65535)
1205 port.min = min_port;
1206 port.max = max_port;
1211 if (pn != pn || pn < 0 || pn > 65535)
1221 parse_network: function(val) {
1222 let rv = this.parse_invert(val);
1227 let nets = this.parse_subnet(rv.val);
1233 rv.addrs = [ ...nets ];
1238 parse_icmptype: function(val) {
1241 if (exists(ipv4_icmptypes, val)) {
1244 rv.type = ipv4_icmptypes[val][0];
1245 rv.code_min = ipv4_icmptypes[val][1];
1246 rv.code_max = ipv4_icmptypes[val][2];
1249 if (exists(ipv6_icmptypes, val)) {
1250 rv.family = rv.family ? 0 : 6;
1252 rv.type6 = ipv6_icmptypes[val][0];
1253 rv.code6_min = ipv6_icmptypes[val][1];
1254 rv.code6_max = ipv6_icmptypes[val][2];
1257 if (!exists(rv, "family")) {
1258 let m = match(val, /^([0-9]+)(\/([0-9]+))?$/);
1265 rv.code_min = +m[3];
1266 rv.code_max = rv.code_min;
1274 if (rv.type > 0xFF || rv.code_min > 0xFF || rv.code_max > 0xFF)
1280 rv.code6_min = rv.code_min;
1281 rv.code6_max = rv.code_max;
1287 parse_invert: function(val) {
1291 let rv = { invert: false };
1293 rv.val = trim(replace(val, /^[ \t]*!/, () => (rv.invert = true, '')));
1295 return length(rv.val) ? rv : null;
1298 parse_limit: function(val) {
1299 let rv = this.parse_invert(val);
1300 let m = rv ? match(rv.val, /^([0-9]+)(\/([a-z]+))?$/) : null;
1306 let u = m[3] ? this.parse_enum(m[3], [ "second", "minute", "hour", "day" ]) : "second";
1317 parse_int: function(val) {
1320 return (n == n) ? n : null;
1323 parse_date: function(val) {
1324 let d = match(val, /^([0-9]{4})(-([0-9]{1,2})(-([0-9]{1,2})(T([0-9:]+))?)?)?$/);
1326 if (d == null || d[1] < 1970 || d[1] > 2038 || d[3] > 12 || d[5] > 31)
1329 let t = this.parse_time(d[7] ?? "0");
1342 parse_time: function(val) {
1343 let t = match(val, /^([0-9]{1,2})(:([0-9]{1,2})(:([0-9]{1,2}))?)?$/);
1345 if (t == null || t[1] > 23 || t[3] > 59 || t[5] > 59)
1355 parse_weekdays: function(val) {
1356 let rv = this.parse_invert(val);
1361 for (let day in to_array(rv.val)) {
1362 day = this.parse_enum(day, [
1375 (rv.days ||= {})[day] = true;
1378 rv.days = keys(rv.days);
1380 return rv.days ? rv : null;
1383 parse_monthdays: function(val) {
1384 let rv = this.parse_invert(val);
1389 for (let day in to_array(rv.val)) {
1392 if (day < 1 || day > 31)
1395 (rv.days ||= [])[day] = true;
1398 return rv.days ? rv : null;
1401 parse_mark: function(val) {
1402 let rv = this.parse_invert(val);
1403 let m = rv ? match(rv.val, /^(0?x?[0-9a-f]+)(\/(0?x?[0-9a-f]+))?$/i) : null;
1410 if (n != n || n > 0xFFFFFFFF)
1414 rv.mask = 0xFFFFFFFF;
1419 if (n != n || n > 0xFFFFFFFF)
1428 parse_dscp: function(val) {
1429 let rv = this.parse_invert(val);
1434 rv.val = uc(rv.val);
1436 if (exists(dscp_classes, rv.val)) {
1437 rv.dscp = dscp_classes[rv.val];
1442 if (n != n || n < 0 || n > 0x3F)
1451 parse_target: function(val) {
1452 return this.parse_enum(val, [
1469 parse_reject_code: function(val) {
1470 return this.parse_enum(val, [
1479 parse_reflection_source: function(val) {
1480 return this.parse_enum(val, [
1486 parse_ipsettype: function(val) {
1487 let m = match(val, /^(src|dst|dest)_(.+)$/);
1488 let t = this.parse_enum(m ? m[2] : val, [
1496 return t ? [ (!m || m[1] == 'src') ? 'src' : 'dst', t ] : null;
1499 parse_ipsetentry: function(val, set) {
1500 let values = split(val, /[ \t]+/);
1502 if (length(values) != length(set.types))
1508 for (let i, t in set.types) {
1511 ip = filter(this.parse_subnet(values[i]), a => (a.family == 4));
1513 switch (length(ip) ?? 0) {
1514 case 0: return null;
1516 default: this.warn("Set entry '%s' resolves to multiple addresses, using first one", values[i]);
1519 rv[i] = ("net" in set.fw4types) ? `${ip[0].addr}/${ip[0].bits}` : ip[0].addr;
1523 ip = filter(this.parse_subnet(values[i]), a => (a.family == 6));
1525 switch (length(ip) ?? 0) {
1526 case 0: return null;
1528 case 2: this.warn("Set entry '%s' resolves to multiple addresses, using first one", values[i]);
1531 rv[i] = ("net" in set.fw4types) ? `${ip[0].addr}/${ip[0].bits}` : ip[0].addr;
1536 mac = this.parse_mac(values[i]);
1538 if (!mac || mac.invert)
1544 case 'inet_service':
1545 port = this.parse_port(values[i]);
1547 if (!port || port.invert || port.min != port.max)
1558 return length(rv) ? rv : null;
1561 parse_includetype: function(val) {
1562 return this.parse_enum(val, [
1568 parse_includeposition: function(val) {
1569 return replace(this.parse_enum(val, [
1581 ]), "postpend", "append");
1584 parse_string: function(val) {
1588 parse_opt: function(s, opt, fn, defval, flags) {
1592 if (flags & REQUIRED) {
1593 this.warn_section(s, `option '${opt}' is mandatory but not set`);
1600 if (type(val) == "array") {
1601 this.warn_section(s, `option '${opt}' must not be a list`);
1604 else if (val == null) {
1608 let res = this[fn](val);
1611 this.warn_section(s, `option '${opt}' specifies invalid value '${val}'`);
1618 parse_list: function(s, opt, fn, defval, flags) {
1623 if (flags & REQUIRED) {
1624 this.warn_section(s, `option '${opt}' is mandatory but not set`);
1631 for (val in to_array(val)) {
1632 let res = this[fn](val);
1635 this.warn_section(s, `option '${opt}' specifies invalid value '${val}'`);
1639 if (flags & FLATTEN_LIST)
1640 push(rv, ...to_array(res));
1645 return length(rv) ? rv : null;
1648 quote: function(s, force) {
1649 if (force === true || !match(s, /^([0-9A-Fa-f:.\/-]+)( \. [0-9A-Fa-f:.\/-]+)*$/))
1650 return `"${replace(s + "", /(["\\])/g, '\\$1')}"`;
1657 return `${a.addr}-${a.addr2}`;
1659 if ((a.family == 4 && a.bits == 32) ||
1660 (a.family == 6 && a.bits == 128))
1664 return `${apply_mask(a.addr, a.bits)}/${a.bits}`;
1666 return `${a.addr}/${a.mask}`;
1669 host: function(a, v6brackets) {
1671 ? `${a.addr}-${a.addr2}`
1672 : (a.family == 6 && v6brackets)
1673 ? `[${apply_mask(a.addr, a.bits)}]` : apply_mask(a.addr, a.bits);
1680 return `${p.min}-${p.max}`;
1683 set: function(v, force) {
1686 v = filter(to_array(v), item => !seen[item]++);
1688 if (force || length(v) != 1)
1689 return `{ ${join(', ', map(v, this.quote))} }`;
1691 return this.quote(v[0]);
1694 concat: function(v) {
1695 return join(' . ', to_array(v));
1698 ipproto: function(family) {
1708 nfproto: function(family, human_readable) {
1711 return human_readable ? "IPv4" : "ipv4";
1714 return human_readable ? "IPv6" : "ipv6";
1717 return human_readable ? "IPv4/IPv6" : null;
1721 l4proto: function(family, proto) {
1722 switch (proto.name) {
1724 switch (family ?? 0) {
1726 return this.set(['icmp', 'ipv6-icmp']);
1737 datetime: function(stamp) {
1738 return sprintf('"%04d-%02d-%02d %02d:%02d:%02d"',
1739 stamp.year, stamp.month, stamp.day,
1740 stamp.hour, stamp.min, stamp.sec);
1743 date: function(stamp) {
1744 return sprintf('"%04d-%02d-%02d"', stamp.year, stamp.month, stamp.day);
1747 datestamp: function(stamp) {
1748 return exists(stamp, 'hour') ? this.datetime(stamp) : this.date(stamp);
1751 time: function(stamp) {
1752 return sprintf('"%02d:%02d:%02d"', stamp.hour, stamp.min, stamp.sec);
1756 return sprintf('0x%x', n);
1759 is_loopback_dev: function(dev) {
1760 return !!(+fs.readfile(`/sys/class/net/${dev}/flags`) & 0x8);
1763 is_loopback_addr: function(addr) {
1764 return (index(addr, "127.") == 0 || addr == "::1" || addr == "::1/128");
1767 filter_loopback_devs: function(devs, invert) {
1768 return null_if_empty(filter(devs, d => (this.is_loopback_dev(d) == invert)));
1771 filter_loopback_addrs: function(addrs, invert) {
1772 return null_if_empty(filter(addrs, a => (this.is_loopback_addr(a) == invert)));
1776 input_policy: function(reject_as_drop) {
1777 return (!reject_as_drop || this.state.defaults.input != 'reject') ? this.state.defaults.input : 'drop';
1780 output_policy: function(reject_as_drop) {
1781 return (!reject_as_drop || this.state.defaults.output != 'reject') ? this.state.defaults.output : 'drop';
1784 forward_policy: function(reject_as_drop) {
1785 return (!reject_as_drop || this.state.defaults.forward != 'reject') ? this.state.defaults.forward : 'drop';
1788 default_option: function(flag) {
1789 return this.state.defaults[flag];
1792 helpers: function() {
1793 return this.state.helpers;
1797 return this.state.zones;
1800 rules: function(chain) {
1801 return filter(this.state.rules, r => (r.chain == chain));
1804 redirects: function(chain) {
1805 return filter(this.state.redirects, r => (r.chain == chain));
1808 ipsets: function() {
1809 return this.state.ipsets;
1812 includes: function(position, chain) {
1818 case 'table-prepend':
1819 case 'table-append':
1824 case 'chain-prepend':
1825 case 'chain-append':
1835 for (let inc in this.state.includes)
1836 if (inc.type == 'nftables' && inc.position == position && (!chain || inc.chain == chain))
1837 push(stmts, `${pad}include "${inc.path}"\n`);
1839 print(length(stmts) > 1 ? join('', stmts) : '');
1842 parse_setfile: function(set, cb) {
1843 let fd = fs.open(set.loadfile, "r");
1846 warn(`Unable to load file '${set.loadfile}' for set '${set.name}': ${fs.error()}\n`);
1852 for (let line = fd.read("line"); length(line); line = fd.read("line")) {
1855 if (length(line) == 0 || ord(line) == 35)
1858 let v = this.parse_ipsetentry(line, set);
1861 this.warn(`Skipping invalid entry '${line}' in file '${set.loadfile}' for set '${set.name}'`);
1875 print_setentries: function(set) {
1877 let printer = (entry) => {
1879 print("\t\telements = {\n");
1883 print("\t\t\t", join(" . ", entry), ",\n");
1886 map(set.entries, printer);
1889 this.parse_setfile(set, printer);
1895 parse_helper: function(data) {
1896 let helper = this.parse_options(data, {
1897 name: [ "string", null, REQUIRED ],
1898 description: [ "string" ],
1899 module: [ "string" ],
1900 family: [ "family" ],
1901 proto: [ "protocol", null, PARSE_LIST | FLATTEN_LIST | NO_INVERT ],
1902 port: [ "port", null, NO_INVERT ]
1905 if (helper === false) {
1906 this.warn("Helper definition '%s' skipped due to invalid options", data.name || data['.name']);
1909 else if (helper.proto.any) {
1910 this.warn("Helper definition '%s' must not specify wildcard protocol", data.name || data['.name']);
1913 else if (length(helper.proto) > 1) {
1914 this.warn("Helper definition '%s' must not specify multiple protocols", data.name || data['.name']);
1918 helper.available = (fs.stat(`/sys/module/${helper.module}`)?.type == "directory");
1920 push(this.state.helpers ||= [], helper);
1923 parse_defaults: function(data) {
1924 if (this.state.defaults) {
1925 this.warn_section(data, ": ignoring duplicate defaults section");
1929 let defs = this.parse_options(data, {
1930 input: [ "policy", "drop" ],
1931 output: [ "policy", "drop" ],
1932 forward: [ "policy", "drop" ],
1934 drop_invalid: [ "bool" ],
1935 tcp_reject_code: [ "reject_code", "tcp-reset" ],
1936 any_reject_code: [ "reject_code", "port-unreachable" ],
1938 syn_flood: [ "bool" ],
1939 synflood_protect: [ "bool" ],
1940 synflood_rate: [ "limit", "25/second" ],
1941 synflood_burst: [ "int", "50" ],
1943 tcp_syncookies: [ "bool", "1" ],
1945 tcp_window_scaling: [ "bool", "1" ],
1947 accept_redirects: [ "bool" ],
1948 accept_source_route: [ "bool" ],
1950 auto_helper: [ "bool", "1" ],
1951 custom_chains: [ "bool", null, UNSUPPORTED ],
1952 disable_ipv6: [ "bool", null, UNSUPPORTED ],
1953 flow_offloading: [ "bool", "0" ],
1954 flow_offloading_hw: [ "bool", "0" ],
1956 auto_includes: [ "bool", "1" ]
1959 if (defs.synflood_protect === null)
1960 defs.synflood_protect = defs.syn_flood;
1962 delete defs.syn_flood;
1964 this.state.defaults = defs;
1967 parse_zone: function(data) {
1968 let zone = this.parse_options(data, {
1969 enabled: [ "bool", "1" ],
1971 name: [ "string", null, REQUIRED ],
1972 family: [ "family" ],
1974 network: [ "device", null, PARSE_LIST ],
1975 device: [ "device", null, PARSE_LIST ],
1976 subnet: [ "network", null, PARSE_LIST ],
1978 input: [ "policy", this.state.defaults ? this.state.defaults.input : "drop" ],
1979 output: [ "policy", this.state.defaults ? this.state.defaults.output : "drop" ],
1980 forward: [ "policy", this.state.defaults ? this.state.defaults.forward : "drop" ],
1983 masq_allow_invalid: [ "bool" ],
1984 masq_src: [ "network", null, PARSE_LIST ],
1985 masq_dest: [ "network", null, PARSE_LIST ],
1989 extra: [ "string", null, UNSUPPORTED ],
1990 extra_src: [ "string", null, UNSUPPORTED ],
1991 extra_dest: [ "string", null, UNSUPPORTED ],
1993 mtu_fix: [ "bool" ],
1994 custom_chains: [ "bool", null, UNSUPPORTED ],
1997 log_limit: [ "limit", null, UNSUPPORTED ],
1999 auto_helper: [ "bool", "1" ],
2000 helper: [ "cthelper", null, PARSE_LIST ],
2002 counter: [ "bool", "1" ]
2005 if (zone === false) {
2006 this.warn_section(data, "skipped due to invalid options");
2009 else if (!zone.enabled) {
2010 this.warn_section(data, "is disabled, ignoring section");
2014 for (let helper in zone.helper) {
2015 if (!helper.available) {
2016 this.warn_section(data, `uses unavailable ct helper '${zone.helper.name}'`);
2020 if (zone.mtu_fix && this.kernel < 0x040a0000) {
2021 this.warn_section(data, "option 'mtu_fix' requires kernel 4.10 or later");
2025 if (this.state.defaults?.auto_helper === false)
2026 zone.auto_helper = false;
2028 let match_devices = [];
2029 let related_physdevs = [];
2030 let related_subnets = [];
2031 let related_ubus_networks = [];
2032 let match_subnets, masq_src_subnets, masq_dest_subnets;
2034 for (let name, net in this.state.networks) {
2035 if (net.zone === zone.name)
2036 push(related_ubus_networks, { invert: false, device: name });
2039 zone.network = [ ...to_array(zone.network), ...related_ubus_networks ];
2041 for (let e in zone.network) {
2042 if (exists(this.state.networks, e.device)) {
2043 let net = this.state.networks[e.device];
2046 push(match_devices, {
2052 if (net.physdev && !e.invert)
2053 push(related_physdevs, net.physdev);
2055 push(related_subnets, ...(net.ipaddrs || []));
2059 push(match_devices, ...to_array(zone.device));
2061 match_subnets = subnets_split_af(zone.subnet);
2062 masq_src_subnets = subnets_split_af(zone.masq_src);
2063 masq_dest_subnets = subnets_split_af(zone.masq_dest);
2065 push(related_subnets, ...(match_subnets[0] || []), ...(match_subnets[1] || []));
2067 let match_rules = [];
2069 let add_rule = (family, devices, subnets, zone) => {
2074 r.devices_pos = null_if_empty(devices[0]);
2075 r.devices_neg = null_if_empty(devices[1]);
2076 r.devices_neg_wildcard = null_if_empty(devices[2]);
2078 r.subnets_pos = map(subnets[0], this.cidr);
2079 r.subnets_neg = map(subnets[1], this.cidr);
2080 r.subnets_masked = subnets[2];
2082 push(match_rules, r);
2085 let family = infer_family(zone.family, [
2086 match_subnets, "subnet list"
2089 if (type(family) == "string") {
2090 this.warn_section(data, `${family}, skipping`);
2094 // group non-inverted device matches into wildcard and non-wildcard ones
2095 let devices = [], plain_devices = [], plain_invert_devices = [], wildcard_invert_devices = [];
2097 for (let device in match_devices) {
2098 let m = match(device.device, /^([^+]*)(\+)?$/);
2101 this.warn_section(data, `skipping invalid wildcard pattern '${device.device}'`);
2105 // filter `+` (match any device) since nftables does not support
2106 // wildcard only matches
2107 if (!device.invert && m[0] == '+')
2110 // replace inverted `+` (match no device) with invalid pattern
2111 if (device.invert && m[0] == '+') {
2112 device.device = '/never/';
2113 device.invert = false;
2116 // replace "name+" matches with "name*"
2117 else if (m[2] == '+')
2118 device.device = m[1] + '*';
2120 device.wildcard = !!m[2];
2122 if (!device.invert && device.wildcard)
2123 push(devices, [ [ device.device ], plain_invert_devices, wildcard_invert_devices ]);
2124 else if (!device.invert)
2125 push(plain_devices, device.device);
2126 else if (device.wildcard)
2127 push(wildcard_invert_devices, device.device);
2129 push(plain_invert_devices, device.device);
2132 if (length(plain_devices))
2135 plain_invert_devices,
2136 wildcard_invert_devices
2138 else if (!length(devices))
2141 plain_invert_devices,
2142 wildcard_invert_devices
2145 // emit zone jump rules for each device group
2146 if (length(match_devices) || length(match_subnets[0]) || length(match_subnets[1])) {
2147 for (let devgroup in devices) {
2148 // check if there's no AF specific bits, in this case we can do AF agnostic matching
2149 if (!family && !length(match_subnets[0]) && !length(match_subnets[1])) {
2150 add_rule(0, devgroup, [], zone);
2153 // we need to emit one or two AF specific rules
2155 if (!family || family == 4)
2156 for (let subnets in subnets_group_by_masking(match_subnets[0]))
2157 add_rule(4, devgroup, subnets, zone);
2159 if (!family || family == 6)
2160 for (let subnets in subnets_group_by_masking(match_subnets[1]))
2161 add_rule(6, devgroup, subnets, zone);
2166 zone.family = family;
2168 zone.match_rules = match_rules;
2170 zone.masq4_src_subnets = subnets_group_by_masking(masq_src_subnets[0]);
2171 zone.masq4_dest_subnets = subnets_group_by_masking(masq_dest_subnets[0]);
2173 zone.masq6_src_subnets = subnets_group_by_masking(masq_src_subnets[1]);
2174 zone.masq6_dest_subnets = subnets_group_by_masking(masq_dest_subnets[1]);
2177 zone.sflags[zone.input] = true;
2180 zone.dflags[zone.output] = true;
2181 zone.dflags[zone.forward] = true;
2183 zone.match_devices = map(filter(match_devices, d => !d.invert), d => d.device);
2184 zone.match_subnets = map(filter(related_subnets, s => !s.invert && s.bits != -1), this.cidr);
2186 zone.related_subnets = related_subnets;
2187 zone.related_physdevs = related_physdevs;
2189 if (zone.masq || zone.masq6)
2190 zone.dflags.snat = true;
2192 if ((zone.auto_helper && !(zone.masq || zone.masq6)) || length(zone.helper)) {
2193 zone.dflags.helper = true;
2195 for (let helper in (length(zone.helper) ? zone.helper : this.state.helpers)) {
2196 if (!helper.available)
2199 for (let proto in helper.proto) {
2200 push(this.state.rules ||= [], {
2201 chain: `helper_${zone.name}`,
2202 family: helper.family,
2203 name: helper.description || helper.name,
2206 dports_pos: [ this.port(helper.port) ],
2214 push(this.state.zones ||= [], zone);
2217 parse_forwarding: function(data) {
2218 let fwd = this.parse_options(data, {
2219 enabled: [ "bool", "1" ],
2222 family: [ "family" ],
2224 src: [ "zone_ref", null, REQUIRED ],
2225 dest: [ "zone_ref", null, REQUIRED ]
2228 if (fwd === false) {
2229 this.warn_section(data, "skipped due to invalid options");
2232 else if (!fwd.enabled) {
2233 this.warn_section(data, "is disabled, ignoring section");
2237 let add_rule = (family, fwd) => {
2242 proto: { any: true }
2245 f.name ||= `Accept ${fwd.src.any ? "any" : fwd.src.zone.name} to ${fwd.dest.any ? "any" : fwd.dest.zone.name} ${family ? `${this.nfproto(family, true)} ` : ''}forwarding`;
2246 f.chain = fwd.src.any ? "forward" : `forward_${fwd.src.zone.name}`;
2249 f.target = "accept";
2251 f.jump_chain = `accept_to_${fwd.dest.zone.name}`;
2253 push(this.state.rules ||= [], f);
2257 /* inherit family restrictions from related zones */
2258 let family = infer_family(fwd.family, [
2259 fwd.src?.zone, "source zone",
2260 fwd.dest?.zone, "destination zone"
2263 if (type(family) == "string") {
2264 this.warn_section(data, `${family}, skipping`);
2268 add_rule(family, fwd);
2271 fwd.dest.zone.dflags.accept = true;
2274 parse_rule: function(data) {
2275 let rule = this.parse_options(data, {
2276 enabled: [ "bool", "1" ],
2278 name: [ "string", this.section_id(data[".name"]) ],
2279 _name: [ "string", null, DEPRECATED ],
2280 family: [ "family" ],
2282 src: [ "zone_ref" ],
2283 dest: [ "zone_ref" ],
2285 device: [ "device", null, NO_INVERT ],
2286 direction: [ "direction" ],
2288 ipset: [ "setmatch" ],
2289 helper: [ "cthelper" ],
2290 set_helper: [ "cthelper", null, NO_INVERT ],
2292 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2294 src_ip: [ "network", null, PARSE_LIST ],
2295 src_mac: [ "mac", null, PARSE_LIST ],
2296 src_port: [ "port", null, PARSE_LIST ],
2298 dest_ip: [ "network", null, PARSE_LIST ],
2299 dest_port: [ "port", null, PARSE_LIST ],
2301 icmp_type: [ "icmptype", null, PARSE_LIST ],
2302 extra: [ "string", null, UNSUPPORTED ],
2305 limit_burst: [ "int" ],
2307 utc_time: [ "bool" ],
2308 start_date: [ "date" ],
2309 stop_date: [ "date" ],
2310 start_time: [ "time" ],
2311 stop_time: [ "time" ],
2312 weekdays: [ "weekdays" ],
2313 monthdays: [ "monthdays", null, UNSUPPORTED ],
2316 set_mark: [ "mark", null, NO_INVERT ],
2317 set_xmark: [ "mark", null, NO_INVERT ],
2320 set_dscp: [ "dscp", null, NO_INVERT ],
2322 counter: [ "bool", "1" ],
2325 target: [ "target" ]
2328 if (rule === false) {
2329 this.warn_section(data, "skipped due to invalid options");
2332 else if (!rule.enabled) {
2333 this.warn_section(data, "is disabled, ignoring section");
2337 if (rule.target in ["helper", "notrack"] && (!rule.src || !rule.src.zone)) {
2338 this.warn_section(data, `must specify a source zone for target '${rule.target}'`);
2341 else if (rule.target == "dscp" && !rule.set_dscp) {
2342 this.warn_section(data, "must specify option 'set_dscp' for target 'dscp'");
2345 else if (rule.target == "mark" && !rule.set_mark && !rule.set_xmark) {
2346 this.warn_section(data, "must specify option 'set_mark' or 'set_xmark' for target 'mark'");
2349 else if (rule.target == "helper" && !rule.set_helper) {
2350 this.warn_section(data, "must specify option 'set_helper' for target 'helper'");
2353 else if (rule.device?.any) {
2354 this.warn_section(data, "must not specify '*' as device");
2358 switch (this.parse_bool(rule.log)) {
2360 rule.log = `${rule.name}: `;
2370 ipset = filter(this.state.ipsets, s => (s.name == rule.ipset.name))?.[0];
2373 this.warn_section(data, `references unknown set '${rule.ipset.name}'`);
2377 if (('inet_service' in ipset.types) && !ensure_tcpudp(rule.proto)) {
2378 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2383 let need_src_action_chain = (rule) => (rule.src?.zone?.log && rule.target && rule.target != "accept");
2385 let add_rule = (family, proto, saddrs, daddrs, sports, dports, icmptypes, icmpcodes, ipset, rule) => {
2391 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2392 has_ports: !!(length(sports) || length(dports)),
2393 saddrs_pos: map(saddrs[0], this.cidr),
2394 saddrs_neg: map(saddrs[1], this.cidr),
2395 saddrs_masked: saddrs[2],
2396 daddrs_pos: map(daddrs[0], this.cidr),
2397 daddrs_neg: map(daddrs[1], this.cidr),
2398 daddrs_masked: daddrs[2],
2399 sports_pos: map(filter_pos(sports), this.port),
2400 sports_neg: map(filter_neg(sports), this.port),
2401 dports_pos: map(filter_pos(dports), this.port),
2402 dports_neg: map(filter_neg(dports), this.port),
2403 smacs_pos: map(filter_pos(rule.src_mac), m => m.mac),
2404 smacs_neg: map(filter_neg(rule.src_mac), m => m.mac),
2405 icmp_types: map(icmptypes, i => (family == 4 ? i.type : i.type6)),
2406 icmp_codes: map(icmpcodes, ic => `${(family == 4) ? ic.type : ic.type6} . ${(family == 4) ? ic.code_min : ic.code6_min}`)
2409 if (!length(r.icmp_types))
2410 delete r.icmp_types;
2412 if (!length(r.icmp_codes))
2413 delete r.icmp_codes;
2417 invert: r.set_mark.invert,
2418 mark: r.set_mark.mark,
2419 mask: r.set_mark.mark | r.set_mark.mask
2425 let set_types = map_setmatch(ipset, rule.ipset, proto.name);
2427 if (set_types !== set_types) {
2428 this.warn_section(data, "destination MAC address matching not supported");
2430 } else if (set_types) {
2431 r.ipset = { ...r.ipset, fields: set_types };
2434 if (r.target == "notrack") {
2435 r.chain = `notrack_${r.src.zone.name}`;
2436 r.src.zone.dflags.notrack = true;
2438 else if (r.target == "helper") {
2439 r.chain = `helper_${r.src.zone.name}`;
2440 r.src.zone.dflags.helper = true;
2442 else if (r.target == "mark" || r.target == "dscp") {
2443 if ((r.src?.any && r.dest?.any) || (r.src?.zone && r.dest?.zone))
2444 r.chain = "mangle_forward";
2445 else if (r.src?.any && r.dest?.zone)
2446 r.chain = "mangle_postrouting";
2447 else if (r.src?.zone && r.dest?.any)
2448 r.chain = "mangle_prerouting";
2449 else if (r.src && !r.dest)
2450 r.chain = "mangle_input";
2452 r.chain = "mangle_output";
2455 r.src.zone.dflags[r.target] = true;
2456 r.iifnames = null_if_empty(r.src.zone.match_devices);
2460 r.dest.zone.dflags[r.target] = true;
2461 r.oifnames = null_if_empty(r.dest.zone.match_devices);
2469 r.chain = `${r.dest ? "forward" : "input"}_${r.src.zone.name}`;
2471 r.chain = r.dest ? "forward" : "input";
2474 if (r.dest && !r.src) {
2476 r.chain = sprintf("output_%s", r.dest.zone.name);
2481 if (r.dest && !r.dest.any) {
2482 r.jump_chain = `${r.target}_to_${r.dest.zone.name}`;
2483 r.dest.zone.dflags[r.target] = true;
2485 else if (need_src_action_chain(r)) {
2486 r.jump_chain = `${r.target}_from_${r.src.zone.name}`;
2487 r.src.zone.sflags[r.target] = true;
2489 else if (r.target == "reject")
2490 r.jump_chain = "handle_reject";
2494 r[r.direction ? "oifnames" : "iifnames"] = [ r.device.device ];
2496 push(this.state.rules ||= [], r);
2499 for (let proto in rule.proto) {
2500 let sip, dip, sports, dports, itypes4, itypes6;
2501 let family = rule.family;
2503 switch (proto.name) {
2505 itypes4 = filter(rule.icmp_type || [], family_is_ipv4);
2506 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2511 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2516 sports = rule.src_port;
2517 dports = rule.dest_port;
2521 sip = subnets_split_af(rule.src_ip);
2522 dip = subnets_split_af(rule.dest_ip);
2524 family = infer_family(family, [
2527 dip, "destination IP",
2528 rule.src?.zone, "source zone",
2529 rule.dest?.zone, "destination zone",
2530 rule.helper, "helper match",
2531 rule.set_helper, "helper to set"
2534 if (type(family) == "string") {
2535 this.warn_section(data, `${family}, skipping`);
2539 let has_ipv4_specifics = (length(sip[0]) || length(dip[0]) || length(itypes4) || rule.dscp !== null);
2540 let has_ipv6_specifics = (length(sip[1]) || length(dip[1]) || length(itypes6) || rule.dscp !== null);
2542 /* if no family was configured, infer target family from IP addresses */
2543 if (family === null) {
2544 if (has_ipv4_specifics && !has_ipv6_specifics)
2546 else if (has_ipv6_specifics && !has_ipv4_specifics)
2552 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2553 if (!family && rule.target != "dscp" && !has_ipv4_specifics && !has_ipv6_specifics) {
2554 add_rule(0, proto, [], [], sports, dports, null, null, null, rule);
2557 /* we need to emit one or two AF specific rules */
2559 if (family == 0 || family == 4) {
2560 let icmp_types = filter(itypes4, i => (i.code_min == 0 && i.code_max == 0xFF));
2561 let icmp_codes = filter(itypes4, i => (i.code_min != 0 || i.code_max != 0xFF));
2563 for (let saddrs in subnets_group_by_masking(sip[0])) {
2564 for (let daddrs in subnets_group_by_masking(dip[0])) {
2565 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2566 add_rule(4, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2568 if (length(icmp_codes))
2569 add_rule(4, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2574 if (family == 0 || family == 6) {
2575 let icmp_types = filter(itypes6, i => (i.code_min == 0 && i.code_max == 0xFF));
2576 let icmp_codes = filter(itypes6, i => (i.code_min != 0 || i.code_max != 0xFF));
2578 for (let saddrs in subnets_group_by_masking(sip[1])) {
2579 for (let daddrs in subnets_group_by_masking(dip[1])) {
2580 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2581 add_rule(6, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2583 if (length(icmp_codes))
2584 add_rule(6, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2592 parse_redirect: function(data) {
2593 let redir = this.parse_options(data, {
2594 enabled: [ "bool", "1" ],
2596 name: [ "string", this.section_id(data[".name"]) ],
2597 _name: [ "string", null, DEPRECATED ],
2598 family: [ "family" ],
2600 src: [ "zone_ref" ],
2601 dest: [ "zone_ref" ],
2603 ipset: [ "setmatch" ],
2604 helper: [ "cthelper", null, NO_INVERT ],
2606 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2608 src_ip: [ "network" ],
2609 src_mac: [ "mac", null, PARSE_LIST ],
2610 src_port: [ "port" ],
2612 src_dip: [ "network" ],
2613 src_dport: [ "port" ],
2615 dest_ip: [ "network" ],
2616 dest_port: [ "port" ],
2618 extra: [ "string", null, UNSUPPORTED ],
2621 limit_burst: [ "int" ],
2623 utc_time: [ "bool" ],
2624 start_date: [ "date" ],
2625 stop_date: [ "date" ],
2626 start_time: [ "time" ],
2627 stop_time: [ "time" ],
2628 weekdays: [ "weekdays" ],
2629 monthdays: [ "monthdays", null, UNSUPPORTED ],
2633 reflection: [ "bool", "1" ],
2634 reflection_src: [ "reflection_source", "internal" ],
2636 reflection_zone: [ "zone_ref", null, PARSE_LIST ],
2638 counter: [ "bool", "1" ],
2641 target: [ "target", "dnat" ]
2644 if (redir === false) {
2645 this.warn_section(data, "skipped due to invalid options");
2648 else if (!redir.enabled) {
2649 this.warn_section(data, "is disabled, ignoring section");
2653 if (!(redir.target in ["dnat", "snat"])) {
2654 this.warn_section(data, "has invalid target specified, defaulting to dnat");
2655 redir.target = "dnat";
2658 switch (this.parse_bool(redir.log)) {
2660 redir.log = `${redir.name}: `;
2670 ipset = filter(this.state.ipsets, s => (s.name == redir.ipset.name))?.[0];
2673 this.warn_section(data, `references unknown set '${redir.ipset.name}'`);
2677 if (('inet_service' in ipset.types) && !ensure_tcpudp(redir.proto)) {
2678 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2683 let resolve_dest = (redir) => {
2684 for (let zone in this.state.zones) {
2685 for (let zone_addr in zone.related_subnets) {
2686 for (let dest_addr in redir.dest_ip.addrs) {
2687 if (dest_addr.family != zone_addr.family)
2690 let a = apply_mask(dest_addr.addr, zone_addr.mask);
2691 let b = apply_mask(zone_addr.addr, zone_addr.mask);
2709 if (redir.target == "dnat") {
2711 return this.warn_section(data, "has no source specified");
2712 else if (redir.src.any)
2713 return this.warn_section(data, "must not have source '*' for dnat target");
2714 else if (redir.dest_ip && redir.dest_ip.invert)
2715 return this.warn_section(data, "must not specify a negated 'dest_ip' value");
2716 else if (redir.dest_ip && length(filter(redir.dest_ip.addrs, a => a.bits == -1)))
2717 return this.warn_section(data, "must not use non-contiguous masks in 'dest_ip'");
2719 if (!redir.dest && redir.dest_ip && resolve_dest(redir))
2720 this.warn_section(data, `does not specify a destination, assuming '${redir.dest.zone.name}'`);
2722 if (!redir.dest_port)
2723 redir.dest_port = redir.src_dport;
2725 if (redir.reflection && redir.dest?.zone && redir.src.zone.masq) {
2726 redir.dest.zone.dflags.accept = true;
2727 redir.dest.zone.dflags.dnat = true;
2728 redir.dest.zone.dflags.snat = true;
2732 redir.src.zone.dflags.helper = true;
2734 redir.src.zone.dflags[redir.target] = true;
2738 return this.warn_section(data, "has no destination specified");
2739 else if (redir.dest.any)
2740 return this.warn_section(data, "must not have destination '*' for snat target");
2741 else if (!redir.src_dip)
2742 return this.warn_section(data, "has no 'src_dip' option specified");
2743 else if (redir.src_dip.invert)
2744 return this.warn_section(data, "must not specify a negated 'src_dip' value");
2745 else if (length(filter(redir.src_dip.addrs, a => a.bits == -1)))
2746 return this.warn_section(data, "must not use non-contiguous masks in 'src_dip'");
2747 else if (redir.src_mac)
2748 return this.warn_section(data, "must not use 'src_mac' option for snat target");
2749 else if (redir.helper)
2750 return this.warn_section(data, "must not use 'helper' option for snat target");
2752 redir.dest.zone.dflags[redir.target] = true;
2755 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, ipset, redir) => {
2761 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2762 has_ports: !!(sport || dport || rport),
2763 saddrs_pos: map(saddrs[0], this.cidr),
2764 saddrs_neg: map(saddrs[1], this.cidr),
2765 saddrs_masked: saddrs[2],
2766 daddrs_pos: map(daddrs[0], this.cidr),
2767 daddrs_neg: map(daddrs[1], this.cidr),
2768 daddrs_masked: daddrs[2],
2769 sports_pos: map(filter_pos(to_array(sport)), this.port),
2770 sports_neg: map(filter_neg(to_array(sport)), this.port),
2771 dports_pos: map(filter_pos(to_array(dport)), this.port),
2772 dports_neg: map(filter_neg(to_array(dport)), this.port),
2773 smacs_pos: map(filter_pos(redir.src_mac), m => m.mac),
2774 smacs_neg: map(filter_neg(redir.src_mac), m => m.mac),
2776 raddr: raddrs ? raddrs[0] : null,
2780 let set_types = map_setmatch(ipset, redir.ipset, proto.name);
2782 if (set_types !== set_types) {
2783 this.warn_section(data, "destination MAC address matching not supported");
2785 } else if (set_types) {
2786 r.ipset = { ...r.ipset, fields: set_types };
2791 r.chain = `dstnat_${r.src.zone.name}`;
2792 r.src.zone.dflags.dnat = true;
2795 r.target = "redirect";
2800 r.chain = `srcnat_${r.dest.zone.name}`;
2801 r.dest.zone.dflags.snat = true;
2805 push(this.state.redirects ||= [], r);
2808 let to_hostaddr = (a) => {
2809 let bits = (a.family == 4) ? 32 : 128;
2813 addr: apply_mask(a.addr, bits),
2818 for (let proto in redir.proto) {
2819 let sip, dip, rip, iip, eip, refip, sport, dport, rport;
2820 let family = redir.family;
2822 if (proto.name == "ipv6-icmp")
2825 switch (redir.target) {
2827 sip = subnets_split_af(redir.src_ip);
2828 dip = subnets_split_af(redir.src_dip);
2829 rip = subnets_split_af(redir.dest_ip);
2831 switch (proto.name) {
2834 sport = redir.src_port;
2835 dport = redir.src_dport;
2836 rport = redir.dest_port;
2843 sip = subnets_split_af(redir.src_ip);
2844 dip = subnets_split_af(redir.dest_ip);
2845 rip = subnets_split_af(redir.src_dip);
2847 switch (proto.name) {
2850 sport = redir.src_port;
2851 dport = redir.dest_port;
2852 rport = redir.src_dport;
2859 family = infer_family(family, [
2862 dip, "destination IP",
2864 redir.src?.zone, "source zone",
2865 redir.dest?.zone, "destination zone",
2866 redir.helper, "helper match"
2869 if (type(family) == "string") {
2870 this.warn_section(data, `${family}, skipping`);
2874 /* build reflection rules */
2875 if (redir.target == "dnat" && redir.reflection &&
2876 (length(rip[0]) || length(rip[1])) && redir.src?.zone && redir.dest?.zone) {
2878 name: `${redir.name} (reflection)`,
2880 helper: redir.helper,
2882 // XXX: this likely makes no sense for reflection rules
2883 //src_mac: redir.src_mac,
2886 limit_burst: redir.limit_burst,
2888 start_date: redir.start_date,
2889 stop_date: redir.stop_date,
2890 start_time: redir.start_time,
2891 stop_time: redir.stop_time,
2892 weekdays: redir.weekdays,
2897 let eaddrs = length(dip) ? dip : subnets_split_af({ addrs: map(redir.src.zone.related_subnets, to_hostaddr) });
2898 let rzones = length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
2900 for (let rzone in rzones) {
2901 if (!is_family(rzone, family)) {
2902 this.warn_section(data,
2903 `is restricted to IPv${family} but referenced reflection zone is IPv${rzone.family} only, skipping`);
2907 let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
2908 let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
2910 for (let i = 0; i <= 1; i++) {
2911 if (redir.src.zone[i ? "masq6" : "masq"] && length(rip[i])) {
2912 let snat_addr = refaddrs[i]?.[0];
2914 /* For internal reflection sources try to find a suitable candiate IP
2915 * among the reflection zone subnets which is within the same subnet
2916 * as the original DNAT destination. If we can't find any matching
2917 * one then simply take the first candidate. */
2918 if (redir.reflection_src == "internal") {
2919 for (let zone_addr in rzone.zone.related_subnets) {
2920 if (zone_addr.family != rip[i][0].family)
2923 let r = apply_mask(rip[i][0].addr, zone_addr.mask);
2924 let a = apply_mask(zone_addr.addr, zone_addr.mask);
2929 snat_addr = zone_addr;
2935 this.warn_section(data, `${redir.reflection_src || "external"} rewrite IP cannot be determined, disabling reflection`);
2937 else if (!length(iaddrs[i])) {
2938 this.warn_section(data, "internal address range cannot be determined, disabling reflection");
2940 else if (!length(eaddrs[i])) {
2941 this.warn_section(data, "external address range cannot be determined, disabling reflection");
2944 refredir.src = rzone;
2945 refredir.dest = null;
2946 refredir.target = "dnat";
2948 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2949 for (let daddrs in subnets_group_by_masking(eaddrs[i]))
2950 add_rule(i ? 6 : 4, proto, saddrs, daddrs, rip[i], sport, dport, rport, null, refredir);
2952 refredir.src = null;
2953 refredir.dest = rzone;
2954 refredir.target = "snat";
2956 for (let daddrs in subnets_group_by_masking(rip[i]))
2957 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2958 add_rule(i ? 6 : 4, proto, saddrs, daddrs, [ to_hostaddr(snat_addr) ], null, rport, null, null, refredir);
2965 if (length(rip[0]) > 1 || length(rip[1]) > 1)
2966 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
2968 let has_ip4_addr = length(sip[0]) || length(dip[0]) || length(rip[0]),
2969 has_ip6_addr = length(sip[1]) || length(dip[1]) || length(rip[1]),
2970 has_any_addr = has_ip4_addr || has_ip6_addr;
2972 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2973 if (!family && !has_any_addr) {
2974 /* for backwards compatibility, treat unspecified family as IPv4 unless user explicitly requested any (0) */
2978 add_rule(family, proto, [], [], null, sport, dport, rport, null, redir);
2981 /* we need to emit one or two AF specific rules */
2983 if ((!family || family == 4) && (!has_any_addr || has_ip4_addr)) {
2984 for (let saddrs in subnets_group_by_masking(sip[0]))
2985 for (let daddrs in subnets_group_by_masking(dip[0]))
2986 add_rule(4, proto, saddrs, daddrs, rip[0], sport, dport, rport, ipset, redir);
2989 if ((!family || family == 6) && (!has_any_addr || has_ip6_addr)) {
2990 for (let saddrs in subnets_group_by_masking(sip[1]))
2991 for (let daddrs in subnets_group_by_masking(dip[1]))
2992 add_rule(6, proto, saddrs, daddrs, rip[1], sport, dport, rport, ipset, redir);
2998 parse_nat: function(data) {
2999 let snat = this.parse_options(data, {
3000 enabled: [ "bool", "1" ],
3002 name: [ "string", this.section_id(data[".name"]) ],
3003 family: [ "family" ],
3005 src: [ "zone_ref" ],
3006 device: [ "string" ],
3008 ipset: [ "setmatch", null, UNSUPPORTED ],
3010 proto: [ "protocol", "all", PARSE_LIST | FLATTEN_LIST ],
3012 src_ip: [ "network" ],
3013 src_port: [ "port" ],
3015 snat_ip: [ "network", null, NO_INVERT ],
3016 snat_port: [ "port", null, NO_INVERT ],
3018 dest_ip: [ "network" ],
3019 dest_port: [ "port" ],
3021 extra: [ "string", null, UNSUPPORTED ],
3024 limit_burst: [ "int" ],
3026 connlimit_ports: [ "bool" ],
3028 utc_time: [ "bool" ],
3029 start_date: [ "date" ],
3030 stop_date: [ "date" ],
3031 start_time: [ "time" ],
3032 stop_time: [ "time" ],
3033 weekdays: [ "weekdays" ],
3034 monthdays: [ "monthdays", null, UNSUPPORTED ],
3038 counter: [ "bool", "1" ],
3041 target: [ "target", "masquerade" ]
3044 if (snat === false) {
3045 this.warn_section(data, "skipped due to invalid options");
3048 else if (!snat.enabled) {
3049 this.warn_section(data, "is disabled, ignoring section");
3053 if (!(snat.target in ["accept", "snat", "masquerade"])) {
3054 this.warn_section(data, "has invalid target specified, defaulting to masquerade");
3055 snat.target = "masquerade";
3058 if (snat.target == "snat" && !snat.snat_ip && !snat.snat_port) {
3059 this.warn_section(data, "needs either 'snat_ip' or 'snat_port' for target snat, ignoring section");
3062 else if (snat.target != "snat" && snat.snat_ip) {
3063 this.warn_section(data, "must not use 'snat_ip' for non-snat target, ignoring section");
3066 else if (snat.target != "snat" && snat.snat_port) {
3067 this.warn_section(data, "must not use 'snat_port' for non-snat target, ignoring section");
3071 if ((snat.snat_port || snat.src_port || snat.dest_port) && !ensure_tcpudp(snat.proto)) {
3072 this.warn_section(data, "specifies ports but no UDP/TCP protocol, ignoring section");
3076 if (snat.snat_ip && length(filter(snat.snat_ip.addrs, a => a.bits == -1 || a.invert))) {
3077 this.warn_section(data, "must not use inversion or non-contiguous masks in 'snat_ip', ignoring section");
3081 switch (this.parse_bool(snat.log)) {
3083 snat.log = `${snat.name}: `;
3090 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, snat) => {
3096 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
3097 has_ports: !!(sport || dport),
3098 saddrs_pos: map(saddrs[0], this.cidr),
3099 saddrs_neg: map(saddrs[1], this.cidr),
3100 saddrs_masked: saddrs[2],
3101 daddrs_pos: map(daddrs[0], this.cidr),
3102 daddrs_neg: map(daddrs[1], this.cidr),
3103 daddrs_masked: daddrs[2],
3104 sports_pos: map(filter_pos(to_array(sport)), this.port),
3105 sports_neg: map(filter_neg(to_array(sport)), this.port),
3106 dports_pos: map(filter_pos(to_array(dport)), this.port),
3107 dports_neg: map(filter_neg(to_array(dport)), this.port),
3109 raddr: raddrs ? raddrs[0] : null,
3112 chain: snat.src?.zone ? `srcnat_${snat.src.zone.name}` : "srcnat"
3115 push(this.state.redirects ||= [], n);
3118 for (let proto in snat.proto) {
3119 let sip, dip, rip, sport, dport, rport;
3120 let family = snat.family;
3122 sip = subnets_split_af(snat.src_ip);
3123 dip = subnets_split_af(snat.dest_ip);
3124 rip = subnets_split_af(snat.snat_ip);
3126 switch (proto.name) {
3129 sport = snat.src_port;
3130 dport = snat.dest_port;
3131 rport = snat.snat_port;
3135 if (length(rip[0]) > 1 || length(rip[1]) > 1)
3136 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
3138 family = infer_family(family, [
3140 dip, "destination IP",
3142 snat.src?.zone, "source zone"
3145 if (type(family) == "string") {
3146 this.warn_section(data, `${family}, skipping`);
3151 snat.src.zone.dflags.snat = true;
3153 /* if no family was configured, infer target family from IP addresses */
3154 if (family === null) {
3155 if ((length(sip[0]) || length(dip[0]) || length(rip[0])) && !length(sip[1]) && !length(dip[1]) && !length(rip[1]))
3157 else if ((length(sip[1]) || length(dip[1]) || length(rip[1])) && !length(sip[0]) && !length(dip[0]) && !length(rip[0]))
3160 family = 4; /* default to IPv4 only for backwards compatibility, unless an explict family any was configured */
3163 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
3164 if (!family && !length(sip[0]) && !length(sip[1]) && !length(dip[0]) && !length(dip[1]) && !length(rip[0]) && !length(rip[1])) {
3165 add_rule(0, proto, [], [], null, sport, dport, rport, snat);
3168 /* we need to emit one or two AF specific rules */
3170 if (family == 0 || family == 4)
3171 for (let saddr in subnets_group_by_masking(sip[0]))
3172 for (let daddr in subnets_group_by_masking(dip[0]))
3173 add_rule(4, proto, saddr, daddr, rip[0], sport, dport, rport, snat);
3175 if (family == 0 || family == 6)
3176 for (let saddr in subnets_group_by_masking(sip[1]))
3177 for (let daddr in subnets_group_by_masking(dip[1]))
3178 add_rule(6, proto, saddr, daddr, rip[1], sport, dport, rport, snat);
3183 parse_include: function(data) {
3184 let inc = this.parse_options(data, {
3185 enabled: [ "bool", "1" ],
3187 path: [ "string", null, REQUIRED ],
3188 type: [ "includetype", "script" ],
3190 fw4_compatible: [ "bool", data.path != "/etc/firewall.user" ],
3192 family: [ "family", null, UNSUPPORTED ],
3193 reload: [ "bool", null, UNSUPPORTED ],
3195 position: [ "includeposition" ],
3200 this.warn_section(data, "is disabled, ignoring section");
3204 if (inc.type == "script" && !inc.fw4_compatible) {
3205 this.warn_section(data, "is not marked as compatible with fw4, ignoring section");
3206 this.warn_section(data, "requires 'option fw4_compatible 1' to be considered compatible");
3210 for (let opt in [ "table", "chain", "position" ]) {
3211 if (inc.type != "nftables" && inc[opt]) {
3212 this.warn_section(data, `must not specify '${opt}' for non-nftables includes, ignoring section`);
3217 switch (inc.position ??= 'table-append') {
3218 case 'ruleset-prepend':
3219 case 'ruleset-append':
3220 case 'table-prepend':
3221 case 'table-append':
3223 this.warn_section(data, `specifies 'chain' which has no effect for position ${inc.position}`);
3228 case 'chain-prepend':
3229 case 'chain-append':
3231 this.warn_section(data, `must specify 'chain' for position ${inc.position}, ignoring section`);
3238 let path = fs.readlink(inc.path) ?? inc.path;
3240 if (!fs.access(path)) {
3241 this.warn_section(data, `specifies unreachable path '${path}', ignoring section`);
3246 this.warn(`Automatically including '${path}'`);
3248 push(this.state.includes ||= [], { ...inc, path });
3251 parse_ipset: function(data) {
3252 let ipset = this.parse_options(data, {
3253 enabled: [ "bool", "1" ],
3254 reload_set: [ "bool" ],
3255 counters: [ "bool" ],
3256 comment: [ "string" ],
3258 name: [ "string", null, REQUIRED ],
3259 family: [ "family", "4" ],
3261 storage: [ "string", null, UNSUPPORTED ],
3262 match: [ "ipsettype", null, PARSE_LIST ],
3264 iprange: [ "string", null, UNSUPPORTED ],
3265 portrange: [ "string", null, UNSUPPORTED ],
3267 netmask: [ "int", null, UNSUPPORTED ],
3269 hashsize: [ "int", null, UNSUPPORTED ],
3270 timeout: [ "int", "-1" ],
3272 external: [ "string", null, UNSUPPORTED ],
3274 entry: [ "string", null, PARSE_LIST ],
3275 loadfile: [ "string" ]
3278 if (ipset === false) {
3279 this.warn_section(data, "skipped due to invalid options");
3282 else if (!ipset.enabled) {
3283 this.warn_section(data, "is disabled, ignoring section");
3287 if (ipset.family == 0) {
3288 this.warn_section(data, "must not specify family 'any'");
3291 else if (!length(ipset.match)) {
3292 this.warn_section(data, "has no datatypes assigned");
3296 let dirs = map(ipset.match, m => m[0]),
3297 types = map(ipset.match, m => m[1]),
3300 if ("set" in types) {
3301 this.warn_section(data, "match type 'set' is not supported");
3305 if ("net" in types) {
3306 if (this.kernel < 0x05060000) {
3307 this.warn_section(data, "match type 'net' requires kernel 5.6 or later");
3319 types: map(types, (t) => {
3323 return (ipset.family == 4) ? 'ipv4_addr' : 'ipv6_addr';
3326 return 'ether_addr';
3329 return 'inet_service';
3338 push(s.flags ??= [], 'interval');
3341 push(s.flags ??= [], 'timeout');
3343 s.entries = filter(map(ipset.entry, (e) => {
3344 let v = this.parse_ipsetentry(e, s);
3347 this.warn_section(data, `ignoring invalid ipset entry '${e}'`);
3350 }), (e) => (e != null));
3352 push(this.state.ipsets ||= [], s);