ruleset: ensure that family-agnostic ICMP rules cover ICMPv6 as well
[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) ?? 0) {
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 l4proto: function(family, proto) {
1620 switch (proto.name) {
1621 case 'icmp':
1622 switch (family ?? 0) {
1623 case 0:
1624 return this.set(['icmp', 'ipv6-icmp']);
1625
1626 case 6:
1627 return 'ipv6-icmp';
1628 }
1629
1630 default:
1631 return proto.name;
1632 }
1633 },
1634
1635 datetime: function(stamp) {
1636 return sprintf('"%04d-%02d-%02d %02d:%02d:%02d"',
1637 stamp.year, stamp.month, stamp.day,
1638 stamp.hour, stamp.min, stamp.sec);
1639 },
1640
1641 date: function(stamp) {
1642 return sprintf('"%04d-%02d-%02d"', stamp.year, stamp.month, stamp.day);
1643 },
1644
1645 time: function(stamp) {
1646 return sprintf('"%02d:%02d:%02d"', stamp.hour, stamp.min, stamp.sec);
1647 },
1648
1649 hex: function(n) {
1650 return sprintf('0x%x', n);
1651 },
1652
1653 is_loopback_dev: function(dev) {
1654 let fd = fs.open(sprintf("/sys/class/net/%s/flags", dev), "r");
1655
1656 if (!fd)
1657 return false;
1658
1659 let flags = +fd.read("line");
1660
1661 fd.close();
1662
1663 return !!(flags & 0x8);
1664 },
1665
1666 is_loopback_addr: function(addr) {
1667 return (index(addr, "127.") == 0 || addr == "::1" || addr == "::1/128");
1668 },
1669
1670 filter_loopback_devs: function(devs, invert) {
1671 return null_if_empty(filter(devs, d => (this.is_loopback_dev(d) == invert)));
1672 },
1673
1674 filter_loopback_addrs: function(addrs, invert) {
1675 return null_if_empty(filter(addrs, a => (this.is_loopback_addr(a) == invert)));
1676 },
1677
1678
1679 input_policy: function(reject_as_drop) {
1680 return (!reject_as_drop || this.state.defaults.input != 'reject') ? this.state.defaults.input : 'drop';
1681 },
1682
1683 output_policy: function(reject_as_drop) {
1684 return (!reject_as_drop || this.state.defaults.output != 'reject') ? this.state.defaults.output : 'drop';
1685 },
1686
1687 forward_policy: function(reject_as_drop) {
1688 return (!reject_as_drop || this.state.defaults.forward != 'reject') ? this.state.defaults.forward : 'drop';
1689 },
1690
1691 default_option: function(flag) {
1692 return this.state.defaults[flag];
1693 },
1694
1695 helpers: function() {
1696 return this.state.helpers;
1697 },
1698
1699 zones: function() {
1700 return this.state.zones;
1701 },
1702
1703 rules: function(chain) {
1704 return filter(this.state.rules, r => (r.chain == chain));
1705 },
1706
1707 redirects: function(chain) {
1708 return filter(this.state.redirects, r => (r.chain == chain));
1709 },
1710
1711 ipsets: function() {
1712 return this.state.ipsets;
1713 },
1714
1715 parse_setfile: function(set, cb) {
1716 let fd = fs.open(set.loadfile, "r");
1717
1718 if (!fd) {
1719 warn(sprintf("Unable to load file '%s' for set '%s': %s\n",
1720 set.loadfile, set.name, fs.error()));
1721 return;
1722 }
1723
1724 let line = null, count = 0;
1725
1726 while ((line = fd.read("line")) !== "") {
1727 line = trim(line);
1728
1729 if (length(line) == 0 || ord(line) == 35)
1730 continue;
1731
1732 let v = this.parse_ipsetentry(line, set);
1733
1734 if (!v) {
1735 this.warn("Skipping invalid entry '%s' in file '%s' for set '%s'",
1736 line, set.loadfile, set.name);
1737 continue;
1738 }
1739
1740 cb(v);
1741
1742 count++;
1743 }
1744
1745 fd.close();
1746
1747 return count;
1748 },
1749
1750 print_setentries: function(set) {
1751 let first = true;
1752 let printer = (entry) => {
1753 if (first) {
1754 print("\t\telements = {\n");
1755 first = false;
1756 }
1757
1758 print("\t\t\t", join(" . ", entry), ",\n");
1759 };
1760
1761 map(set.entries, printer);
1762
1763 if (set.loadfile)
1764 this.parse_setfile(set, printer);
1765
1766 if (!first)
1767 print("\t\t}\n");
1768 },
1769
1770 parse_helper: function(data) {
1771 let helper = this.parse_options(data, {
1772 name: [ "string", null, REQUIRED ],
1773 description: [ "string" ],
1774 module: [ "string" ],
1775 family: [ "family" ],
1776 proto: [ "protocol", null, PARSE_LIST | FLATTEN_LIST | NO_INVERT ],
1777 port: [ "port", null, NO_INVERT ]
1778 });
1779
1780 if (helper === false) {
1781 this.warn("Helper definition '%s' skipped due to invalid options", data.name || data['.name']);
1782 return;
1783 }
1784 else if (helper.proto.any) {
1785 this.warn("Helper definition '%s' must not specify wildcard protocol", data.name || data['.name']);
1786 return;
1787 }
1788 else if (length(helper.proto) > 1) {
1789 this.warn("Helper definition '%s' must not specify multiple protocols", data.name || data['.name']);
1790 return;
1791 }
1792
1793 helper.available = ((fs.stat("/sys/module/" + helper.module) || {}).type == "directory");
1794
1795 this.state.helpers = this.state.helpers || [];
1796 push(this.state.helpers, helper);
1797 },
1798
1799 parse_defaults: function(data) {
1800 if (this.state.defaults) {
1801 this.warn_section(data, ": ignoring duplicate defaults section");
1802 return;
1803 }
1804
1805 let defs = this.parse_options(data, {
1806 input: [ "policy", "drop" ],
1807 output: [ "policy", "drop" ],
1808 forward: [ "policy", "drop" ],
1809
1810 drop_invalid: [ "bool" ],
1811 tcp_reject_code: [ "reject_code", "tcp-reset" ],
1812 any_reject_code: [ "reject_code", "port-unreachable" ],
1813
1814 syn_flood: [ "bool" ],
1815 synflood_protect: [ "bool" ],
1816 synflood_rate: [ "limit", "25/second" ],
1817 synflood_burst: [ "int", "50" ],
1818
1819 tcp_syncookies: [ "bool", "1" ],
1820 tcp_ecn: [ "int" ],
1821 tcp_window_scaling: [ "bool", "1" ],
1822
1823 accept_redirects: [ "bool" ],
1824 accept_source_route: [ "bool" ],
1825
1826 auto_helper: [ "bool", "1" ],
1827 custom_chains: [ "bool", null, UNSUPPORTED ],
1828 disable_ipv6: [ "bool", null, UNSUPPORTED ],
1829 flow_offloading: [ "bool", "0" ],
1830 flow_offloading_hw: [ "bool", "0" ]
1831 });
1832
1833 if (defs.synflood_protect === null)
1834 defs.synflood_protect = defs.syn_flood;
1835
1836 delete defs.syn_flood;
1837
1838 this.state.defaults = defs;
1839 },
1840
1841 parse_zone: function(data) {
1842 let zone = this.parse_options(data, {
1843 enabled: [ "bool", "1" ],
1844
1845 name: [ "string", null, REQUIRED ],
1846 family: [ "family" ],
1847
1848 network: [ "device", null, PARSE_LIST ],
1849 device: [ "device", null, PARSE_LIST ],
1850 subnet: [ "network", null, PARSE_LIST ],
1851
1852 input: [ "policy", this.state.defaults ? this.state.defaults.input : "drop" ],
1853 output: [ "policy", this.state.defaults ? this.state.defaults.output : "drop" ],
1854 forward: [ "policy", this.state.defaults ? this.state.defaults.forward : "drop" ],
1855
1856 masq: [ "bool" ],
1857 masq_allow_invalid: [ "bool" ],
1858 masq_src: [ "network", null, PARSE_LIST ],
1859 masq_dest: [ "network", null, PARSE_LIST ],
1860
1861 masq6: [ "bool" ],
1862
1863 extra: [ "string", null, UNSUPPORTED ],
1864 extra_src: [ "string", null, UNSUPPORTED ],
1865 extra_dest: [ "string", null, UNSUPPORTED ],
1866
1867 mtu_fix: [ "bool" ],
1868 custom_chains: [ "bool", null, UNSUPPORTED ],
1869
1870 log: [ "int" ],
1871 log_limit: [ "limit", null, UNSUPPORTED ],
1872
1873 auto_helper: [ "bool", "1" ],
1874 helper: [ "cthelper", null, PARSE_LIST ],
1875
1876 counter: [ "bool", "1" ]
1877 });
1878
1879 if (zone === false) {
1880 this.warn_section(data, "skipped due to invalid options");
1881 return;
1882 }
1883 else if (!zone.enabled) {
1884 this.warn_section(data, "is disabled, ignoring section");
1885 return;
1886 }
1887 else if (zone.helper && !zone.helper.available) {
1888 this.warn_section(data, "uses unavailable ct helper '" + zone.helper.name + "', ignoring section");
1889 return;
1890 }
1891
1892 if (zone.mtu_fix && this.kernel < 0x040a0000) {
1893 this.warn_section(data, "option 'mtu_fix' requires kernel 4.10 or later");
1894 return;
1895 }
1896
1897 if (this.state.defaults && this.state.defaults.auto_helper === false)
1898 zone.auto_helper = false;
1899
1900 let match_devices = [];
1901 let related_physdevs = [];
1902 let related_subnets = [];
1903 let related_ubus_networks = [];
1904 let match_subnets, masq_src_subnets, masq_dest_subnets;
1905
1906 for (let name, net in this.state.networks) {
1907 if (net.zone === zone.name)
1908 push(related_ubus_networks, { invert: false, device: name });
1909 }
1910
1911 for (let e in [ ...to_array(zone.network), ...related_ubus_networks ]) {
1912 if (exists(this.state.networks, e.device)) {
1913 let net = this.state.networks[e.device];
1914
1915 if (net.device) {
1916 push(match_devices, {
1917 invert: e.invert,
1918 device: net.device
1919 });
1920 }
1921
1922 if (net.physdev && !e.invert)
1923 push(related_physdevs, net.physdev);
1924
1925 push(related_subnets, ...(net.ipaddrs || []));
1926 }
1927 }
1928
1929 push(match_devices, ...to_array(zone.device));
1930
1931 match_subnets = subnets_split_af(zone.subnet);
1932 masq_src_subnets = subnets_split_af(zone.masq_src);
1933 masq_dest_subnets = subnets_split_af(zone.masq_dest);
1934
1935 push(related_subnets, ...(match_subnets[0] || []), ...(match_subnets[1] || []));
1936
1937 let match_rules = [];
1938
1939 let add_rule = (family, devices, subnets, zone) => {
1940 let r = {};
1941
1942 r.family = family;
1943
1944 r.devices_pos = null_if_empty(devices[0]);
1945 r.devices_neg = null_if_empty(devices[1]);
1946 r.devices_neg_wildcard = null_if_empty(devices[2]);
1947
1948 r.subnets_pos = map(subnets[0], this.cidr);
1949 r.subnets_neg = map(subnets[1], this.cidr);
1950 r.subnets_masked = subnets[2];
1951
1952 push(match_rules, r);
1953 };
1954
1955 let family = infer_family(zone.family, [
1956 zone.helper, "ct helper",
1957 match_subnets, "subnet list"
1958 ]);
1959
1960 if (type(family) == "string") {
1961 this.warn_section(data, family + ", skipping");
1962 return;
1963 }
1964
1965 // group non-inverted device matches into wildcard and non-wildcard ones
1966 let devices = [], plain_devices = [], plain_invert_devices = [], wildcard_invert_devices = [];
1967
1968 for (let device in match_devices) {
1969 let m = match(device.device, /^([^+]*)(\+)?$/);
1970
1971 if (!m) {
1972 this.warn_section(data, "skipping invalid wildcard pattern '" + device.device + '"');
1973 continue;
1974 }
1975
1976 // filter `+` (match any device) since nftables does not support
1977 // wildcard only matches
1978 if (!device.invert && m[0] == '+')
1979 continue;
1980
1981 // replace inverted `+` (match no device) with invalid pattern
1982 if (device.invert && m[0] == '+') {
1983 device.device = '/never/';
1984 device.invert = false;
1985 }
1986
1987 // replace "name+" matches with "name*"
1988 else if (m[2] == '+')
1989 device.device = m[1] + '*';
1990
1991 device.wildcard = !!m[2];
1992
1993 if (!device.invert && device.wildcard)
1994 push(devices, [ [ device.device ], plain_invert_devices, wildcard_invert_devices ]);
1995 else if (!device.invert)
1996 push(plain_devices, device.device);
1997 else if (device.wildcard)
1998 push(wildcard_invert_devices, device.device);
1999 else
2000 push(plain_invert_devices, device.device);
2001 }
2002
2003 if (length(plain_devices))
2004 push(devices, [
2005 plain_devices,
2006 plain_invert_devices,
2007 wildcard_invert_devices
2008 ]);
2009 else if (!length(devices))
2010 push(devices, [
2011 null,
2012 plain_invert_devices,
2013 wildcard_invert_devices
2014 ]);
2015
2016 // emit zone jump rules for each device group
2017 if (length(match_devices) || length(match_subnets[0]) || length(match_subnets[1])) {
2018 for (let devgroup in devices) {
2019 // check if there's no AF specific bits, in this case we can do AF agnostic matching
2020 if (!family && !length(match_subnets[0]) && !length(match_subnets[1])) {
2021 add_rule(0, devgroup, [], zone);
2022 }
2023
2024 // we need to emit one or two AF specific rules
2025 else {
2026 if (family_is_ipv4(zone) && length(match_subnets[0]))
2027 for (let subnets in subnets_group_by_masking(match_subnets[0]))
2028 add_rule(4, devgroup, subnets, zone);
2029
2030 if (family_is_ipv6(zone) && length(match_subnets[1]))
2031 for (let subnets in subnets_group_by_masking(match_subnets[1]))
2032 add_rule(6, devgroup, subnets, zone);
2033 }
2034 }
2035 }
2036
2037 zone.family = family;
2038
2039 zone.match_rules = match_rules;
2040
2041 zone.masq4_src_subnets = subnets_group_by_masking(masq_src_subnets[0]);
2042 zone.masq4_dest_subnets = subnets_group_by_masking(masq_dest_subnets[0]);
2043
2044 zone.masq6_src_subnets = subnets_group_by_masking(masq_src_subnets[1]);
2045 zone.masq6_dest_subnets = subnets_group_by_masking(masq_dest_subnets[1]);
2046
2047 zone.sflags = {};
2048 zone.sflags[zone.input] = true;
2049
2050 zone.dflags = {};
2051 zone.dflags[zone.output] = true;
2052 zone.dflags[zone.forward] = true;
2053
2054 zone.match_devices = map(filter(match_devices, d => !d.invert), d => d.device);
2055 zone.match_subnets = map(filter(related_subnets, s => !s.invert && s.bits != -1), this.cidr);
2056
2057 zone.related_subnets = related_subnets;
2058 zone.related_physdevs = related_physdevs;
2059
2060 if (zone.masq || zone.masq6)
2061 zone.dflags.snat = true;
2062
2063 if ((zone.auto_helper && !(zone.masq || zone.masq6)) || length(zone.helper)) {
2064 zone.dflags.helper = true;
2065
2066 for (let helper in (length(zone.helper) ? zone.helper : this.state.helpers)) {
2067 if (!helper.available)
2068 continue;
2069
2070 for (let proto in helper.proto) {
2071 this.state.rules = this.state.rules || [];
2072 push(this.state.rules, {
2073 chain: "helper_" + zone.name,
2074 family: helper.family,
2075 name: helper.description || helper.name,
2076 proto: proto,
2077 src: zone,
2078 dports_pos: [ this.port(helper.port) ],
2079 target: "helper",
2080 set_helper: helper
2081 });
2082 }
2083 }
2084 }
2085
2086 this.state.zones = this.state.zones || [];
2087 push(this.state.zones, zone);
2088 },
2089
2090 parse_forwarding: function(data) {
2091 let fwd = this.parse_options(data, {
2092 enabled: [ "bool", "1" ],
2093
2094 name: [ "string" ],
2095 family: [ "family" ],
2096
2097 src: [ "zone_ref", null, REQUIRED ],
2098 dest: [ "zone_ref", null, REQUIRED ]
2099 });
2100
2101 if (fwd === false) {
2102 this.warn_section(data, "skipped due to invalid options");
2103 return;
2104 }
2105 else if (!fwd.enabled) {
2106 this.warn_section(data, "is disabled, ignoring section");
2107 return;
2108 }
2109
2110 let add_rule = (family, fwd) => {
2111 let f = {
2112 ...fwd,
2113
2114 family: family,
2115 proto: { any: true }
2116 };
2117
2118 f.name = fwd.name || sprintf("Accept %s to %s forwarding",
2119 fwd.src.any ? "any" : fwd.src.zone.name,
2120 fwd.dest.any ? "any" : fwd.dest.zone.name);
2121
2122 f.chain = fwd.src.any ? "forward" : sprintf("forward_%s", fwd.src.zone.name);
2123
2124 if (fwd.dest.any)
2125 f.target = "accept";
2126 else
2127 f.jump_chain = sprintf("accept_to_%s", fwd.dest.zone.name);
2128
2129 this.state.rules = this.state.rules || [];
2130 push(this.state.rules, f);
2131 };
2132
2133
2134 let family = fwd.family;
2135
2136 /* inherit family restrictions from related zones */
2137 if (family === 0 || family === null) {
2138 let f1 = fwd.src.zone ? fwd.src.zone.family : 0;
2139 let f2 = fwd.dest.zone ? fwd.dest.zone.family : 0;
2140
2141 if (f1 && f2 && f1 != f2) {
2142 this.warn_section(data,
2143 sprintf("references src %s restricted to %s and dest %s restricted to %s, ignoring forwarding",
2144 fwd.src.zone.name, this.nfproto(f1, true),
2145 fwd.dest.zone.name, this.nfproto(f2, true)));
2146
2147 return;
2148 }
2149 else if (f1) {
2150 this.warn_section(data,
2151 sprintf("inheriting %s restriction from src %s",
2152 this.nfproto(f1, true), fwd.src.zone.name));
2153
2154 family = f1;
2155 }
2156 else if (f2) {
2157 this.warn_section(data,
2158 sprintf("inheriting %s restriction from dest %s",
2159 this.nfproto(f2, true), fwd.dest.zone.name));
2160
2161 family = f2;
2162 }
2163 }
2164
2165 add_rule(family, fwd);
2166
2167 if (fwd.dest.zone)
2168 fwd.dest.zone.dflags.accept = true;
2169 },
2170
2171 parse_rule: function(data) {
2172 let rule = this.parse_options(data, {
2173 enabled: [ "bool", "1" ],
2174
2175 name: [ "string", this.section_id(data[".name"]) ],
2176 _name: [ "string", null, DEPRECATED ],
2177 family: [ "family" ],
2178
2179 src: [ "zone_ref" ],
2180 dest: [ "zone_ref" ],
2181
2182 device: [ "device", null, NO_INVERT ],
2183 direction: [ "direction" ],
2184
2185 ipset: [ "setmatch" ],
2186 helper: [ "cthelper" ],
2187 set_helper: [ "cthelper", null, NO_INVERT ],
2188
2189 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2190
2191 src_ip: [ "network", null, PARSE_LIST ],
2192 src_mac: [ "mac", null, PARSE_LIST ],
2193 src_port: [ "port", null, PARSE_LIST ],
2194
2195 dest_ip: [ "network", null, PARSE_LIST ],
2196 dest_port: [ "port", null, PARSE_LIST ],
2197
2198 icmp_type: [ "icmptype", null, PARSE_LIST ],
2199 extra: [ "string", null, UNSUPPORTED ],
2200
2201 limit: [ "limit" ],
2202 limit_burst: [ "int" ],
2203
2204 utc_time: [ "bool" ],
2205 start_date: [ "date" ],
2206 stop_date: [ "date" ],
2207 start_time: [ "time" ],
2208 stop_time: [ "time" ],
2209 weekdays: [ "weekdays" ],
2210 monthdays: [ "monthdays", null, UNSUPPORTED ],
2211
2212 mark: [ "mark" ],
2213 set_mark: [ "mark", null, NO_INVERT ],
2214 set_xmark: [ "mark", null, NO_INVERT ],
2215
2216 dscp: [ "dscp" ],
2217 set_dscp: [ "dscp", null, NO_INVERT ],
2218
2219 counter: [ "bool", "1" ],
2220
2221 target: [ "target" ]
2222 });
2223
2224 if (rule === false) {
2225 this.warn_section(data, "skipped due to invalid options");
2226 return;
2227 }
2228 else if (!rule.enabled) {
2229 this.warn_section(data, "is disabled, ignoring section");
2230 return;
2231 }
2232
2233 if (rule.target in ["helper", "notrack"] && (!rule.src || !rule.src.zone)) {
2234 this.warn_section(data, "must specify a source zone for target '" + rule.target + "'");
2235 return;
2236 }
2237 else if (rule.target == "dscp" && !rule.set_dscp) {
2238 this.warn_section(data, "must specify option 'set_dscp' for target 'dscp'");
2239 return;
2240 }
2241 else if (rule.target == "mark" && !rule.set_mark && !rule.set_xmark) {
2242 this.warn_section(data, "must specify option 'set_mark' or 'set_xmark' for target 'mark'");
2243 return;
2244 }
2245 else if (rule.target == "helper" && !rule.set_helper) {
2246 this.warn_section(data, "must specify option 'set_helper' for target 'helper'");
2247 return;
2248 }
2249 else if (rule.device?.any) {
2250 this.warn_section(data, "must not specify '*' as device");
2251 return;
2252 }
2253
2254 let ipset;
2255
2256 if (rule.ipset) {
2257 ipset = filter(this.state.ipsets, s => (s.name == rule.ipset.name))[0];
2258
2259 if (!ipset) {
2260 this.warn_section(data, "references unknown set '" + rule.ipset.name + "'");
2261 return;
2262 }
2263
2264 if (('inet_service' in ipset.types) && !ensure_tcpudp(rule.proto)) {
2265 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2266 return;
2267 }
2268 }
2269
2270 let need_src_action_chain = (rule) => (rule.src && rule.src.zone && rule.src.zone.log && rule.target != "accept");
2271
2272 let add_rule = (family, proto, saddrs, daddrs, sports, dports, icmptypes, icmpcodes, ipset, rule) => {
2273 let r = {
2274 ...rule,
2275
2276 family: family,
2277 proto: proto,
2278 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2279 has_ports: !!(length(sports) || length(dports)),
2280 saddrs_pos: map(saddrs[0], this.cidr),
2281 saddrs_neg: map(saddrs[1], this.cidr),
2282 saddrs_masked: saddrs[2],
2283 daddrs_pos: map(daddrs[0], this.cidr),
2284 daddrs_neg: map(daddrs[1], this.cidr),
2285 daddrs_masked: daddrs[2],
2286 sports_pos: map(filter_pos(sports), this.port),
2287 sports_neg: map(filter_neg(sports), this.port),
2288 dports_pos: map(filter_pos(dports), this.port),
2289 dports_neg: map(filter_neg(dports), this.port),
2290 smacs_pos: map(filter_pos(rule.src_mac), m => m.mac),
2291 smacs_neg: map(filter_neg(rule.src_mac), m => m.mac),
2292 icmp_types: map(icmptypes, i => (family == 4 ? i.type : i.type6)),
2293 icmp_codes: map(icmpcodes, ic => sprintf('%d . %d', (family == 4) ? ic.type : ic.type6, (family == 4) ? ic.code_min : ic.code6_min))
2294 };
2295
2296 if (!length(r.icmp_types))
2297 delete r.icmp_types;
2298
2299 if (!length(r.icmp_codes))
2300 delete r.icmp_codes;
2301
2302 if (r.set_mark) {
2303 r.set_xmark = {
2304 invert: r.set_mark.invert,
2305 mark: r.set_mark.mark,
2306 mask: r.set_mark.mark | r.set_mark.mask
2307 };
2308
2309 delete r.set_mark;
2310 }
2311
2312 let set_types = map_setmatch(ipset, rule.ipset, proto.name);
2313
2314 if (set_types !== set_types) {
2315 this.warn_section(data, "destination MAC address matching not supported");
2316 return;
2317 } else if (set_types) {
2318 r.ipset = { ...r.ipset, fields: set_types };
2319 }
2320
2321 if (r.target == "notrack") {
2322 r.chain = sprintf("notrack_%s", r.src.zone.name);
2323 r.src.zone.dflags.notrack = true;
2324 }
2325 else if (r.target == "helper") {
2326 r.chain = sprintf("helper_%s", r.src.zone.name);
2327 r.src.zone.dflags.helper = true;
2328 }
2329 else if (r.target == "mark" || r.target == "dscp") {
2330 if ((r.src?.any && r.dest?.any) || (r.src?.zone && r.dest?.zone))
2331 r.chain = "mangle_forward";
2332 else if (r.src?.any && r.dest?.zone)
2333 r.chain = "mangle_postrouting";
2334 else if (r.src?.zone && r.dest?.any)
2335 r.chain = "mangle_prerouting";
2336 else if (r.src && !r.dest)
2337 r.chain = "mangle_input";
2338 else
2339 r.chain = "mangle_output";
2340
2341 if (r.src?.zone) {
2342 r.src.zone.dflags[r.target] = true;
2343 r.iifnames = null_if_empty(r.src.zone.match_devices);
2344 }
2345
2346 if (r.dest?.zone) {
2347 r.dest.zone.dflags[r.target] = true;
2348 r.oifnames = null_if_empty(r.dest.zone.match_devices);
2349 }
2350 }
2351 else {
2352 r.chain = "output";
2353
2354 if (r.src) {
2355 if (!r.src.any)
2356 r.chain = sprintf("%s_%s", r.dest ? "forward" : "input", r.src.zone.name);
2357 else
2358 r.chain = r.dest ? "forward" : "input";
2359 }
2360
2361 if (r.dest && !r.src) {
2362 if (!r.dest.any)
2363 r.chain = sprintf("output_%s", r.dest.zone.name);
2364 else
2365 r.chain = "output";
2366 }
2367
2368 if (r.dest && !r.dest.any) {
2369 r.jump_chain = sprintf("%s_to_%s", r.target, r.dest.zone.name);
2370 r.dest.zone.dflags[r.target] = true;
2371 }
2372 else if (need_src_action_chain(r)) {
2373 r.jump_chain = sprintf("%s_from_%s", r.target, r.src.zone.name);
2374 r.src.zone.sflags[r.target] = true;
2375 }
2376 else if (r.target == "reject")
2377 r.jump_chain = "handle_reject";
2378 }
2379
2380 if (r.device)
2381 r[r.direction ? "oifnames" : "iifnames"] = [ r.device.device ];
2382
2383 this.state.rules = this.state.rules || [];
2384 push(this.state.rules, r);
2385 };
2386
2387 for (let proto in rule.proto) {
2388 let sip, dip, sports, dports, itypes4, itypes6;
2389 let family = rule.family;
2390
2391 switch (proto.name) {
2392 case "icmp":
2393 itypes4 = filter(rule.icmp_type || [], family_is_ipv4);
2394 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2395 break;
2396
2397 case "ipv6-icmp":
2398 family = 6;
2399 itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
2400 break;
2401
2402 case "tcp":
2403 case "udp":
2404 sports = rule.src_port;
2405 dports = rule.dest_port;
2406 break;
2407 }
2408
2409 sip = subnets_split_af(rule.src_ip);
2410 dip = subnets_split_af(rule.dest_ip);
2411
2412 family = infer_family(family, [
2413 ipset, "set match",
2414 sip, "source IP",
2415 dip, "destination IP",
2416 rule.src?.zone, "source zone",
2417 rule.dest?.zone, "destination zone",
2418 rule.helper, "helper match",
2419 rule.set_helper, "helper to set"
2420 ]);
2421
2422 if (type(family) == "string") {
2423 this.warn_section(data, family + ", skipping");
2424 continue;
2425 }
2426
2427 let has_ipv4_specifics = (length(sip[0]) || length(dip[0]) || length(itypes4) || rule.dscp !== null);
2428 let has_ipv6_specifics = (length(sip[1]) || length(dip[1]) || length(itypes6) || rule.dscp !== null);
2429
2430 /* if no family was configured, infer target family from IP addresses */
2431 if (family === null) {
2432 if (has_ipv4_specifics && !has_ipv6_specifics)
2433 family = 4;
2434 else if (has_ipv6_specifics && !has_ipv4_specifics)
2435 family = 6;
2436 else
2437 family = 0;
2438 }
2439
2440 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2441 if (!family && rule.target != "dscp" && !has_ipv4_specifics && !has_ipv6_specifics) {
2442 add_rule(0, proto, [], [], sports, dports, null, null, null, rule);
2443 }
2444
2445 /* we need to emit one or two AF specific rules */
2446 else {
2447 if (family == 0 || family == 4) {
2448 let icmp_types = filter(itypes4, i => (i.code_min == 0 && i.code_max == 0xFF));
2449 let icmp_codes = filter(itypes4, i => (i.code_min != 0 || i.code_max != 0xFF));
2450
2451 for (let saddrs in subnets_group_by_masking(sip[0])) {
2452 for (let daddrs in subnets_group_by_masking(dip[0])) {
2453 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2454 add_rule(4, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2455
2456 if (length(icmp_codes))
2457 add_rule(4, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2458 }
2459 }
2460 }
2461
2462 if (family == 0 || family == 6) {
2463 let icmp_types = filter(itypes6, i => (i.code_min == 0 && i.code_max == 0xFF));
2464 let icmp_codes = filter(itypes6, i => (i.code_min != 0 || i.code_max != 0xFF));
2465
2466 for (let saddrs in subnets_group_by_masking(sip[1])) {
2467 for (let daddrs in subnets_group_by_masking(dip[1])) {
2468 if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
2469 add_rule(6, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
2470
2471 if (length(icmp_codes))
2472 add_rule(6, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
2473 }
2474 }
2475 }
2476 }
2477 }
2478 },
2479
2480 parse_redirect: function(data) {
2481 let redir = this.parse_options(data, {
2482 enabled: [ "bool", "1" ],
2483
2484 name: [ "string", this.section_id(data[".name"]) ],
2485 _name: [ "string", null, DEPRECATED ],
2486 family: [ "family" ],
2487
2488 src: [ "zone_ref" ],
2489 dest: [ "zone_ref" ],
2490
2491 ipset: [ "setmatch" ],
2492 helper: [ "cthelper", null, NO_INVERT ],
2493
2494 proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
2495
2496 src_ip: [ "network" ],
2497 src_mac: [ "mac", null, PARSE_LIST ],
2498 src_port: [ "port" ],
2499
2500 src_dip: [ "network" ],
2501 src_dport: [ "port" ],
2502
2503 dest_ip: [ "network" ],
2504 dest_port: [ "port" ],
2505
2506 extra: [ "string", null, UNSUPPORTED ],
2507
2508 limit: [ "limit" ],
2509 limit_burst: [ "int" ],
2510
2511 utc_time: [ "bool" ],
2512 start_date: [ "date" ],
2513 stop_date: [ "date" ],
2514 start_time: [ "time" ],
2515 stop_time: [ "time" ],
2516 weekdays: [ "weekdays" ],
2517 monthdays: [ "monthdays", null, UNSUPPORTED ],
2518
2519 mark: [ "mark" ],
2520
2521 reflection: [ "bool", "1" ],
2522 reflection_src: [ "reflection_source", "internal" ],
2523
2524 reflection_zone: [ "zone_ref", null, PARSE_LIST ],
2525
2526 counter: [ "bool", "1" ],
2527
2528 target: [ "target", "dnat" ]
2529 });
2530
2531 if (redir === false) {
2532 this.warn_section(data, "skipped due to invalid options");
2533 return;
2534 }
2535 else if (!redir.enabled) {
2536 this.warn_section(data, "is disabled, ignoring section");
2537 return;
2538 }
2539
2540 if (!(redir.target in ["dnat", "snat"])) {
2541 this.warn_section(data, "has invalid target specified, defaulting to dnat");
2542 redir.target = "dnat";
2543 }
2544
2545 let ipset;
2546
2547 if (redir.ipset) {
2548 ipset = filter(this.state.ipsets, s => (s.name == redir.ipset.name))[0];
2549
2550 if (!ipset) {
2551 this.warn_section(data, "references unknown set '" + redir.ipset.name + "'");
2552 return;
2553 }
2554
2555 if (('inet_service' in ipset.types) && !ensure_tcpudp(redir.proto)) {
2556 this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
2557 return;
2558 }
2559 }
2560
2561 let resolve_dest = (redir) => {
2562 for (let zone in this.state.zones) {
2563 for (let zone_addr in zone.related_subnets) {
2564 for (let dest_addr in redir.dest_ip.addrs) {
2565 if (dest_addr.family != zone_addr.family)
2566 continue;
2567
2568 let a = apply_mask(dest_addr.addr, zone_addr.mask);
2569 let b = apply_mask(zone_addr.addr, zone_addr.mask);
2570
2571 if (a != b)
2572 continue;
2573
2574 redir.dest = {
2575 any: false,
2576 zone: zone
2577 };
2578
2579 return true;
2580 }
2581 }
2582 }
2583
2584 return false;
2585 };
2586
2587 if (redir.target == "dnat") {
2588 if (!redir.src)
2589 return this.warn_section(data, "has no source specified");
2590 else if (redir.src.any)
2591 return this.warn_section(data, "must not have source '*' for dnat target");
2592 else if (redir.dest_ip && redir.dest_ip.invert)
2593 return this.warn_section(data, "must not specify a negated 'dest_ip' value");
2594 else if (redir.dest_ip && length(filter(redir.dest_ip.addrs, a => a.bits == -1)))
2595 return this.warn_section(data, "must not use non-contiguous masks in 'dest_ip'");
2596
2597 if (!redir.dest && redir.dest_ip && resolve_dest(redir))
2598 this.warn_section(data, "does not specify a destination, assuming '" + redir.dest.zone.name + "'");
2599
2600 if (!redir.dest_port)
2601 redir.dest_port = redir.src_dport;
2602
2603 if (redir.reflection && redir.dest && redir.dest.zone && redir.src.zone.masq) {
2604 redir.dest.zone.dflags.accept = true;
2605 redir.dest.zone.dflags.dnat = true;
2606 redir.dest.zone.dflags.snat = true;
2607 }
2608
2609 if (redir.helper)
2610 redir.src.zone.dflags.helper = true;
2611
2612 redir.src.zone.dflags[redir.target] = true;
2613 }
2614 else {
2615 if (!redir.dest)
2616 return this.warn_section(data, "has no destination specified");
2617 else if (redir.dest.any)
2618 return this.warn_section(data, "must not have destination '*' for snat target");
2619 else if (!redir.src_dip)
2620 return this.warn_section(data, "has no 'src_dip' option specified");
2621 else if (redir.src_dip.invert)
2622 return this.warn_section(data, "must not specify a negated 'src_dip' value");
2623 else if (length(filter(redir.src_dip.addrs, a => a.bits == -1)))
2624 return this.warn_section(data, "must not use non-contiguous masks in 'src_dip'");
2625 else if (redir.src_mac)
2626 return this.warn_section(data, "must not use 'src_mac' option for snat target");
2627 else if (redir.helper)
2628 return this.warn_section(data, "must not use 'helper' option for snat target");
2629
2630 redir.dest.zone.dflags[redir.target] = true;
2631 }
2632
2633
2634 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, ipset, redir) => {
2635 let r = {
2636 ...redir,
2637
2638 family: family,
2639 proto: proto,
2640 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2641 has_ports: !!(sport || dport || rport),
2642 saddrs_pos: map(saddrs[0], this.cidr),
2643 saddrs_neg: map(saddrs[1], this.cidr),
2644 saddrs_masked: saddrs[2],
2645 daddrs_pos: map(daddrs[0], this.cidr),
2646 daddrs_neg: map(daddrs[1], this.cidr),
2647 daddrs_masked: daddrs[2],
2648 sports_pos: map(filter_pos(to_array(sport)), this.port),
2649 sports_neg: map(filter_neg(to_array(sport)), this.port),
2650 dports_pos: map(filter_pos(to_array(dport)), this.port),
2651 dports_neg: map(filter_neg(to_array(dport)), this.port),
2652 smacs_pos: map(filter_pos(redir.src_mac), m => m.mac),
2653 smacs_neg: map(filter_neg(redir.src_mac), m => m.mac),
2654
2655 raddr: raddrs ? raddrs[0] : null,
2656 rport: rport
2657 };
2658
2659 let set_types = map_setmatch(ipset, redir.ipset, proto.name);
2660
2661 if (set_types !== set_types) {
2662 this.warn_section(data, "destination MAC address matching not supported");
2663 return;
2664 } else if (set_types) {
2665 r.ipset = { ...r.ipset, fields: set_types };
2666 }
2667
2668 switch (r.target) {
2669 case "dnat":
2670 r.chain = sprintf("dstnat_%s", r.src.zone.name);
2671 r.src.zone.dflags.dnat = true;
2672
2673 if (!r.raddr)
2674 r.target = "redirect";
2675
2676 break;
2677
2678 case "snat":
2679 r.chain = sprintf("srcnat_%s", r.dest.zone.name);
2680 r.dest.zone.dflags.snat = true;
2681 break;
2682 }
2683
2684 this.state.redirects = this.state.redirects || [];
2685 push(this.state.redirects, r);
2686 };
2687
2688 let to_hostaddr = (a) => {
2689 let bits = (a.family == 4) ? 32 : 128;
2690
2691 return {
2692 family: a.family,
2693 addr: apply_mask(a.addr, bits),
2694 bits: bits
2695 };
2696 };
2697
2698 for (let proto in redir.proto) {
2699 let sip, dip, rip, iip, eip, refip, sport, dport, rport;
2700 let family = redir.family;
2701
2702 if (proto.name == "ipv6-icmp")
2703 family = 6;
2704
2705 switch (redir.target) {
2706 case "dnat":
2707 sip = subnets_split_af(redir.src_ip);
2708 dip = subnets_split_af(redir.src_dip);
2709 rip = subnets_split_af(redir.dest_ip);
2710
2711 switch (proto.name) {
2712 case "tcp":
2713 case "udp":
2714 sport = redir.src_port;
2715 dport = redir.src_dport;
2716 rport = redir.dest_port;
2717 break;
2718 }
2719
2720 break;
2721
2722 case "snat":
2723 sip = subnets_split_af(redir.src_ip);
2724 dip = subnets_split_af(redir.dest_ip);
2725 rip = subnets_split_af(redir.src_dip);
2726
2727 switch (proto.name) {
2728 case "tcp":
2729 case "udp":
2730 sport = redir.src_port;
2731 dport = redir.dest_port;
2732 rport = redir.src_dport;
2733 break;
2734 }
2735
2736 break;
2737 }
2738
2739 family = infer_family(family, [
2740 ipset, "set match",
2741 sip, "source IP",
2742 dip, "destination IP",
2743 rip, "rewrite IP",
2744 redir.src?.zone, "source zone",
2745 redir.dest?.zone, "destination zone",
2746 redir.helper, "helper match"
2747 ]);
2748
2749 if (type(family) == "string") {
2750 this.warn_section(data, family + ", skipping");
2751 continue;
2752 }
2753
2754 /* build reflection rules */
2755 if (redir.target == "dnat" && redir.reflection &&
2756 (length(rip[0]) || length(rip[1])) && redir.src?.zone && redir.dest?.zone) {
2757 let refredir = {
2758 name: redir.name + " (reflection)",
2759
2760 helper: redir.helper,
2761
2762 // XXX: this likely makes no sense for reflection rules
2763 //src_mac: redir.src_mac,
2764
2765 limit: redir.limit,
2766 limit_burst: redir.limit_burst,
2767
2768 start_date: redir.start_date,
2769 stop_date: redir.stop_date,
2770 start_time: redir.start_time,
2771 stop_time: redir.stop_time,
2772 weekdays: redir.weekdays,
2773
2774 mark: redir.mark
2775 };
2776
2777 let eaddrs = length(dip) ? dip : subnets_split_af({ addrs: map(redir.src.zone.related_subnets, to_hostaddr) });
2778 let rzones = length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
2779
2780 for (let rzone in rzones) {
2781 if (!is_family(rzone, family)) {
2782 this.warn_section(data,
2783 sprintf("is restricted to IPv%d but referenced reflection zone is IPv%d only, skipping",
2784 family, rzone.family));
2785 continue;
2786 }
2787
2788 let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
2789 let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
2790
2791 for (let i = 0; i <= 1; i++) {
2792 if (redir.src.zone[i ? "masq6" : "masq"] && length(rip[i])) {
2793 let snat_addr = refaddrs[i]?.[0];
2794
2795 /* For internal reflection sources try to find a suitable candiate IP
2796 * among the reflection zone subnets which is within the same subnet
2797 * as the original DNAT destination. If we can't find any matching
2798 * one then simply take the first candidate. */
2799 if (redir.reflection_src == "internal") {
2800 for (let zone_addr in rzone.zone.related_subnets) {
2801 if (zone_addr.family != rip[i][0].family)
2802 continue;
2803
2804 let r = apply_mask(rip[i][0].addr, zone_addr.mask);
2805 let a = apply_mask(zone_addr.addr, zone_addr.mask);
2806
2807 if (r != a)
2808 continue;
2809
2810 snat_addr = zone_addr;
2811 break;
2812 }
2813 }
2814
2815 if (!snat_addr) {
2816 this.warn_section(data, (redir.reflection_src || "external") + " rewrite IP cannot be determined, disabling reflection");
2817 }
2818 else if (!length(iaddrs[i])) {
2819 this.warn_section(data, "internal address range cannot be determined, disabling reflection");
2820 }
2821 else if (!length(eaddrs[i])) {
2822 this.warn_section(data, "external address range cannot be determined, disabling reflection");
2823 }
2824 else {
2825 refredir.src = rzone;
2826 refredir.dest = null;
2827 refredir.target = "dnat";
2828
2829 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2830 for (let daddrs in subnets_group_by_masking(eaddrs[i]))
2831 add_rule(i ? 6 : 4, proto, saddrs, daddrs, rip[i], sport, dport, rport, null, refredir);
2832
2833 refredir.src = null;
2834 refredir.dest = rzone;
2835 refredir.target = "snat";
2836
2837 for (let daddrs in subnets_group_by_masking(rip[i]))
2838 for (let saddrs in subnets_group_by_masking(iaddrs[i]))
2839 add_rule(i ? 6 : 4, proto, saddrs, daddrs, [ to_hostaddr(snat_addr) ], null, rport, null, null, refredir);
2840 }
2841 }
2842 }
2843 }
2844 }
2845
2846 if (length(rip[0]) > 1 || length(rip[1]) > 1)
2847 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
2848
2849 let has_ip4_addr = length(sip[0]) || length(dip[0]) || length(rip[0]),
2850 has_ip6_addr = length(sip[1]) || length(dip[1]) || length(rip[1]),
2851 has_any_addr = has_ip4_addr || has_ip6_addr;
2852
2853 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
2854 if (!family && !has_any_addr) {
2855 /* for backwards compatibility, treat unspecified family as IPv4 unless user explicitly requested any (0) */
2856 if (family == null)
2857 family = 4;
2858
2859 add_rule(family, proto, [], [], null, sport, dport, rport, null, redir);
2860 }
2861
2862 /* we need to emit one or two AF specific rules */
2863 else {
2864 if ((!family || family == 4) && (!has_any_addr || has_ip4_addr)) {
2865 for (let saddrs in subnets_group_by_masking(sip[0]))
2866 for (let daddrs in subnets_group_by_masking(dip[0]))
2867 add_rule(4, proto, saddrs, daddrs, rip[0], sport, dport, rport, ipset, redir);
2868 }
2869
2870 if ((!family || family == 6) && (!has_any_addr || has_ip6_addr)) {
2871 for (let saddrs in subnets_group_by_masking(sip[1]))
2872 for (let daddrs in subnets_group_by_masking(dip[1]))
2873 add_rule(6, proto, saddrs, daddrs, rip[1], sport, dport, rport, ipset, redir);
2874 }
2875 }
2876 }
2877 },
2878
2879 parse_nat: function(data) {
2880 let snat = this.parse_options(data, {
2881 enabled: [ "bool", "1" ],
2882
2883 name: [ "string", this.section_id(data[".name"]) ],
2884 family: [ "family", "4" ],
2885
2886 src: [ "zone_ref" ],
2887 device: [ "string" ],
2888
2889 ipset: [ "setmatch", null, UNSUPPORTED ],
2890
2891 proto: [ "protocol", "all", PARSE_LIST | FLATTEN_LIST ],
2892
2893 src_ip: [ "network" ],
2894 src_port: [ "port" ],
2895
2896 snat_ip: [ "network", null, NO_INVERT ],
2897 snat_port: [ "port", null, NO_INVERT ],
2898
2899 dest_ip: [ "network" ],
2900 dest_port: [ "port" ],
2901
2902 extra: [ "string", null, UNSUPPORTED ],
2903
2904 limit: [ "limit" ],
2905 limit_burst: [ "int" ],
2906
2907 connlimit_ports: [ "bool" ],
2908
2909 utc_time: [ "bool" ],
2910 start_date: [ "date" ],
2911 stop_date: [ "date" ],
2912 start_time: [ "time" ],
2913 stop_time: [ "time" ],
2914 weekdays: [ "weekdays" ],
2915 monthdays: [ "monthdays", null, UNSUPPORTED ],
2916
2917 mark: [ "mark" ],
2918
2919 target: [ "target", "masquerade" ]
2920 });
2921
2922 if (snat === false) {
2923 this.warn_section(data, "skipped due to invalid options");
2924 return;
2925 }
2926 else if (!snat.enabled) {
2927 this.warn_section(data, "is disabled, ignoring section");
2928 return;
2929 }
2930
2931 if (!(snat.target in ["accept", "snat", "masquerade"])) {
2932 this.warn_section(data, "has invalid target specified, defaulting to masquerade");
2933 snat.target = "masquerade";
2934 }
2935
2936 if (snat.target == "snat" && !snat.snat_ip && !snat.snat_port) {
2937 this.warn_section(data, "needs either 'snat_ip' or 'snat_port' for target snat, ignoring section");
2938 return;
2939 }
2940 else if (snat.target != "snat" && snat.snat_ip) {
2941 this.warn_section(data, "must not use 'snat_ip' for non-snat target, ignoring section");
2942 return;
2943 }
2944 else if (snat.target != "snat" && snat.snat_port) {
2945 this.warn_section(data, "must not use 'snat_port' for non-snat target, ignoring section");
2946 return;
2947 }
2948
2949 if ((snat.snat_port || snat.src_port || snat.dest_port) && !ensure_tcpudp(snat.proto)) {
2950 this.warn_section(data, "specifies ports but no UDP/TCP protocol, ignoring section");
2951 return;
2952 }
2953
2954 if (snat.snat_ip && length(filter(snat.snat_ip.addrs, a => a.bits == -1 || a.invert))) {
2955 this.warn_section(data, "must not use inversion or non-contiguous masks in 'snat_ip', ignoring section");
2956 return;
2957 }
2958
2959 if (snat.src && snat.src.zone)
2960 snat.src.zone.dflags.snat = true;
2961
2962 let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, snat) => {
2963 let n = {
2964 ...snat,
2965
2966 family: family,
2967 proto: proto,
2968 has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
2969 has_ports: !!(sport || dport),
2970 saddrs_pos: map(saddrs[0], this.cidr),
2971 saddrs_neg: map(saddrs[1], this.cidr),
2972 saddrs_masked: saddrs[2],
2973 daddrs_pos: map(daddrs[0], this.cidr),
2974 daddrs_neg: map(daddrs[1], this.cidr),
2975 daddrs_masked: daddrs[2],
2976 sports_pos: map(filter_pos(to_array(sport)), this.port),
2977 sports_neg: map(filter_neg(to_array(sport)), this.port),
2978 dports_pos: map(filter_pos(to_array(dport)), this.port),
2979 dports_neg: map(filter_neg(to_array(dport)), this.port),
2980
2981 raddr: raddrs ? raddrs[0] : null,
2982 rport: rport,
2983
2984 chain: (snat.src && snat.src.zone) ? sprintf("srcnat_%s", snat.src.zone.name) : "srcnat"
2985 };
2986
2987 this.state.redirects = this.state.redirects || [];
2988 push(this.state.redirects, n);
2989 };
2990
2991 for (let proto in snat.proto) {
2992 let sip, dip, rip, sport, dport, rport;
2993 let family = snat.family;
2994
2995 sip = subnets_split_af(snat.src_ip);
2996 dip = subnets_split_af(snat.dest_ip);
2997 rip = subnets_split_af(snat.snat_ip);
2998
2999 switch (proto.name) {
3000 case "tcp":
3001 case "udp":
3002 sport = snat.src_port;
3003 dport = snat.dest_port;
3004 rport = snat.snat_port;
3005 break;
3006 }
3007
3008 if (length(rip[0]) > 1 || length(rip[1]) > 1)
3009 this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
3010
3011 /* inherit family restrictions from related zones */
3012 if (family === 0 || family === null) {
3013 let f = (rule.src && rule.src.zone) ? rule.src.zone.family : 0;
3014
3015 if (f) {
3016 this.warn_section(r,
3017 sprintf("inheriting %s restriction from src %s",
3018 this.nfproto(f1, true), rule.src.zone.name));
3019
3020 family = f;
3021 }
3022 }
3023
3024 /* if no family was configured, infer target family from IP addresses */
3025 if (family === null) {
3026 if ((length(sip[0]) || length(dip[0]) || length(rip[0])) && !length(sip[1]) && !length(dip[1]) && !length(rip[1]))
3027 family = 4;
3028 else if ((length(sip[1]) || length(dip[1]) || length(rip[1])) && !length(sip[0]) && !length(dip[0]) && !length(rip[0]))
3029 family = 6;
3030 else
3031 family = 0;
3032 }
3033
3034 /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
3035 if (!family && !length(sip[0]) && !length(sip[1]) && !length(dip[0]) && !length(dip[1]) && !length(rip[0]) && !length(rip[1])) {
3036 add_rule(0, proto, [], [], null, sport, dport, rport, snat);
3037 }
3038
3039 /* we need to emit one or two AF specific rules */
3040 else {
3041 if (family == 0 || family == 4)
3042 for (let saddr in subnets_group_by_masking(sip[0]))
3043 for (let daddr in subnets_group_by_masking(dip[0]))
3044 add_rule(4, proto, saddr, daddr, rip[0], sport, dport, rport, snat);
3045
3046 if (family == 0 || family == 6)
3047 for (let saddr in subnets_group_by_masking(sip[1]))
3048 for (let daddr in subnets_group_by_masking(dip[1]))
3049 add_rule(6, proto, saddr, daddr, rip[1], sport, dport, rport, snat);
3050 }
3051 }
3052 },
3053
3054 parse_ipset: function(data) {
3055 let ipset = this.parse_options(data, {
3056 enabled: [ "bool", "1" ],
3057 reload_set: [ "bool" ],
3058 counters: [ "bool" ],
3059 comment: [ "bool" ],
3060
3061 name: [ "string", null, REQUIRED ],
3062 family: [ "family", "4" ],
3063
3064 storage: [ "string", null, UNSUPPORTED ],
3065 match: [ "ipsettype", null, PARSE_LIST ],
3066
3067 iprange: [ "string", null, UNSUPPORTED ],
3068 portrange: [ "string", null, UNSUPPORTED ],
3069
3070 netmask: [ "int", null, UNSUPPORTED ],
3071 maxelem: [ "int" ],
3072 hashsize: [ "int", null, UNSUPPORTED ],
3073 timeout: [ "int", "-1" ],
3074
3075 external: [ "string", null, UNSUPPORTED ],
3076
3077 entry: [ "string", null, PARSE_LIST ],
3078 loadfile: [ "string" ]
3079 });
3080
3081 if (ipset === false) {
3082 this.warn_section(data, "skipped due to invalid options");
3083 return;
3084 }
3085 else if (!ipset.enabled) {
3086 this.warn_section(data, "is disabled, ignoring section");
3087 return;
3088 }
3089
3090 if (ipset.family == 0) {
3091 this.warn_section(data, "must not specify family 'any'");
3092 return;
3093 }
3094 else if (!length(ipset.match)) {
3095 this.warn_section(data, "has no datatypes assigned");
3096 return;
3097 }
3098
3099 let dirs = map(ipset.match, m => m[0]),
3100 types = map(ipset.match, m => m[1]),
3101 interval = false;
3102
3103 if ("set" in types) {
3104 this.warn_section(data, "match type 'set' is not supported");
3105 return;
3106 }
3107
3108 if ("net" in types) {
3109 if (this.kernel < 0x05060000) {
3110 this.warn_section(data, "match type 'net' requires kernel 5.6 or later");
3111 return;
3112 }
3113
3114 interval = true;
3115 }
3116
3117 let s = {
3118 ...ipset,
3119
3120 fw4types: types,
3121
3122 types: map(types, (t) => {
3123 switch (t) {
3124 case 'ip':
3125 case 'net':
3126 return (ipset.family == 4) ? 'ipv4_addr' : 'ipv6_addr';
3127
3128 case 'mac':
3129 return 'ether_addr';
3130
3131 case 'port':
3132 return 'inet_service';
3133 }
3134 }),
3135
3136 directions: dirs,
3137 interval: interval
3138 };
3139
3140 let self = this;
3141 s.entries = filter(map(ipset.entry, (e) => {
3142 let v = self.parse_ipsetentry(e, s);
3143
3144 if (!v)
3145 self.warn_section(data, "ignoring invalid ipset entry '" + e + "'");
3146
3147 return v;
3148 }), (e) => (e != null));
3149
3150 this.state.ipsets = this.state.ipsets || [];
3151 push(this.state.ipsets, s);
3152 }
3153 };