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