3 let STATEFILE = "/var/run/fw4.state";
6 let FLATTEN_LIST = 0x02;
8 let UNSUPPORTED = 0x08;
11 let ipv4_icmptypes = {
12 "any": [ 0xFF, 0, 0xFF ],
13 "echo-reply": [ 0, 0, 0xFF ],
14 "pong": [ 0, 0, 0xFF ], /* Alias */
16 "destination-unreachable": [ 3, 0, 0xFF ],
17 "network-unreachable": [ 3, 0, 0 ],
18 "host-unreachable": [ 3, 1, 1 ],
19 "protocol-unreachable": [ 3, 2, 2 ],
20 "port-unreachable": [ 3, 3, 3 ],
21 "fragmentation-needed": [ 3, 4, 4 ],
22 "source-route-failed": [ 3, 5, 5 ],
23 "network-unknown": [ 3, 6, 6 ],
24 "host-unknown": [ 3, 7, 7 ],
25 "network-prohibited": [ 3, 9, 9 ],
26 "host-prohibited": [ 3, 10, 10 ],
27 "TOS-network-unreachable": [ 3, 11, 11 ],
28 "TOS-host-unreachable": [ 3, 12, 12 ],
29 "communication-prohibited": [ 3, 13, 13 ],
30 "host-precedence-violation": [ 3, 14, 14 ],
31 "precedence-cutoff": [ 3, 15, 15 ],
33 "source-quench": [ 4, 0, 0xFF ],
35 "redirect": [ 5, 0, 0xFF ],
36 "network-redirect": [ 5, 0, 0 ],
37 "host-redirect": [ 5, 1, 1 ],
38 "TOS-network-redirect": [ 5, 2, 2 ],
39 "TOS-host-redirect": [ 5, 3, 3 ],
41 "echo-request": [ 8, 0, 0xFF ],
42 "ping": [ 8, 0, 0xFF ], /* Alias */
44 "router-advertisement": [ 9, 0, 0xFF ],
46 "router-solicitation": [ 10, 0, 0xFF ],
48 "time-exceeded": [ 11, 0, 0xFF ],
49 "ttl-exceeded": [ 11, 0, 0xFF ], /* Alias */
50 "ttl-zero-during-transit": [ 11, 0, 0 ],
51 "ttl-zero-during-reassembly": [ 11, 1, 1 ],
53 "parameter-problem": [ 12, 0, 0xFF ],
54 "ip-header-bad": [ 12, 0, 0 ],
55 "required-option-missing": [ 12, 1, 1 ],
57 "timestamp-request": [ 13, 0, 0xFF ],
59 "timestamp-reply": [ 14, 0, 0xFF ],
61 "address-mask-request": [ 17, 0, 0xFF ],
63 "address-mask-reply": [ 18, 0, 0xFF ]
66 let ipv6_icmptypes = {
67 "destination-unreachable": [ 1, 0, 0xFF ],
68 "no-route": [ 1, 0, 0 ],
69 "communication-prohibited": [ 1, 1, 1 ],
70 "address-unreachable": [ 1, 3, 3 ],
71 "port-unreachable": [ 1, 4, 4 ],
73 "packet-too-big": [ 2, 0, 0xFF ],
75 "time-exceeded": [ 3, 0, 0xFF ],
76 "ttl-exceeded": [ 3, 0, 0xFF ], /* Alias */
77 "ttl-zero-during-transit": [ 3, 0, 0 ],
78 "ttl-zero-during-reassembly": [ 3, 1, 1 ],
80 "parameter-problem": [ 4, 0, 0xFF ],
81 "bad-header": [ 4, 0, 0 ],
82 "unknown-header-type": [ 4, 1, 1 ],
83 "unknown-option": [ 4, 2, 2 ],
85 "echo-request": [ 128, 0, 0xFF ],
86 "ping": [ 128, 0, 0xFF ], /* Alias */
88 "echo-reply": [ 129, 0, 0xFF ],
89 "pong": [ 129, 0, 0xFF ], /* Alias */
91 "router-solicitation": [ 133, 0, 0xFF ],
93 "router-advertisement": [ 134, 0, 0xFF ],
95 "neighbour-solicitation": [ 135, 0, 0xFF ],
96 "neighbor-solicitation": [ 135, 0, 0xFF ], /* Alias */
98 "neighbour-advertisement": [ 136, 0, 0xFF ],
99 "neighbor-advertisement": [ 136, 0, 0xFF ], /* Alias */
101 "redirect": [ 137, 0, 0xFF ]
129 /* cache used functions as upvalues */
130 let _arrtoip = arrtoip;
131 let _delete = delete;
132 let _exists = exists;
133 let _filter = filter;
134 let _getenv = getenv;
137 let _iptoarr = iptoarr;
142 let _length = length;
148 let _replace = replace;
149 let _splice = splice;
151 let _sprintf = sprintf;
152 let _substr = substr;
160 function to_mask(bits, v6) {
163 if (bits < 0 || bits > (v6 ? 128 : 32))
166 for (let i = 0; i < (v6 ? 16 : 4); i++) {
167 let b = (bits < 8) ? bits : 8;
168 m[i] = (0xff << (8 - b)) & 0xff;
175 function to_bits(mask) {
176 let a = _iptoarr(mask);
183 for (let i = 0, z = false; i < _length(a); i++) {
186 while (!z && (a[i] & 0x80)) {
187 a[i] = (a[i] << 1) & 0xff;
198 function apply_mask(addr, mask) {
199 let a = _iptoarr(addr);
204 if (_type(mask) == "int") {
205 for (let i = 0; i < _length(a); i++) {
206 let b = (mask < 8) ? mask : 8;
207 a[i] &= (0xff << (8 - b)) & 0xff;
212 let m = _iptoarr(mask);
214 if (!m || _length(a) != _length(m))
217 for (let i = 0; i < _length(a); i++)
224 function to_array(x) {
225 if (_type(x) == "array")
231 if (_type(x) == "object")
236 return (x == "") ? [] : _split(x, /[ \t]+/);
239 function filter_pos(x) {
240 let rv = _filter(x, e => !e.invert);
241 return _length(rv) ? rv : null;
244 function filter_neg(x) {
245 let rv = _filter(x, e => e.invert);
246 return _length(rv) ? rv : null;
249 function subnets_split_af(x) {
252 for (let ag in to_array(x)) {
253 for (let a in _filter(ag.addrs, a => (a.family == 4))) {
255 _push(rv[0], { ...a, invert: ag.invert });
258 for (let a in _filter(ag.addrs, a => (a.family == 6))) {
260 _push(rv[1], { ...a, invert: ag.invert });
267 function ensure_tcpudp(x) {
268 if (_length(_filter(x, p => (p.name == "tcp" || p.name == "udp"))))
271 let rest = _filter(x, p => !p.any),
272 any = _filter(x, p => p.any);
274 if (_length(any) && !_length(rest)) {
276 _push(x, { name: "tcp" }, { name: "udp" });
283 function is_family(x, v) { x.family == 0 || x.family == v }
284 function family_is_ipv4(x) { x.family == 0 || x.family == 4 }
285 function family_is_ipv6(x) { x.family == 0 || x.family == 6 }
287 function infer_family(f, objects) {
291 for (let i = 0; i < _length(objects); i += 2) {
292 let objs = to_array(objects[i]),
293 desc = objects[i + 1];
295 for (let obj in objs) {
296 if (!obj || obj.family == 0 || obj.family == res)
306 ? _sprintf('references IPv%d only %s but is restricted to IPv%d by %s', obj.family, desc, res, by)
307 : _sprintf('is restricted to IPv%d but referenced %s is IPv%d only', res, desc, obj.family);
314 function map_setmatch(set, match, proto) {
315 if (!set || (('inet_service' in set.types) && proto != 'tcp' && proto != 'udp'))
320 for (let i, t in set.types) {
321 let dir = (((match.dir && match.dir[i]) || set.directions[i] || 'src') == 'src' ? 's' : 'd');
325 fields[i] = _sprintf('ip %saddr', dir);
329 fields[i] = _sprintf('ip6 %saddr', dir);
336 fields[i] = 'ether saddr';
340 fields[i] = _sprintf('%s %sport', proto, dir);
350 read_kernel_version: function() {
351 let fd = _fs.open("/proc/version", "r"),
355 let m = _match(fd.read("line"), /^Linux version ([0-9]+)\.([0-9]+)\.([0-9]+)/);
357 v = m ? (+m[1] << 24) | (+m[2] << 16) | (+m[3] << 8) : 0;
364 read_state: function() {
365 let fd = _fs.open(STATEFILE, "r");
370 state = _json(fd.read("all"));
373 _warn(_sprintf("Unable to parse '%s': %s\n", STATEFILE, e));
382 read_ubus: function() {
385 rules = [], networks = {},
386 bus = ubus.connect();
389 ifaces = bus.call("network.interface", "dump");
390 services = bus.call("service", "get_data", { "type": "firewall" });
395 _warn(_sprintf("Unable to connect to ubus: %s\n", ubus.error()));
400 // Gather logical network information from ubus
403 if (_type(ifaces) == "object" && _type(ifaces.interface) == "array") {
404 for (let ifc in ifaces.interface) {
407 device: ifc.l3_device
410 if (_type(ifc["ipv4-address"]) == "array") {
411 for (let addr in ifc["ipv4-address"]) {
412 net.ipaddrs = net.ipaddrs || [];
416 mask: to_mask(addr.mask, false),
422 if (_type(ifc["ipv6-address"]) == "array") {
423 for (let addr in ifc["ipv6-address"]) {
424 net.ipaddrs = net.ipaddrs || [];
428 mask: to_mask(addr.mask, true),
434 if (_type(ifc["ipv6-prefix-assignment"]) == "array") {
435 for (let addr in ifc["ipv6-prefix-assignment"]) {
436 if (addr["local-address"]) {
437 net.ipaddrs = net.ipaddrs || [];
440 addr: addr["local-address"].address,
441 mask: to_mask(addr["local-address"].mask, true),
442 bits: addr["local-address"].mask
448 if (_type(ifc.data) == "object" && _type(ifc.data.firewall) == "array") {
451 for (let rulespec in ifc.data.firewall) {
455 name: (rulespec.type != 'ipset') ? _sprintf('ubus:%s[%s] %s %d', ifc.interface, ifc.proto, rulespec.type || 'rule', n) : rulespec.name,
456 device: rulespec.device || ifc.l3_device
463 networks[ifc.interface] = net;
469 // Gather firewall rule definitions from ubus services
472 if (_type(services) == "object") {
473 for (let svcname, service in services) {
474 if (_type(service) == "object" && _type(service.firewall) == "array") {
477 for (let rulespec in services[svcname].firewall) {
481 name: (rulespec.type != 'ipset') ? _sprintf('ubus:%s %s %d', svcname, rulespec.type || 'rule', n) : rulespec.name
488 for (let svcinst, instance in service) {
489 if (_type(instance) == "object" && _type(instance.firewall) == "array") {
492 for (let rulespec in instance.firewall) {
496 name: (rulespec.type != 'ipset') ? _sprintf('ubus:%s[%s] %s %d', svcname, svcinst, rulespec.type || 'rule', n) : rulespec.name
512 load: function(use_statefile) {
515 this.state = use_statefile ? this.read_state() : null;
517 this.cursor = uci.cursor();
518 this.cursor.load("firewall");
519 this.cursor.load("/usr/share/firewall4/helpers");
522 this.state = this.read_ubus();
524 this.kernel = this.read_kernel_version();
528 // Read helper mapping
531 this.cursor.foreach("helpers", "helper", h => self.parse_helper(h));
535 // Read default policies
538 this.cursor.foreach("firewall", "defaults", d => self.parse_defaults(d));
542 // Build list of ipsets
545 if (!this.state.ipsets) {
546 _map(_filter(this.state.ubus_rules, n => (n.type == "ipset")), s => self.parse_ipset(s));
547 this.cursor.foreach("firewall", "ipset", s => self.parse_ipset(s));
552 // Build list of logical zones
555 if (!this.state.zones)
556 this.cursor.foreach("firewall", "zone", z => self.parse_zone(z));
560 // Build list of forwardings
563 this.cursor.foreach("firewall", "forwarding", f => self.parse_forwarding(f));
567 // Build list of rules
570 _map(_filter(this.state.ubus_rules, r => (r.type == "rule")), r => self.parse_rule(r));
571 this.cursor.foreach("firewall", "rule", r => self.parse_rule(r));
575 // Build list of redirects
578 _map(_filter(this.state.ubus_rules, r => (r.type == "redirect")), r => self.parse_redirect(r));
579 this.cursor.foreach("firewall", "redirect", r => self.parse_redirect(r));
583 // Build list of snats
586 _map(_filter(this.state.ubus_rules, n => (n.type == "nat")), n => self.parse_nat(n));
587 this.cursor.foreach("firewall", "nat", n => self.parse_nat(n));
591 let fd = _fs.open(STATEFILE, "w");
595 zones: this.state.zones,
596 ipsets: this.state.ipsets,
597 networks: this.state.networks,
598 ubus_rules: this.state.ubus_rules
604 _warn("Unable to write '%s': %s\n", STATEFILE, _fs.error());
609 warn: function(fmt, ...args) {
610 if (_getenv("QUIET"))
613 let msg = _sprintf(fmt, ...args);
616 _warn("\033[33m", msg, "\033[m\n");
618 _warn("[!] ", msg, "\n");
621 get: function(sid, opt) {
622 return this.cursor.get("firewall", sid, opt);
625 get_all: function(sid) {
626 return this.cursor.get_all("firewall", sid);
629 parse_options: function(s, spec) {
632 for (let key, val in spec) {
633 let datatype = "parse_" + val[0],
636 parsefn = (flags & PARSE_LIST) ? "parse_list" : "parse_opt";
638 let res = this[parsefn](s, key, datatype, defval, flags);
643 if (_type(res) == "object" && res.invert && (flags & NO_INVERT)) {
644 this.warn_section(s, "option '" + key + '" must not be negated');
649 if (flags & UNSUPPORTED)
650 this.warn_section(s, "option '" + key + "' is not supported by fw4");
657 if (_index(opt, '.') != 0 && opt != 'type' && !_exists(spec, opt)) {
658 this.warn_section(s, "specifies unknown option '" + opt + "'");
666 parse_subnet: function(subnet) {
667 let parts = _split(subnet, "/");
670 switch (_length(parts)) {
672 a = _iptoarr(parts[0]);
673 m = _iptoarr(parts[1]);
679 if (_length(a) != _length(m))
682 b = to_bits(parts[1]);
692 if (_type(b) != "int")
695 m = to_mask(b, _length(a) == 16);
699 family: (_length(a) == 16) ? 6 : 4,
706 parts = _split(parts[0], "-");
708 switch (_length(parts)) {
710 a = _iptoarr(parts[0]);
711 b = _iptoarr(parts[1]);
713 if (a && b && _length(a) == _length(b)) {
715 family: (_length(a) == 16) ? 6 : 4,
725 a = _iptoarr(parts[0]);
729 family: (_length(a) == 16) ? 6 : 4,
731 mask: to_mask(_length(a) * 8, _length(a) == 16),
736 n = this.state.networks[parts[0]];
739 return [ ...(n.ipaddrs || []) ];
746 parse_enum: function(val, choices) {
747 if (_type(val) == "string") {
750 for (let i = 0; i < _length(choices); i++)
751 if (_substr(choices[i], 0, _length(val)) == val)
758 section_id: function(sid) {
759 let s = this.get_all(sid);
764 if (s[".anonymous"]) {
767 this.cursor.foreach("firewall", s[".type"], function(ss) {
768 if (ss[".name"] == s[".name"])
774 return _sprintf("@%s[%d]", s[".type"], c);
780 warn_section: function(s, msg) {
783 this.warn("Section %s (%s) %s", this.section_id(s[".name"]), s.name, msg);
785 this.warn("Section %s %s", this.section_id(s[".name"]), msg);
789 this.warn("ubus %s (%s) %s", s.type || "rule", s.name, msg);
791 this.warn("ubus %s %s", s.type || "rule", msg);
795 parse_policy: function(val) {
796 return this.parse_enum(val, [
803 parse_bool: function(val) {
804 if (val == "1" || val == "on" || val == "true" || val == "yes")
806 else if (val == "0" || val == "off" || val == "false" || val == "no")
812 parse_family: function(val) {
813 if (val == 'any' || val == 'all' || val == '*')
815 else if (val == 'inet' || _index(val, '4') > -1)
817 else if (_index(val, '6') > -1)
823 parse_zone_ref: function(val) {
828 return { any: true };
830 for (let zone in this.state.zones) {
831 if (zone.name == val) {
842 parse_device: function(val) {
843 let rv = this.parse_invert(val);
856 parse_direction: function(val) {
857 if (val == 'in' || val == 'ingress')
859 else if (val == 'out' || val == 'egress')
865 parse_setmatch: function(val) {
866 let rv = this.parse_invert(val);
871 rv.val = _trim(_replace(rv.val, /^[^ \t]+/, function(m) {
876 let dir = _split(rv.val, /[ \t,]/);
878 for (let i = 0; i < 3 && i < _length(dir); i++) {
879 if (dir[i] == "dst" || dir[i] == "dest") {
880 rv.dir = rv.dir || [];
883 else if (dir[i] == "src") {
884 rv.dir = rv.dir || [];
889 return _length(rv.name) ? rv : null;
892 parse_cthelper: function(val) {
893 let rv = this.parse_invert(val);
898 let helper = _filter(this.state.helpers, h => (h.name == rv.val))[0];
900 return helper ? { ...rv, ...helper } : null;
903 parse_protocol: function(val) {
904 let p = this.parse_invert(val);
926 p.name = 'ipv6-icmp';
931 { invert: p.invert, name: 'tcp' },
932 { invert: p.invert, name: 'udp' }
947 return (p.any || _length(p.name)) ? p : null;
950 parse_mac: function(val) {
951 let mac = this.parse_invert(val);
952 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;
957 mac.mac = _sprintf('%02x:%02x:%02x:%02x:%02x:%02x',
958 _hex(m[1]), _hex(m[2]), _hex(m[3]),
959 _hex(m[4]), _hex(m[5]), _hex(m[6]));
964 parse_port: function(val) {
965 let port = this.parse_invert(val);
966 let m = port ? _match(port.val, /^([0-9]{1,5})([-:]([0-9]{1,5}))?$/i) : null;
972 let min_port = +m[1];
973 let max_port = +m[3];
975 if (min_port > max_port ||
976 min_port < 0 || max_port < 0 ||
977 min_port > 65535 || max_port > 65535)
986 if (pn != pn || pn < 0 || pn > 65535)
996 parse_network: function(val) {
997 let rv = this.parse_invert(val);
1002 let nets = this.parse_subnet(rv.val);
1008 rv.addrs = [ ...nets ];
1013 parse_icmptype: function(val) {
1016 if (_exists(ipv4_icmptypes, val)) {
1019 rv.type = ipv4_icmptypes[val][0];
1020 rv.code_min = ipv4_icmptypes[val][1];
1021 rv.code_max = ipv4_icmptypes[val][2];
1024 if (_exists(ipv6_icmptypes, val)) {
1025 rv.family = rv.family ? 0 : 6;
1027 rv.type6 = ipv6_icmptypes[val][0];
1028 rv.code6_min = ipv6_icmptypes[val][1];
1029 rv.code6_max = ipv6_icmptypes[val][2];
1032 if (!_exists(rv, "family")) {
1033 let m = _match(val, /^([0-9]+)(\/([0-9]+))?$/);
1040 rv.code_min = +m[3];
1041 rv.code_max = rv.code_min;
1049 if (rv.type > 0xFF || rv.code_min > 0xFF || rv.code_max > 0xFF)
1055 rv.code6_min = rv.code_min;
1056 rv.code6_max = rv.code_max;
1062 parse_invert: function(val) {
1066 let rv = { invert: false };
1068 rv.val = _trim(_replace(val, /^[ \t]*!/, () => (rv.invert = true, '')));
1070 return _length(rv.val) ? rv : null;
1073 parse_limit: function(val) {
1074 let rv = this.parse_invert(val);
1075 let m = rv ? _match(rv.val, /^([0-9]+)(\/([a-z]+))?$/) : null;
1081 let u = m[3] ? this.parse_enum(m[3], [ "second", "minute", "hour", "day" ]) : "second";
1092 parse_int: function(val) {
1095 return (n == n) ? n : null;
1098 parse_date: function(val) {
1099 let m = _match(val, /^([0-9-]+)T([0-9:]+)$/);
1100 let d = m ? _match(m[1], /^([0-9]{1,4})(-([0-9]{1,2})(-([0-9]{1,2}))?)?$/) : null;
1101 let t = this.parse_time(m[2]);
1106 if (d == null || d[1] < 1970 || d[1] > 2038 || d[3] < 1 || d[3] > 12 || d[5] < 1 || d[5] > 31)
1116 hour: t ? +t[1] : 0,
1122 parse_time: function(val) {
1123 let t = _match(val, /^([0-9]{1,2})(:([0-9]{1,2})(:([0-9]{1,2}))?)?$/);
1125 if (t == null || t[1] > 23 || t[3] > 59 || t[5] > 59)
1135 parse_weekdays: function(val) {
1136 let rv = this.parse_invert(val);
1141 for (let day in to_array(rv.val)) {
1142 day = this.parse_enum(day, [
1155 rv.days = rv.days || {};
1156 rv.days[day] = true;
1159 rv.days = _keys(rv.days);
1161 return rv.days ? rv : null;
1164 parse_monthdays: function(val) {
1165 let rv = this.parse_invert(val);
1170 for (let day in to_array(rv.val)) {
1173 if (day < 1 || day > 31)
1176 rv.days = rv.days || [];
1177 rv.days[day] = true;
1180 return rv.days ? rv : null;
1183 parse_mark: function(val) {
1184 let rv = this.parse_invert(val);
1185 let m = rv ? _match(rv.val, /^(0?x?[0-9a-f]+)(\/(0?x?[0-9a-f]+))?$/i) : null;
1192 if (n != n || n > 0xFFFFFFFF)
1196 rv.mask = 0xFFFFFFFF;
1201 if (n != n || n > 0xFFFFFFFF)
1210 parse_dscp: function(val) {
1211 let rv = this.parse_invert(val);
1216 rv.val = _uc(rv.val);
1218 if (_exists(dscp_classes, rv.val)) {
1219 rv.dscp = dscp_classes[rv.val];
1224 if (n != n || n < 0 || n > 0x3F)
1233 parse_target: function(val) {
1234 return this.parse_enum(val, [
1251 parse_reject_code: function(val) {
1252 return this.parse_enum(val, [
1261 parse_reflection_source: function(val) {
1262 return this.parse_enum(val, [
1268 parse_ipsettype: function(val) {
1269 let m = _match(val, /^(src|dst|dest)_(.+)$/);
1270 let t = this.parse_enum(m ? m[2] : val, [
1278 return t ? [ (!m || m[1] == 'src') ? 'src' : 'dst', t ] : null;
1281 parse_ipsetentry: function(val, set) {
1282 let values = _split(val, /[ \t]+/);
1284 if (_length(values) != _length(set.types))
1290 for (let i, t in set.types) {
1293 ip = _iptoarr(values[i]);
1295 if (_length(ip) != 4)
1298 rv[i] = _arrtoip(ip);
1302 ip = _iptoarr(values[i]);
1304 if (_length(ip) != 16)
1307 rv[i] = _arrtoip(ip);
1311 mac = this.parse_mac(values[i]);
1313 if (!mac || mac.invert)
1319 case 'inet_service':
1320 port = this.parse_port(values[i]);
1322 if (!port || port.invert || port.min != port.max)
1333 return _length(rv) ? rv : null;
1336 parse_string: function(val) {
1340 parse_opt: function(s, opt, fn, defval, flags) {
1344 if (flags & REQUIRED) {
1345 this.warn_section(s, "option '" + opt + "' is mandatory but not set");
1352 if (_type(val) == "array") {
1353 this.warn_section(s, "option '" + opt + "' must not be a list");
1356 else if (val == null) {
1360 let res = this[fn](val);
1363 this.warn_section(s, "option '" + opt + "' specifies invalid value '" + val + "'");
1370 parse_list: function(s, opt, fn, defval, flags) {
1375 if (flags & REQUIRED) {
1376 this.warn_section(s, "option '" + opt + "' is mandatory but not set");
1383 for (val in to_array(val)) {
1384 let res = this[fn](val);
1387 this.warn_section(s, "option '" + opt + "' specifies invalid value '" + val + "'");
1391 if (flags & FLATTEN_LIST)
1392 _push(rv, ...to_array(res));
1397 return _length(rv) ? rv : null;
1400 quote: function(s, force) {
1401 if (force === true || !_match(s, /^([0-9A-Fa-f:.\/]+)( \. [0-9A-Fa-f:.\/]+)*$/))
1402 return _sprintf('"%s"', _replace(s + "", /(["\\])/g, '\\$1'));
1409 return _sprintf("%s-%s", a.addr, a.addr2);
1411 if ((a.family == 4 && a.bits == 32) ||
1412 (a.family == 6 && a.bits == 128))
1415 return _sprintf("%s/%d", apply_mask(a.addr, a.bits), a.bits);
1420 ? _sprintf("%s-%s", a.addr, a.addr2)
1421 : apply_mask(a.addr, a.bits);
1426 return _sprintf('%d', p.min);
1428 return _sprintf('%d-%d', p.min, p.max);
1431 set: function(v, force) {
1434 if (force || _length(v) != 1)
1435 return _sprintf('{ %s }', _join(', ', _map(v, this.quote)));
1437 return this.quote(v[0]);
1440 concat: function(v) {
1441 return _join(' . ', to_array(v));
1444 ipproto: function(family) {
1454 nfproto: function(family, human_readable) {
1457 return human_readable ? "IPv4" : "ipv4";
1460 return human_readable ? "IPv6" : "ipv6";
1463 return human_readable ? "IPv4/IPv6" : null;
1467 datetime: function(stamp) {
1468 return _sprintf('"%04d-%02d-%02d %02d:%02d:%02d"',
1469 stamp.year, stamp.month, stamp.day,
1470 stamp.hour, stamp.min, stamp.sec);
1473 date: function(stamp) {
1474 return _sprintf('"%04d-%02d-%02d"', stamp.year, stamp.month, stamp.day);
1477 time: function(stamp) {
1478 return _sprintf('"%02d:%02d:%02d"', stamp.hour, stamp.min, stamp.sec);
1482 return _sprintf('0x%x', n);
1485 is_loopback_dev: function(dev) {
1486 let fd = _fs.open(_sprintf("/sys/class/net/%s/flags", dev), "r");
1491 let flags = +fd.read("line");
1495 return !!(flags & 0x8);
1498 is_loopback_addr: function(addr) {
1499 return (_index(addr, "127.") == 0 || addr == "::1" || addr == "::1/128");
1502 filter_loopback_devs: function(devs, invert) {
1504 return _filter(devs, d => (self.is_loopback_dev(d) == invert));
1507 filter_loopback_addrs: function(addrs, invert) {
1509 return _filter(addrs, a => (self.is_loopback_addr(a) == invert));
1513 input_policy: function(reject_as_drop) {
1514 return (!reject_as_drop || this.state.defaults.input != 'reject') ? this.state.defaults.input : 'drop';
1517 output_policy: function(reject_as_drop) {
1518 return (!reject_as_drop || this.state.defaults.output != 'reject') ? this.state.defaults.output : 'drop';
1521 forward_policy: function(reject_as_drop) {
1522 return (!reject_as_drop || this.state.defaults.forward != 'reject') ? this.state.defaults.forward : 'drop';
1525 default_option: function(flag) {
1526 return this.state.defaults[flag];
1529 helpers: function() {
1530 return this.state.helpers;
1534 return this.state.zones;
1537 rules: function(chain) {
1538 return _filter(this.state.rules, r => (r.chain == chain));
1541 redirects: function(chain) {
1542 return _filter(this.state.redirects, r => (r.chain == chain));
1545 ipsets: function() {
1546 return this.state.ipsets;
1549 parse_setfile: function(set, cb) {
1550 let fd = _fs.open(set.loadfile, "r");
1553 _warn(_sprintf("Unable to load file '%s' for set '%s': %s\n",
1554 set.loadfile, set.name, _fs.error()));
1558 let line = null, count = 0;
1560 while ((line = fd.read("line")) !== "") {
1563 if (_length(line) == 0 || _ord(line) == 35)
1566 let v = this.parse_ipsetentry(line, set);
1569 this.warn("Skipping invalid entry '%s' in file '%s' for set '%s'",
1570 line, set.loadfile, set.name);
1584 print_setentries: function(set) {
1586 let printer = (entry) => {
1588 _print("\t\telements = {\n");
1592 _print("\t\t\t", _join(" . ", entry), ",\n");
1595 _map(set.entries, printer);
1598 this.parse_setfile(set, printer);
1604 parse_helper: function(data) {
1605 let helper = this.parse_options(data, {
1606 name: [ "string", null, REQUIRED ],
1607 description: [ "string" ],
1608 module: [ "string" ],
1609 family: [ "family" ],
1610 proto: [ "protocol", null, PARSE_LIST | FLATTEN_LIST | NO_INVERT ],
1611 port: [ "port", null, NO_INVERT ]
1614 if (helper === false) {
1615 this.warn("Helper definition '%s' skipped due to invalid options", data.name || data['.name']);
1618 else if (helper.proto.any) {
1619 this.warn("Helper definition '%s' must not specify wildcard protocol", data.name || data['.name']);
1622 else if (_length(helper.proto) > 1) {
1623 this.warn("Helper definition '%s' must not specify multiple protocols", data.name || data['.name']);
1627 helper.available = ((_fs.stat("/sys/module/" + helper.module) || {}).type == "directory");
1629 this.state.helpers = this.state.helpers || [];
1630 _push(this.state.helpers, helper);
1633 parse_defaults: function(data) {
1634 if (this.state.defaults) {
1635 this.warn_section(data, ": ignoring duplicate defaults section");
1639 let defs = this.parse_options(data, {
1640 input: [ "policy", "drop" ],
1641 output: [ "policy", "drop" ],
1642 forward: [ "policy", "drop" ],
1644 drop_invalid: [ "bool" ],
1645 tcp_reject_code: [ "reject_code", "tcp-reset" ],
1646 any_reject_code: [ "reject_code", "port-unreachable" ],
1648 syn_flood: [ "bool" ],
1649 synflood_protect: [ "bool" ],
1650 synflood_rate: [ "limit", "25/second" ],
1651 synflood_burst: [ "int", "50" ],
1653 tcp_syncookies: [ "bool", "1" ],
1655 tcp_window_scaling: [ "bool", "1" ],
1657 accept_redirects: [ "bool" ],
1658 accept_source_route: [ "bool" ],
1660 auto_helper: [ "bool", "1" ],
1661 custom_chains: [ "bool", null, UNSUPPORTED ],
1662 disable_ipv6: [ "bool", null, UNSUPPORTED ],
1663 flow_offloading: [ "bool", null, UNSUPPORTED ],
1664 flow_offloading_hw: [ "bool", null, UNSUPPORTED ]
1667 if (defs === false) {
1668 this.warn_section(data, "skipped due to invalid options");
1672 if (defs.synflood_protect === null)
1673 defs.synflood_protect = defs.syn_flood;
1675 _delete(defs, "syn_flood");
1677 this.state.defaults = defs;
1680 parse_zone: function(data) {
1681 let zone = this.parse_options(data, {
1682 enabled: [ "bool", "1" ],
1684 name: [ "string", null, REQUIRED ],
1685 family: [ "family" ],
1687 network: [ "device", null, PARSE_LIST ],
1688 device: [ "device", null, PARSE_LIST ],
1689 subnet: [ "network", null, PARSE_LIST ],
1691 input: [ "policy", this.state.defaults ? this.state.defaults.input : "drop" ],
1692 output: [ "policy", this.state.defaults ? this.state.defaults.output : "drop" ],
1693 forward: [ "policy", this.state.defaults ? this.state.defaults.forward : "drop" ],
1696 masq_allow_invalid: [ "bool" ],
1697 masq_src: [ "network", null, PARSE_LIST ],
1698 masq_dest: [ "network", null, PARSE_LIST ],
1700 extra: [ "string", null, UNSUPPORTED ],
1701 extra_src: [ "string", null, UNSUPPORTED ],
1702 extra_dest: [ "string", null, UNSUPPORTED ],
1704 mtu_fix: [ "bool" ],
1705 custom_chains: [ "bool", null, UNSUPPORTED ],
1708 log_limit: [ "limit", null, UNSUPPORTED ],
1710 auto_helper: [ "bool", "1" ],
1711 helper: [ "cthelper", null, PARSE_LIST ],
1713 counter: [ "bool", "1" ]
1716 if (zone === false) {
1717 this.warn_section(data, "skipped due to invalid options");
1720 else if (!zone.enabled) {
1721 this.warn_section(data, "is disabled, ignoring section");
1724 else if (zone.helper && !zone.helper.available) {
1725 this.warn_section(data, "uses unavailable ct helper '" + zone.helper.name + "', ignoring section");
1729 if (zone.mtu_fix && this.kernel < 0x040a0000) {
1730 this.warn_section(data, "option 'mtu_fix' requires kernel 4.10 or later");
1734 if (this.state.defaults && this.state.defaults.auto_helper === false)
1735 zone.auto_helper = false;
1737 let match_devices = [];
1738 let related_subnets = [];
1739 let match_subnets, masq_src_subnets, masq_dest_subnets;
1741 for (let e in to_array(zone.network)) {
1742 if (_exists(this.state.networks, e.device)) {
1743 let net = this.state.networks[e.device];
1746 _push(match_devices, {
1752 _push(related_subnets, ...(net.ipaddrs || []));
1756 _push(match_devices, ...to_array(zone.device));
1758 match_subnets = subnets_split_af(zone.subnet);
1759 masq_src_subnets = subnets_split_af(zone.masq_src);
1760 masq_dest_subnets = subnets_split_af(zone.masq_dest);
1762 _push(related_subnets, ...(match_subnets[0] || []), ...(match_subnets[1] || []));
1764 let match_rules = [];
1766 let add_rule = (family, devices, subnets, zone) => {
1771 r.devices_pos = _map(filter_pos(devices), d => d.device);
1772 r.devices_neg = _map(filter_neg(devices), d => d.device);
1774 r.subnets_pos = _map(filter_pos(subnets), this.cidr);
1775 r.subnets_neg = _map(filter_neg(subnets), this.cidr);
1777 _push(match_rules, r);
1780 let family = infer_family(zone.family, [
1781 zone.helper, "ct helper"
1784 // check if there's no AF specific bits, in this case we can do AF agnostic matching
1785 if (!family && _length(match_devices) && !_length(match_subnets[0]) && !_length(match_subnets[1])) {
1786 add_rule(0, match_devices, null, zone);
1789 // we need to emit one or two AF specific rules
1791 if (family_is_ipv4(zone) && (_length(match_devices) || _length(match_subnets[0])))
1792 add_rule(4, match_devices, match_subnets[0], zone);
1794 if (family_is_ipv6(zone) && (_length(match_devices) || _length(match_subnets[1])))
1795 add_rule(6, match_devices, match_subnets[1], zone);
1798 zone.match_rules = match_rules;
1800 if (masq_src_subnets[0]) {
1801 zone.masq4_src_pos = _map(filter_pos(masq_src_subnets[0]), this.cidr);
1802 zone.masq4_src_neg = _map(filter_neg(masq_src_subnets[0]), this.cidr);
1805 if (masq_src_subnets[1]) {
1806 zone.masq6_src_pos = _map(filter_pos(masq_src_subnets[1]), this.cidr);
1807 zone.masq6_src_neg = _map(filter_neg(masq_src_subnets[1]), this.cidr);
1810 if (masq_dest_subnets[0]) {
1811 zone.masq4_dest_pos = _map(filter_pos(masq_dest_subnets[0]), this.cidr);
1812 zone.masq4_dest_neg = _map(filter_neg(masq_dest_subnets[0]), this.cidr);
1815 if (masq_dest_subnets[1]) {
1816 zone.masq6_dest_pos = _map(filter_pos(masq_dest_subnets[1]), this.cidr);
1817 zone.masq6_dest_neg = _map(filter_neg(masq_dest_subnets[1]), this.cidr);
1821 zone.sflags[zone.input] = true;
1824 zone.dflags[zone.output] = true;
1825 zone.dflags[zone.forward] = true;
1827 zone.match_devices = _map(_filter(match_devices, d => !d.invert), d => d.device);
1828 zone.match_subnets = _map(_filter(related_subnets, s => !s.invert), this.cidr);
1830 zone.related_subnets = related_subnets;
1832 if (zone.masq || zone.masq6)
1833 zone.dflags.snat = true;
1835 if ((zone.auto_helper && !(zone.masq || zone.masq6)) || _length(zone.helper)) {
1836 zone.dflags.helper = true;
1838 for (let helper in (_length(zone.helper) ? zone.helper : this.state.helpers)) {
1839 if (!helper.available)
1842 for (let proto in helper.proto) {
1843 this.state.rules = this.state.rules || [];
1844 _push(this.state.rules, {
1845 chain: "helper_" + zone.name,
1846 family: helper.family,
1847 name: helper.description || helper.name,
1850 dports_pos: [ this.port(helper.port) ],
1858 this.state.zones = this.state.zones || [];
1859 _push(this.state.zones, zone);
1862 parse_forwarding: function(data) {
1863 let fwd = this.parse_options(data, {
1864 enabled: [ "bool", "1" ],
1867 family: [ "family" ],
1869 src: [ "zone_ref", null, REQUIRED ],
1870 dest: [ "zone_ref", null, REQUIRED ]
1873 if (fwd === false) {
1874 this.warn_section(data, "skipped due to invalid options");
1877 else if (!fwd.enabled) {
1878 this.warn_section(data, "is disabled, ignoring section");
1882 let add_rule = (family, fwd) => {
1887 proto: { any: true }
1890 f.name = fwd.name || _sprintf("Accept %s to %s forwarding",
1891 fwd.src.any ? "any" : fwd.src.zone.name,
1892 fwd.dest.any ? "any" : fwd.dest.zone.name);
1894 f.chain = fwd.src.any ? "forward" : _sprintf("forward_%s", fwd.src.zone.name);
1897 f.target = "accept";
1899 f.jump_chain = _sprintf("accept_to_%s", fwd.dest.zone.name);
1901 this.state.rules = this.state.rules || [];
1902 _push(this.state.rules, f);
1906 let family = fwd.family;
1908 /* inherit family restrictions from related zones */
1909 if (family === 0 || family === null) {
1910 let f1 = fwd.src.zone ? fwd.src.zone.family : 0;
1911 let f2 = fwd.dest.zone ? fwd.dest.zone.family : 0;
1913 if (f1 != 0 && f2 != 0 && f1 != f2) {
1914 this.warn_section(data,
1915 _sprintf("references src %s restricted to %s and dest restricted to %s, ignoring forwarding",
1916 fwd.src.zone.name, this.nfproto(f1, true),
1917 fwd.dest.zone.name, this.nfproto(f2, true)));
1922 this.warn_section(data,
1923 _sprintf("inheriting %s restriction from src %s",
1924 this.nfproto(f1, true), fwd.src.zone.name));
1929 this.warn_section(data,
1930 _sprintf("inheriting %s restriction from dest %s",
1931 this.nfproto(f2, true), fwd.dest.zone.name));
1937 add_rule(family, fwd);
1940 fwd.dest.zone.dflags.accept = true;
1943 parse_rule: function(data) {
1944 let rule = this.parse_options(data, {
1945 enabled: [ "bool", "1" ],
1947 name: [ "string", this.section_id(data[".name"]) ],
1948 family: [ "family" ],
1950 src: [ "zone_ref" ],
1951 dest: [ "zone_ref" ],
1953 device: [ "device" ],
1954 direction: [ "direction" ],
1956 ipset: [ "setmatch" ],
1957 helper: [ "cthelper" ],
1958 set_helper: [ "cthelper", null, NO_INVERT ],
1960 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
1962 src_ip: [ "network", null, PARSE_LIST ],
1963 src_mac: [ "mac", null, PARSE_LIST ],
1964 src_port: [ "port", null, PARSE_LIST ],
1966 dest_ip: [ "network", null, PARSE_LIST ],
1967 dest_port: [ "port", null, PARSE_LIST ],
1969 icmp_type: [ "icmptype", null, PARSE_LIST ],
1970 extra: [ "string", null, UNSUPPORTED ],
1973 limit_burst: [ "int" ],
1975 utc_time: [ "bool" ],
1976 start_date: [ "date" ],
1977 stop_date: [ "date" ],
1978 start_time: [ "time" ],
1979 stop_time: [ "time" ],
1980 weekdays: [ "weekdays" ],
1981 monthdays: [ "monthdays", null, UNSUPPORTED ],
1984 set_mark: [ "mark", null, NO_INVERT ],
1985 set_xmark: [ "mark", null, NO_INVERT ],
1988 set_dscp: [ "dscp", null, NO_INVERT ],
1990 counter: [ "bool", "1" ],
1992 target: [ "target" ]
1995 if (rule === false) {
1996 this.warn_section(data, "skipped due to invalid options");
1999 else if (!rule.enabled) {
2000 this.warn_section(data, "is disabled, ignoring section");
2004 if (rule.target in ["helper", "notrack"] && (!rule.src || !rule.src.zone)) {
2005 this.warn_section(data, "must specify a source zone for target '" + rule.target + "'");
2008 else if (rule.target in ["dscp", "mark"] && rule.dest) {
2009 this.warn_section(data, "must not specify option 'dest' for target '" + rule.target + "'");
2012 else if (rule.target == "dscp" && !rule.set_dscp) {
2013 this.warn_section(data, "must specify option 'set_dscp' for target 'dscp'");
2016 else if (rule.target == "mark" && !rule.set_mark && !rule.set_xmark) {
2017 this.warn_section(data, "must specify option 'set_mark' or 'set_xmark' for target 'mark'");
2020 else if (rule.target == "helper" && !rule.set_helper) {
2021 this.warn_section(data, "must specify option 'set_helper' for target 'helper'");
2028 ipset = _filter(this.state.ipsets, s => (s.name == rule.ipset.name))[0];
2031 this.warn_section(data, "references unknown set '" + rule.ipset.name + "'");
2035 if (('inet_service' in ipset.types) && !ensure_tcpudp(rule.proto)) {
2036 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2041 let need_src_action_chain = (rule) => (rule.src && rule.src.zone && rule.src.zone.log && rule.target != "accept");
2043 let add_rule = (family, proto, saddrs, daddrs, sports, dports, icmptypes, icmpcodes, ipset, rule) => {
2049 has_addrs: !!(_length(saddrs) || _length(daddrs)),
2050 has_ports: !!(_length(sports) || _length(dports)),
2051 saddrs_pos: _map(filter_pos(saddrs), this.cidr),
2052 saddrs_neg: _map(filter_neg(saddrs), this.cidr),
2053 daddrs_pos: _map(filter_pos(daddrs), this.cidr),
2054 daddrs_neg: _map(filter_neg(daddrs), this.cidr),
2055 sports_pos: _map(filter_pos(sports), this.port),
2056 sports_neg: _map(filter_neg(sports), this.port),
2057 dports_pos: _map(filter_pos(dports), this.port),
2058 dports_neg: _map(filter_neg(dports), this.port),
2059 smacs_pos: _map(filter_pos(rule.src_mac), m => m.mac),
2060 smacs_neg: _map(filter_neg(rule.src_mac), m => m.mac),
2061 icmp_types: _map(icmptypes, i => (family == 4 ? i.type : i.type6)),
2062 icmp_codes: _map(icmpcodes, ic => _sprintf('%d . %d', (family == 4) ? ic.type : ic.type6, (family == 4) ? ic.code_min : ic.code6_min))
2065 if (!_length(r.icmp_types))
2066 _delete(r, "icmp_types");
2068 if (!_length(r.icmp_codes))
2069 _delete(r, "icmp_codes");
2073 invert: r.set_mark.invert,
2074 mark: r.set_mark.mark,
2075 mask: r.set_mark.mark | r.set_mark.mask
2078 _delete(r, "set_mark");
2081 let set_types = map_setmatch(ipset, rule.ipset, proto.name);
2083 if (set_types !== set_types) {
2084 this.warn_section(data, "destination MAC address matching not supported");
2086 } else if (set_types) {
2087 r.ipset = { ...r.ipset, fields: set_types };
2090 if (r.target == "notrack") {
2091 r.chain = _sprintf("notrack_%s", r.src.zone.name);
2092 r.src.zone.dflags.notrack = true;
2094 else if (r.target == "helper") {
2095 r.chain = _sprintf("helper_%s", r.src.zone.name);
2096 r.src.zone.dflags.helper = true;
2098 else if (r.target == "mark" || r.target == "dscp") {
2100 r.chain = "mangle_prerouting";
2101 r.src.zone.dflags[r.target] = true;
2104 r.chain = "mangle_output";
2112 r.chain = _sprintf("%s_%s", r.dest ? "forward" : "input", r.src.zone.name);
2114 r.chain = r.dest ? "forward" : "input";
2117 if (r.dest && !r.src) {
2119 r.chain = _sprintf("output_%s", r.dest.zone.name);
2124 if (r.dest && !r.dest.any) {
2125 r.jump_chain = _sprintf("%s_to_%s", r.target, r.dest.zone.name);
2126 r.dest.zone.dflags[r.target] = true;
2128 else if (need_src_action_chain(r)) {
2129 r.jump_chain = _sprintf("%s_from_%s", r.target, r.src.zone.name);
2130 r.src.zone.dflags[r.target] = true;
2132 else if (r.target == "reject")
2133 r.jump_chain = "handle_reject";
2136 this.state.rules = this.state.rules || [];
2137 _push(this.state.rules, r);
2140 for (let proto in rule.proto) {
2141 let sip, dip, sports, dports, itypes4, itypes6;
2142 let family = rule.family;
2144 switch (proto.name) {
2146 itypes4 = _filter(rule.icmp_type || [], family_is_ipv4);
2147 itypes6 = _filter(rule.icmp_type || [], family_is_ipv6);
2152 itypes6 = _filter(rule.icmp_type || [], family_is_ipv6);
2157 sports = rule.src_port;
2158 dports = rule.dest_port;
2162 family = infer_family(family, [
2164 rule.src, "source zone",
2165 rule.dest, "destination zone",
2166 rule.helper, "helper match",
2167 rule.set_helper, "helper to set"
2170 if (_type(family) == "string") {
2171 this.warn_section(data, family + ", skipping");
2175 sip = subnets_split_af(rule.src_ip);
2176 dip = subnets_split_af(rule.dest_ip);
2178 let has_ipv4_specifics = (_length(sip[0]) || _length(dip[0]) || _length(itypes4));
2179 let has_ipv6_specifics = (_length(sip[1]) || _length(dip[1]) || _length(itypes6));
2181 /* if no family was configured, infer target family from IP addresses */
2182 if (family === null) {
2183 if (has_ipv4_specifics && !has_ipv6_specifics)
2185 else if (has_ipv6_specifics && !has_ipv4_specifics)
2191 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2192 if (!family && rule.target != "dscp" && !has_ipv4_specifics && !has_ipv6_specifics) {
2193 add_rule(0, proto, null, null, sports, dports, null, null, null, rule);
2196 /* we need to emit one or two AF specific rules */
2198 if (family == 0 || family == 4) {
2199 let icmp_types = filter(itypes4, i => (i.code_min == 0 && i.code_max == 0xFF));
2200 let icmp_codes = _filter(itypes4, i => (i.code_min != 0 || i.code_max != 0xFF));
2202 if (_length(icmp_types) || (!_length(icmp_types) && !_length(icmp_codes)))
2203 add_rule(4, proto, sip[0], dip[0], sports, dports, icmp_types, null, ipset, rule);
2205 if (_length(icmp_codes))
2206 add_rule(4, proto, sip[0], dip[0], sports, dports, null, icmp_codes, ipset, rule);
2209 if (family == 0 || family == 6) {
2210 let icmp_types = filter(itypes6, i => (i.code_min == 0 && i.code_max == 0xFF));
2211 let icmp_codes = _filter(itypes6, i => (i.code_min != 0 || i.code_max != 0xFF));
2213 if (_length(icmp_types) || (!_length(icmp_types) && !_length(icmp_codes)))
2214 add_rule(6, proto, sip[1], dip[1], sports, dports, icmp_types, null, ipset, rule);
2216 if (_length(icmp_codes))
2217 add_rule(6, proto, sip[1], dip[1], sports, dports, null, icmp_codes, ipset, rule);
2223 parse_redirect: function(data) {
2224 let redir = this.parse_options(data, {
2225 enabled: [ "bool", "1" ],
2227 name: [ "string", this.section_id(data[".name"]) ],
2228 family: [ "family", "4" ],
2230 src: [ "zone_ref" ],
2231 dest: [ "zone_ref" ],
2233 ipset: [ "setmatch" ],
2234 helper: [ "cthelper", null, NO_INVERT ],
2236 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2238 src_ip: [ "network" ],
2239 src_mac: [ "mac", null, PARSE_LIST ],
2240 src_port: [ "port" ],
2242 src_dip: [ "network" ],
2243 src_dport: [ "port" ],
2245 dest_ip: [ "network" ],
2246 dest_port: [ "port" ],
2248 extra: [ "string", null, UNSUPPORTED ],
2251 limit_burst: [ "int" ],
2253 utc_time: [ "bool" ],
2254 start_date: [ "date" ],
2255 stop_date: [ "date" ],
2256 start_time: [ "time" ],
2257 stop_time: [ "time" ],
2258 weekdays: [ "weekdays" ],
2259 monthdays: [ "monthdays", null, UNSUPPORTED ],
2263 reflection: [ "bool", "1" ],
2264 reflection_src: [ "reflection_source", "internal" ],
2266 reflection_zone: [ "zone_ref", null, PARSE_LIST ],
2268 counter: [ "bool", "1" ],
2270 target: [ "target", "dnat" ]
2273 if (redir === false) {
2274 this.warn_section(data, "skipped due to invalid options");
2277 else if (!redir.enabled) {
2278 this.warn_section(data, "is disabled, ignoring section");
2282 if (!(redir.target in ["dnat", "snat"])) {
2283 this.warn_section(data, "has invalid target specified, defaulting to dnat");
2284 redir.target = "dnat";
2290 ipset = _filter(this.state.ipsets, s => (s.name == redir.ipset.name))[0];
2293 this.warn_section(data, "references unknown set '" + redir.ipset.name + "'");
2297 if (('inet_service' in ipset.types) && !ensure_tcpudp(redir.proto)) {
2298 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2303 let resolve_dest = (redir) => {
2304 for (let zone in this.state.zones) {
2305 for (let addr in zone.related_subnets) {
2306 if (redir.dest_ip.family != addr.family)
2309 let a = apply_mask(redir.dest_ip.addr, addr.bits);
2310 let b = apply_mask(addr.addr, addr.bits);
2327 if (redir.target == "dnat") {
2329 return this.warn_section(r, "has no source specified");
2330 else if (redir.src.any)
2331 return this.warn_section(r, "must not have source '*' for dnat target");
2332 else if (redir.dest_ip && redir.dest_ip.invert)
2333 return this.warn_section(r, "must not specify a negated 'dest_ip' value");
2335 if (!redir.dest && redir.dest_ip && resolve_dest(redir))
2336 this.warn_section(r, "does not specify a destination, assuming '" + redir.dest.zone.name + "'");
2338 if (!redir.dest_port)
2339 redir.dest_port = redir.src_dport;
2341 if (redir.reflection && redir.dest && redir.dest.zone && redir.src.zone.masq) {
2342 redir.dest.zone.dflags.accept = true;
2343 redir.dest.zone.dflags.dnat = true;
2344 redir.dest.zone.dflags.snat = true;
2348 redir.src.zone.dflags.helper = true;
2350 redir.src.zone.dflags[redir.target] = true;
2354 return this.warn_section(data, "has no destination specified");
2355 else if (redir.dest.any)
2356 return this.warn_section(data, "must not have destination '*' for snat target");
2357 else if (!redir.src_dip)
2358 return this.warn_section(data, "has no 'src_dip' option specified");
2359 else if (redir.src_dip.invert)
2360 return this.warn_section(data, "must not specify a negated 'src_dip' value");
2361 else if (redir.src_mac)
2362 return this.warn_section(data, "must not use 'src_mac' option for snat target");
2363 else if (redir.helper)
2364 return this.warn_section(data, "must not use 'helper' option for snat target");
2366 redir.dest.zone.dflags[redir.target] = true;
2370 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, ipset, redir) => {
2376 has_addrs: !!(_length(saddrs) || _length(daddrs)),
2377 has_ports: !!(sport || dport || rport),
2378 saddrs_pos: _map(filter_pos(saddrs), this.cidr),
2379 saddrs_neg: _map(filter_neg(saddrs), this.cidr),
2380 daddrs_pos: _map(filter_pos(daddrs), this.cidr),
2381 daddrs_neg: _map(filter_neg(daddrs), this.cidr),
2382 sports_pos: _map(filter_pos(to_array(sport)), this.port),
2383 sports_neg: _map(filter_neg(to_array(sport)), this.port),
2384 dports_pos: _map(filter_pos(to_array(dport)), this.port),
2385 dports_neg: _map(filter_neg(to_array(dport)), this.port),
2386 smacs_pos: _map(filter_pos(redir.src_mac), m => m.mac),
2387 smacs_neg: _map(filter_neg(redir.src_mac), m => m.mac),
2389 raddr: raddrs ? raddrs[0] : null,
2393 let set_types = map_setmatch(ipset, redir.ipset, proto.name);
2395 if (set_types !== set_types) {
2396 this.warn_section(data, "destination MAC address matching not supported");
2398 } else if (set_types) {
2399 r.ipset = { ...r.ipset, fields: set_types };
2404 r.chain = _sprintf("dstnat_%s", r.src.zone.name);
2407 r.target = "redirect";
2412 r.chain = _sprintf("srcnat_%s", r.dest.zone.name);
2416 this.state.redirects = this.state.redirects || [];
2417 _push(this.state.redirects, r);
2420 let to_hostaddr = (a) => {
2421 let bits = (a.family == 4) ? 32 : 128;
2425 addr: apply_mask(a.addr, bits),
2430 for (let proto in redir.proto) {
2431 let sip, dip, rip, iip, eip, refip, sport, dport, rport;
2432 let family = redir.family;
2434 if (proto.name == "ipv6-icmp")
2437 family = infer_family(family, [
2439 redir.src, "source zone",
2440 redir.dest, "destination zone",
2441 redir.helper, "helper match"
2444 if (_type(family) == "string") {
2445 this.warn_section(data, family + ", skipping");
2449 switch (redir.target) {
2451 sip = subnets_split_af(redir.src_ip);
2452 dip = subnets_split_af(redir.src_dip);
2453 rip = subnets_split_af(redir.dest_ip);
2455 switch (proto.name) {
2458 sport = redir.src_port;
2459 dport = redir.src_dport;
2460 rport = redir.dest_port;
2464 /* build reflection rules */
2465 if (redir.reflection && (_length(rip[0]) || _length(rip[1])) &&
2466 redir.src && redir.src.zone && redir.src.zone[family == 4 ? "masq" : "masq6"] &&
2467 redir.dest && redir.dest.zone) {
2470 name: redir.name + " (reflection)",
2472 helper: redir.helper,
2474 // XXX: this likely makes no sense for reflection rules
2475 //src_mac: redir.src_mac,
2478 limit_burst: redir.limit_burst,
2480 start_date: redir.start_date,
2481 stop_date: redir.stop_date,
2482 start_time: redir.start_time,
2483 stop_time: redir.stop_time,
2484 weekdays: redir.weekdays,
2489 let eaddrs = subnets_split_af(_length(dip) ? dip : { addrs: redir.src.zone.related_subnets });
2490 let rzones = _length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
2492 for (let rzone in rzones) {
2493 if (!is_family(rzone, family)) {
2494 this.warn_section(data,
2495 _sprintf("is restricted to IPv%d but referenced reflection zone is IPv%d only, skipping",
2496 family, rzone.family));
2500 let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
2501 let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
2504 _map(refaddrs[0], to_hostaddr),
2505 _map(refaddrs[1], to_hostaddr)
2509 _map(eaddrs[0], to_hostaddr),
2510 _map(eaddrs[1], to_hostaddr)
2513 for (let i = 0; i <= 1; i++) {
2514 if (_length(rip[i])) {
2515 refredir.src = rzone;
2516 refredir.dest = null;
2517 refredir.target = "dnat";
2518 add_rule(i ? 6 : 4, proto, iaddrs[i], eaddrs[i], rip[i], sport, dport, rport, null, refredir);
2520 for (let refaddr in refaddrs[i]) {
2521 refredir.src = null;
2522 refredir.dest = rzone;
2523 refredir.target = "snat";
2524 add_rule(i ? 6 : 4, proto, iaddrs[i], rip[i], [ refaddr ], null, rport, null, null, refredir);
2535 sip = subnets_split_af(redir.src_ip);
2536 dip = subnets_split_af(redir.dest_ip);
2537 rip = subnets_split_af(redir.src_dip);
2539 switch (proto.name) {
2542 sport = redir.src_port;
2543 dport = redir.dest_port;
2544 rport = redir.src_dport;
2551 if (_length(rip[0]) > 1 || _length(rip[1]) > 1)
2552 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
2554 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2555 if (!family && !_length(sip[0]) && !_length(sip[1]) && !_length(dip[0]) && !_length(dip[1]) && !_length(rip[0]) && !_length(rip[1])) {
2556 add_rule(0, proto, null, null, null, sport, dport, rport, null, redir);
2559 /* we need to emit one or two AF specific rules */
2561 if (family == 0 || family == 4)
2562 add_rule(4, proto, sip[0], dip[0], rip[0], sport, dport, rport, ipset, redir);
2564 if (family == 0 || family == 6)
2565 add_rule(6, proto, sip[1], dip[1], rip[1], sport, dport, rport, ipset, redir);
2570 parse_nat: function(data) {
2571 let snat = this.parse_options(data, {
2572 enabled: [ "bool", "1" ],
2574 name: [ "string", this.section_id(data[".name"]) ],
2575 family: [ "family", "4" ],
2577 src: [ "zone_ref" ],
2578 device: [ "string" ],
2580 ipset: [ "setmatch", null, UNSUPPORTED ],
2582 proto: [ "protocol", "all", PARSE_LIST | FLATTEN_LIST ],
2584 src_ip: [ "network" ],
2585 src_port: [ "port" ],
2587 snat_ip: [ "network", null, NO_INVERT ],
2588 snat_port: [ "port", null, NO_INVERT ],
2590 dest_ip: [ "network" ],
2591 dest_port: [ "port" ],
2593 extra: [ "string", null, UNSUPPORTED ],
2596 limit_burst: [ "int" ],
2598 connlimit_ports: [ "bool" ],
2600 utc_time: [ "bool" ],
2601 start_date: [ "date" ],
2602 stop_date: [ "date" ],
2603 start_time: [ "time" ],
2604 stop_time: [ "time" ],
2605 weekdays: [ "weekdays" ],
2606 monthdays: [ "monthdays", null, UNSUPPORTED ],
2610 target: [ "target", "masquerade" ]
2613 if (snat === false) {
2614 this.warn_section(data, "skipped due to invalid options");
2617 else if (!snat.enabled) {
2618 this.warn_section(data, "is disabled, ignoring section");
2622 if (!(snat.target in ["accept", "snat", "masquerade"])) {
2623 this.warn_section(data, "has invalid target specified, defaulting to masquerade");
2624 snat.target = "masquerade";
2627 if (snat.target == "snat" && !snat.snat_ip && !snat.snat_port) {
2628 this.warn_section(data, "needs either 'snat_ip' or 'snat_port' for target snat, ignoring section");
2631 else if (snat.target != "snat" && snat.snat_ip) {
2632 this.warn_section(data, "must not use 'snat_ip' for non-snat target, ignoring section");
2635 else if (snat.target != "snat" && snat.snat_port) {
2636 this.warn_section(data, "must not use 'snat_port' for non-snat target, ignoring section");
2640 if ((snat.snat_port || snat.src_port || snat.dest_port) && !ensure_tcpudp(snat.proto)) {
2641 this.warn_section(data, "specifies ports but no UDP/TCP protocol, ignoring section");
2645 if (snat.src && snat.src.zone)
2646 snat.src.zone.dflags.snat = true;
2648 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, snat) => {
2654 has_addrs: !!(_length(saddrs) || _length(daddrs) || _length(raddrs)),
2655 has_ports: !!(sport || dport),
2656 saddrs_pos: _map(filter_pos(saddrs), this.cidr),
2657 saddrs_neg: _map(filter_neg(saddrs), this.cidr),
2658 daddrs_pos: _map(filter_pos(daddrs), this.cidr),
2659 daddrs_neg: _map(filter_neg(daddrs), this.cidr),
2660 sports_pos: _map(filter_pos(to_array(sport)), this.port),
2661 sports_neg: _map(filter_neg(to_array(sport)), this.port),
2662 dports_pos: _map(filter_pos(to_array(dport)), this.port),
2663 dports_neg: _map(filter_neg(to_array(dport)), this.port),
2665 raddr: raddrs ? raddrs[0] : null,
2668 chain: (snat.src && snat.src.zone) ? _sprintf("srcnat_%s", snat.src.zone.name) : "srcnat"
2671 this.state.redirects = this.state.redirects || [];
2672 _push(this.state.redirects, n);
2675 for (let proto in snat.proto) {
2676 let sip, dip, rip, sport, dport, rport;
2677 let family = snat.family;
2679 sip = subnets_split_af(snat.src_ip);
2680 dip = subnets_split_af(snat.dest_ip);
2681 rip = subnets_split_af(snat.snat_ip);
2683 switch (proto.name) {
2686 sport = snat.src_port;
2687 dport = snat.dest_port;
2688 rport = snat.snat_port;
2692 if (_length(rip[0]) > 1 || _length(rip[1]) > 1)
2693 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
2695 /* inherit family restrictions from related zones */
2696 if (family === 0 || family === null) {
2697 let f = (rule.src && rule.src.zone) ? rule.src.zone.family : 0;
2700 this.warn_section(r,
2701 _sprintf("inheriting %s restriction from src %s",
2702 this.nfproto(f1, true), rule.src.zone.name));
2708 /* if no family was configured, infer target family from IP addresses */
2709 if (family === null) {
2710 if ((_length(sip[0]) || _length(dip[0]) || _length(rip[0])) && !_length(sip[1]) && !_length(dip[1]) && !_length(rip[1]))
2712 else if ((_length(sip[1]) || _length(dip[1]) || _length(rip[1])) && !_length(sip[0]) && !_length(dip[0]) && !_length(rip[0]))
2718 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2719 if (!family && !_length(sip[0]) && !_length(sip[1]) && !_length(dip[0]) && !_length(dip[1]) && !_length(rip[0]) && !_length(rip[1])) {
2720 add_rule(0, proto, null, null, null, sport, dport, rport, snat);
2723 /* we need to emit one or two AF specific rules */
2725 if (family == 0 || family == 4)
2726 add_rule(4, proto, sip[0], dip[0], rip[0], sport, dport, rport, snat);
2728 if (family == 0 || family == 6)
2729 add_rule(6, proto, sip[1], dip[1], rip[1], sport, dport, rport, snat);
2734 parse_ipset: function(data) {
2735 let ipset = this.parse_options(data, {
2736 enabled: [ "bool", "1" ],
2737 reload_set: [ "bool" ],
2738 counters: [ "bool" ],
2739 comment: [ "bool" ],
2741 name: [ "string", null, REQUIRED ],
2742 family: [ "family", "4" ],
2744 storage: [ "string", null, UNSUPPORTED ],
2745 match: [ "ipsettype", null, PARSE_LIST ],
2747 iprange: [ "string", null, UNSUPPORTED ],
2748 portrange: [ "string", null, UNSUPPORTED ],
2750 netmask: [ "int", null, UNSUPPORTED ],
2752 hashsize: [ "int", null, UNSUPPORTED ],
2753 timeout: [ "int", null, UNSUPPORTED ],
2755 external: [ "string", null, UNSUPPORTED ],
2757 entry: [ "string", null, PARSE_LIST ],
2758 loadfile: [ "string" ]
2761 if (ipset === false) {
2762 this.warn_section(data, "skipped due to invalid options");
2765 else if (!ipset.enabled) {
2766 this.warn_section(data, "is disabled, ignoring section");
2770 if (ipset.family == 0) {
2771 this.warn_section(data, "must not specify family 'any'");
2774 else if (!_length(ipset.match)) {
2775 this.warn_section(data, "has no datatypes assigned");
2779 let dirs = _map(ipset.match, m => m[0]),
2780 types = _map(ipset.match, m => m[1]),
2783 if ("set" in types) {
2784 this.warn_section(data, "match type 'set' is not supported");
2788 if ("net" in types) {
2789 if (this.kernel < 0x05060000) {
2790 this.warn_section(data, "match type 'net' requires kernel 5.6 or later");
2800 types: _map(types, (t) => {
2804 return (ipset.family == 4) ? 'ipv4_addr' : 'ipv6_addr';
2807 return 'ether_addr';
2810 return 'inet_service';
2819 s.entries = _filter(_map(ipset.entry, (e) => {
2820 let v = self.parse_ipsetentry(e, s);
2823 self.warn_section(data, "ignoring invalid ipset entry '" + e + "'");
2826 }), (e) => (e != null));
2828 this.state.ipsets = this.state.ipsets || [];
2829 _push(this.state.ipsets, s);