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