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