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