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