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