243e27c51627d5ebce602e5d3029f09df015d5d5
[project/firewall4.git] / root / usr / share / ucode / fw4.uc
1 {%
2
3 let fs = require("fs");
4 let uci = require("uci");
5 let ubus = require("ubus");
6
7 let STATEFILE = "/var/run/fw4.state";
8
9 let PARSE_LIST = 0x01;
10 let FLATTEN_LIST = 0x02;
11 let NO_INVERT = 0x04;
12 let UNSUPPORTED = 0x08;
13 let REQUIRED = 0x10;
14 let DEPRECATED = 0x20;
15
16 let ipv4_icmptypes = {
17 "any": [ 0xFF, 0, 0xFF ],
18 "echo-reply": [ 0, 0, 0xFF ],
19 "pong": [ 0, 0, 0xFF ], /* Alias */
20
21 "destination-unreachable": [ 3, 0, 0xFF ],
22 "network-unreachable": [ 3, 0, 0 ],
23 "host-unreachable": [ 3, 1, 1 ],
24 "protocol-unreachable": [ 3, 2, 2 ],
25 "port-unreachable": [ 3, 3, 3 ],
26 "fragmentation-needed": [ 3, 4, 4 ],
27 "source-route-failed": [ 3, 5, 5 ],
28 "network-unknown": [ 3, 6, 6 ],
29 "host-unknown": [ 3, 7, 7 ],
30 "network-prohibited": [ 3, 9, 9 ],
31 "host-prohibited": [ 3, 10, 10 ],
32 "TOS-network-unreachable": [ 3, 11, 11 ],
33 "TOS-host-unreachable": [ 3, 12, 12 ],
34 "communication-prohibited": [ 3, 13, 13 ],
35 "host-precedence-violation": [ 3, 14, 14 ],
36 "precedence-cutoff": [ 3, 15, 15 ],
37
38 "source-quench": [ 4, 0, 0xFF ],
39
40 "redirect": [ 5, 0, 0xFF ],
41 "network-redirect": [ 5, 0, 0 ],
42 "host-redirect": [ 5, 1, 1 ],
43 "TOS-network-redirect": [ 5, 2, 2 ],
44 "TOS-host-redirect": [ 5, 3, 3 ],
45
46 "echo-request": [ 8, 0, 0xFF ],
47 "ping": [ 8, 0, 0xFF ], /* Alias */
48
49 "router-advertisement": [ 9, 0, 0xFF ],
50
51 "router-solicitation": [ 10, 0, 0xFF ],
52
53 "time-exceeded": [ 11, 0, 0xFF ],
54 "ttl-exceeded": [ 11, 0, 0xFF ], /* Alias */
55 "ttl-zero-during-transit": [ 11, 0, 0 ],
56 "ttl-zero-during-reassembly": [ 11, 1, 1 ],
57
58 "parameter-problem": [ 12, 0, 0xFF ],
59 "ip-header-bad": [ 12, 0, 0 ],
60 "required-option-missing": [ 12, 1, 1 ],
61
62 "timestamp-request": [ 13, 0, 0xFF ],
63
64 "timestamp-reply": [ 14, 0, 0xFF ],
65
66 "address-mask-request": [ 17, 0, 0xFF ],
67
68 "address-mask-reply": [ 18, 0, 0xFF ]
69 };
70
71 let ipv6_icmptypes = {
72 "destination-unreachable": [ 1, 0, 0xFF ],
73 "no-route": [ 1, 0, 0 ],
74 "communication-prohibited": [ 1, 1, 1 ],
75 "address-unreachable": [ 1, 3, 3 ],
76 "port-unreachable": [ 1, 4, 4 ],
77
78 "packet-too-big": [ 2, 0, 0xFF ],
79
80 "time-exceeded": [ 3, 0, 0xFF ],
81 "ttl-exceeded": [ 3, 0, 0xFF ], /* Alias */
82 "ttl-zero-during-transit": [ 3, 0, 0 ],
83 "ttl-zero-during-reassembly": [ 3, 1, 1 ],
84
85 "parameter-problem": [ 4, 0, 0xFF ],
86 "bad-header": [ 4, 0, 0 ],
87 "unknown-header-type": [ 4, 1, 1 ],
88 "unknown-option": [ 4, 2, 2 ],
89
90 "echo-request": [ 128, 0, 0xFF ],
91 "ping": [ 128, 0, 0xFF ], /* Alias */
92
93 "echo-reply": [ 129, 0, 0xFF ],
94 "pong": [ 129, 0, 0xFF ], /* Alias */
95
96 "router-solicitation": [ 133, 0, 0xFF ],
97
98 "router-advertisement": [ 134, 0, 0xFF ],
99
100 "neighbour-solicitation": [ 135, 0, 0xFF ],
101 "neighbor-solicitation": [ 135, 0, 0xFF ], /* Alias */
102
103 "neighbour-advertisement": [ 136, 0, 0xFF ],
104 "neighbor-advertisement": [ 136, 0, 0xFF ], /* Alias */
105
106 "redirect": [ 137, 0, 0xFF ]
107 };
108
109 let dscp_classes = {
110 "CS0": 0x00,
111 "CS1": 0x08,
112 "CS2": 0x10,
113 "CS3": 0x18,
114 "CS4": 0x20,
115 "CS5": 0x28,
116 "CS6": 0x30,
117 "CS7": 0x38,
118 "BE": 0x00,
119 "LE": 0x01,
120 "AF11": 0x0a,
121 "AF12": 0x0c,
122 "AF13": 0x0e,
123 "AF21": 0x12,
124 "AF22": 0x14,
125 "AF23": 0x16,
126 "AF31": 0x1a,
127 "AF32": 0x1c,
128 "AF33": 0x1e,
129 "AF41": 0x22,
130 "AF42": 0x24,
131 "AF43": 0x26,
132 "EF": 0x2e
133 };
134
135 function to_mask(bits, v6) {
136 let m = [];
137
138 if (bits < 0 || bits > (v6 ? 128 : 32))
139 return null;
140
141 for (let i = 0; i < (v6 ? 16 : 4); i++) {
142 let b = (bits < 8) ? bits : 8;
143 m[i] = (0xff << (8 - b)) & 0xff;
144 bits -= b;
145 }
146
147 return arrtoip(m);
148 }
149
150 function to_bits(mask) {
151 let a = iptoarr(mask);
152
153 if (!a)
154 return null;
155
156 let bits = 0;
157
158 for (let i = 0, z = false; i < length(a); i++) {
159 z = z || !a[i];
160
161 while (!z && (a[i] & 0x80)) {
162 a[i] = (a[i] << 1) & 0xff;
163 bits++;
164 }
165
166 if (a[i])
167 return null;
168 }
169
170 return bits;
171 }
172
173 function apply_mask(addr, mask) {
174 let a = iptoarr(addr);
175
176 if (!a)
177 return null;
178
179 if (type(mask) == "int") {
180 for (let i = 0; i < length(a); i++) {
181 let b = (mask < 8) ? mask : 8;
182 a[i] &= (0xff << (8 - b)) & 0xff;
183 mask -= b;
184 }
185 }
186 else {
187 let m = iptoarr(mask);
188
189 if (!m || length(a) != length(m))
190 return null;
191
192 for (let i = 0; i < length(a); i++)
193 a[i] &= m[i];
194 }
195
196 return arrtoip(a);
197 }
198
199 function to_array(x) {
200 if (type(x) == "array")
201 return x;
202
203 if (x == null)
204 return [];
205
206 if (type(x) == "object")
207 return [ x ];
208
209 x = trim("" + x);
210
211 return (x == "") ? [] : split(x, /[ \t]+/);
212 }
213
214 function filter_pos(x) {
215 let rv = filter(x, e => !e.invert);
216 return length(rv) ? rv : null;
217 }
218
219 function filter_neg(x) {
220 let rv = filter(x, e => e.invert);
221 return length(rv) ? rv : null;
222 }
223
224 function null_if_empty(x) {
225 return length(x) ? x : null;
226 }
227
228 function subnets_split_af(x) {
229 let rv = {};
230
231 for (let ag in to_array(x)) {
232 for (let a in filter(ag.addrs, a => (a.family == 4))) {
233 rv[0] = rv[0] || [];
234 push(rv[0], { ...a, invert: ag.invert });
235 }
236
237 for (let a in filter(ag.addrs, a => (a.family == 6))) {
238 rv[1] = rv[1] || [];
239 push(rv[1], { ...a, invert: ag.invert });
240 }
241 }
242
243 if (rv[0] || rv[1])
244 rv.family = (!rv[0] ^ !rv[1]) ? (rv[0] ? 4 : 6) : 0;
245
246 return rv;
247 }
248
249 function subnets_group_by_masking(x) {
250 let groups = [], plain = [], nc = [], invert_plain = [], invert_masked = [];
251
252 for (let a in to_array(x)) {
253 if (a.bits == -1 && !a.invert)
254 push(nc, a);
255 else if (!a.invert)
256 push(plain, a);
257 else if (a.bits == -1)
258 push(invert_masked, a);
259 else
260 push(invert_plain, a);
261 }
262
263 for (let a in nc)
264 push(groups, [ null, null_if_empty(invert_plain), [ a, ...invert_masked ] ]);
265
266 if (length(plain)) {
267 push(groups, [
268 plain,
269 null_if_empty(invert_plain),
270 null_if_empty(invert_masked)
271 ]);
272 }
273 else if (!length(groups)) {
274 push(groups, [
275 null,
276 null_if_empty(invert_plain),
277 null_if_empty(invert_masked)
278 ]);
279 }
280
281 return groups;
282 }
283
284 function ensure_tcpudp(x) {
285 if (length(filter(x, p => (p.name == "tcp" || p.name == "udp"))))
286 return true;
287
288 let rest = filter(x, p => !p.any),
289 any = filter(x, p => p.any);
290
291 if (length(any) && !length(rest)) {
292 splice(x, 0);
293 push(x, { name: "tcp" }, { name: "udp" });
294 return true;
295 }
296
297 return false;
298 }
299
300 let is_family = (x, v) => (!x.family || x.family == v);
301 let family_is_ipv4 = (x) => (!x.family || x.family == 4);
302 let family_is_ipv6 = (x) => (!x.family || x.family == 6);
303
304 function infer_family(f, objects) {
305 let res = f;
306 let by = null;
307
308 for (let i = 0; i < length(objects); i += 2) {
309 let objs = to_array(objects[i]),
310 desc = objects[i + 1];
311
312 for (let obj in objs) {
313 if (!obj || !obj.family || obj.family == res)
314 continue;
315
316 if (!res) {
317 res = obj.family;
318 by = obj.desc;
319 continue;
320 }
321
322 return by
323 ? sprintf('references IPv%d only %s but is restricted to IPv%d by %s', obj.family, desc, res, by)
324 : sprintf('is restricted to IPv%d but referenced %s is IPv%d only', res, desc, obj.family);
325 }
326 }
327
328 return res;
329 }
330
331 function map_setmatch(set, match, proto) {
332 if (!set || (('inet_service' in set.types) && proto != 'tcp' && proto != 'udp'))
333 return null;
334
335 let fields = [];
336
337 for (let i, t in set.types) {
338 let dir = (((match.dir && match.dir[i]) || set.directions[i] || 'src') == 'src' ? 's' : 'd');
339
340 switch (t) {
341 case 'ipv4_addr':
342 fields[i] = sprintf('ip %saddr', dir);
343 break;
344
345 case 'ipv6_addr':
346 fields[i] = sprintf('ip6 %saddr', dir);
347 break;
348
349 case 'ether_addr':
350 if (dir != 's')
351 return NaN;
352
353 fields[i] = 'ether saddr';
354 break;
355
356 case 'inet_service':
357 fields[i] = sprintf('%s %sport', proto, dir);
358 break;
359 }
360 }
361
362 return fields;
363 }
364
365 function resolve_lower_devices(devstatus, devname) {
366 let dir = fs.opendir("/sys/class/net/" + devname);
367 let devs = [];
368
369 if (dir) {
370 if (!devstatus || devstatus[devname]?.["hw-tc-offload"]) {
371 push(devs, devname);
372 }
373 else {
374 let e;
375
376 while ((e = dir.read()) != null)
377 if (index(e, "lower_") === 0)
378 push(devs, ...resolve_lower_devices(devstatus, substr(e, 6)));
379 }
380
381 dir.close();
382 }
383
384 return devs;
385 }
386
387 function nft_json_command(...args) {
388 let cmd = [ "/usr/sbin/nft", "--terse", "--json", ...args ];
389 let nft = fs.popen(join(" ", cmd), "r");
390 let info;
391
392 if (nft) {
393 try {
394 info = filter(json(nft.read("all"))?.nftables,
395 item => (type(item) == "object" && !item.metainfo));
396 }
397 catch (e) {
398 warn(sprintf("Unable to parse nftables JSON output: %s\n", e));
399 }
400
401 nft.close();
402 }
403 else {
404 warn(sprintf("Unable to popen() %s: %s\n", cmd, fs.error()));
405 }
406
407 return info || [];
408 }
409
410 function nft_try_hw_offload(devices) {
411 let nft_test =
412 'add table inet fw4-hw-offload-test; ' +
413 'add flowtable inet fw4-hw-offload-test ft { ' +
414 'hook ingress priority 0; ' +
415 'devices = { "' + join('", "', devices) + '" }; ' +
416 'flags offload; ' +
417 '}';
418
419 let rc = system(sprintf("/usr/sbin/nft -c '%s' 2>/dev/null", replace(nft_test, "'", "'\\''")));
420
421 return (rc == 0);
422 }
423
424
425 return {
426 read_kernel_version: function() {
427 let fd = fs.open("/proc/version", "r"),
428 v = 0;
429
430 if (fd) {
431 let m = match(fd.read("line"), /^Linux version ([0-9]+)\.([0-9]+)\.([0-9]+)/);
432
433 v = m ? (+m[1] << 24) | (+m[2] << 16) | (+m[3] << 8) : 0;
434 fd.close();
435 }
436
437 return v;
438 },
439
440 resolve_offload_devices: function() {
441 if (!this.default_option("flow_offloading"))
442 return [];
443
444 let devstatus = null;
445 let devices = [];
446
447 if (this.default_option("flow_offloading_hw")) {
448 let bus = ubus.connect();
449
450 if (bus) {
451 devstatus = bus.call("network.device", "status") || {};
452 bus.disconnect();
453 }
454
455 for (let zone in this.zones())
456 for (let device in zone.match_devices)
457 push(devices, ...resolve_lower_devices(devstatus, device));
458
459 devices = uniq(devices);
460
461 if (nft_try_hw_offload(devices))
462 return devices;
463
464 this.warn('Hardware flow offloading unavailable, falling back to software offloading');
465 this.state.defaults.flow_offloading_hw = false;
466 }
467
468 devices = [];
469
470 for (let zone in this.zones())
471 for (let device in zone.match_devices)
472 push(devices, ...resolve_lower_devices(null, device));
473
474 return uniq(devices);
475 },
476
477 check_set_types: function() {
478 let sets = {};
479
480 for (let item in nft_json_command("list", "sets", "inet"))
481 if (item.set?.table == "fw4")
482 sets[item.set.name] = (type(item.set.type) == "array") ? item.set.type : [ item.set.type ];
483
484 return sets;
485 },
486
487 check_flowtable: function() {
488 for (let item in nft_json_command("list", "flowtables", "inet"))
489 if (item.flowtable?.table == "fw4" && item.flowtable?.name == "ft")
490 return true;
491
492 return false;
493 },
494
495 read_state: function() {
496 let fd = fs.open(STATEFILE, "r");
497 let state = null;
498
499 if (fd) {
500 try {
501 state = json(fd.read("all"));
502 }
503 catch (e) {
504 warn(sprintf("Unable to parse '%s': %s\n", STATEFILE, e));
505 }
506
507 fd.close();
508 }
509
510 return state;
511 },
512
513 read_ubus: function() {
514 let self = this,
515 ifaces, services,
516 rules = [], networks = {},
517 bus = ubus.connect();
518
519 if (bus) {
520 ifaces = bus.call("network.interface", "dump");
521 services = bus.call("service", "get_data", { "type": "firewall" });
522
523 bus.disconnect();
524 }
525 else {
526 warn(sprintf("Unable to connect to ubus: %s\n", ubus.error()));
527 }
528
529
530 //
531 // Gather logical network information from ubus
532 //
533
534 if (type(ifaces) == "object" && type(ifaces.interface) == "array") {
535 for (let ifc in ifaces.interface) {
536 let net = {
537 up: ifc.up,
538 device: ifc.l3_device,
539 zone: ifc.data?.zone
540 };
541
542 if (type(ifc["ipv4-address"]) == "array") {
543 for (let addr in ifc["ipv4-address"]) {
544 net.ipaddrs = net.ipaddrs || [];
545 push(net.ipaddrs, {
546 family: 4,
547 addr: addr.address,
548 mask: to_mask(addr.mask, false),
549 bits: addr.mask
550 });
551 }
552 }
553
554 if (type(ifc["ipv6-address"]) == "array") {
555 for (let addr in ifc["ipv6-address"]) {
556 net.ipaddrs = net.ipaddrs || [];
557 push(net.ipaddrs, {
558 family: 6,
559 addr: addr.address,
560 mask: to_mask(addr.mask, true),
561 bits: addr.mask
562 });
563 }
564 }
565
566 if (type(ifc["ipv6-prefix-assignment"]) == "array") {
567 for (let addr in ifc["ipv6-prefix-assignment"]) {
568 if (addr["local-address"]) {
569 net.ipaddrs = net.ipaddrs || [];
570 push(net.ipaddrs, {
571 family: 6,
572 addr: addr["local-address"].address,
573 mask: to_mask(addr["local-address"].mask, true),
574 bits: addr["local-address"].mask
575 });
576 }
577 }
578 }
579
580 if (type(ifc.data) == "object" && type(ifc.data.firewall) == "array") {
581 let n = 0;
582
583 for (let rulespec in ifc.data.firewall) {
584 push(rules, {
585 ...rulespec,
586
587 name: (rulespec.type != 'ipset') ? sprintf('ubus:%s[%s] %s %d', ifc.interface, ifc.proto, rulespec.type || 'rule', n) : rulespec.name,
588 device: rulespec.device || ifc.l3_device
589 });
590
591 n++;
592 }
593 }
594
595 networks[ifc.interface] = net;
596 }
597 }
598
599
600 //
601 // Gather firewall rule definitions from ubus services
602 //
603
604 if (type(services) == "object") {
605 for (let svcname, service in services) {
606 if (type(service) == "object" && type(service.firewall) == "array") {
607 let n = 0;
608
609 for (let rulespec in services[svcname].firewall) {
610 push(rules, {
611 ...rulespec,
612
613 name: (rulespec.type != 'ipset') ? sprintf('ubus:%s %s %d', svcname, rulespec.type || 'rule', n) : rulespec.name
614 });
615
616 n++;
617 }
618 }
619
620 for (let svcinst, instance in service) {
621 if (type(instance) == "object" && type(instance.firewall) == "array") {
622 let n = 0;
623
624 for (let rulespec in instance.firewall) {
625 push(rules, {
626 ...rulespec,
627
628 name: (rulespec.type != 'ipset') ? sprintf('ubus:%s[%s] %s %d', svcname, svcinst, rulespec.type || 'rule', n) : rulespec.name
629 });
630
631 n++;
632 }
633 }
634 }
635 }
636 }
637
638 return {
639 networks: networks,
640 ubus_rules: rules
641 };
642 },
643
644 load: function(use_statefile) {
645 let self = this;
646
647 this.state = use_statefile ? this.read_state() : null;
648
649 this.cursor = uci.cursor();
650 this.cursor.load("firewall");
651 this.cursor.load("/usr/share/firewall4/helpers");
652
653 if (!this.state)
654 this.state = this.read_ubus();
655
656 this.kernel = this.read_kernel_version();
657
658
659 //
660 // Read helper mapping
661 //
662
663 this.cursor.foreach("helpers", "helper", h => self.parse_helper(h));
664
665
666 //
667 // Read default policies
668 //
669
670 this.cursor.foreach("firewall", "defaults", d => self.parse_defaults(d));
671
672 if (!this.state.defaults)
673 this.parse_defaults({});
674
675
676 //
677 // Build list of ipsets
678 //
679
680 if (!this.state.ipsets) {
681 map(filter(this.state.ubus_rules, n => (n.type == "ipset")), s => self.parse_ipset(s));
682 this.cursor.foreach("firewall", "ipset", s => self.parse_ipset(s));
683 }
684
685
686 //
687 // Build list of logical zones
688 //
689
690 if (!this.state.zones)
691 this.cursor.foreach("firewall", "zone", z => self.parse_zone(z));
692
693
694 //
695 // Build list of rules
696 //
697
698 map(filter(this.state.ubus_rules, r => (r.type == "rule")), r => self.parse_rule(r));
699 this.cursor.foreach("firewall", "rule", r => self.parse_rule(r));
700
701
702 //
703 // Build list of forwardings
704 //
705
706 this.cursor.foreach("firewall", "forwarding", f => self.parse_forwarding(f));
707
708
709 //
710 // Build list of redirects
711 //
712
713 map(filter(this.state.ubus_rules, r => (r.type == "redirect")), r => self.parse_redirect(r));
714 this.cursor.foreach("firewall", "redirect", r => self.parse_redirect(r));
715
716
717 //
718 // Build list of snats
719 //
720
721 map(filter(this.state.ubus_rules, n => (n.type == "nat")), n => self.parse_nat(n));
722 this.cursor.foreach("firewall", "nat", n => self.parse_nat(n));
723
724
725 if (use_statefile) {
726 let fd = fs.open(STATEFILE, "w");
727
728 if (fd) {
729 fd.write({
730 zones: this.state.zones,
731 ipsets: this.state.ipsets,
732 networks: this.state.networks,
733 ubus_rules: this.state.ubus_rules
734 });
735
736 fd.close();
737 }
738 else {
739 warn("Unable to write '%s': %s\n", STATEFILE, fs.error());
740 }
741 }
742 },
743
744 warn: function(fmt, ...args) {
745 if (getenv("QUIET"))
746 return;
747
748 let msg = sprintf(fmt, ...args);
749
750 if (getenv("TTY"))
751 warn("\033[33m", msg, "\033[m\n");
752 else
753 warn("[!] ", msg, "\n");
754 },
755
756 get: function(sid, opt) {
757 return this.cursor.get("firewall", sid, opt);
758 },
759
760 get_all: function(sid) {
761 return this.cursor.get_all("firewall", sid);
762 },
763
764 parse_options: function(s, spec) {
765 let rv = {};
766
767 for (let key, val in spec) {
768 let datatype = "parse_" + val[0],
769 defval = val[1],
770 flags = val[2] || 0,
771 parsefn = (flags & PARSE_LIST) ? "parse_list" : "parse_opt";
772
773 let res = this[parsefn](s, key, datatype, defval, flags);
774
775 if (res !== res)
776 return false;
777
778 if (type(res) == "object" && res.invert && (flags & NO_INVERT)) {
779 this.warn_section(s, "option '" + key + '" must not be negated');
780 return false;
781 }
782
783 if (res != null) {
784 if (flags & DEPRECATED)
785 this.warn_section(s, "option '" + key + "' is deprecated by fw4");
786 else if (flags & UNSUPPORTED)
787 this.warn_section(s, "option '" + key + "' is not supported by fw4");
788 else
789 rv[key] = res;
790 }
791 }
792
793 for (let opt in s) {
794 if (index(opt, '.') != 0 && opt != 'type' && !exists(spec, opt)) {
795 this.warn_section(s, "specifies unknown option '" + opt + "'");
796 }
797 }
798
799 return rv;
800 },
801
802 parse_subnet: function(subnet) {
803 let parts = split(subnet, "/");
804 let a, b, m, n;
805
806 switch (length(parts)) {
807 case 2:
808 a = iptoarr(parts[0]);
809 m = iptoarr(parts[1]);
810
811 if (!a)
812 return null;
813
814 if (m) {
815 if (length(a) != length(m))
816 return null;
817
818 b = to_bits(parts[1]);
819
820 /* allow non-contiguous masks such as `::ffff:ffff:ffff:ffff` */
821 if (b == null) {
822 b = -1;
823
824 for (let i, x in m)
825 a[i] &= x;
826 }
827
828 m = arrtoip(m);
829 }
830 else {
831 b = +parts[1];
832
833 if (type(b) != "int")
834 return null;
835
836 m = to_mask(b, length(a) == 16);
837 }
838
839 return [{
840 family: (length(a) == 16) ? 6 : 4,
841 addr: arrtoip(a),
842 mask: m,
843 bits: b
844 }];
845
846 case 1:
847 parts = split(parts[0], "-");
848
849 switch (length(parts)) {
850 case 2:
851 a = iptoarr(parts[0]);
852 b = iptoarr(parts[1]);
853
854 if (a && b && length(a) == length(b)) {
855 return [{
856 family: (length(a) == 16) ? 6 : 4,
857 addr: arrtoip(a),
858 addr2: arrtoip(b),
859 range: true
860 }];
861 }
862
863 break;
864
865 case 1:
866 a = iptoarr(parts[0]);
867
868 if (a) {
869 return [{
870 family: (length(a) == 16) ? 6 : 4,
871 addr: arrtoip(a),
872 mask: to_mask(length(a) * 8, length(a) == 16),
873 bits: length(a) * 8
874 }];
875 }
876
877 n = this.state.networks[parts[0]];
878
879 if (n)
880 return [ ...(n.ipaddrs || []) ];
881 }
882 }
883
884 return null;
885 },
886
887 parse_enum: function(val, choices) {
888 if (type(val) == "string") {
889 val = lc(val);
890
891 for (let i = 0; i < length(choices); i++)
892 if (substr(choices[i], 0, length(val)) == val)
893 return choices[i];
894 }
895
896 return null;
897 },
898
899 section_id: function(sid) {
900 let s = this.get_all(sid);
901
902 if (!s)
903 return null;
904
905 if (s[".anonymous"]) {
906 let c = 0;
907
908 this.cursor.foreach("firewall", s[".type"], function(ss) {
909 if (ss[".name"] == s[".name"])
910 return false;
911
912 c++;
913 });
914
915 return sprintf("@%s[%d]", s[".type"], c);
916 }
917
918 return s[".name"];
919 },
920
921 warn_section: function(s, msg) {
922 if (s[".name"]) {
923 if (s.name)
924 this.warn("Section %s (%s) %s", this.section_id(s[".name"]), s.name, msg);
925 else
926 this.warn("Section %s %s", this.section_id(s[".name"]), msg);
927 }
928 else {
929 if (s.name)
930 this.warn("ubus %s (%s) %s", s.type || "rule", s.name, msg);
931 else
932 this.warn("ubus %s %s", s.type || "rule", msg);
933 }
934 },
935
936 parse_policy: function(val) {
937 return this.parse_enum(val, [
938 "accept",
939 "reject",
940 "drop"
941 ]);
942 },
943
944 parse_bool: function(val) {
945 if (val == "1" || val == "on" || val == "true" || val == "yes")
946 return true;
947 else if (val == "0" || val == "off" || val == "false" || val == "no")
948 return false;
949 else
950 return null;
951 },
952
953 parse_family: function(val) {
954 if (val == 'any' || val == 'all' || val == '*')
955 return 0;
956 else if (val == 'inet' || index(val, '4') > -1)
957 return 4;
958 else if (index(val, '6') > -1)
959 return 6;
960
961 return null;
962 },
963
964 parse_zone_ref: function(val) {
965 if (val == null)
966 return null;
967
968 if (val == '*')
969 return { any: true };
970
971 for (let zone in this.state.zones) {
972 if (zone.name == val) {
973 return {
974 any: false,
975 zone: zone
976 };
977 }
978 }
979
980 return null;
981 },
982
983 parse_device: function(val) {
984 let rv = this.parse_invert(val);
985
986 if (!rv)
987 return null;
988
989 if (rv.val == '*')
990 rv.any = true;
991 else
992 rv.device = rv.val;
993
994 return rv;
995 },
996
997 parse_direction: function(val) {
998 if (val == 'in' || val == 'ingress')
999 return false;
1000 else if (val == 'out' || val == 'egress')
1001 return true;
1002
1003 return null;
1004 },
1005
1006 parse_setmatch: function(val) {
1007 let rv = this.parse_invert(val);
1008
1009 if (!rv)
1010 return null;
1011
1012 rv.val = trim(replace(rv.val, /^[^ \t]+/, function(m) {
1013 rv.name = m;
1014 return '';
1015 }));
1016
1017 let dir = split(rv.val, /[ \t,]/);
1018
1019 for (let i = 0; i < 3 && i < length(dir); i++) {
1020 if (dir[i] == "dst" || dir[i] == "dest") {
1021 rv.dir = rv.dir || [];
1022 rv.dir[i] = "dst";
1023 }
1024 else if (dir[i] == "src") {
1025 rv.dir = rv.dir || [];
1026 rv.dir[i] = "src";
1027 }
1028 }
1029
1030 return length(rv.name) ? rv : null;
1031 },
1032
1033 parse_cthelper: function(val) {
1034 let rv = this.parse_invert(val);
1035
1036 if (!rv)
1037 return null;
1038
1039 let helper = filter(this.state.helpers, h => (h.name == rv.val))[0];
1040
1041 return helper ? { ...rv, ...helper } : null;
1042 },
1043
1044 parse_protocol: function(val) {
1045 let p = this.parse_invert(val);
1046
1047 if (!p)
1048 return null;
1049
1050 p.val = lc(p.val);
1051
1052 switch (p.val) {
1053 case 'all':
1054 case 'any':
1055 case '*':
1056 p.any = true;
1057 break;
1058
1059 case '1':
1060 case 'icmp':
1061 p.name = 'icmp';
1062 break;
1063
1064 case '58':
1065 case 'icmpv6':
1066 case 'ipv6-icmp':
1067 p.name = 'ipv6-icmp';
1068 break;
1069
1070 case 'tcpudp':
1071 return [
1072 { invert: p.invert, name: 'tcp' },
1073 { invert: p.invert, name: 'udp' }
1074 ];
1075
1076 case '6':
1077 p.name = 'tcp';
1078 break;
1079
1080 case '17':
1081 p.name = 'udp';
1082 break;
1083
1084 default:
1085 p.name = p.val;
1086 }
1087
1088 return (p.any || length(p.name)) ? p : null;
1089 },
1090
1091 parse_mac: function(val) {
1092 let mac = this.parse_invert(val);
1093 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;
1094
1095 if (!m)
1096 return null;
1097
1098 mac.mac = sprintf('%02x:%02x:%02x:%02x:%02x:%02x',
1099 hex(m[1]), hex(m[2]), hex(m[3]),
1100 hex(m[4]), hex(m[5]), hex(m[6]));
1101
1102 return mac;
1103 },
1104
1105 parse_port: function(val) {
1106 let port = this.parse_invert(val);
1107 let m = port ? match(port.val, /^([0-9]{1,5})([-:]([0-9]{1,5}))?$/i) : null;
1108
1109 if (!m)
1110 return null;
1111
1112 if (m[3]) {
1113 let min_port = +m[1];
1114 let max_port = +m[3];
1115
1116 if (min_port > max_port ||
1117 min_port < 0 || max_port < 0 ||
1118 min_port > 65535 || max_port > 65535)
1119 return null;
1120
1121 port.min = min_port;
1122 port.max = max_port;
1123 }
1124 else {
1125 let pn = +m[1];
1126
1127 if (pn != pn || pn < 0 || pn > 65535)
1128 return null;
1129
1130 port.min = pn;
1131 port.max = pn;
1132 }
1133
1134 return port;
1135 },
1136
1137 parse_network: function(val) {
1138 let rv = this.parse_invert(val);
1139
1140 if (!rv)
1141 return null;
1142
1143 let nets = this.parse_subnet(rv.val);
1144
1145 if (nets === null)
1146 return null;
1147
1148 if (length(nets))
1149 rv.addrs = [ ...nets ];
1150
1151 return rv;
1152 },
1153
1154 parse_icmptype: function(val) {
1155 let rv = {};
1156
1157 if (exists(ipv4_icmptypes, val)) {
1158 rv.family = 4;
1159
1160 rv.type = ipv4_icmptypes[val][0];
1161 rv.code_min = ipv4_icmptypes[val][1];
1162 rv.code_max = ipv4_icmptypes[val][2];
1163 }
1164
1165 if (exists(ipv6_icmptypes, val)) {
1166 rv.family = rv.family ? 0 : 6;
1167
1168 rv.type6 = ipv6_icmptypes[val][0];
1169 rv.code6_min = ipv6_icmptypes[val][1];
1170 rv.code6_max = ipv6_icmptypes[val][2];
1171 }
1172
1173 if (!exists(rv, "family")) {
1174 let m = match(val, /^([0-9]+)(\/([0-9]+))?$/);
1175
1176 if (!m)
1177 return null;
1178
1179 if (m[3]) {
1180 rv.type = +m[1];
1181 rv.code_min = +m[3];
1182 rv.code_max = rv.code_min;
1183 }
1184 else {
1185 rv.type = +m[1];
1186 rv.code_min = 0;
1187 rv.code_max = 0xFF;
1188 }
1189
1190 if (rv.type > 0xFF || rv.code_min > 0xFF || rv.code_max > 0xFF)
1191 return null;
1192
1193 rv.family = 0;
1194
1195 rv.type6 = rv.type;
1196 rv.code6_min = rv.code_min;
1197 rv.code6_max = rv.code_max;
1198 }
1199
1200 return rv;
1201 },
1202
1203 parse_invert: function(val) {
1204 if (val == null)
1205 return null;
1206
1207 let rv = { invert: false };
1208
1209 rv.val = trim(replace(val, /^[ \t]*!/, () => (rv.invert = true, '')));
1210
1211 return length(rv.val) ? rv : null;
1212 },
1213
1214 parse_limit: function(val) {
1215 let rv = this.parse_invert(val);
1216 let m = rv ? match(rv.val, /^([0-9]+)(\/([a-z]+))?$/) : null;
1217
1218 if (!m)
1219 return null;
1220
1221 let n = +m[1];
1222 let u = m[3] ? this.parse_enum(m[3], [ "second", "minute", "hour", "day" ]) : "second";
1223
1224 if (!u)
1225 return null;
1226
1227 rv.rate = n;
1228 rv.unit = u;
1229
1230 return rv;
1231 },
1232
1233 parse_int: function(val) {
1234 let n = +val;
1235
1236 return (n == n) ? n : null;
1237 },
1238
1239 parse_date: function(val) {
1240 let m = match(val, /^([0-9-]+)T([0-9:]+)$/);
1241 let d = m ? match(m[1], /^([0-9]{1,4})(-([0-9]{1,2})(-([0-9]{1,2}))?)?$/) : null;
1242 let t = this.parse_time(m[2]);
1243
1244 d[3] = d[3] || 1;
1245 d[5] = d[5] || 1;
1246
1247 if (d == null || d[1] < 1970 || d[1] > 2038 || d[3] < 1 || d[3] > 12 || d[5] < 1 || d[5] > 31)
1248 return null;
1249
1250 if (m[2] && !t)
1251 return null;
1252
1253 return {
1254 year: +d[1],
1255 month: +d[3],
1256 day: +d[5],
1257 hour: t ? +t[1] : 0,
1258 min: t ? +t[3] : 0,
1259 sec: t ? +t[5] : 0
1260 };
1261 },
1262
1263 parse_time: function(val) {
1264 let t = match(val, /^([0-9]{1,2})(:([0-9]{1,2})(:([0-9]{1,2}))?)?$/);
1265
1266 if (t == null || t[1] > 23 || t[3] > 59 || t[5] > 59)
1267 return null;
1268
1269 return {
1270 hour: +t[1],
1271 min: +t[3],
1272 sec: +t[5]
1273 };
1274 },
1275
1276 parse_weekdays: function(val) {
1277 let rv = this.parse_invert(val);
1278
1279 if (!rv)
1280 return null;
1281
1282 for (let day in to_array(rv.val)) {
1283 day = this.parse_enum(day, [
1284 "monday",
1285 "tuesday",
1286 "wednesday",
1287 "thursday",
1288 "friday",
1289 "saturday",
1290 "sunday"
1291 ]);
1292
1293 if (!day)
1294 return null;
1295
1296 rv.days = rv.days || {};
1297 rv.days[day] = true;
1298 }
1299
1300 rv.days = keys(rv.days);
1301
1302 return rv.days ? rv : null;
1303 },
1304
1305 parse_monthdays: function(val) {
1306 let rv = this.parse_invert(val);
1307
1308 if (!rv)
1309 return null;
1310
1311 for (let day in to_array(rv.val)) {
1312 day = +day;
1313
1314 if (day < 1 || day > 31)
1315 return null;
1316
1317 rv.days = rv.days || [];
1318 rv.days[day] = true;
1319 }
1320
1321 return rv.days ? rv : null;
1322 },
1323
1324 parse_mark: function(val) {
1325 let rv = this.parse_invert(val);
1326 let m = rv ? match(rv.val, /^(0?x?[0-9a-f]+)(\/(0?x?[0-9a-f]+))?$/i) : null;
1327
1328 if (!m)
1329 return null;
1330
1331 let n = +m[1];
1332
1333 if (n != n || n > 0xFFFFFFFF)
1334 return null;
1335
1336 rv.mark = n;
1337 rv.mask = 0xFFFFFFFF;
1338
1339 if (m[3]) {
1340 n = +m[3];
1341
1342 if (n != n || n > 0xFFFFFFFF)
1343 return null;
1344
1345 rv.mask = n;
1346 }
1347
1348 return rv;
1349 },
1350
1351 parse_dscp: function(val) {
1352 let rv = this.parse_invert(val);
1353
1354 if (!rv)
1355 return null;
1356
1357 rv.val = uc(rv.val);
1358
1359 if (exists(dscp_classes, rv.val)) {
1360 rv.dscp = dscp_classes[rv.val];
1361 }
1362 else {
1363 let n = +rv.val;
1364
1365 if (n != n || n < 0 || n > 0x3F)
1366 return null;
1367
1368 rv.dscp = n;
1369 }
1370
1371 return rv;
1372 },
1373
1374 parse_target: function(val) {
1375 return this.parse_enum(val, [
1376 "accept",
1377 "reject",
1378 "drop",
1379 "notrack",
1380 "helper",
1381 "mark",
1382 "dscp",
1383 "dnat",
1384 "snat",
1385 "masquerade",
1386 "accept",
1387 "reject",
1388 "drop"
1389 ]);
1390 },
1391
1392 parse_reject_code: function(val) {
1393 return this.parse_enum(val, [
1394 "tcp-reset",
1395 "port-unreachable",
1396 "admin-prohibited",
1397 "host-unreachable",
1398 "no-route"
1399 ]);
1400 },
1401
1402 parse_reflection_source: function(val) {
1403 return this.parse_enum(val, [
1404 "internal",
1405 "external"
1406 ]);
1407 },
1408
1409 parse_ipsettype: function(val) {
1410 let m = match(val, /^(src|dst|dest)_(.+)$/);
1411 let t = this.parse_enum(m ? m[2] : val, [
1412 "ip",
1413 "port",
1414 "mac",
1415 "net",
1416 "set"
1417 ]);
1418
1419 return t ? [ (!m || m[1] == 'src') ? 'src' : 'dst', t ] : null;
1420 },
1421
1422 parse_ipsetentry: function(val, set) {
1423 let values = split(val, /[ \t]+/);
1424
1425 if (length(values) != length(set.types))
1426 return null;
1427
1428 let rv = [];
1429 let ip, mac, port;
1430
1431 for (let i, t in set.types) {
1432 switch (t) {
1433 case 'ipv4_addr':
1434 ip = filter(this.parse_subnet(values[i]), a => (a.family == 4));
1435
1436 switch (length(ip)) {
1437 case 0: return null;
1438 case 1: break;
1439 default: this.warn("Set entry '%s' resolves to multiple addresses, using first one", values[i]);
1440 }
1441
1442 rv[i] = ("net" in set.fw4types) ? ip[0].addr + "/" + ip[0].bits : ip[0].addr;
1443 break;
1444
1445 case 'ipv6_addr':
1446 ip = filter(this.parse_subnet(values[i]), a => (a.family == 6));
1447
1448 switch(length(ip)) {
1449 case 0: return null;
1450 case 1: break;
1451 case 2: this.warn("Set entry '%s' resolves to multiple addresses, using first one", values[i]);
1452 }
1453
1454 rv[i] = ("net" in set.fw4types) ? ip[0].addr + "/" + ip[0].bits : ip[0].addr;
1455
1456 break;
1457
1458 case 'ether_addr':
1459 mac = this.parse_mac(values[i]);
1460
1461 if (!mac || mac.invert)
1462 return null;
1463
1464 rv[i] = mac.mac;
1465 break;
1466
1467 case 'inet_service':
1468 port = this.parse_port(values[i]);
1469
1470 if (!port || port.invert || port.min != port.max)
1471 return null;
1472
1473 rv[i] = port.min;
1474 break;
1475
1476 default:
1477 rv[i] = values[i];
1478 }
1479 }
1480
1481 return length(rv) ? rv : null;
1482 },
1483
1484 parse_string: function(val) {
1485 return "" + val;
1486 },
1487
1488 parse_opt: function(s, opt, fn, defval, flags) {
1489 let val = s[opt];
1490
1491 if (val === null) {
1492 if (flags & REQUIRED) {
1493 this.warn_section(s, "option '" + opt + "' is mandatory but not set");
1494 return NaN;
1495 }
1496
1497 val = defval;
1498 }
1499
1500 if (type(val) == "array") {
1501 this.warn_section(s, "option '" + opt + "' must not be a list");
1502 return NaN;
1503 }
1504 else if (val == null) {
1505 return null;
1506 }
1507
1508 let res = this[fn](val);
1509
1510 if (res === null) {
1511 this.warn_section(s, "option '" + opt + "' specifies invalid value '" + val + "'");
1512 return NaN;
1513 }
1514
1515 return res;
1516 },
1517
1518 parse_list: function(s, opt, fn, defval, flags) {
1519 let val = s[opt];
1520 let rv = [];
1521
1522 if (val == null) {
1523 if (flags & REQUIRED) {
1524 this.warn_section(s, "option '" + opt + "' is mandatory but not set");
1525 return NaN;
1526 }
1527
1528 val = defval;
1529 }
1530
1531 for (val in to_array(val)) {
1532 let res = this[fn](val);
1533
1534 if (res === null) {
1535 this.warn_section(s, "option '" + opt + "' specifies invalid value '" + val + "'");
1536 return NaN;
1537 }
1538
1539 if (flags & FLATTEN_LIST)
1540 push(rv, ...to_array(res));
1541 else
1542 push(rv, res);
1543 }
1544
1545 return length(rv) ? rv : null;
1546 },
1547
1548 quote: function(s, force) {
1549 if (force === true || !match(s, /^([0-9A-Fa-f:.\/-]+)( \. [0-9A-Fa-f:.\/-]+)*$/))
1550 return sprintf('"%s"', replace(s + "", /(["\\])/g, '\\$1'));
1551
1552 return s;
1553 },
1554
1555 cidr: function(a) {
1556 if (a.range)
1557 return sprintf("%s-%s", a.addr, a.addr2);
1558
1559 if ((a.family == 4 && a.bits == 32) ||
1560 (a.family == 6 && a.bits == 128))
1561 return a.addr;
1562
1563 if (a.bits >= 0)
1564 return sprintf("%s/%d", apply_mask(a.addr, a.bits), a.bits);
1565
1566 return sprintf("%s/%s", a.addr, a.mask);
1567 },
1568
1569 host: function(a) {
1570 return a.range
1571 ? sprintf("%s-%s", a.addr, a.addr2)
1572 : apply_mask(a.addr, a.bits);
1573 },
1574
1575 port: function(p) {
1576 if (p.min == p.max)
1577 return sprintf('%d', p.min);
1578
1579 return sprintf('%d-%d', p.min, p.max);
1580 },
1581
1582 set: function(v, force) {
1583 let seen = {};
1584
1585 v = filter(to_array(v), item => !seen[item]++);
1586
1587 if (force || length(v) != 1)
1588 return sprintf('{ %s }', join(', ', map(v, this.quote)));
1589
1590 return this.quote(v[0]);
1591 },
1592
1593 concat: function(v) {
1594 return join(' . ', to_array(v));
1595 },
1596
1597 ipproto: function(family) {
1598 switch (family) {
1599 case 4:
1600 return "ip";
1601
1602 case 6:
1603 return "ip6";
1604 }
1605 },
1606
1607 nfproto: function(family, human_readable) {
1608 switch (family) {
1609 case 4:
1610 return human_readable ? "IPv4" : "ipv4";
1611
1612 case 6:
1613 return human_readable ? "IPv6" : "ipv6";
1614
1615 default:
1616 return human_readable ? "IPv4/IPv6" : null;
1617 }
1618 },
1619
1620 datetime: function(stamp) {
1621 return sprintf('"%04d-%02d-%02d %02d:%02d:%02d"',
1622 stamp.year, stamp.month, stamp.day,
1623 stamp.hour, stamp.min, stamp.sec);
1624 },
1625
1626 date: function(stamp) {
1627 return sprintf('"%04d-%02d-%02d"', stamp.year, stamp.month, stamp.day);
1628 },
1629
1630 time: function(stamp) {
1631 return sprintf('"%02d:%02d:%02d"', stamp.hour, stamp.min, stamp.sec);
1632 },
1633
1634 hex: function(n) {
1635 return sprintf('0x%x', n);
1636 },
1637
1638 is_loopback_dev: function(dev) {
1639 let fd = fs.open(sprintf("/sys/class/net/%s/flags", dev), "r");
1640
1641 if (!fd)
1642 return false;
1643
1644 let flags = +fd.read("line");
1645
1646 fd.close();
1647
1648 return !!(flags & 0x8);
1649 },
1650
1651 is_loopback_addr: function(addr) {
1652 return (index(addr, "127.") == 0 || addr == "::1" || addr == "::1/128");
1653 },
1654
1655 filter_loopback_devs: function(devs, invert) {
1656 return null_if_empty(filter(devs, d => (this.is_loopback_dev(d) == invert)));
1657 },
1658
1659 filter_loopback_addrs: function(addrs, invert) {
1660 return null_if_empty(filter(addrs, a => (this.is_loopback_addr(a) == invert)));
1661 },
1662
1663
1664 input_policy: function(reject_as_drop) {
1665 return (!reject_as_drop || this.state.defaults.input != 'reject') ? this.state.defaults.input : 'drop';
1666 },
1667
1668 output_policy: function(reject_as_drop) {
1669 return (!reject_as_drop || this.state.defaults.output != 'reject') ? this.state.defaults.output : 'drop';
1670 },
1671
1672 forward_policy: function(reject_as_drop) {
1673 return (!reject_as_drop || this.state.defaults.forward != 'reject') ? this.state.defaults.forward : 'drop';
1674 },
1675
1676 default_option: function(flag) {
1677 return this.state.defaults[flag];
1678 },
1679
1680 helpers: function() {
1681 return this.state.helpers;
1682 },
1683
1684 zones: function() {
1685 return this.state.zones;
1686 },
1687
1688 rules: function(chain) {
1689 return filter(this.state.rules, r => (r.chain == chain));
1690 },
1691
1692 redirects: function(chain) {
1693 return filter(this.state.redirects, r => (r.chain == chain));
1694 },
1695
1696 ipsets: function() {
1697 return this.state.ipsets;
1698 },
1699
1700 parse_setfile: function(set, cb) {
1701 let fd = fs.open(set.loadfile, "r");
1702
1703 if (!fd) {
1704 warn(sprintf("Unable to load file '%s' for set '%s': %s\n",
1705 set.loadfile, set.name, fs.error()));
1706 return;
1707 }
1708
1709 let line = null, count = 0;
1710
1711 while ((line = fd.read("line")) !== "") {
1712 line = trim(line);
1713
1714 if (length(line) == 0 || ord(line) == 35)
1715 continue;
1716
1717 let v = this.parse_ipsetentry(line, set);
1718
1719 if (!v) {
1720 this.warn("Skipping invalid entry '%s' in file '%s' for set '%s'",
1721 line, set.loadfile, set.name);
1722 continue;
1723 }
1724
1725 cb(v);
1726
1727 count++;
1728 }
1729
1730 fd.close();
1731
1732 return count;
1733 },
1734
1735 print_setentries: function(set) {
1736 let first = true;
1737 let printer = (entry) => {
1738 if (first) {
1739 print("\t\telements = {\n");
1740 first = false;
1741 }
1742
1743 print("\t\t\t", join(" . ", entry), ",\n");
1744 };
1745
1746 map(set.entries, printer);
1747
1748 if (set.loadfile)
1749 this.parse_setfile(set, printer);
1750
1751 if (!first)
1752 print("\t\t}\n");
1753 },
1754
1755 parse_helper: function(data) {
1756 let helper = this.parse_options(data, {
1757 name: [ "string", null, REQUIRED ],
1758 description: [ "string" ],
1759 module: [ "string" ],
1760 family: [ "family" ],
1761 proto: [ "protocol", null, PARSE_LIST | FLATTEN_LIST | NO_INVERT ],
1762 port: [ "port", null, NO_INVERT ]
1763 });
1764
1765 if (helper === false) {
1766 this.warn("Helper definition '%s' skipped due to invalid options", data.name || data['.name']);
1767 return;
1768 }
1769 else if (helper.proto.any) {
1770 this.warn("Helper definition '%s' must not specify wildcard protocol", data.name || data['.name']);
1771 return;
1772 }
1773 else if (length(helper.proto) > 1) {
1774 this.warn("Helper definition '%s' must not specify multiple protocols", data.name || data['.name']);
1775 return;
1776 }
1777
1778 helper.available = ((fs.stat("/sys/module/" + helper.module) || {}).type == "directory");
1779
1780 this.state.helpers = this.state.helpers || [];
1781 push(this.state.helpers, helper);
1782 },
1783
1784 parse_defaults: function(data) {
1785 if (this.state.defaults) {
1786 this.warn_section(data, ": ignoring duplicate defaults section");
1787 return;
1788 }
1789
1790 let defs = this.parse_options(data, {
1791 input: [ "policy", "drop" ],
1792 output: [ "policy", "drop" ],
1793 forward: [ "policy", "drop" ],
1794
1795 drop_invalid: [ "bool" ],
1796 tcp_reject_code: [ "reject_code", "tcp-reset" ],
1797 any_reject_code: [ "reject_code", "port-unreachable" ],
1798
1799 syn_flood: [ "bool" ],
1800 synflood_protect: [ "bool" ],
1801 synflood_rate: [ "limit", "25/second" ],
1802 synflood_burst: [ "int", "50" ],
1803
1804 tcp_syncookies: [ "bool", "1" ],
1805 tcp_ecn: [ "int" ],
1806 tcp_window_scaling: [ "bool", "1" ],
1807
1808 accept_redirects: [ "bool" ],
1809 accept_source_route: [ "bool" ],
1810
1811 auto_helper: [ "bool", "1" ],
1812 custom_chains: [ "bool", null, UNSUPPORTED ],
1813 disable_ipv6: [ "bool", null, UNSUPPORTED ],
1814 flow_offloading: [ "bool", "0" ],
1815 flow_offloading_hw: [ "bool", "0" ]
1816 });
1817
1818 if (defs.synflood_protect === null)
1819 defs.synflood_protect = defs.syn_flood;
1820
1821 delete defs.syn_flood;
1822
1823 this.state.defaults = defs;
1824 },
1825
1826 parse_zone: function(data) {
1827 let zone = this.parse_options(data, {
1828 enabled: [ "bool", "1" ],
1829
1830 name: [ "string", null, REQUIRED ],
1831 family: [ "family" ],
1832
1833 network: [ "device", null, PARSE_LIST ],
1834 device: [ "device", null, PARSE_LIST ],
1835 subnet: [ "network", null, PARSE_LIST ],
1836
1837 input: [ "policy", this.state.defaults ? this.state.defaults.input : "drop" ],
1838 output: [ "policy", this.state.defaults ? this.state.defaults.output : "drop" ],
1839 forward: [ "policy", this.state.defaults ? this.state.defaults.forward : "drop" ],
1840
1841 masq: [ "bool" ],
1842 masq_allow_invalid: [ "bool" ],
1843 masq_src: [ "network", null, PARSE_LIST ],
1844 masq_dest: [ "network", null, PARSE_LIST ],
1845
1846 masq6: [ "bool" ],
1847
1848 extra: [ "string", null, UNSUPPORTED ],
1849 extra_src: [ "string", null, UNSUPPORTED ],
1850 extra_dest: [ "string", null, UNSUPPORTED ],
1851
1852 mtu_fix: [ "bool" ],
1853 custom_chains: [ "bool", null, UNSUPPORTED ],
1854
1855 log: [ "int" ],
1856 log_limit: [ "limit", null, UNSUPPORTED ],
1857
1858 auto_helper: [ "bool", "1" ],
1859 helper: [ "cthelper", null, PARSE_LIST ],
1860
1861 counter: [ "bool", "1" ]
1862 });
1863
1864 if (zone === false) {
1865 this.warn_section(data, "skipped due to invalid options");
1866 return;
1867 }
1868 else if (!zone.enabled) {
1869 this.warn_section(data, "is disabled, ignoring section");
1870 return;
1871 }
1872 else if (zone.helper && !zone.helper.available) {
1873 this.warn_section(data, "uses unavailable ct helper '" + zone.helper.name + "', ignoring section");
1874 return;
1875 }
1876
1877 if (zone.mtu_fix && this.kernel < 0x040a0000) {
1878 this.warn_section(data, "option 'mtu_fix' requires kernel 4.10 or later");
1879 return;
1880 }
1881
1882 if (this.state.defaults && this.state.defaults.auto_helper === false)
1883 zone.auto_helper = false;
1884
1885 let match_devices = [];
1886 let related_subnets = [];
1887 let related_ubus_networks = [];
1888 let match_subnets, masq_src_subnets, masq_dest_subnets;
1889
1890 for (let name, net in this.state.networks) {
1891 if (net.zone === zone.name)
1892 push(related_ubus_networks, { invert: false, device: name });
1893 }
1894
1895 for (let e in [ ...to_array(zone.network), ...related_ubus_networks ]) {
1896 if (exists(this.state.networks, e.device)) {
1897 let net = this.state.networks[e.device];
1898
1899 if (net.device) {
1900 push(match_devices, {
1901 invert: e.invert,
1902 device: net.device
1903 });
1904 }
1905
1906 push(related_subnets, ...(net.ipaddrs || []));
1907 }
1908 }
1909
1910 push(match_devices, ...to_array(zone.device));
1911
1912 match_subnets = subnets_split_af(zone.subnet);
1913 masq_src_subnets = subnets_split_af(zone.masq_src);
1914 masq_dest_subnets = subnets_split_af(zone.masq_dest);
1915
1916 push(related_subnets, ...(match_subnets[0] || []), ...(match_subnets[1] || []));
1917
1918 let match_rules = [];
1919
1920 let add_rule = (family, devices, subnets, zone) => {
1921 let r = {};
1922
1923 r.family = family;
1924
1925 r.devices_pos = null_if_empty(devices[0]);
1926 r.devices_neg = null_if_empty(devices[1]);
1927 r.devices_neg_wildcard = null_if_empty(devices[2]);
1928
1929 r.subnets_pos = map(subnets[0], this.cidr);
1930 r.subnets_neg = map(subnets[1], this.cidr);
1931 r.subnets_masked = subnets[2];
1932
1933 push(match_rules, r);
1934 };
1935
1936 let family = infer_family(zone.family, [
1937 zone.helper, "ct helper",
1938 match_subnets, "subnet list"
1939 ]);
1940
1941 if (type(family) == "string") {
1942 this.warn_section(data, family + ", skipping");
1943 return;
1944 }
1945
1946 // group non-inverted device matches into wildcard and non-wildcard ones
1947 let devices = [], plain_devices = [], plain_invert_devices = [], wildcard_invert_devices = [];
1948
1949 for (let device in match_devices) {
1950 let m = match(device.device, /^([^+]*)(\+)?$/);
1951
1952 if (!m) {
1953 this.warn_section(data, "skipping invalid wildcard pattern '" + device.device + '"');
1954 continue;
1955 }
1956
1957 // filter `+` (match any device) since nftables does not support
1958 // wildcard only matches
1959 if (!device.invert && m[0] == '+')
1960 continue;
1961
1962 // replace inverted `+` (match no device) with invalid pattern
1963 if (device.invert && m[0] == '+') {
1964 device.device = '/never/';
1965 device.invert = false;
1966 }
1967
1968 // replace "name+" matches with "name*"
1969 else if (m[2] == '+')
1970 device.device = m[1] + '*';
1971
1972 device.wildcard = !!m[2];
1973
1974 if (!device.invert && device.wildcard)
1975 push(devices, [ [ device.device ], plain_invert_devices, wildcard_invert_devices ]);
1976 else if (!device.invert)
1977 push(plain_devices, device.device);
1978 else if (device.wildcard)
1979 push(wildcard_invert_devices, device.device);
1980 else
1981 push(plain_invert_devices, device.device);
1982 }
1983
1984 if (length(plain_devices))
1985 push(devices, [
1986 plain_devices,
1987 plain_invert_devices,
1988 wildcard_invert_devices
1989 ]);
1990 else if (!length(devices))
1991 push(devices, [
1992 null,
1993 plain_invert_devices,
1994 wildcard_invert_devices
1995 ]);
1996
1997 // emit zone jump rules for each device group
1998 if (length(match_devices) || length(match_subnets[0]) || length(match_subnets[1])) {
1999 for (let devgroup in devices) {
2000 // check if there's no AF specific bits, in this case we can do AF agnostic matching
2001 if (!family && !length(match_subnets[0]) && !length(match_subnets[1])) {
2002 add_rule(0, devgroup, [], zone);
2003 }
2004
2005 // we need to emit one or two AF specific rules
2006 else {
2007 if (family_is_ipv4(zone) && length(match_subnets[0]))
2008 for (let subnets in subnets_group_by_masking(match_subnets[0]))
2009 add_rule(4, devgroup, subnets, zone);
2010
2011 if (family_is_ipv6(zone) && length(match_subnets[1]))
2012 for (let subnets in subnets_group_by_masking(match_subnets[1]))
2013 add_rule(6, devgroup, subnets, zone);
2014 }
2015 }
2016 }
2017
2018 zone.family = family;
2019
2020 zone.match_rules = match_rules;
2021
2022 zone.masq4_src_subnets = subnets_group_by_masking(masq_src_subnets[0]);
2023 zone.masq4_dest_subnets = subnets_group_by_masking(masq_dest_subnets[0]);
2024
2025 zone.masq6_src_subnets = subnets_group_by_masking(masq_src_subnets[1]);
2026 zone.masq6_dest_subnets = subnets_group_by_masking(masq_dest_subnets[1]);
2027
2028 zone.sflags = {};
2029 zone.sflags[zone.input] = true;
2030
2031 zone.dflags = {};
2032 zone.dflags[zone.output] = true;
2033 zone.dflags[zone.forward] = true;
2034
2035 zone.match_devices = map(filter(match_devices, d => !d.invert), d => d.device);
2036 zone.match_subnets = map(filter(related_subnets, s => !s.invert && s.bits != -1), this.cidr);
2037
2038 zone.related_subnets = related_subnets;
2039
2040 if (zone.masq || zone.masq6)
2041 zone.dflags.snat = true;
2042
2043 if ((zone.auto_helper && !(zone.masq || zone.masq6)) || length(zone.helper)) {
2044 zone.dflags.helper = true;
2045
2046 for (let helper in (length(zone.helper) ? zone.helper : this.state.helpers)) {
2047 if (!helper.available)
2048 continue;
2049
2050 for (let proto in helper.proto) {
2051 this.state.rules = this.state.rules || [];
2052 push(this.state.rules, {
2053 chain: "helper_" + zone.name,
2054 family: helper.family,
2055 name: helper.description || helper.name,
2056 proto: proto,
2057 src: zone,
2058 dports_pos: [ this.port(helper.port) ],
2059 target: "helper",
2060 set_helper: helper
2061 });
2062 }
2063 }
2064 }
2065
2066 this.state.zones = this.state.zones || [];
2067 push(this.state.zones, zone);
2068 },
2069
2070 parse_forwarding: function(data) {
2071 let fwd = this.parse_options(data, {
2072 enabled: [ "bool", "1" ],
2073
2074 name: [ "string" ],
2075 family: [ "family" ],
2076
2077 src: [ "zone_ref", null, REQUIRED ],
2078 dest: [ "zone_ref", null, REQUIRED ]
2079 });
2080
2081 if (fwd === false) {
2082 this.warn_section(data, "skipped due to invalid options");
2083 return;
2084 }
2085 else if (!fwd.enabled) {
2086 this.warn_section(data, "is disabled, ignoring section");
2087 return;
2088 }
2089
2090 let add_rule = (family, fwd) => {
2091 let f = {
2092 ...fwd,
2093
2094 family: family,
2095 proto: { any: true }
2096 };
2097
2098 f.name = fwd.name || sprintf("Accept %s to %s forwarding",
2099 fwd.src.any ? "any" : fwd.src.zone.name,
2100 fwd.dest.any ? "any" : fwd.dest.zone.name);
2101
2102 f.chain = fwd.src.any ? "forward" : sprintf("forward_%s", fwd.src.zone.name);
2103
2104 if (fwd.dest.any)
2105 f.target = "accept";
2106 else
2107 f.jump_chain = sprintf("accept_to_%s", fwd.dest.zone.name);
2108
2109 this.state.rules = this.state.rules || [];
2110 push(this.state.rules, f);
2111 };
2112
2113
2114 let family = fwd.family;
2115
2116 /* inherit family restrictions from related zones */
2117 if (family === 0 || family === null) {
2118 let f1 = fwd.src.zone ? fwd.src.zone.family : 0;
2119 let f2 = fwd.dest.zone ? fwd.dest.zone.family : 0;
2120
2121 if (f1 && f2 && f1 != f2) {
2122 this.warn_section(data,
2123 sprintf("references src %s restricted to %s and dest %s restricted to %s, ignoring forwarding",
2124 fwd.src.zone.name, this.nfproto(f1, true),
2125 fwd.dest.zone.name, this.nfproto(f2, true)));
2126
2127 return;
2128 }
2129 else if (f1) {
2130 this.warn_section(data,
2131 sprintf("inheriting %s restriction from src %s",
2132 this.nfproto(f1, true), fwd.src.zone.name));
2133
2134 family = f1;
2135 }
2136 else if (f2) {
2137 this.warn_section(data,
2138 sprintf("inheriting %s restriction from dest %s",
2139 this.nfproto(f2, true), fwd.dest.zone.name));
2140
2141 family = f2;
2142 }
2143 }
2144
2145 add_rule(family, fwd);
2146
2147 if (fwd.dest.zone)
2148 fwd.dest.zone.dflags.accept = true;
2149 },
2150
2151 parse_rule: function(data) {
2152 let rule = this.parse_options(data, {
2153 enabled: [ "bool", "1" ],
2154
2155 name: [ "string", this.section_id(data[".name"]) ],
2156 _name: [ "string", null, DEPRECATED ],
2157 family: [ "family" ],
2158
2159 src: [ "zone_ref" ],
2160 dest: [ "zone_ref" ],
2161
2162 device: [ "device", null, NO_INVERT ],
2163 direction: [ "direction" ],
2164
2165 ipset: [ "setmatch" ],
2166 helper: [ "cthelper" ],
2167 set_helper: [ "cthelper", null, NO_INVERT ],
2168
2169 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2170
2171 src_ip: [ "network", null, PARSE_LIST ],
2172 src_mac: [ "mac", null, PARSE_LIST ],
2173 src_port: [ "port", null, PARSE_LIST ],
2174
2175 dest_ip: [ "network", null, PARSE_LIST ],
2176 dest_port: [ "port", null, PARSE_LIST ],
2177
2178 icmp_type: [ "icmptype", null, PARSE_LIST ],
2179 extra: [ "string", null, UNSUPPORTED ],
2180
2181 limit: [ "limit" ],
2182 limit_burst: [ "int" ],
2183
2184 utc_time: [ "bool" ],
2185 start_date: [ "date" ],
2186 stop_date: [ "date" ],
2187 start_time: [ "time" ],
2188 stop_time: [ "time" ],
2189 weekdays: [ "weekdays" ],
2190 monthdays: [ "monthdays", null, UNSUPPORTED ],
2191
2192 mark: [ "mark" ],
2193 set_mark: [ "mark", null, NO_INVERT ],
2194 set_xmark: [ "mark", null, NO_INVERT ],
2195
2196 dscp: [ "dscp" ],
2197 set_dscp: [ "dscp", null, NO_INVERT ],
2198
2199 counter: [ "bool", "1" ],
2200
2201 target: [ "target" ]
2202 });
2203
2204 if (rule === false) {
2205 this.warn_section(data, "skipped due to invalid options");
2206 return;
2207 }
2208 else if (!rule.enabled) {
2209 this.warn_section(data, "is disabled, ignoring section");
2210 return;
2211 }
2212
2213 if (rule.target in ["helper", "notrack"] && (!rule.src || !rule.src.zone)) {
2214 this.warn_section(data, "must specify a source zone for target '" + rule.target + "'");
2215 return;
2216 }
2217 else if (rule.target == "dscp" && !rule.set_dscp) {
2218 this.warn_section(data, "must specify option 'set_dscp' for target 'dscp'");
2219 return;
2220 }
2221 else if (rule.target == "mark" && !rule.set_mark && !rule.set_xmark) {
2222 this.warn_section(data, "must specify option 'set_mark' or 'set_xmark' for target 'mark'");
2223 return;
2224 }
2225 else if (rule.target == "helper" && !rule.set_helper) {
2226 this.warn_section(data, "must specify option 'set_helper' for target 'helper'");
2227 return;
2228 }
2229 else if (rule.device?.any) {
2230 this.warn_section(data, "must not specify '*' as device");
2231 return;
2232 }
2233
2234 let ipset;
2235
2236 if (rule.ipset) {
2237 ipset = filter(this.state.ipsets, s => (s.name == rule.ipset.name))[0];
2238
2239 if (!ipset) {
2240 this.warn_section(data, "references unknown set '" + rule.ipset.name + "'");
2241 return;
2242 }
2243
2244 if (('inet_service' in ipset.types) && !ensure_tcpudp(rule.proto)) {
2245 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2246 return;
2247 }
2248 }
2249
2250 let need_src_action_chain = (rule) => (rule.src && rule.src.zone && rule.src.zone.log && rule.target != "accept");
2251
2252 let add_rule = (family, proto, saddrs, daddrs, sports, dports, icmptypes, icmpcodes, ipset, rule) => {
2253 let r = {
2254 ...rule,
2255
2256 family: family,
2257 proto: proto,
2258 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2259 has_ports: !!(length(sports) || length(dports)),
2260 saddrs_pos: map(saddrs[0], this.cidr),
2261 saddrs_neg: map(saddrs[1], this.cidr),
2262 saddrs_masked: saddrs[2],
2263 daddrs_pos: map(daddrs[0], this.cidr),
2264 daddrs_neg: map(daddrs[1], this.cidr),
2265 daddrs_masked: daddrs[2],
2266 sports_pos: map(filter_pos(sports), this.port),
2267 sports_neg: map(filter_neg(sports), this.port),
2268 dports_pos: map(filter_pos(dports), this.port),
2269 dports_neg: map(filter_neg(dports), this.port),
2270 smacs_pos: map(filter_pos(rule.src_mac), m => m.mac),
2271 smacs_neg: map(filter_neg(rule.src_mac), m => m.mac),
2272 icmp_types: map(icmptypes, i => (family == 4 ? i.type : i.type6)),
2273 icmp_codes: map(icmpcodes, ic => sprintf('%d . %d', (family == 4) ? ic.type : ic.type6, (family == 4) ? ic.code_min : ic.code6_min))
2274 };
2275
2276 if (!length(r.icmp_types))
2277 delete r.icmp_types;
2278
2279 if (!length(r.icmp_codes))
2280 delete r.icmp_codes;
2281
2282 if (r.set_mark) {
2283 r.set_xmark = {
2284 invert: r.set_mark.invert,
2285 mark: r.set_mark.mark,
2286 mask: r.set_mark.mark | r.set_mark.mask
2287 };
2288
2289 delete r.set_mark;
2290 }
2291
2292 let set_types = map_setmatch(ipset, rule.ipset, proto.name);
2293
2294 if (set_types !== set_types) {
2295 this.warn_section(data, "destination MAC address matching not supported");
2296 return;
2297 } else if (set_types) {
2298 r.ipset = { ...r.ipset, fields: set_types };
2299 }
2300
2301 if (r.target == "notrack") {
2302 r.chain = sprintf("notrack_%s", r.src.zone.name);
2303 r.src.zone.dflags.notrack = true;
2304 }
2305 else if (r.target == "helper") {
2306 r.chain = sprintf("helper_%s", r.src.zone.name);
2307 r.src.zone.dflags.helper = true;
2308 }
2309 else if (r.target == "mark" || r.target == "dscp") {
2310 if ((r.src?.any && r.dest?.any) || (r.src?.zone && r.dest?.zone))
2311 r.chain = "mangle_forward";
2312 else if (r.src?.any && r.dest?.zone)
2313 r.chain = "mangle_postrouting";
2314 else if (r.src?.zone && r.dest?.any)
2315 r.chain = "mangle_prerouting";
2316 else if (r.src && !r.dest)
2317 r.chain = "mangle_input";
2318 else
2319 r.chain = "mangle_output";
2320
2321 if (r.src?.zone) {
2322 r.src.zone.dflags[r.target] = true;
2323 r.iifnames = null_if_empty(r.src.zone.match_devices);
2324 }
2325
2326 if (r.dest?.zone) {
2327 r.dest.zone.dflags[r.target] = true;
2328 r.oifnames = null_if_empty(r.dest.zone.match_devices);
2329 }
2330 }
2331 else {
2332 r.chain = "output";
2333
2334 if (r.src) {
2335 if (!r.src.any)
2336 r.chain = sprintf("%s_%s", r.dest ? "forward" : "input", r.src.zone.name);
2337 else
2338 r.chain = r.dest ? "forward" : "input";
2339 }
2340
2341 if (r.dest && !r.src) {
2342 if (!r.dest.any)
2343 r.chain = sprintf("output_%s", r.dest.zone.name);
2344 else
2345 r.chain = "output";
2346 }
2347
2348 if (r.dest && !r.dest.any) {
2349 r.jump_chain = sprintf("%s_to_%s", r.target, r.dest.zone.name);
2350 r.dest.zone.dflags[r.target] = true;
2351 }
2352 else if (need_src_action_chain(r)) {
2353 r.jump_chain = sprintf("%s_from_%s", r.target, r.src.zone.name);
2354 r.src.zone.dflags[r.target] = true;
2355 }
2356 else if (r.target == "reject")
2357 r.jump_chain = "handle_reject";
2358 }
2359
2360 if (r.device)
2361 r[r.direction ? "oifnames" : "iifnames"] = [ r.device.device ];
2362
2363 this.state.rules = this.state.rules || [];
2364 push(this.state.rules, r);
2365 };
2366
2367 for (let proto in rule.proto) {
2368 let sip, dip, sports, dports, itypes4, itypes6;
2369 let family = rule.family;
2370
2371 switch (proto.name) {
2372 case "icmp":
2373 itypes4 = filter(rule.icmp_type || [], family_is_ipv4);
2374 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2375 break;
2376
2377 case "ipv6-icmp":
2378 family = 6;
2379 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2380 break;
2381
2382 case "tcp":
2383 case "udp":
2384 sports = rule.src_port;
2385 dports = rule.dest_port;
2386 break;
2387 }
2388
2389 sip = subnets_split_af(rule.src_ip);
2390 dip = subnets_split_af(rule.dest_ip);
2391
2392 family = infer_family(family, [
2393 ipset, "set match",
2394 sip, "source IP",
2395 dip, "destination IP",
2396 rule.src?.zone, "source zone",
2397 rule.dest?.zone, "destination zone",
2398 rule.helper, "helper match",
2399 rule.set_helper, "helper to set"
2400 ]);
2401
2402 if (type(family) == "string") {
2403 this.warn_section(data, family + ", skipping");
2404 continue;
2405 }
2406
2407 let has_ipv4_specifics = (length(sip[0]) || length(dip[0]) || length(itypes4) || rule.dscp !== null);
2408 let has_ipv6_specifics = (length(sip[1]) || length(dip[1]) || length(itypes6) || rule.dscp !== null);
2409
2410 /* if no family was configured, infer target family from IP addresses */
2411 if (family === null) {
2412 if (has_ipv4_specifics && !has_ipv6_specifics)
2413 family = 4;
2414 else if (has_ipv6_specifics && !has_ipv4_specifics)
2415 family = 6;
2416 else
2417 family = 0;
2418 }
2419
2420 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2421 if (!family && rule.target != "dscp" && !has_ipv4_specifics && !has_ipv6_specifics) {
2422 add_rule(0, proto, [], [], sports, dports, null, null, null, rule);
2423 }
2424
2425 /* we need to emit one or two AF specific rules */
2426 else {
2427 if (family == 0 || family == 4) {
2428 let icmp_types = filter(itypes4, i => (i.code_min == 0 && i.code_max == 0xFF));
2429 let icmp_codes = filter(itypes4, i => (i.code_min != 0 || i.code_max != 0xFF));
2430
2431 for (let saddrs in subnets_group_by_masking(sip[0])) {
2432 for (let daddrs in subnets_group_by_masking(dip[0])) {
2433 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2434 add_rule(4, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2435
2436 if (length(icmp_codes))
2437 add_rule(4, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2438 }
2439 }
2440 }
2441
2442 if (family == 0 || family == 6) {
2443 let icmp_types = filter(itypes6, i => (i.code_min == 0 && i.code_max == 0xFF));
2444 let icmp_codes = filter(itypes6, i => (i.code_min != 0 || i.code_max != 0xFF));
2445
2446 for (let saddrs in subnets_group_by_masking(sip[1])) {
2447 for (let daddrs in subnets_group_by_masking(dip[1])) {
2448 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2449 add_rule(6, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2450
2451 if (length(icmp_codes))
2452 add_rule(6, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2453 }
2454 }
2455 }
2456 }
2457 }
2458 },
2459
2460 parse_redirect: function(data) {
2461 let redir = this.parse_options(data, {
2462 enabled: [ "bool", "1" ],
2463
2464 name: [ "string", this.section_id(data[".name"]) ],
2465 _name: [ "string", null, DEPRECATED ],
2466 family: [ "family" ],
2467
2468 src: [ "zone_ref" ],
2469 dest: [ "zone_ref" ],
2470
2471 ipset: [ "setmatch" ],
2472 helper: [ "cthelper", null, NO_INVERT ],
2473
2474 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2475
2476 src_ip: [ "network" ],
2477 src_mac: [ "mac", null, PARSE_LIST ],
2478 src_port: [ "port" ],
2479
2480 src_dip: [ "network" ],
2481 src_dport: [ "port" ],
2482
2483 dest_ip: [ "network" ],
2484 dest_port: [ "port" ],
2485
2486 extra: [ "string", null, UNSUPPORTED ],
2487
2488 limit: [ "limit" ],
2489 limit_burst: [ "int" ],
2490
2491 utc_time: [ "bool" ],
2492 start_date: [ "date" ],
2493 stop_date: [ "date" ],
2494 start_time: [ "time" ],
2495 stop_time: [ "time" ],
2496 weekdays: [ "weekdays" ],
2497 monthdays: [ "monthdays", null, UNSUPPORTED ],
2498
2499 mark: [ "mark" ],
2500
2501 reflection: [ "bool", "1" ],
2502 reflection_src: [ "reflection_source", "internal" ],
2503
2504 reflection_zone: [ "zone_ref", null, PARSE_LIST ],
2505
2506 counter: [ "bool", "1" ],
2507
2508 target: [ "target", "dnat" ]
2509 });
2510
2511 if (redir === false) {
2512 this.warn_section(data, "skipped due to invalid options");
2513 return;
2514 }
2515 else if (!redir.enabled) {
2516 this.warn_section(data, "is disabled, ignoring section");
2517 return;
2518 }
2519
2520 if (!(redir.target in ["dnat", "snat"])) {
2521 this.warn_section(data, "has invalid target specified, defaulting to dnat");
2522 redir.target = "dnat";
2523 }
2524
2525 let ipset;
2526
2527 if (redir.ipset) {
2528 ipset = filter(this.state.ipsets, s => (s.name == redir.ipset.name))[0];
2529
2530 if (!ipset) {
2531 this.warn_section(data, "references unknown set '" + redir.ipset.name + "'");
2532 return;
2533 }
2534
2535 if (('inet_service' in ipset.types) && !ensure_tcpudp(redir.proto)) {
2536 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2537 return;
2538 }
2539 }
2540
2541 let resolve_dest = (redir) => {
2542 for (let zone in this.state.zones) {
2543 for (let zone_addr in zone.related_subnets) {
2544 for (let dest_addr in redir.dest_ip.addrs) {
2545 if (dest_addr.family != zone_addr.family)
2546 continue;
2547
2548 let a = apply_mask(dest_addr.addr, zone_addr.mask);
2549 let b = apply_mask(zone_addr.addr, zone_addr.mask);
2550
2551 if (a != b)
2552 continue;
2553
2554 redir.dest = {
2555 any: false,
2556 zone: zone
2557 };
2558
2559 return true;
2560 }
2561 }
2562 }
2563
2564 return false;
2565 };
2566
2567 if (redir.target == "dnat") {
2568 if (!redir.src)
2569 return this.warn_section(data, "has no source specified");
2570 else if (redir.src.any)
2571 return this.warn_section(data, "must not have source '*' for dnat target");
2572 else if (redir.dest_ip && redir.dest_ip.invert)
2573 return this.warn_section(data, "must not specify a negated 'dest_ip' value");
2574 else if (redir.dest_ip && length(filter(redir.dest_ip.addrs, a => a.bits == -1)))
2575 return this.warn_section(data, "must not use non-contiguous masks in 'dest_ip'");
2576
2577 if (!redir.dest && redir.dest_ip && resolve_dest(redir))
2578 this.warn_section(data, "does not specify a destination, assuming '" + redir.dest.zone.name + "'");
2579
2580 if (!redir.dest_port)
2581 redir.dest_port = redir.src_dport;
2582
2583 if (redir.reflection && redir.dest && redir.dest.zone && redir.src.zone.masq) {
2584 redir.dest.zone.dflags.accept = true;
2585 redir.dest.zone.dflags.dnat = true;
2586 redir.dest.zone.dflags.snat = true;
2587 }
2588
2589 if (redir.helper)
2590 redir.src.zone.dflags.helper = true;
2591
2592 redir.src.zone.dflags[redir.target] = true;
2593 }
2594 else {
2595 if (!redir.dest)
2596 return this.warn_section(data, "has no destination specified");
2597 else if (redir.dest.any)
2598 return this.warn_section(data, "must not have destination '*' for snat target");
2599 else if (!redir.src_dip)
2600 return this.warn_section(data, "has no 'src_dip' option specified");
2601 else if (redir.src_dip.invert)
2602 return this.warn_section(data, "must not specify a negated 'src_dip' value");
2603 else if (length(filter(redir.src_dip.addrs, a => a.bits == -1)))
2604 return this.warn_section(data, "must not use non-contiguous masks in 'src_dip'");
2605 else if (redir.src_mac)
2606 return this.warn_section(data, "must not use 'src_mac' option for snat target");
2607 else if (redir.helper)
2608 return this.warn_section(data, "must not use 'helper' option for snat target");
2609
2610 redir.dest.zone.dflags[redir.target] = true;
2611 }
2612
2613
2614 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, ipset, redir) => {
2615 let r = {
2616 ...redir,
2617
2618 family: family,
2619 proto: proto,
2620 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2621 has_ports: !!(sport || dport || rport),
2622 saddrs_pos: map(saddrs[0], this.cidr),
2623 saddrs_neg: map(saddrs[1], this.cidr),
2624 saddrs_masked: saddrs[2],
2625 daddrs_pos: map(daddrs[0], this.cidr),
2626 daddrs_neg: map(daddrs[1], this.cidr),
2627 daddrs_masked: daddrs[2],
2628 sports_pos: map(filter_pos(to_array(sport)), this.port),
2629 sports_neg: map(filter_neg(to_array(sport)), this.port),
2630 dports_pos: map(filter_pos(to_array(dport)), this.port),
2631 dports_neg: map(filter_neg(to_array(dport)), this.port),
2632 smacs_pos: map(filter_pos(redir.src_mac), m => m.mac),
2633 smacs_neg: map(filter_neg(redir.src_mac), m => m.mac),
2634
2635 raddr: raddrs ? raddrs[0] : null,
2636 rport: rport
2637 };
2638
2639 let set_types = map_setmatch(ipset, redir.ipset, proto.name);
2640
2641 if (set_types !== set_types) {
2642 this.warn_section(data, "destination MAC address matching not supported");
2643 return;
2644 } else if (set_types) {
2645 r.ipset = { ...r.ipset, fields: set_types };
2646 }
2647
2648 switch (r.target) {
2649 case "dnat":
2650 r.chain = sprintf("dstnat_%s", r.src.zone.name);
2651 r.src.zone.dflags.dnat = true;
2652
2653 if (!r.raddr)
2654 r.target = "redirect";
2655
2656 break;
2657
2658 case "snat":
2659 r.chain = sprintf("srcnat_%s", r.dest.zone.name);
2660 r.dest.zone.dflags.snat = true;
2661 break;
2662 }
2663
2664 this.state.redirects = this.state.redirects || [];
2665 push(this.state.redirects, r);
2666 };
2667
2668 let to_hostaddr = (a) => {
2669 let bits = (a.family == 4) ? 32 : 128;
2670
2671 return {
2672 family: a.family,
2673 addr: apply_mask(a.addr, bits),
2674 bits: bits
2675 };
2676 };
2677
2678 for (let proto in redir.proto) {
2679 let sip, dip, rip, iip, eip, refip, sport, dport, rport;
2680 let family = redir.family;
2681
2682 if (proto.name == "ipv6-icmp")
2683 family = 6;
2684
2685 switch (redir.target) {
2686 case "dnat":
2687 sip = subnets_split_af(redir.src_ip);
2688 dip = subnets_split_af(redir.src_dip);
2689 rip = subnets_split_af(redir.dest_ip);
2690
2691 switch (proto.name) {
2692 case "tcp":
2693 case "udp":
2694 sport = redir.src_port;
2695 dport = redir.src_dport;
2696 rport = redir.dest_port;
2697 break;
2698 }
2699
2700 break;
2701
2702 case "snat":
2703 sip = subnets_split_af(redir.src_ip);
2704 dip = subnets_split_af(redir.dest_ip);
2705 rip = subnets_split_af(redir.src_dip);
2706
2707 switch (proto.name) {
2708 case "tcp":
2709 case "udp":
2710 sport = redir.src_port;
2711 dport = redir.dest_port;
2712 rport = redir.src_dport;
2713 break;
2714 }
2715
2716 break;
2717 }
2718
2719 family = infer_family(family, [
2720 ipset, "set match",
2721 sip, "source IP",
2722 dip, "destination IP",
2723 rip, "rewrite IP",
2724 redir.src?.zone, "source zone",
2725 redir.dest?.zone, "destination zone",
2726 redir.helper, "helper match"
2727 ]);
2728
2729 if (type(family) == "string") {
2730 this.warn_section(data, family + ", skipping");
2731 continue;
2732 }
2733
2734 /* build reflection rules */
2735 if (redir.target == "dnat" && redir.reflection &&
2736 (length(rip[0]) || length(rip[1])) && redir.src?.zone && redir.dest?.zone) {
2737 let refredir = {
2738 name: redir.name + " (reflection)",
2739
2740 helper: redir.helper,
2741
2742 // XXX: this likely makes no sense for reflection rules
2743 //src_mac: redir.src_mac,
2744
2745 limit: redir.limit,
2746 limit_burst: redir.limit_burst,
2747
2748 start_date: redir.start_date,
2749 stop_date: redir.stop_date,
2750 start_time: redir.start_time,
2751 stop_time: redir.stop_time,
2752 weekdays: redir.weekdays,
2753
2754 mark: redir.mark
2755 };
2756
2757 let eaddrs = length(dip) ? dip : subnets_split_af({ addrs: map(redir.src.zone.related_subnets, to_hostaddr) });
2758 let rzones = length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
2759
2760 for (let rzone in rzones) {
2761 if (!is_family(rzone, family)) {
2762 this.warn_section(data,
2763 sprintf("is restricted to IPv%d but referenced reflection zone is IPv%d only, skipping",
2764 family, rzone.family));
2765 continue;
2766 }
2767
2768 let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
2769 let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
2770
2771 for (let i = 0; i <= 1; i++) {
2772 if (redir.src.zone[i ? "masq6" : "masq"] && length(rip[i])) {
2773 let snat_addr = refaddrs[i]?.[0];
2774
2775 /* For internal reflection sources try to find a suitable candiate IP
2776 * among the reflection zone subnets which is within the same subnet
2777 * as the original DNAT destination. If we can't find any matching
2778 * one then simply take the first candidate. */
2779 if (redir.reflection_src == "internal") {
2780 for (let zone_addr in rzone.zone.related_subnets) {
2781 if (zone_addr.family != rip[i][0].family)
2782 continue;
2783
2784 let r = apply_mask(rip[i][0].addr, zone_addr.mask);
2785 let a = apply_mask(zone_addr.addr, zone_addr.mask);
2786
2787 if (r != a)
2788 continue;
2789
2790 snat_addr = zone_addr;
2791 break;
2792 }
2793 }
2794
2795 if (!snat_addr) {
2796 this.warn_section(data, (redir.reflection_src || "external") + " rewrite IP cannot be determined, disabling reflection");
2797 }
2798 else if (!length(iaddrs[i])) {
2799 this.warn_section(data, "internal address range cannot be determined, disabling reflection");
2800 }
2801 else if (!length(eaddrs[i])) {
2802 this.warn_section(data, "external address range cannot be determined, disabling reflection");
2803 }
2804 else {
2805 refredir.src = rzone;
2806 refredir.dest = null;
2807 refredir.target = "dnat";
2808
2809 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2810 for (let daddrs in subnets_group_by_masking(eaddrs[i]))
2811 add_rule(i ? 6 : 4, proto, saddrs, daddrs, rip[i], sport, dport, rport, null, refredir);
2812
2813 refredir.src = null;
2814 refredir.dest = rzone;
2815 refredir.target = "snat";
2816
2817 for (let daddrs in subnets_group_by_masking(rip[i]))
2818 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2819 add_rule(i ? 6 : 4, proto, saddrs, daddrs, [ to_hostaddr(snat_addr) ], null, rport, null, null, refredir);
2820 }
2821 }
2822 }
2823 }
2824 }
2825
2826 if (length(rip[0]) > 1 || length(rip[1]) > 1)
2827 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
2828
2829 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2830 if (!family && !length(sip[0]) && !length(sip[1]) && !length(dip[0]) && !length(dip[1]) && !length(rip[0]) && !length(rip[1])) {
2831 /* for backwards compatibility, treat unspecified family as IPv4 unless user explicitly requested any (0) */
2832 if (family == null)
2833 family = 4;
2834
2835 add_rule(family, proto, [], [], null, sport, dport, rport, null, redir);
2836 }
2837
2838 /* we need to emit one or two AF specific rules */
2839 else {
2840 if ((!family || family == 4) && (length(sip[0]) || length(dip[0]) || length(rip[0]))) {
2841 for (let saddrs in subnets_group_by_masking(sip[0]))
2842 for (let daddrs in subnets_group_by_masking(dip[0]))
2843 add_rule(4, proto, saddrs, daddrs, rip[0], sport, dport, rport, ipset, redir);
2844 }
2845
2846 if ((!family || family == 6) && (length(sip[1]) || length(dip[1]) || length(rip[1]))) {
2847 for (let saddrs in subnets_group_by_masking(sip[1]))
2848 for (let daddrs in subnets_group_by_masking(dip[1]))
2849 add_rule(6, proto, saddrs, daddrs, rip[1], sport, dport, rport, ipset, redir);
2850 }
2851 }
2852 }
2853 },
2854
2855 parse_nat: function(data) {
2856 let snat = this.parse_options(data, {
2857 enabled: [ "bool", "1" ],
2858
2859 name: [ "string", this.section_id(data[".name"]) ],
2860 family: [ "family", "4" ],
2861
2862 src: [ "zone_ref" ],
2863 device: [ "string" ],
2864
2865 ipset: [ "setmatch", null, UNSUPPORTED ],
2866
2867 proto: [ "protocol", "all", PARSE_LIST | FLATTEN_LIST ],
2868
2869 src_ip: [ "network" ],
2870 src_port: [ "port" ],
2871
2872 snat_ip: [ "network", null, NO_INVERT ],
2873 snat_port: [ "port", null, NO_INVERT ],
2874
2875 dest_ip: [ "network" ],
2876 dest_port: [ "port" ],
2877
2878 extra: [ "string", null, UNSUPPORTED ],
2879
2880 limit: [ "limit" ],
2881 limit_burst: [ "int" ],
2882
2883 connlimit_ports: [ "bool" ],
2884
2885 utc_time: [ "bool" ],
2886 start_date: [ "date" ],
2887 stop_date: [ "date" ],
2888 start_time: [ "time" ],
2889 stop_time: [ "time" ],
2890 weekdays: [ "weekdays" ],
2891 monthdays: [ "monthdays", null, UNSUPPORTED ],
2892
2893 mark: [ "mark" ],
2894
2895 target: [ "target", "masquerade" ]
2896 });
2897
2898 if (snat === false) {
2899 this.warn_section(data, "skipped due to invalid options");
2900 return;
2901 }
2902 else if (!snat.enabled) {
2903 this.warn_section(data, "is disabled, ignoring section");
2904 return;
2905 }
2906
2907 if (!(snat.target in ["accept", "snat", "masquerade"])) {
2908 this.warn_section(data, "has invalid target specified, defaulting to masquerade");
2909 snat.target = "masquerade";
2910 }
2911
2912 if (snat.target == "snat" && !snat.snat_ip && !snat.snat_port) {
2913 this.warn_section(data, "needs either 'snat_ip' or 'snat_port' for target snat, ignoring section");
2914 return;
2915 }
2916 else if (snat.target != "snat" && snat.snat_ip) {
2917 this.warn_section(data, "must not use 'snat_ip' for non-snat target, ignoring section");
2918 return;
2919 }
2920 else if (snat.target != "snat" && snat.snat_port) {
2921 this.warn_section(data, "must not use 'snat_port' for non-snat target, ignoring section");
2922 return;
2923 }
2924
2925 if ((snat.snat_port || snat.src_port || snat.dest_port) && !ensure_tcpudp(snat.proto)) {
2926 this.warn_section(data, "specifies ports but no UDP/TCP protocol, ignoring section");
2927 return;
2928 }
2929
2930 if (snat.snat_ip && length(filter(snat.snat_ip.addrs, a => a.bits == -1 || a.invert))) {
2931 this.warn_section(data, "must not use inversion or non-contiguous masks in 'snat_ip', ignoring section");
2932 return;
2933 }
2934
2935 if (snat.src && snat.src.zone)
2936 snat.src.zone.dflags.snat = true;
2937
2938 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, snat) => {
2939 let n = {
2940 ...snat,
2941
2942 family: family,
2943 proto: proto,
2944 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2945 has_ports: !!(sport || dport),
2946 saddrs_pos: map(saddrs[0], this.cidr),
2947 saddrs_neg: map(saddrs[1], this.cidr),
2948 saddrs_masked: saddrs[2],
2949 daddrs_pos: map(daddrs[0], this.cidr),
2950 daddrs_neg: map(daddrs[1], this.cidr),
2951 daddrs_masked: daddrs[2],
2952 sports_pos: map(filter_pos(to_array(sport)), this.port),
2953 sports_neg: map(filter_neg(to_array(sport)), this.port),
2954 dports_pos: map(filter_pos(to_array(dport)), this.port),
2955 dports_neg: map(filter_neg(to_array(dport)), this.port),
2956
2957 raddr: raddrs ? raddrs[0] : null,
2958 rport: rport,
2959
2960 chain: (snat.src && snat.src.zone) ? sprintf("srcnat_%s", snat.src.zone.name) : "srcnat"
2961 };
2962
2963 this.state.redirects = this.state.redirects || [];
2964 push(this.state.redirects, n);
2965 };
2966
2967 for (let proto in snat.proto) {
2968 let sip, dip, rip, sport, dport, rport;
2969 let family = snat.family;
2970
2971 sip = subnets_split_af(snat.src_ip);
2972 dip = subnets_split_af(snat.dest_ip);
2973 rip = subnets_split_af(snat.snat_ip);
2974
2975 switch (proto.name) {
2976 case "tcp":
2977 case "udp":
2978 sport = snat.src_port;
2979 dport = snat.dest_port;
2980 rport = snat.snat_port;
2981 break;
2982 }
2983
2984 if (length(rip[0]) > 1 || length(rip[1]) > 1)
2985 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
2986
2987 /* inherit family restrictions from related zones */
2988 if (family === 0 || family === null) {
2989 let f = (rule.src && rule.src.zone) ? rule.src.zone.family : 0;
2990
2991 if (f) {
2992 this.warn_section(r,
2993 sprintf("inheriting %s restriction from src %s",
2994 this.nfproto(f1, true), rule.src.zone.name));
2995
2996 family = f;
2997 }
2998 }
2999
3000 /* if no family was configured, infer target family from IP addresses */
3001 if (family === null) {
3002 if ((length(sip[0]) || length(dip[0]) || length(rip[0])) && !length(sip[1]) && !length(dip[1]) && !length(rip[1]))
3003 family = 4;
3004 else if ((length(sip[1]) || length(dip[1]) || length(rip[1])) && !length(sip[0]) && !length(dip[0]) && !length(rip[0]))
3005 family = 6;
3006 else
3007 family = 0;
3008 }
3009
3010 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
3011 if (!family && !length(sip[0]) && !length(sip[1]) && !length(dip[0]) && !length(dip[1]) && !length(rip[0]) && !length(rip[1])) {
3012 add_rule(0, proto, [], [], null, sport, dport, rport, snat);
3013 }
3014
3015 /* we need to emit one or two AF specific rules */
3016 else {
3017 if (family == 0 || family == 4)
3018 for (let saddr in subnets_group_by_masking(sip[0]))
3019 for (let daddr in subnets_group_by_masking(dip[0]))
3020 add_rule(4, proto, saddr, daddr, rip[0], sport, dport, rport, snat);
3021
3022 if (family == 0 || family == 6)
3023 for (let saddr in subnets_group_by_masking(sip[1]))
3024 for (let daddr in subnets_group_by_masking(dip[1]))
3025 add_rule(6, proto, saddr, daddr, rip[1], sport, dport, rport, snat);
3026 }
3027 }
3028 },
3029
3030 parse_ipset: function(data) {
3031 let ipset = this.parse_options(data, {
3032 enabled: [ "bool", "1" ],
3033 reload_set: [ "bool" ],
3034 counters: [ "bool" ],
3035 comment: [ "bool" ],
3036
3037 name: [ "string", null, REQUIRED ],
3038 family: [ "family", "4" ],
3039
3040 storage: [ "string", null, UNSUPPORTED ],
3041 match: [ "ipsettype", null, PARSE_LIST ],
3042
3043 iprange: [ "string", null, UNSUPPORTED ],
3044 portrange: [ "string", null, UNSUPPORTED ],
3045
3046 netmask: [ "int", null, UNSUPPORTED ],
3047 maxelem: [ "int" ],
3048 hashsize: [ "int", null, UNSUPPORTED ],
3049 timeout: [ "int", "-1" ],
3050
3051 external: [ "string", null, UNSUPPORTED ],
3052
3053 entry: [ "string", null, PARSE_LIST ],
3054 loadfile: [ "string" ]
3055 });
3056
3057 if (ipset === false) {
3058 this.warn_section(data, "skipped due to invalid options");
3059 return;
3060 }
3061 else if (!ipset.enabled) {
3062 this.warn_section(data, "is disabled, ignoring section");
3063 return;
3064 }
3065
3066 if (ipset.family == 0) {
3067 this.warn_section(data, "must not specify family 'any'");
3068 return;
3069 }
3070 else if (!length(ipset.match)) {
3071 this.warn_section(data, "has no datatypes assigned");
3072 return;
3073 }
3074
3075 let dirs = map(ipset.match, m => m[0]),
3076 types = map(ipset.match, m => m[1]),
3077 interval = false;
3078
3079 if ("set" in types) {
3080 this.warn_section(data, "match type 'set' is not supported");
3081 return;
3082 }
3083
3084 if ("net" in types) {
3085 if (this.kernel < 0x05060000) {
3086 this.warn_section(data, "match type 'net' requires kernel 5.6 or later");
3087 return;
3088 }
3089
3090 interval = true;
3091 }
3092
3093 let s = {
3094 ...ipset,
3095
3096 fw4types: types,
3097
3098 types: map(types, (t) => {
3099 switch (t) {
3100 case 'ip':
3101 case 'net':
3102 return (ipset.family == 4) ? 'ipv4_addr' : 'ipv6_addr';
3103
3104 case 'mac':
3105 return 'ether_addr';
3106
3107 case 'port':
3108 return 'inet_service';
3109 }
3110 }),
3111
3112 directions: dirs,
3113 interval: interval
3114 };
3115
3116 let self = this;
3117 s.entries = filter(map(ipset.entry, (e) => {
3118 let v = self.parse_ipsetentry(e, s);
3119
3120 if (!v)
3121 self.warn_section(data, "ignoring invalid ipset entry '" + e + "'");
3122
3123 return v;
3124 }), (e) => (e != null));
3125
3126 this.state.ipsets = this.state.ipsets || [];
3127 push(this.state.ipsets, s);
3128 }
3129 };