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