3 let fs = require("fs");
4 let uci = require("uci");
5 let ubus = require("ubus");
7 let STATEFILE = "/var/run/fw4.state";
10 let FLATTEN_LIST = 0x02;
12 let UNSUPPORTED = 0x08;
15 let ipv4_icmptypes = {
16 "any": [ 0xFF, 0, 0xFF ],
17 "echo-reply": [ 0, 0, 0xFF ],
18 "pong": [ 0, 0, 0xFF ], /* Alias */
20 "destination-unreachable": [ 3, 0, 0xFF ],
21 "network-unreachable": [ 3, 0, 0 ],
22 "host-unreachable": [ 3, 1, 1 ],
23 "protocol-unreachable": [ 3, 2, 2 ],
24 "port-unreachable": [ 3, 3, 3 ],
25 "fragmentation-needed": [ 3, 4, 4 ],
26 "source-route-failed": [ 3, 5, 5 ],
27 "network-unknown": [ 3, 6, 6 ],
28 "host-unknown": [ 3, 7, 7 ],
29 "network-prohibited": [ 3, 9, 9 ],
30 "host-prohibited": [ 3, 10, 10 ],
31 "TOS-network-unreachable": [ 3, 11, 11 ],
32 "TOS-host-unreachable": [ 3, 12, 12 ],
33 "communication-prohibited": [ 3, 13, 13 ],
34 "host-precedence-violation": [ 3, 14, 14 ],
35 "precedence-cutoff": [ 3, 15, 15 ],
37 "source-quench": [ 4, 0, 0xFF ],
39 "redirect": [ 5, 0, 0xFF ],
40 "network-redirect": [ 5, 0, 0 ],
41 "host-redirect": [ 5, 1, 1 ],
42 "TOS-network-redirect": [ 5, 2, 2 ],
43 "TOS-host-redirect": [ 5, 3, 3 ],
45 "echo-request": [ 8, 0, 0xFF ],
46 "ping": [ 8, 0, 0xFF ], /* Alias */
48 "router-advertisement": [ 9, 0, 0xFF ],
50 "router-solicitation": [ 10, 0, 0xFF ],
52 "time-exceeded": [ 11, 0, 0xFF ],
53 "ttl-exceeded": [ 11, 0, 0xFF ], /* Alias */
54 "ttl-zero-during-transit": [ 11, 0, 0 ],
55 "ttl-zero-during-reassembly": [ 11, 1, 1 ],
57 "parameter-problem": [ 12, 0, 0xFF ],
58 "ip-header-bad": [ 12, 0, 0 ],
59 "required-option-missing": [ 12, 1, 1 ],
61 "timestamp-request": [ 13, 0, 0xFF ],
63 "timestamp-reply": [ 14, 0, 0xFF ],
65 "address-mask-request": [ 17, 0, 0xFF ],
67 "address-mask-reply": [ 18, 0, 0xFF ]
70 let ipv6_icmptypes = {
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 "router-solicitation": [ 133, 0, 0xFF ],
97 "router-advertisement": [ 134, 0, 0xFF ],
99 "neighbour-solicitation": [ 135, 0, 0xFF ],
100 "neighbor-solicitation": [ 135, 0, 0xFF ], /* Alias */
102 "neighbour-advertisement": [ 136, 0, 0xFF ],
103 "neighbor-advertisement": [ 136, 0, 0xFF ], /* Alias */
105 "redirect": [ 137, 0, 0xFF ]
133 function to_mask(bits, v6) {
136 if (bits < 0 || bits > (v6 ? 128 : 32))
139 for (let i = 0; i < (v6 ? 16 : 4); i++) {
140 let b = (bits < 8) ? bits : 8;
141 m[i] = (0xff << (8 - b)) & 0xff;
148 function to_bits(mask) {
149 let a = iptoarr(mask);
156 for (let i = 0, z = false; i < length(a); i++) {
159 while (!z && (a[i] & 0x80)) {
160 a[i] = (a[i] << 1) & 0xff;
171 function apply_mask(addr, mask) {
172 let a = iptoarr(addr);
177 if (type(mask) == "int") {
178 for (let i = 0; i < length(a); i++) {
179 let b = (mask < 8) ? mask : 8;
180 a[i] &= (0xff << (8 - b)) & 0xff;
185 let m = iptoarr(mask);
187 if (!m || length(a) != length(m))
190 for (let i = 0; i < length(a); i++)
197 function to_array(x) {
198 if (type(x) == "array")
204 if (type(x) == "object")
209 return (x == "") ? [] : split(x, /[ \t]+/);
212 function filter_pos(x) {
213 let rv = filter(x, e => !e.invert);
214 return length(rv) ? rv : null;
217 function filter_neg(x) {
218 let rv = filter(x, e => e.invert);
219 return length(rv) ? rv : null;
222 function subnets_split_af(x) {
225 for (let ag in to_array(x)) {
226 for (let a in filter(ag.addrs, a => (a.family == 4))) {
228 push(rv[0], { ...a, invert: ag.invert });
231 for (let a in filter(ag.addrs, a => (a.family == 6))) {
233 push(rv[1], { ...a, invert: ag.invert });
240 function ensure_tcpudp(x) {
241 if (length(filter(x, p => (p.name == "tcp" || p.name == "udp"))))
244 let rest = filter(x, p => !p.any),
245 any = filter(x, p => p.any);
247 if (length(any) && !length(rest)) {
249 push(x, { name: "tcp" }, { name: "udp" });
256 let is_family = (x, v) => (x.family == 0 || x.family == v);
257 let family_is_ipv4 = (x) => (x.family == 0 || x.family == 4);
258 let family_is_ipv6 = (x) => (x.family == 0 || x.family == 6);
260 function infer_family(f, objects) {
264 for (let i = 0; i < length(objects); i += 2) {
265 let objs = to_array(objects[i]),
266 desc = objects[i + 1];
268 for (let obj in objs) {
269 if (!obj || obj.family == 0 || obj.family == res)
279 ? sprintf('references IPv%d only %s but is restricted to IPv%d by %s', obj.family, desc, res, by)
280 : sprintf('is restricted to IPv%d but referenced %s is IPv%d only', res, desc, obj.family);
287 function map_setmatch(set, match, proto) {
288 if (!set || (('inet_service' in set.types) && proto != 'tcp' && proto != 'udp'))
293 for (let i, t in set.types) {
294 let dir = (((match.dir && match.dir[i]) || set.directions[i] || 'src') == 'src' ? 's' : 'd');
298 fields[i] = sprintf('ip %saddr', dir);
302 fields[i] = sprintf('ip6 %saddr', dir);
309 fields[i] = 'ether saddr';
313 fields[i] = sprintf('%s %sport', proto, dir);
323 read_kernel_version: function() {
324 let fd = fs.open("/proc/version", "r"),
328 let m = match(fd.read("line"), /^Linux version ([0-9]+)\.([0-9]+)\.([0-9]+)/);
330 v = m ? (+m[1] << 24) | (+m[2] << 16) | (+m[3] << 8) : 0;
337 read_state: function() {
338 let fd = fs.open(STATEFILE, "r");
343 state = json(fd.read("all"));
346 warn(sprintf("Unable to parse '%s': %s\n", STATEFILE, e));
355 read_ubus: function() {
358 rules = [], networks = {},
359 bus = ubus.connect();
362 ifaces = bus.call("network.interface", "dump");
363 services = bus.call("service", "get_data", { "type": "firewall" });
368 warn(sprintf("Unable to connect to ubus: %s\n", ubus.error()));
373 // Gather logical network information from ubus
376 if (type(ifaces) == "object" && type(ifaces.interface) == "array") {
377 for (let ifc in ifaces.interface) {
380 device: ifc.l3_device
383 if (type(ifc["ipv4-address"]) == "array") {
384 for (let addr in ifc["ipv4-address"]) {
385 net.ipaddrs = net.ipaddrs || [];
389 mask: to_mask(addr.mask, false),
395 if (type(ifc["ipv6-address"]) == "array") {
396 for (let addr in ifc["ipv6-address"]) {
397 net.ipaddrs = net.ipaddrs || [];
401 mask: to_mask(addr.mask, true),
407 if (type(ifc["ipv6-prefix-assignment"]) == "array") {
408 for (let addr in ifc["ipv6-prefix-assignment"]) {
409 if (addr["local-address"]) {
410 net.ipaddrs = net.ipaddrs || [];
413 addr: addr["local-address"].address,
414 mask: to_mask(addr["local-address"].mask, true),
415 bits: addr["local-address"].mask
421 if (type(ifc.data) == "object" && type(ifc.data.firewall) == "array") {
424 for (let rulespec in ifc.data.firewall) {
428 name: (rulespec.type != 'ipset') ? sprintf('ubus:%s[%s] %s %d', ifc.interface, ifc.proto, rulespec.type || 'rule', n) : rulespec.name,
429 device: rulespec.device || ifc.l3_device
436 networks[ifc.interface] = net;
442 // Gather firewall rule definitions from ubus services
445 if (type(services) == "object") {
446 for (let svcname, service in services) {
447 if (type(service) == "object" && type(service.firewall) == "array") {
450 for (let rulespec in services[svcname].firewall) {
454 name: (rulespec.type != 'ipset') ? sprintf('ubus:%s %s %d', svcname, rulespec.type || 'rule', n) : rulespec.name
461 for (let svcinst, instance in service) {
462 if (type(instance) == "object" && type(instance.firewall) == "array") {
465 for (let rulespec in instance.firewall) {
469 name: (rulespec.type != 'ipset') ? sprintf('ubus:%s[%s] %s %d', svcname, svcinst, rulespec.type || 'rule', n) : rulespec.name
485 load: function(use_statefile) {
488 this.state = use_statefile ? this.read_state() : null;
490 this.cursor = uci.cursor();
491 this.cursor.load("firewall");
492 this.cursor.load("/usr/share/firewall4/helpers");
495 this.state = this.read_ubus();
497 this.kernel = this.read_kernel_version();
501 // Read helper mapping
504 this.cursor.foreach("helpers", "helper", h => self.parse_helper(h));
508 // Read default policies
511 this.cursor.foreach("firewall", "defaults", d => self.parse_defaults(d));
513 if (!this.state.defaults)
514 this.parse_defaults({});
518 // Build list of ipsets
521 if (!this.state.ipsets) {
522 map(filter(this.state.ubus_rules, n => (n.type == "ipset")), s => self.parse_ipset(s));
523 this.cursor.foreach("firewall", "ipset", s => self.parse_ipset(s));
528 // Build list of logical zones
531 if (!this.state.zones)
532 this.cursor.foreach("firewall", "zone", z => self.parse_zone(z));
536 // Build list of forwardings
539 this.cursor.foreach("firewall", "forwarding", f => self.parse_forwarding(f));
543 // Build list of rules
546 map(filter(this.state.ubus_rules, r => (r.type == "rule")), r => self.parse_rule(r));
547 this.cursor.foreach("firewall", "rule", r => self.parse_rule(r));
551 // Build list of redirects
554 map(filter(this.state.ubus_rules, r => (r.type == "redirect")), r => self.parse_redirect(r));
555 this.cursor.foreach("firewall", "redirect", r => self.parse_redirect(r));
559 // Build list of snats
562 map(filter(this.state.ubus_rules, n => (n.type == "nat")), n => self.parse_nat(n));
563 this.cursor.foreach("firewall", "nat", n => self.parse_nat(n));
567 let fd = fs.open(STATEFILE, "w");
571 zones: this.state.zones,
572 ipsets: this.state.ipsets,
573 networks: this.state.networks,
574 ubus_rules: this.state.ubus_rules
580 warn("Unable to write '%s': %s\n", STATEFILE, fs.error());
585 warn: function(fmt, ...args) {
589 let msg = sprintf(fmt, ...args);
592 warn("\033[33m", msg, "\033[m\n");
594 warn("[!] ", msg, "\n");
597 get: function(sid, opt) {
598 return this.cursor.get("firewall", sid, opt);
601 get_all: function(sid) {
602 return this.cursor.get_all("firewall", sid);
605 parse_options: function(s, spec) {
608 for (let key, val in spec) {
609 let datatype = "parse_" + val[0],
612 parsefn = (flags & PARSE_LIST) ? "parse_list" : "parse_opt";
614 let res = this[parsefn](s, key, datatype, defval, flags);
619 if (type(res) == "object" && res.invert && (flags & NO_INVERT)) {
620 this.warn_section(s, "option '" + key + '" must not be negated');
625 if (flags & UNSUPPORTED)
626 this.warn_section(s, "option '" + key + "' is not supported by fw4");
633 if (index(opt, '.') != 0 && opt != 'type' && !exists(spec, opt)) {
634 this.warn_section(s, "specifies unknown option '" + opt + "'");
642 parse_subnet: function(subnet) {
643 let parts = split(subnet, "/");
646 switch (length(parts)) {
648 a = iptoarr(parts[0]);
649 m = iptoarr(parts[1]);
655 if (length(a) != length(m))
658 b = to_bits(parts[1]);
668 if (type(b) != "int")
671 m = to_mask(b, length(a) == 16);
675 family: (length(a) == 16) ? 6 : 4,
682 parts = split(parts[0], "-");
684 switch (length(parts)) {
686 a = iptoarr(parts[0]);
687 b = iptoarr(parts[1]);
689 if (a && b && length(a) == length(b)) {
691 family: (length(a) == 16) ? 6 : 4,
701 a = iptoarr(parts[0]);
705 family: (length(a) == 16) ? 6 : 4,
707 mask: to_mask(length(a) * 8, length(a) == 16),
712 n = this.state.networks[parts[0]];
715 return [ ...(n.ipaddrs || []) ];
722 parse_enum: function(val, choices) {
723 if (type(val) == "string") {
726 for (let i = 0; i < length(choices); i++)
727 if (substr(choices[i], 0, length(val)) == val)
734 section_id: function(sid) {
735 let s = this.get_all(sid);
740 if (s[".anonymous"]) {
743 this.cursor.foreach("firewall", s[".type"], function(ss) {
744 if (ss[".name"] == s[".name"])
750 return sprintf("@%s[%d]", s[".type"], c);
756 warn_section: function(s, msg) {
759 this.warn("Section %s (%s) %s", this.section_id(s[".name"]), s.name, msg);
761 this.warn("Section %s %s", this.section_id(s[".name"]), msg);
765 this.warn("ubus %s (%s) %s", s.type || "rule", s.name, msg);
767 this.warn("ubus %s %s", s.type || "rule", msg);
771 parse_policy: function(val) {
772 return this.parse_enum(val, [
779 parse_bool: function(val) {
780 if (val == "1" || val == "on" || val == "true" || val == "yes")
782 else if (val == "0" || val == "off" || val == "false" || val == "no")
788 parse_family: function(val) {
789 if (val == 'any' || val == 'all' || val == '*')
791 else if (val == 'inet' || index(val, '4') > -1)
793 else if (index(val, '6') > -1)
799 parse_zone_ref: function(val) {
804 return { any: true };
806 for (let zone in this.state.zones) {
807 if (zone.name == val) {
818 parse_device: function(val) {
819 let rv = this.parse_invert(val);
832 parse_direction: function(val) {
833 if (val == 'in' || val == 'ingress')
835 else if (val == 'out' || val == 'egress')
841 parse_setmatch: function(val) {
842 let rv = this.parse_invert(val);
847 rv.val = trim(replace(rv.val, /^[^ \t]+/, function(m) {
852 let dir = split(rv.val, /[ \t,]/);
854 for (let i = 0; i < 3 && i < length(dir); i++) {
855 if (dir[i] == "dst" || dir[i] == "dest") {
856 rv.dir = rv.dir || [];
859 else if (dir[i] == "src") {
860 rv.dir = rv.dir || [];
865 return length(rv.name) ? rv : null;
868 parse_cthelper: function(val) {
869 let rv = this.parse_invert(val);
874 let helper = filter(this.state.helpers, h => (h.name == rv.val))[0];
876 return helper ? { ...rv, ...helper } : null;
879 parse_protocol: function(val) {
880 let p = this.parse_invert(val);
902 p.name = 'ipv6-icmp';
907 { invert: p.invert, name: 'tcp' },
908 { invert: p.invert, name: 'udp' }
923 return (p.any || length(p.name)) ? p : null;
926 parse_mac: function(val) {
927 let mac = this.parse_invert(val);
928 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;
933 mac.mac = sprintf('%02x:%02x:%02x:%02x:%02x:%02x',
934 hex(m[1]), hex(m[2]), hex(m[3]),
935 hex(m[4]), hex(m[5]), hex(m[6]));
940 parse_port: function(val) {
941 let port = this.parse_invert(val);
942 let m = port ? match(port.val, /^([0-9]{1,5})([-:]([0-9]{1,5}))?$/i) : null;
948 let min_port = +m[1];
949 let max_port = +m[3];
951 if (min_port > max_port ||
952 min_port < 0 || max_port < 0 ||
953 min_port > 65535 || max_port > 65535)
962 if (pn != pn || pn < 0 || pn > 65535)
972 parse_network: function(val) {
973 let rv = this.parse_invert(val);
978 let nets = this.parse_subnet(rv.val);
984 rv.addrs = [ ...nets ];
989 parse_icmptype: function(val) {
992 if (exists(ipv4_icmptypes, val)) {
995 rv.type = ipv4_icmptypes[val][0];
996 rv.code_min = ipv4_icmptypes[val][1];
997 rv.code_max = ipv4_icmptypes[val][2];
1000 if (exists(ipv6_icmptypes, val)) {
1001 rv.family = rv.family ? 0 : 6;
1003 rv.type6 = ipv6_icmptypes[val][0];
1004 rv.code6_min = ipv6_icmptypes[val][1];
1005 rv.code6_max = ipv6_icmptypes[val][2];
1008 if (!exists(rv, "family")) {
1009 let m = match(val, /^([0-9]+)(\/([0-9]+))?$/);
1016 rv.code_min = +m[3];
1017 rv.code_max = rv.code_min;
1025 if (rv.type > 0xFF || rv.code_min > 0xFF || rv.code_max > 0xFF)
1031 rv.code6_min = rv.code_min;
1032 rv.code6_max = rv.code_max;
1038 parse_invert: function(val) {
1042 let rv = { invert: false };
1044 rv.val = trim(replace(val, /^[ \t]*!/, () => (rv.invert = true, '')));
1046 return length(rv.val) ? rv : null;
1049 parse_limit: function(val) {
1050 let rv = this.parse_invert(val);
1051 let m = rv ? match(rv.val, /^([0-9]+)(\/([a-z]+))?$/) : null;
1057 let u = m[3] ? this.parse_enum(m[3], [ "second", "minute", "hour", "day" ]) : "second";
1068 parse_int: function(val) {
1071 return (n == n) ? n : null;
1074 parse_date: function(val) {
1075 let m = match(val, /^([0-9-]+)T([0-9:]+)$/);
1076 let d = m ? match(m[1], /^([0-9]{1,4})(-([0-9]{1,2})(-([0-9]{1,2}))?)?$/) : null;
1077 let t = this.parse_time(m[2]);
1082 if (d == null || d[1] < 1970 || d[1] > 2038 || d[3] < 1 || d[3] > 12 || d[5] < 1 || d[5] > 31)
1092 hour: t ? +t[1] : 0,
1098 parse_time: function(val) {
1099 let t = match(val, /^([0-9]{1,2})(:([0-9]{1,2})(:([0-9]{1,2}))?)?$/);
1101 if (t == null || t[1] > 23 || t[3] > 59 || t[5] > 59)
1111 parse_weekdays: function(val) {
1112 let rv = this.parse_invert(val);
1117 for (let day in to_array(rv.val)) {
1118 day = this.parse_enum(day, [
1131 rv.days = rv.days || {};
1132 rv.days[day] = true;
1135 rv.days = keys(rv.days);
1137 return rv.days ? rv : null;
1140 parse_monthdays: function(val) {
1141 let rv = this.parse_invert(val);
1146 for (let day in to_array(rv.val)) {
1149 if (day < 1 || day > 31)
1152 rv.days = rv.days || [];
1153 rv.days[day] = true;
1156 return rv.days ? rv : null;
1159 parse_mark: function(val) {
1160 let rv = this.parse_invert(val);
1161 let m = rv ? match(rv.val, /^(0?x?[0-9a-f]+)(\/(0?x?[0-9a-f]+))?$/i) : null;
1168 if (n != n || n > 0xFFFFFFFF)
1172 rv.mask = 0xFFFFFFFF;
1177 if (n != n || n > 0xFFFFFFFF)
1186 parse_dscp: function(val) {
1187 let rv = this.parse_invert(val);
1192 rv.val = uc(rv.val);
1194 if (exists(dscp_classes, rv.val)) {
1195 rv.dscp = dscp_classes[rv.val];
1200 if (n != n || n < 0 || n > 0x3F)
1209 parse_target: function(val) {
1210 return this.parse_enum(val, [
1227 parse_reject_code: function(val) {
1228 return this.parse_enum(val, [
1237 parse_reflection_source: function(val) {
1238 return this.parse_enum(val, [
1244 parse_ipsettype: function(val) {
1245 let m = match(val, /^(src|dst|dest)_(.+)$/);
1246 let t = this.parse_enum(m ? m[2] : val, [
1254 return t ? [ (!m || m[1] == 'src') ? 'src' : 'dst', t ] : null;
1257 parse_ipsetentry: function(val, set) {
1258 let values = split(val, /[ \t]+/);
1260 if (length(values) != length(set.types))
1266 for (let i, t in set.types) {
1269 ip = iptoarr(values[i]);
1271 if (length(ip) != 4)
1274 rv[i] = arrtoip(ip);
1278 ip = iptoarr(values[i]);
1280 if (length(ip) != 16)
1283 rv[i] = arrtoip(ip);
1287 mac = this.parse_mac(values[i]);
1289 if (!mac || mac.invert)
1295 case 'inet_service':
1296 port = this.parse_port(values[i]);
1298 if (!port || port.invert || port.min != port.max)
1309 return length(rv) ? rv : null;
1312 parse_string: function(val) {
1316 parse_opt: function(s, opt, fn, defval, flags) {
1320 if (flags & REQUIRED) {
1321 this.warn_section(s, "option '" + opt + "' is mandatory but not set");
1328 if (type(val) == "array") {
1329 this.warn_section(s, "option '" + opt + "' must not be a list");
1332 else if (val == null) {
1336 let res = this[fn](val);
1339 this.warn_section(s, "option '" + opt + "' specifies invalid value '" + val + "'");
1346 parse_list: function(s, opt, fn, defval, flags) {
1351 if (flags & REQUIRED) {
1352 this.warn_section(s, "option '" + opt + "' is mandatory but not set");
1359 for (val in to_array(val)) {
1360 let res = this[fn](val);
1363 this.warn_section(s, "option '" + opt + "' specifies invalid value '" + val + "'");
1367 if (flags & FLATTEN_LIST)
1368 push(rv, ...to_array(res));
1373 return length(rv) ? rv : null;
1376 quote: function(s, force) {
1377 if (force === true || !match(s, /^([0-9A-Fa-f:.\/-]+)( \. [0-9A-Fa-f:.\/-]+)*$/))
1378 return sprintf('"%s"', replace(s + "", /(["\\])/g, '\\$1'));
1385 return sprintf("%s-%s", a.addr, a.addr2);
1387 if ((a.family == 4 && a.bits == 32) ||
1388 (a.family == 6 && a.bits == 128))
1391 return sprintf("%s/%d", apply_mask(a.addr, a.bits), a.bits);
1396 ? sprintf("%s-%s", a.addr, a.addr2)
1397 : apply_mask(a.addr, a.bits);
1402 return sprintf('%d', p.min);
1404 return sprintf('%d-%d', p.min, p.max);
1407 set: function(v, force) {
1410 v = filter(to_array(v), item => !seen[item]++);
1412 if (force || length(v) != 1)
1413 return sprintf('{ %s }', join(', ', map(v, this.quote)));
1415 return this.quote(v[0]);
1418 concat: function(v) {
1419 return join(' . ', to_array(v));
1422 ipproto: function(family) {
1432 nfproto: function(family, human_readable) {
1435 return human_readable ? "IPv4" : "ipv4";
1438 return human_readable ? "IPv6" : "ipv6";
1441 return human_readable ? "IPv4/IPv6" : null;
1445 datetime: function(stamp) {
1446 return sprintf('"%04d-%02d-%02d %02d:%02d:%02d"',
1447 stamp.year, stamp.month, stamp.day,
1448 stamp.hour, stamp.min, stamp.sec);
1451 date: function(stamp) {
1452 return sprintf('"%04d-%02d-%02d"', stamp.year, stamp.month, stamp.day);
1455 time: function(stamp) {
1456 return sprintf('"%02d:%02d:%02d"', stamp.hour, stamp.min, stamp.sec);
1460 return sprintf('0x%x', n);
1463 is_loopback_dev: function(dev) {
1464 let fd = fs.open(sprintf("/sys/class/net/%s/flags", dev), "r");
1469 let flags = +fd.read("line");
1473 return !!(flags & 0x8);
1476 is_loopback_addr: function(addr) {
1477 return (index(addr, "127.") == 0 || addr == "::1" || addr == "::1/128");
1480 filter_loopback_devs: function(devs, invert) {
1482 return filter(devs, d => (self.is_loopback_dev(d) == invert));
1485 filter_loopback_addrs: function(addrs, invert) {
1487 return filter(addrs, a => (self.is_loopback_addr(a) == invert));
1491 input_policy: function(reject_as_drop) {
1492 return (!reject_as_drop || this.state.defaults.input != 'reject') ? this.state.defaults.input : 'drop';
1495 output_policy: function(reject_as_drop) {
1496 return (!reject_as_drop || this.state.defaults.output != 'reject') ? this.state.defaults.output : 'drop';
1499 forward_policy: function(reject_as_drop) {
1500 return (!reject_as_drop || this.state.defaults.forward != 'reject') ? this.state.defaults.forward : 'drop';
1503 default_option: function(flag) {
1504 return this.state.defaults[flag];
1507 helpers: function() {
1508 return this.state.helpers;
1512 return this.state.zones;
1515 rules: function(chain) {
1516 return filter(this.state.rules, r => (r.chain == chain));
1519 redirects: function(chain) {
1520 return filter(this.state.redirects, r => (r.chain == chain));
1523 ipsets: function() {
1524 return this.state.ipsets;
1527 parse_setfile: function(set, cb) {
1528 let fd = fs.open(set.loadfile, "r");
1531 warn(sprintf("Unable to load file '%s' for set '%s': %s\n",
1532 set.loadfile, set.name, fs.error()));
1536 let line = null, count = 0;
1538 while ((line = fd.read("line")) !== "") {
1541 if (length(line) == 0 || ord(line) == 35)
1544 let v = this.parse_ipsetentry(line, set);
1547 this.warn("Skipping invalid entry '%s' in file '%s' for set '%s'",
1548 line, set.loadfile, set.name);
1562 print_setentries: function(set) {
1564 let printer = (entry) => {
1566 print("\t\telements = {\n");
1570 print("\t\t\t", join(" . ", entry), ",\n");
1573 map(set.entries, printer);
1576 this.parse_setfile(set, printer);
1582 parse_helper: function(data) {
1583 let helper = this.parse_options(data, {
1584 name: [ "string", null, REQUIRED ],
1585 description: [ "string" ],
1586 module: [ "string" ],
1587 family: [ "family" ],
1588 proto: [ "protocol", null, PARSE_LIST | FLATTEN_LIST | NO_INVERT ],
1589 port: [ "port", null, NO_INVERT ]
1592 if (helper === false) {
1593 this.warn("Helper definition '%s' skipped due to invalid options", data.name || data['.name']);
1596 else if (helper.proto.any) {
1597 this.warn("Helper definition '%s' must not specify wildcard protocol", data.name || data['.name']);
1600 else if (length(helper.proto) > 1) {
1601 this.warn("Helper definition '%s' must not specify multiple protocols", data.name || data['.name']);
1605 helper.available = ((fs.stat("/sys/module/" + helper.module) || {}).type == "directory");
1607 this.state.helpers = this.state.helpers || [];
1608 push(this.state.helpers, helper);
1611 parse_defaults: function(data) {
1612 if (this.state.defaults) {
1613 this.warn_section(data, ": ignoring duplicate defaults section");
1617 let defs = this.parse_options(data, {
1618 input: [ "policy", "drop" ],
1619 output: [ "policy", "drop" ],
1620 forward: [ "policy", "drop" ],
1622 drop_invalid: [ "bool" ],
1623 tcp_reject_code: [ "reject_code", "tcp-reset" ],
1624 any_reject_code: [ "reject_code", "port-unreachable" ],
1626 syn_flood: [ "bool" ],
1627 synflood_protect: [ "bool" ],
1628 synflood_rate: [ "limit", "25/second" ],
1629 synflood_burst: [ "int", "50" ],
1631 tcp_syncookies: [ "bool", "1" ],
1633 tcp_window_scaling: [ "bool", "1" ],
1635 accept_redirects: [ "bool" ],
1636 accept_source_route: [ "bool" ],
1638 auto_helper: [ "bool", "1" ],
1639 custom_chains: [ "bool", null, UNSUPPORTED ],
1640 disable_ipv6: [ "bool", null, UNSUPPORTED ],
1641 flow_offloading: [ "bool", "0" ],
1642 flow_offloading_hw: [ "bool", "0" ]
1645 if (defs === false) {
1646 this.warn_section(data, "skipped due to invalid options");
1650 if (defs.synflood_protect === null)
1651 defs.synflood_protect = defs.syn_flood;
1653 delete defs.syn_flood;
1655 this.state.defaults = defs;
1658 parse_zone: function(data) {
1659 let zone = this.parse_options(data, {
1660 enabled: [ "bool", "1" ],
1662 name: [ "string", null, REQUIRED ],
1663 family: [ "family" ],
1665 network: [ "device", null, PARSE_LIST ],
1666 device: [ "device", null, PARSE_LIST ],
1667 subnet: [ "network", null, PARSE_LIST ],
1669 input: [ "policy", this.state.defaults ? this.state.defaults.input : "drop" ],
1670 output: [ "policy", this.state.defaults ? this.state.defaults.output : "drop" ],
1671 forward: [ "policy", this.state.defaults ? this.state.defaults.forward : "drop" ],
1674 masq_allow_invalid: [ "bool" ],
1675 masq_src: [ "network", null, PARSE_LIST ],
1676 masq_dest: [ "network", null, PARSE_LIST ],
1678 extra: [ "string", null, UNSUPPORTED ],
1679 extra_src: [ "string", null, UNSUPPORTED ],
1680 extra_dest: [ "string", null, UNSUPPORTED ],
1682 mtu_fix: [ "bool" ],
1683 custom_chains: [ "bool", null, UNSUPPORTED ],
1686 log_limit: [ "limit", null, UNSUPPORTED ],
1688 auto_helper: [ "bool", "1" ],
1689 helper: [ "cthelper", null, PARSE_LIST ],
1691 counter: [ "bool", "1" ]
1694 if (zone === false) {
1695 this.warn_section(data, "skipped due to invalid options");
1698 else if (!zone.enabled) {
1699 this.warn_section(data, "is disabled, ignoring section");
1702 else if (zone.helper && !zone.helper.available) {
1703 this.warn_section(data, "uses unavailable ct helper '" + zone.helper.name + "', ignoring section");
1707 if (zone.mtu_fix && this.kernel < 0x040a0000) {
1708 this.warn_section(data, "option 'mtu_fix' requires kernel 4.10 or later");
1712 if (this.state.defaults && this.state.defaults.auto_helper === false)
1713 zone.auto_helper = false;
1715 let match_devices = [];
1716 let related_subnets = [];
1717 let match_subnets, masq_src_subnets, masq_dest_subnets;
1719 for (let e in to_array(zone.network)) {
1720 if (exists(this.state.networks, e.device)) {
1721 let net = this.state.networks[e.device];
1724 push(match_devices, {
1730 push(related_subnets, ...(net.ipaddrs || []));
1734 push(match_devices, ...to_array(zone.device));
1736 match_subnets = subnets_split_af(zone.subnet);
1737 masq_src_subnets = subnets_split_af(zone.masq_src);
1738 masq_dest_subnets = subnets_split_af(zone.masq_dest);
1740 push(related_subnets, ...(match_subnets[0] || []), ...(match_subnets[1] || []));
1742 let match_rules = [];
1744 let add_rule = (family, devices, subnets, zone) => {
1749 r.devices_pos = map(filter_pos(devices), d => d.device);
1750 r.devices_neg = map(filter_neg(devices), d => d.device);
1752 r.subnets_pos = map(filter_pos(subnets), this.cidr);
1753 r.subnets_neg = map(filter_neg(subnets), this.cidr);
1755 push(match_rules, r);
1758 let family = infer_family(zone.family, [
1759 zone.helper, "ct helper"
1762 // check if there's no AF specific bits, in this case we can do AF agnostic matching
1763 if (!family && length(match_devices) && !length(match_subnets[0]) && !length(match_subnets[1])) {
1764 add_rule(0, match_devices, null, zone);
1767 // we need to emit one or two AF specific rules
1769 if (family_is_ipv4(zone) && (length(match_devices) || length(match_subnets[0])))
1770 add_rule(4, match_devices, match_subnets[0], zone);
1772 if (family_is_ipv6(zone) && (length(match_devices) || length(match_subnets[1])))
1773 add_rule(6, match_devices, match_subnets[1], zone);
1776 zone.match_rules = match_rules;
1778 if (masq_src_subnets[0]) {
1779 zone.masq4_src_pos = map(filter_pos(masq_src_subnets[0]), this.cidr);
1780 zone.masq4_src_neg = map(filter_neg(masq_src_subnets[0]), this.cidr);
1783 if (masq_src_subnets[1]) {
1784 zone.masq6_src_pos = map(filter_pos(masq_src_subnets[1]), this.cidr);
1785 zone.masq6_src_neg = map(filter_neg(masq_src_subnets[1]), this.cidr);
1788 if (masq_dest_subnets[0]) {
1789 zone.masq4_dest_pos = map(filter_pos(masq_dest_subnets[0]), this.cidr);
1790 zone.masq4_dest_neg = map(filter_neg(masq_dest_subnets[0]), this.cidr);
1793 if (masq_dest_subnets[1]) {
1794 zone.masq6_dest_pos = map(filter_pos(masq_dest_subnets[1]), this.cidr);
1795 zone.masq6_dest_neg = map(filter_neg(masq_dest_subnets[1]), this.cidr);
1799 zone.sflags[zone.input] = true;
1802 zone.dflags[zone.output] = true;
1803 zone.dflags[zone.forward] = true;
1805 zone.match_devices = map(filter(match_devices, d => !d.invert), d => d.device);
1806 zone.match_subnets = map(filter(related_subnets, s => !s.invert), this.cidr);
1808 zone.related_subnets = related_subnets;
1810 if (zone.masq || zone.masq6)
1811 zone.dflags.snat = true;
1813 if ((zone.auto_helper && !(zone.masq || zone.masq6)) || length(zone.helper)) {
1814 zone.dflags.helper = true;
1816 for (let helper in (length(zone.helper) ? zone.helper : this.state.helpers)) {
1817 if (!helper.available)
1820 for (let proto in helper.proto) {
1821 this.state.rules = this.state.rules || [];
1822 push(this.state.rules, {
1823 chain: "helper_" + zone.name,
1824 family: helper.family,
1825 name: helper.description || helper.name,
1828 dports_pos: [ this.port(helper.port) ],
1836 this.state.zones = this.state.zones || [];
1837 push(this.state.zones, zone);
1840 parse_forwarding: function(data) {
1841 let fwd = this.parse_options(data, {
1842 enabled: [ "bool", "1" ],
1845 family: [ "family" ],
1847 src: [ "zone_ref", null, REQUIRED ],
1848 dest: [ "zone_ref", null, REQUIRED ]
1851 if (fwd === false) {
1852 this.warn_section(data, "skipped due to invalid options");
1855 else if (!fwd.enabled) {
1856 this.warn_section(data, "is disabled, ignoring section");
1860 let add_rule = (family, fwd) => {
1865 proto: { any: true }
1868 f.name = fwd.name || sprintf("Accept %s to %s forwarding",
1869 fwd.src.any ? "any" : fwd.src.zone.name,
1870 fwd.dest.any ? "any" : fwd.dest.zone.name);
1872 f.chain = fwd.src.any ? "forward" : sprintf("forward_%s", fwd.src.zone.name);
1875 f.target = "accept";
1877 f.jump_chain = sprintf("accept_to_%s", fwd.dest.zone.name);
1879 this.state.rules = this.state.rules || [];
1880 push(this.state.rules, f);
1884 let family = fwd.family;
1886 /* inherit family restrictions from related zones */
1887 if (family === 0 || family === null) {
1888 let f1 = fwd.src.zone ? fwd.src.zone.family : 0;
1889 let f2 = fwd.dest.zone ? fwd.dest.zone.family : 0;
1891 if (f1 != 0 && f2 != 0 && f1 != f2) {
1892 this.warn_section(data,
1893 sprintf("references src %s restricted to %s and dest restricted to %s, ignoring forwarding",
1894 fwd.src.zone.name, this.nfproto(f1, true),
1895 fwd.dest.zone.name, this.nfproto(f2, true)));
1900 this.warn_section(data,
1901 sprintf("inheriting %s restriction from src %s",
1902 this.nfproto(f1, true), fwd.src.zone.name));
1907 this.warn_section(data,
1908 sprintf("inheriting %s restriction from dest %s",
1909 this.nfproto(f2, true), fwd.dest.zone.name));
1915 add_rule(family, fwd);
1918 fwd.dest.zone.dflags.accept = true;
1921 parse_rule: function(data) {
1922 let rule = this.parse_options(data, {
1923 enabled: [ "bool", "1" ],
1925 name: [ "string", this.section_id(data[".name"]) ],
1926 family: [ "family" ],
1928 src: [ "zone_ref" ],
1929 dest: [ "zone_ref" ],
1931 device: [ "device" ],
1932 direction: [ "direction" ],
1934 ipset: [ "setmatch" ],
1935 helper: [ "cthelper" ],
1936 set_helper: [ "cthelper", null, NO_INVERT ],
1938 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
1940 src_ip: [ "network", null, PARSE_LIST ],
1941 src_mac: [ "mac", null, PARSE_LIST ],
1942 src_port: [ "port", null, PARSE_LIST ],
1944 dest_ip: [ "network", null, PARSE_LIST ],
1945 dest_port: [ "port", null, PARSE_LIST ],
1947 icmp_type: [ "icmptype", null, PARSE_LIST ],
1948 extra: [ "string", null, UNSUPPORTED ],
1951 limit_burst: [ "int" ],
1953 utc_time: [ "bool" ],
1954 start_date: [ "date" ],
1955 stop_date: [ "date" ],
1956 start_time: [ "time" ],
1957 stop_time: [ "time" ],
1958 weekdays: [ "weekdays" ],
1959 monthdays: [ "monthdays", null, UNSUPPORTED ],
1962 set_mark: [ "mark", null, NO_INVERT ],
1963 set_xmark: [ "mark", null, NO_INVERT ],
1966 set_dscp: [ "dscp", null, NO_INVERT ],
1968 counter: [ "bool", "1" ],
1970 target: [ "target" ]
1973 if (rule === false) {
1974 this.warn_section(data, "skipped due to invalid options");
1977 else if (!rule.enabled) {
1978 this.warn_section(data, "is disabled, ignoring section");
1982 if (rule.target in ["helper", "notrack"] && (!rule.src || !rule.src.zone)) {
1983 this.warn_section(data, "must specify a source zone for target '" + rule.target + "'");
1986 else if (rule.target in ["dscp", "mark"] && rule.dest) {
1987 this.warn_section(data, "must not specify option 'dest' for target '" + rule.target + "'");
1990 else if (rule.target == "dscp" && !rule.set_dscp) {
1991 this.warn_section(data, "must specify option 'set_dscp' for target 'dscp'");
1994 else if (rule.target == "mark" && !rule.set_mark && !rule.set_xmark) {
1995 this.warn_section(data, "must specify option 'set_mark' or 'set_xmark' for target 'mark'");
1998 else if (rule.target == "helper" && !rule.set_helper) {
1999 this.warn_section(data, "must specify option 'set_helper' for target 'helper'");
2006 ipset = filter(this.state.ipsets, s => (s.name == rule.ipset.name))[0];
2009 this.warn_section(data, "references unknown set '" + rule.ipset.name + "'");
2013 if (('inet_service' in ipset.types) && !ensure_tcpudp(rule.proto)) {
2014 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2019 let need_src_action_chain = (rule) => (rule.src && rule.src.zone && rule.src.zone.log && rule.target != "accept");
2021 let add_rule = (family, proto, saddrs, daddrs, sports, dports, icmptypes, icmpcodes, ipset, rule) => {
2027 has_addrs: !!(length(saddrs) || length(daddrs)),
2028 has_ports: !!(length(sports) || length(dports)),
2029 saddrs_pos: map(filter_pos(saddrs), this.cidr),
2030 saddrs_neg: map(filter_neg(saddrs), this.cidr),
2031 daddrs_pos: map(filter_pos(daddrs), this.cidr),
2032 daddrs_neg: map(filter_neg(daddrs), this.cidr),
2033 sports_pos: map(filter_pos(sports), this.port),
2034 sports_neg: map(filter_neg(sports), this.port),
2035 dports_pos: map(filter_pos(dports), this.port),
2036 dports_neg: map(filter_neg(dports), this.port),
2037 smacs_pos: map(filter_pos(rule.src_mac), m => m.mac),
2038 smacs_neg: map(filter_neg(rule.src_mac), m => m.mac),
2039 icmp_types: map(icmptypes, i => (family == 4 ? i.type : i.type6)),
2040 icmp_codes: map(icmpcodes, ic => sprintf('%d . %d', (family == 4) ? ic.type : ic.type6, (family == 4) ? ic.code_min : ic.code6_min))
2043 if (!length(r.icmp_types))
2044 delete r.icmp_types;
2046 if (!length(r.icmp_codes))
2047 delete r.icmp_codes;
2051 invert: r.set_mark.invert,
2052 mark: r.set_mark.mark,
2053 mask: r.set_mark.mark | r.set_mark.mask
2059 let set_types = map_setmatch(ipset, rule.ipset, proto.name);
2061 if (set_types !== set_types) {
2062 this.warn_section(data, "destination MAC address matching not supported");
2064 } else if (set_types) {
2065 r.ipset = { ...r.ipset, fields: set_types };
2068 if (r.target == "notrack") {
2069 r.chain = sprintf("notrack_%s", r.src.zone.name);
2070 r.src.zone.dflags.notrack = true;
2072 else if (r.target == "helper") {
2073 r.chain = sprintf("helper_%s", r.src.zone.name);
2074 r.src.zone.dflags.helper = true;
2076 else if (r.target == "mark" || r.target == "dscp") {
2078 r.chain = "mangle_prerouting";
2079 r.src.zone.dflags[r.target] = true;
2082 r.chain = "mangle_output";
2090 r.chain = sprintf("%s_%s", r.dest ? "forward" : "input", r.src.zone.name);
2092 r.chain = r.dest ? "forward" : "input";
2095 if (r.dest && !r.src) {
2097 r.chain = sprintf("output_%s", r.dest.zone.name);
2102 if (r.dest && !r.dest.any) {
2103 r.jump_chain = sprintf("%s_to_%s", r.target, r.dest.zone.name);
2104 r.dest.zone.dflags[r.target] = true;
2106 else if (need_src_action_chain(r)) {
2107 r.jump_chain = sprintf("%s_from_%s", r.target, r.src.zone.name);
2108 r.src.zone.dflags[r.target] = true;
2110 else if (r.target == "reject")
2111 r.jump_chain = "handle_reject";
2114 this.state.rules = this.state.rules || [];
2115 push(this.state.rules, r);
2118 for (let proto in rule.proto) {
2119 let sip, dip, sports, dports, itypes4, itypes6;
2120 let family = rule.family;
2122 switch (proto.name) {
2124 itypes4 = filter(rule.icmp_type || [], family_is_ipv4);
2125 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2130 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2135 sports = rule.src_port;
2136 dports = rule.dest_port;
2140 family = infer_family(family, [
2142 rule.src, "source zone",
2143 rule.dest, "destination zone",
2144 rule.helper, "helper match",
2145 rule.set_helper, "helper to set"
2148 if (type(family) == "string") {
2149 this.warn_section(data, family + ", skipping");
2153 sip = subnets_split_af(rule.src_ip);
2154 dip = subnets_split_af(rule.dest_ip);
2156 let has_ipv4_specifics = (length(sip[0]) || length(dip[0]) || length(itypes4));
2157 let has_ipv6_specifics = (length(sip[1]) || length(dip[1]) || length(itypes6));
2159 /* if no family was configured, infer target family from IP addresses */
2160 if (family === null) {
2161 if (has_ipv4_specifics && !has_ipv6_specifics)
2163 else if (has_ipv6_specifics && !has_ipv4_specifics)
2169 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2170 if (!family && rule.target != "dscp" && !has_ipv4_specifics && !has_ipv6_specifics) {
2171 add_rule(0, proto, null, null, sports, dports, null, null, null, rule);
2174 /* we need to emit one or two AF specific rules */
2176 if (family == 0 || family == 4) {
2177 let icmp_types = filter(itypes4, i => (i.code_min == 0 && i.code_max == 0xFF));
2178 let icmp_codes = filter(itypes4, i => (i.code_min != 0 || i.code_max != 0xFF));
2180 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2181 add_rule(4, proto, sip[0], dip[0], sports, dports, icmp_types, null, ipset, rule);
2183 if (length(icmp_codes))
2184 add_rule(4, proto, sip[0], dip[0], sports, dports, null, icmp_codes, ipset, rule);
2187 if (family == 0 || family == 6) {
2188 let icmp_types = filter(itypes6, i => (i.code_min == 0 && i.code_max == 0xFF));
2189 let icmp_codes = filter(itypes6, i => (i.code_min != 0 || i.code_max != 0xFF));
2191 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2192 add_rule(6, proto, sip[1], dip[1], sports, dports, icmp_types, null, ipset, rule);
2194 if (length(icmp_codes))
2195 add_rule(6, proto, sip[1], dip[1], sports, dports, null, icmp_codes, ipset, rule);
2201 parse_redirect: function(data) {
2202 let redir = this.parse_options(data, {
2203 enabled: [ "bool", "1" ],
2205 name: [ "string", this.section_id(data[".name"]) ],
2206 family: [ "family", "4" ],
2208 src: [ "zone_ref" ],
2209 dest: [ "zone_ref" ],
2211 ipset: [ "setmatch" ],
2212 helper: [ "cthelper", null, NO_INVERT ],
2214 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2216 src_ip: [ "network" ],
2217 src_mac: [ "mac", null, PARSE_LIST ],
2218 src_port: [ "port" ],
2220 src_dip: [ "network" ],
2221 src_dport: [ "port" ],
2223 dest_ip: [ "network" ],
2224 dest_port: [ "port" ],
2226 extra: [ "string", null, UNSUPPORTED ],
2229 limit_burst: [ "int" ],
2231 utc_time: [ "bool" ],
2232 start_date: [ "date" ],
2233 stop_date: [ "date" ],
2234 start_time: [ "time" ],
2235 stop_time: [ "time" ],
2236 weekdays: [ "weekdays" ],
2237 monthdays: [ "monthdays", null, UNSUPPORTED ],
2241 reflection: [ "bool", "1" ],
2242 reflection_src: [ "reflection_source", "internal" ],
2244 reflection_zone: [ "zone_ref", null, PARSE_LIST ],
2246 counter: [ "bool", "1" ],
2248 target: [ "target", "dnat" ]
2251 if (redir === false) {
2252 this.warn_section(data, "skipped due to invalid options");
2255 else if (!redir.enabled) {
2256 this.warn_section(data, "is disabled, ignoring section");
2260 if (!(redir.target in ["dnat", "snat"])) {
2261 this.warn_section(data, "has invalid target specified, defaulting to dnat");
2262 redir.target = "dnat";
2268 ipset = filter(this.state.ipsets, s => (s.name == redir.ipset.name))[0];
2271 this.warn_section(data, "references unknown set '" + redir.ipset.name + "'");
2275 if (('inet_service' in ipset.types) && !ensure_tcpudp(redir.proto)) {
2276 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2281 let resolve_dest = (redir) => {
2282 for (let zone in this.state.zones) {
2283 for (let addr in zone.related_subnets) {
2284 if (redir.dest_ip.family != addr.family)
2287 let a = apply_mask(redir.dest_ip.addr, addr.bits);
2288 let b = apply_mask(addr.addr, addr.bits);
2305 if (redir.target == "dnat") {
2307 return this.warn_section(r, "has no source specified");
2308 else if (redir.src.any)
2309 return this.warn_section(r, "must not have source '*' for dnat target");
2310 else if (redir.dest_ip && redir.dest_ip.invert)
2311 return this.warn_section(r, "must not specify a negated 'dest_ip' value");
2313 if (!redir.dest && redir.dest_ip && resolve_dest(redir))
2314 this.warn_section(r, "does not specify a destination, assuming '" + redir.dest.zone.name + "'");
2316 if (!redir.dest_port)
2317 redir.dest_port = redir.src_dport;
2319 if (redir.reflection && redir.dest && redir.dest.zone && redir.src.zone.masq) {
2320 redir.dest.zone.dflags.accept = true;
2321 redir.dest.zone.dflags.dnat = true;
2322 redir.dest.zone.dflags.snat = true;
2326 redir.src.zone.dflags.helper = true;
2328 redir.src.zone.dflags[redir.target] = true;
2332 return this.warn_section(data, "has no destination specified");
2333 else if (redir.dest.any)
2334 return this.warn_section(data, "must not have destination '*' for snat target");
2335 else if (!redir.src_dip)
2336 return this.warn_section(data, "has no 'src_dip' option specified");
2337 else if (redir.src_dip.invert)
2338 return this.warn_section(data, "must not specify a negated 'src_dip' value");
2339 else if (redir.src_mac)
2340 return this.warn_section(data, "must not use 'src_mac' option for snat target");
2341 else if (redir.helper)
2342 return this.warn_section(data, "must not use 'helper' option for snat target");
2344 redir.dest.zone.dflags[redir.target] = true;
2348 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, ipset, redir) => {
2354 has_addrs: !!(length(saddrs) || length(daddrs)),
2355 has_ports: !!(sport || dport || rport),
2356 saddrs_pos: map(filter_pos(saddrs), this.cidr),
2357 saddrs_neg: map(filter_neg(saddrs), this.cidr),
2358 daddrs_pos: map(filter_pos(daddrs), this.cidr),
2359 daddrs_neg: map(filter_neg(daddrs), this.cidr),
2360 sports_pos: map(filter_pos(to_array(sport)), this.port),
2361 sports_neg: map(filter_neg(to_array(sport)), this.port),
2362 dports_pos: map(filter_pos(to_array(dport)), this.port),
2363 dports_neg: map(filter_neg(to_array(dport)), this.port),
2364 smacs_pos: map(filter_pos(redir.src_mac), m => m.mac),
2365 smacs_neg: map(filter_neg(redir.src_mac), m => m.mac),
2367 raddr: raddrs ? raddrs[0] : null,
2371 let set_types = map_setmatch(ipset, redir.ipset, proto.name);
2373 if (set_types !== set_types) {
2374 this.warn_section(data, "destination MAC address matching not supported");
2376 } else if (set_types) {
2377 r.ipset = { ...r.ipset, fields: set_types };
2382 r.chain = sprintf("dstnat_%s", r.src.zone.name);
2385 r.target = "redirect";
2390 r.chain = sprintf("srcnat_%s", r.dest.zone.name);
2394 this.state.redirects = this.state.redirects || [];
2395 push(this.state.redirects, r);
2398 let to_hostaddr = (a) => {
2399 let bits = (a.family == 4) ? 32 : 128;
2403 addr: apply_mask(a.addr, bits),
2408 for (let proto in redir.proto) {
2409 let sip, dip, rip, iip, eip, refip, sport, dport, rport;
2410 let family = redir.family;
2412 if (proto.name == "ipv6-icmp")
2415 family = infer_family(family, [
2417 redir.src, "source zone",
2418 redir.dest, "destination zone",
2419 redir.helper, "helper match"
2422 if (type(family) == "string") {
2423 this.warn_section(data, family + ", skipping");
2427 switch (redir.target) {
2429 sip = subnets_split_af(redir.src_ip);
2430 dip = subnets_split_af(redir.src_dip);
2431 rip = subnets_split_af(redir.dest_ip);
2433 switch (proto.name) {
2436 sport = redir.src_port;
2437 dport = redir.src_dport;
2438 rport = redir.dest_port;
2442 /* build reflection rules */
2443 if (redir.reflection && (length(rip[0]) || length(rip[1])) &&
2444 redir.src && redir.src.zone && redir.src.zone[family == 4 ? "masq" : "masq6"] &&
2445 redir.dest && redir.dest.zone) {
2448 name: redir.name + " (reflection)",
2450 helper: redir.helper,
2452 // XXX: this likely makes no sense for reflection rules
2453 //src_mac: redir.src_mac,
2456 limit_burst: redir.limit_burst,
2458 start_date: redir.start_date,
2459 stop_date: redir.stop_date,
2460 start_time: redir.start_time,
2461 stop_time: redir.stop_time,
2462 weekdays: redir.weekdays,
2467 let eaddrs = subnets_split_af(length(dip) ? dip : { addrs: redir.src.zone.related_subnets });
2468 let rzones = length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
2470 for (let rzone in rzones) {
2471 if (!is_family(rzone, family)) {
2472 this.warn_section(data,
2473 sprintf("is restricted to IPv%d but referenced reflection zone is IPv%d only, skipping",
2474 family, rzone.family));
2478 let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
2479 let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
2482 map(refaddrs[0], to_hostaddr),
2483 map(refaddrs[1], to_hostaddr)
2487 map(eaddrs[0], to_hostaddr),
2488 map(eaddrs[1], to_hostaddr)
2491 for (let i = 0; i <= 1; i++) {
2492 if (length(rip[i])) {
2493 refredir.src = rzone;
2494 refredir.dest = null;
2495 refredir.target = "dnat";
2496 add_rule(i ? 6 : 4, proto, iaddrs[i], eaddrs[i], rip[i], sport, dport, rport, null, refredir);
2498 for (let refaddr in refaddrs[i]) {
2499 refredir.src = null;
2500 refredir.dest = rzone;
2501 refredir.target = "snat";
2502 add_rule(i ? 6 : 4, proto, iaddrs[i], rip[i], [ refaddr ], null, rport, null, null, refredir);
2513 sip = subnets_split_af(redir.src_ip);
2514 dip = subnets_split_af(redir.dest_ip);
2515 rip = subnets_split_af(redir.src_dip);
2517 switch (proto.name) {
2520 sport = redir.src_port;
2521 dport = redir.dest_port;
2522 rport = redir.src_dport;
2529 if (length(rip[0]) > 1 || length(rip[1]) > 1)
2530 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
2532 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2533 if (!family && !length(sip[0]) && !length(sip[1]) && !length(dip[0]) && !length(dip[1]) && !length(rip[0]) && !length(rip[1])) {
2534 add_rule(0, proto, null, null, null, sport, dport, rport, null, redir);
2537 /* we need to emit one or two AF specific rules */
2539 if (family == 0 || family == 4)
2540 add_rule(4, proto, sip[0], dip[0], rip[0], sport, dport, rport, ipset, redir);
2542 if (family == 0 || family == 6)
2543 add_rule(6, proto, sip[1], dip[1], rip[1], sport, dport, rport, ipset, redir);
2548 parse_nat: function(data) {
2549 let snat = this.parse_options(data, {
2550 enabled: [ "bool", "1" ],
2552 name: [ "string", this.section_id(data[".name"]) ],
2553 family: [ "family", "4" ],
2555 src: [ "zone_ref" ],
2556 device: [ "string" ],
2558 ipset: [ "setmatch", null, UNSUPPORTED ],
2560 proto: [ "protocol", "all", PARSE_LIST | FLATTEN_LIST ],
2562 src_ip: [ "network" ],
2563 src_port: [ "port" ],
2565 snat_ip: [ "network", null, NO_INVERT ],
2566 snat_port: [ "port", null, NO_INVERT ],
2568 dest_ip: [ "network" ],
2569 dest_port: [ "port" ],
2571 extra: [ "string", null, UNSUPPORTED ],
2574 limit_burst: [ "int" ],
2576 connlimit_ports: [ "bool" ],
2578 utc_time: [ "bool" ],
2579 start_date: [ "date" ],
2580 stop_date: [ "date" ],
2581 start_time: [ "time" ],
2582 stop_time: [ "time" ],
2583 weekdays: [ "weekdays" ],
2584 monthdays: [ "monthdays", null, UNSUPPORTED ],
2588 target: [ "target", "masquerade" ]
2591 if (snat === false) {
2592 this.warn_section(data, "skipped due to invalid options");
2595 else if (!snat.enabled) {
2596 this.warn_section(data, "is disabled, ignoring section");
2600 if (!(snat.target in ["accept", "snat", "masquerade"])) {
2601 this.warn_section(data, "has invalid target specified, defaulting to masquerade");
2602 snat.target = "masquerade";
2605 if (snat.target == "snat" && !snat.snat_ip && !snat.snat_port) {
2606 this.warn_section(data, "needs either 'snat_ip' or 'snat_port' for target snat, ignoring section");
2609 else if (snat.target != "snat" && snat.snat_ip) {
2610 this.warn_section(data, "must not use 'snat_ip' for non-snat target, ignoring section");
2613 else if (snat.target != "snat" && snat.snat_port) {
2614 this.warn_section(data, "must not use 'snat_port' for non-snat target, ignoring section");
2618 if ((snat.snat_port || snat.src_port || snat.dest_port) && !ensure_tcpudp(snat.proto)) {
2619 this.warn_section(data, "specifies ports but no UDP/TCP protocol, ignoring section");
2623 if (snat.src && snat.src.zone)
2624 snat.src.zone.dflags.snat = true;
2626 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, snat) => {
2632 has_addrs: !!(length(saddrs) || length(daddrs) || length(raddrs)),
2633 has_ports: !!(sport || dport),
2634 saddrs_pos: map(filter_pos(saddrs), this.cidr),
2635 saddrs_neg: map(filter_neg(saddrs), this.cidr),
2636 daddrs_pos: map(filter_pos(daddrs), this.cidr),
2637 daddrs_neg: map(filter_neg(daddrs), this.cidr),
2638 sports_pos: map(filter_pos(to_array(sport)), this.port),
2639 sports_neg: map(filter_neg(to_array(sport)), this.port),
2640 dports_pos: map(filter_pos(to_array(dport)), this.port),
2641 dports_neg: map(filter_neg(to_array(dport)), this.port),
2643 raddr: raddrs ? raddrs[0] : null,
2646 chain: (snat.src && snat.src.zone) ? sprintf("srcnat_%s", snat.src.zone.name) : "srcnat"
2649 this.state.redirects = this.state.redirects || [];
2650 push(this.state.redirects, n);
2653 for (let proto in snat.proto) {
2654 let sip, dip, rip, sport, dport, rport;
2655 let family = snat.family;
2657 sip = subnets_split_af(snat.src_ip);
2658 dip = subnets_split_af(snat.dest_ip);
2659 rip = subnets_split_af(snat.snat_ip);
2661 switch (proto.name) {
2664 sport = snat.src_port;
2665 dport = snat.dest_port;
2666 rport = snat.snat_port;
2670 if (length(rip[0]) > 1 || length(rip[1]) > 1)
2671 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
2673 /* inherit family restrictions from related zones */
2674 if (family === 0 || family === null) {
2675 let f = (rule.src && rule.src.zone) ? rule.src.zone.family : 0;
2678 this.warn_section(r,
2679 sprintf("inheriting %s restriction from src %s",
2680 this.nfproto(f1, true), rule.src.zone.name));
2686 /* if no family was configured, infer target family from IP addresses */
2687 if (family === null) {
2688 if ((length(sip[0]) || length(dip[0]) || length(rip[0])) && !length(sip[1]) && !length(dip[1]) && !length(rip[1]))
2690 else if ((length(sip[1]) || length(dip[1]) || length(rip[1])) && !length(sip[0]) && !length(dip[0]) && !length(rip[0]))
2696 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2697 if (!family && !length(sip[0]) && !length(sip[1]) && !length(dip[0]) && !length(dip[1]) && !length(rip[0]) && !length(rip[1])) {
2698 add_rule(0, proto, null, null, null, sport, dport, rport, snat);
2701 /* we need to emit one or two AF specific rules */
2703 if (family == 0 || family == 4)
2704 add_rule(4, proto, sip[0], dip[0], rip[0], sport, dport, rport, snat);
2706 if (family == 0 || family == 6)
2707 add_rule(6, proto, sip[1], dip[1], rip[1], sport, dport, rport, snat);
2712 parse_ipset: function(data) {
2713 let ipset = this.parse_options(data, {
2714 enabled: [ "bool", "1" ],
2715 reload_set: [ "bool" ],
2716 counters: [ "bool" ],
2717 comment: [ "bool" ],
2719 name: [ "string", null, REQUIRED ],
2720 family: [ "family", "4" ],
2722 storage: [ "string", null, UNSUPPORTED ],
2723 match: [ "ipsettype", null, PARSE_LIST ],
2725 iprange: [ "string", null, UNSUPPORTED ],
2726 portrange: [ "string", null, UNSUPPORTED ],
2728 netmask: [ "int", null, UNSUPPORTED ],
2730 hashsize: [ "int", null, UNSUPPORTED ],
2731 timeout: [ "int", null, UNSUPPORTED ],
2733 external: [ "string", null, UNSUPPORTED ],
2735 entry: [ "string", null, PARSE_LIST ],
2736 loadfile: [ "string" ]
2739 if (ipset === false) {
2740 this.warn_section(data, "skipped due to invalid options");
2743 else if (!ipset.enabled) {
2744 this.warn_section(data, "is disabled, ignoring section");
2748 if (ipset.family == 0) {
2749 this.warn_section(data, "must not specify family 'any'");
2752 else if (!length(ipset.match)) {
2753 this.warn_section(data, "has no datatypes assigned");
2757 let dirs = map(ipset.match, m => m[0]),
2758 types = map(ipset.match, m => m[1]),
2761 if ("set" in types) {
2762 this.warn_section(data, "match type 'set' is not supported");
2766 if ("net" in types) {
2767 if (this.kernel < 0x05060000) {
2768 this.warn_section(data, "match type 'net' requires kernel 5.6 or later");
2778 types: map(types, (t) => {
2782 return (ipset.family == 4) ? 'ipv4_addr' : 'ipv6_addr';
2785 return 'ether_addr';
2788 return 'inet_service';
2797 s.entries = filter(map(ipset.entry, (e) => {
2798 let v = self.parse_ipsetentry(e, s);
2801 self.warn_section(data, "ignoring invalid ipset entry '" + e + "'");
2804 }), (e) => (e != null));
2806 this.state.ipsets = this.state.ipsets || [];
2807 push(this.state.ipsets, s);