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