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