fw4: fix family auto-selection for config nat rules
[project/firewall4.git] / root / usr / share / ucode / fw4.uc
index fb8720859763633edf7ca4ba48d361f5eea672ad..05e86469979db4fd6f0aaaf9f96af985c5298b33 100644 (file)
@@ -1,5 +1,3 @@
-{%
-
 let fs = require("fs");
 let uci = require("uci");
 let ubus = require("ubus");
@@ -226,7 +224,7 @@ function null_if_empty(x) {
 }
 
 function subnets_split_af(x) {
-       let rv = [];
+       let rv = {};
 
        for (let ag in to_array(x)) {
                for (let a in filter(ag.addrs, a => (a.family == 4))) {
@@ -240,6 +238,9 @@ function subnets_split_af(x) {
                }
        }
 
+       if (rv[0] || rv[1])
+               rv.family = (!rv[0] ^ !rv[1]) ? (rv[0] ? 4 : 6) : 0;
+
        return rv;
 }
 
@@ -310,7 +311,7 @@ function infer_family(f, objects) {
                        if (!obj || !obj.family || obj.family == res)
                                continue;
 
-                       if (res == 0) {
+                       if (!res) {
                                res = obj.family;
                                by = obj.desc;
                                continue;
@@ -359,6 +360,65 @@ function map_setmatch(set, match, proto) {
        return fields;
 }
 
+function resolve_lower_devices(devstatus, devname) {
+       let dir = fs.opendir("/sys/class/net/" + devname);
+       let devs = [];
+
+       if (dir) {
+               if (!devstatus || devstatus[devname]?.["hw-tc-offload"]) {
+                       push(devs, devname);
+               }
+               else {
+                       let e;
+
+                       while ((e = dir.read()) != null)
+                               if (index(e, "lower_") === 0)
+                                       push(devs, ...resolve_lower_devices(devstatus, substr(e, 6)));
+               }
+
+               dir.close();
+       }
+
+       return devs;
+}
+
+function nft_json_command(...args) {
+       let cmd = [ "/usr/sbin/nft", "--terse", "--json", ...args ];
+       let nft = fs.popen(join(" ", cmd), "r");
+       let info;
+
+       if (nft) {
+               try {
+                       info = filter(json(nft.read("all"))?.nftables,
+                               item => (type(item) == "object" && !item.metainfo));
+               }
+               catch (e) {
+                       warn(sprintf("Unable to parse nftables JSON output: %s\n", e));
+               }
+
+               nft.close();
+       }
+       else {
+               warn(sprintf("Unable to popen() %s: %s\n", cmd, fs.error()));
+       }
+
+       return info || [];
+}
+
+function nft_try_hw_offload(devices) {
+       let nft_test =
+               'add table inet fw4-hw-offload-test; ' +
+               'add flowtable inet fw4-hw-offload-test ft { ' +
+                       'hook ingress priority 0; ' +
+                       'devices = { "' + join('", "', devices) + '" }; ' +
+                       'flags offload; ' +
+               '}';
+
+       let rc = system(sprintf("/usr/sbin/nft -c '%s' 2>/dev/null", replace(nft_test, "'", "'\\''")));
+
+       return (rc == 0);
+}
+
 
 return {
        read_kernel_version: function() {
@@ -375,6 +435,61 @@ return {
                return v;
        },
 
+       resolve_offload_devices: function() {
+               if (!this.default_option("flow_offloading"))
+                       return [];
+
+               let devstatus = null;
+               let devices = [];
+
+               if (this.default_option("flow_offloading_hw")) {
+                       let bus = ubus.connect();
+
+                       if (bus) {
+                               devstatus = bus.call("network.device", "status") || {};
+                               bus.disconnect();
+                       }
+
+                       for (let zone in this.zones())
+                               for (let device in zone.related_physdevs)
+                                       push(devices, ...resolve_lower_devices(devstatus, device));
+
+                       devices = uniq(devices);
+
+                       if (nft_try_hw_offload(devices))
+                               return devices;
+
+                       this.warn('Hardware flow offloading unavailable, falling back to software offloading');
+                       this.state.defaults.flow_offloading_hw = false;
+
+                       devices = [];
+               }
+
+               for (let zone in this.zones())
+                       for (let device in zone.match_devices)
+                               push(devices, ...resolve_lower_devices(null, device));
+
+               return uniq(devices);
+       },
+
+       check_set_types: function() {
+               let sets = {};
+
+               for (let item in nft_json_command("list", "sets", "inet"))
+                       if (item.set?.table == "fw4")
+                               sets[item.set.name] = (type(item.set.type) == "array") ? item.set.type : [ item.set.type ];
+
+               return sets;
+       },
+
+       check_flowtable: function() {
+               for (let item in nft_json_command("list", "flowtables", "inet"))
+                       if (item.flowtable?.table == "fw4" && item.flowtable?.name == "ft")
+                               return true;
+
+               return false;
+       },
+
        read_state: function() {
                let fd = fs.open(STATEFILE, "r");
                let state = null;
@@ -419,6 +534,7 @@ return {
                                let net = {
                                        up: ifc.up,
                                        device: ifc.l3_device,
+                                       physdev: ifc.device,
                                        zone: ifc.data?.zone
                                };
 
@@ -575,18 +691,18 @@ return {
 
 
                //
-               // Build list of forwardings
+               // Build list of rules
                //
 
-               this.cursor.foreach("firewall", "forwarding", f => self.parse_forwarding(f));
+               map(filter(this.state.ubus_rules, r => (r.type == "rule")), r => self.parse_rule(r));
+               this.cursor.foreach("firewall", "rule", r => self.parse_rule(r));
 
 
                //
-               // Build list of rules
+               // Build list of forwardings
                //
 
-               map(filter(this.state.ubus_rules, r => (r.type == "rule")), r => self.parse_rule(r));
-               this.cursor.foreach("firewall", "rule", r => self.parse_rule(r));
+               this.cursor.foreach("firewall", "forwarding", f => self.parse_forwarding(f));
 
 
                //
@@ -772,7 +888,7 @@ return {
                        val = lc(val);
 
                        for (let i = 0; i < length(choices); i++)
-                               if (substr(choices[i], 0, length(val)) == val)
+                               if (lc(substr(choices[i], 0, length(val))) == val)
                                        return choices[i];
                }
 
@@ -879,9 +995,9 @@ return {
 
        parse_direction: function(val) {
                if (val == 'in' || val == 'ingress')
-                       return true;
-               else if (val == 'out' || val == 'egress')
                        return false;
+               else if (val == 'out' || val == 'egress')
+                       return true;
 
                return null;
        },
@@ -1164,13 +1280,13 @@ return {
 
                for (let day in to_array(rv.val)) {
                        day = this.parse_enum(day, [
-                               "monday",
-                               "tuesday",
-                               "wednesday",
-                               "thursday",
-                               "friday",
-                               "saturday",
-                               "sunday"
+                               "Monday",
+                               "Tuesday",
+                               "Wednesday",
+                               "Thursday",
+                               "Friday",
+                               "Saturday",
+                               "Sunday"
                        ]);
 
                        if (!day)
@@ -1316,7 +1432,7 @@ return {
                        case 'ipv4_addr':
                                ip = filter(this.parse_subnet(values[i]), a => (a.family == 4));
 
-                               switch (length(ip)) {
+                               switch (length(ip) ?? 0) {
                                case 0: return null;
                                case 1: break;
                                default: this.warn("Set entry '%s' resolves to multiple addresses, using first one", values[i]);
@@ -1449,10 +1565,10 @@ return {
                return sprintf("%s/%s", a.addr, a.mask);
        },
 
-       host: function(a) {
+       host: function(a, v6brackets) {
                return a.range
                        ? sprintf("%s-%s", a.addr, a.addr2)
-                       : apply_mask(a.addr, a.bits);
+                       : sprintf((a.family == 6 && v6brackets) ? "[%s]" : "%s", apply_mask(a.addr, a.bits));
        },
 
        port: function(p) {
@@ -1500,6 +1616,22 @@ return {
                }
        },
 
+       l4proto: function(family, proto) {
+               switch (proto.name) {
+               case 'icmp':
+                       switch (family ?? 0) {
+                       case 0:
+                               return this.set(['icmp', 'ipv6-icmp']);
+
+                       case 6:
+                               return 'ipv6-icmp';
+                       }
+
+               default:
+                       return proto.name;
+               }
+       },
+
        datetime: function(stamp) {
                return sprintf('"%04d-%02d-%02d %02d:%02d:%02d"',
                               stamp.year, stamp.month, stamp.day,
@@ -1766,6 +1898,7 @@ return {
                        zone.auto_helper = false;
 
                let match_devices = [];
+               let related_physdevs = [];
                let related_subnets = [];
                let related_ubus_networks = [];
                let match_subnets, masq_src_subnets, masq_dest_subnets;
@@ -1786,6 +1919,9 @@ return {
                                        });
                                }
 
+                               if (net.physdev && !e.invert)
+                                       push(related_physdevs, net.physdev);
+
                                push(related_subnets, ...(net.ipaddrs || []));
                        }
                }
@@ -1817,9 +1953,15 @@ return {
                };
 
                let family = infer_family(zone.family, [
-                       zone.helper, "ct helper"
+                       zone.helper, "ct helper",
+                       match_subnets, "subnet list"
                ]);
 
+               if (type(family) == "string") {
+                       this.warn_section(data, family + ", skipping");
+                       return;
+               }
+
                // group non-inverted device matches into wildcard and non-wildcard ones
                let devices = [], plain_devices = [], plain_invert_devices = [], wildcard_invert_devices = [];
 
@@ -1892,6 +2034,8 @@ return {
                        }
                }
 
+               zone.family = family;
+
                zone.match_rules = match_rules;
 
                zone.masq4_src_subnets = subnets_group_by_masking(masq_src_subnets[0]);
@@ -1911,6 +2055,7 @@ return {
                zone.match_subnets = map(filter(related_subnets, s => !s.invert && s.bits != -1), this.cidr);
 
                zone.related_subnets = related_subnets;
+               zone.related_physdevs = related_physdevs;
 
                if (zone.masq || zone.masq6)
                        zone.dflags.snat = true;
@@ -2034,7 +2179,7 @@ return {
                        src: [ "zone_ref" ],
                        dest: [ "zone_ref" ],
 
-                       device: [ "device" ],
+                       device: [ "device", null, NO_INVERT ],
                        direction: [ "direction" ],
 
                        ipset: [ "setmatch" ],
@@ -2101,6 +2246,10 @@ return {
                        this.warn_section(data, "must specify option 'set_helper' for target 'helper'");
                        return;
                }
+               else if (rule.device?.any) {
+                       this.warn_section(data, "must not specify '*' as device");
+                       return;
+               }
 
                let ipset;
 
@@ -2189,11 +2338,15 @@ return {
                                else
                                        r.chain = "mangle_output";
 
-                               if (r.src?.zone)
+                               if (r.src?.zone) {
                                        r.src.zone.dflags[r.target] = true;
+                                       r.iifnames = null_if_empty(r.src.zone.match_devices);
+                               }
 
-                               if (r.dest?.zone)
+                               if (r.dest?.zone) {
                                        r.dest.zone.dflags[r.target] = true;
+                                       r.oifnames = null_if_empty(r.dest.zone.match_devices);
+                               }
                        }
                        else {
                                r.chain = "output";
@@ -2218,12 +2371,15 @@ return {
                                }
                                else if (need_src_action_chain(r)) {
                                        r.jump_chain = sprintf("%s_from_%s", r.target, r.src.zone.name);
-                                       r.src.zone.dflags[r.target] = true;
+                                       r.src.zone.sflags[r.target] = true;
                                }
                                else if (r.target == "reject")
                                        r.jump_chain = "handle_reject";
                        }
 
+                       if (r.device)
+                               r[r.direction ? "oifnames" : "iifnames"] = [ r.device.device ];
+
                        this.state.rules = this.state.rules || [];
                        push(this.state.rules, r);
                };
@@ -2250,10 +2406,15 @@ return {
                                break;
                        }
 
+                       sip = subnets_split_af(rule.src_ip);
+                       dip = subnets_split_af(rule.dest_ip);
+
                        family = infer_family(family, [
                                ipset, "set match",
-                               rule.src, "source zone",
-                               rule.dest, "destination zone",
+                               sip, "source IP",
+                               dip, "destination IP",
+                               rule.src?.zone, "source zone",
+                               rule.dest?.zone, "destination zone",
                                rule.helper, "helper match",
                                rule.set_helper, "helper to set"
                        ]);
@@ -2263,9 +2424,6 @@ return {
                                continue;
                        }
 
-                       sip = subnets_split_af(rule.src_ip);
-                       dip = subnets_split_af(rule.dest_ip);
-
                        let has_ipv4_specifics = (length(sip[0]) || length(dip[0]) || length(itypes4) || rule.dscp !== null);
                        let has_ipv6_specifics = (length(sip[1]) || length(dip[1]) || length(itypes6) || rule.dscp !== null);
 
@@ -2544,18 +2702,6 @@ return {
                        if (proto.name == "ipv6-icmp")
                                family = 6;
 
-                       family = infer_family(family, [
-                               ipset, "set match",
-                               redir.src, "source zone",
-                               redir.dest, "destination zone",
-                               redir.helper, "helper match"
-                       ]);
-
-                       if (type(family) == "string") {
-                               this.warn_section(data, family + ", skipping");
-                               continue;
-                       }
-
                        switch (redir.target) {
                        case "dnat":
                                sip = subnets_split_af(redir.src_ip);
@@ -2571,113 +2717,141 @@ return {
                                        break;
                                }
 
-                               /* build reflection rules */
-                               if (redir.reflection && (length(rip[0]) || length(rip[1])) && redir.src?.zone && redir.dest?.zone) {
-                                       let refredir = {
-                                               name: redir.name + " (reflection)",
+                               break;
 
-                                               helper: redir.helper,
+                       case "snat":
+                               sip = subnets_split_af(redir.src_ip);
+                               dip = subnets_split_af(redir.dest_ip);
+                               rip = subnets_split_af(redir.src_dip);
 
-                                               // XXX: this likely makes no sense for reflection rules
-                                               //src_mac: redir.src_mac,
+                               switch (proto.name) {
+                               case "tcp":
+                               case "udp":
+                                       sport = redir.src_port;
+                                       dport = redir.dest_port;
+                                       rport = redir.src_dport;
+                                       break;
+                               }
 
-                                               limit: redir.limit,
-                                               limit_burst: redir.limit_burst,
+                               break;
+                       }
 
-                                               start_date: redir.start_date,
-                                               stop_date: redir.stop_date,
-                                               start_time: redir.start_time,
-                                               stop_time: redir.stop_time,
-                                               weekdays: redir.weekdays,
+                       family = infer_family(family, [
+                               ipset, "set match",
+                               sip, "source IP",
+                               dip, "destination IP",
+                               rip, "rewrite IP",
+                               redir.src?.zone, "source zone",
+                               redir.dest?.zone, "destination zone",
+                               redir.helper, "helper match"
+                       ]);
 
-                                               mark: redir.mark
-                                       };
+                       if (type(family) == "string") {
+                               this.warn_section(data, family + ", skipping");
+                               continue;
+                       }
 
-                                       let eaddrs = length(dip) ? dip : subnets_split_af({ addrs: map(redir.src.zone.related_subnets, to_hostaddr) });
-                                       let rzones = length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
+                       /* build reflection rules */
+                       if (redir.target == "dnat" && redir.reflection &&
+                           (length(rip[0]) || length(rip[1])) && redir.src?.zone && redir.dest?.zone) {
+                               let refredir = {
+                                       name: redir.name + " (reflection)",
 
-                                       for (let rzone in rzones) {
-                                               if (!is_family(rzone, family)) {
-                                                       this.warn_section(data,
-                                                               sprintf("is restricted to IPv%d but referenced reflection zone is IPv%d only, skipping",
-                                                                       family, rzone.family));
-                                                       continue;
-                                               }
+                                       helper: redir.helper,
 
-                                               let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
-                                               let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
+                                       // XXX: this likely makes no sense for reflection rules
+                                       //src_mac: redir.src_mac,
 
-                                               for (let i = 0; i <= 1; i++) {
-                                                       if (redir.src.zone[i ? "masq6" : "masq"] && length(rip[i])) {
-                                                               let snat_addr = refaddrs[i]?.[0];
+                                       limit: redir.limit,
+                                       limit_burst: redir.limit_burst,
 
-                                                               /* For internal reflection sources try to find a suitable candiate IP
-                                                                * among the reflection zone subnets which is within the same subnet
-                                                                * as the original DNAT destination. If we can't find any matching
-                                                                * one then simply take the first candidate. */
-                                                               if (redir.reflection_src == "internal") {
-                                                                       for (let zone_addr in rzone.zone.related_subnets) {
-                                                                               if (zone_addr.family != rip[i][0].family)
-                                                                                       continue;
+                                       start_date: redir.start_date,
+                                       stop_date: redir.stop_date,
+                                       start_time: redir.start_time,
+                                       stop_time: redir.stop_time,
+                                       weekdays: redir.weekdays,
 
-                                                                               let r = apply_mask(rip[i][0].addr, zone_addr.mask);
-                                                                               let a = apply_mask(zone_addr.addr, zone_addr.mask);
+                                       mark: redir.mark
+                               };
 
-                                                                               if (r != a)
-                                                                                       continue;
+                               let eaddrs = length(dip) ? dip : subnets_split_af({ addrs: map(redir.src.zone.related_subnets, to_hostaddr) });
+                               let rzones = length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
 
-                                                                               snat_addr = zone_addr;
-                                                                               break;
-                                                                       }
-                                                               }
+                               for (let rzone in rzones) {
+                                       if (!is_family(rzone, family)) {
+                                               this.warn_section(data,
+                                                       sprintf("is restricted to IPv%d but referenced reflection zone is IPv%d only, skipping",
+                                                               family, rzone.family));
+                                               continue;
+                                       }
 
-                                                               if (snat_addr) {
-                                                                       refredir.src = rzone;
-                                                                       refredir.dest = null;
-                                                                       refredir.target = "dnat";
+                                       let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
+                                       let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
 
-                                                                       for (let saddrs in subnets_group_by_masking(iaddrs[i]))
-                                                                               for (let daddrs in subnets_group_by_masking(eaddrs[i]))
-                                                                                       add_rule(i ? 6 : 4, proto, saddrs, daddrs, rip[i], sport, dport, rport, null, refredir);
+                                       for (let i = 0; i <= 1; i++) {
+                                               if (redir.src.zone[i ? "masq6" : "masq"] && length(rip[i])) {
+                                                       let snat_addr = refaddrs[i]?.[0];
+
+                                                       /* For internal reflection sources try to find a suitable candiate IP
+                                                        * among the reflection zone subnets which is within the same subnet
+                                                        * as the original DNAT destination. If we can't find any matching
+                                                        * one then simply take the first candidate. */
+                                                       if (redir.reflection_src == "internal") {
+                                                               for (let zone_addr in rzone.zone.related_subnets) {
+                                                                       if (zone_addr.family != rip[i][0].family)
+                                                                               continue;
+
+                                                                       let r = apply_mask(rip[i][0].addr, zone_addr.mask);
+                                                                       let a = apply_mask(zone_addr.addr, zone_addr.mask);
 
-                                                                       refredir.src = null;
-                                                                       refredir.dest = rzone;
-                                                                       refredir.target = "snat";
+                                                                       if (r != a)
+                                                                               continue;
 
-                                                                       for (let daddrs in subnets_group_by_masking(rip[i]))
-                                                                               for (let saddrs in subnets_group_by_masking(iaddrs[i]))
-                                                                                       add_rule(i ? 6 : 4, proto, saddrs, daddrs, [ to_hostaddr(snat_addr) ], null, rport, null, null, refredir);
+                                                                       snat_addr = zone_addr;
+                                                                       break;
                                                                }
                                                        }
-                                               }
-                                       }
-                               }
 
+                                                       if (!snat_addr) {
+                                                               this.warn_section(data, (redir.reflection_src || "external") + " rewrite IP cannot be determined, disabling reflection");
+                                                       }
+                                                       else if (!length(iaddrs[i])) {
+                                                               this.warn_section(data, "internal address range cannot be determined, disabling reflection");
+                                                       }
+                                                       else if (!length(eaddrs[i])) {
+                                                               this.warn_section(data, "external address range cannot be determined, disabling reflection");
+                                                       }
+                                                       else {
+                                                               refredir.src = rzone;
+                                                               refredir.dest = null;
+                                                               refredir.target = "dnat";
 
-                               break;
+                                                               for (let saddrs in subnets_group_by_masking(iaddrs[i]))
+                                                                       for (let daddrs in subnets_group_by_masking(eaddrs[i]))
+                                                                               add_rule(i ? 6 : 4, proto, saddrs, daddrs, rip[i], sport, dport, rport, null, refredir);
 
-                       case "snat":
-                               sip = subnets_split_af(redir.src_ip);
-                               dip = subnets_split_af(redir.dest_ip);
-                               rip = subnets_split_af(redir.src_dip);
+                                                               refredir.src = null;
+                                                               refredir.dest = rzone;
+                                                               refredir.target = "snat";
 
-                               switch (proto.name) {
-                               case "tcp":
-                               case "udp":
-                                       sport = redir.src_port;
-                                       dport = redir.dest_port;
-                                       rport = redir.src_dport;
-                                       break;
+                                                               for (let daddrs in subnets_group_by_masking(rip[i]))
+                                                                       for (let saddrs in subnets_group_by_masking(iaddrs[i]))
+                                                                               add_rule(i ? 6 : 4, proto, saddrs, daddrs, [ to_hostaddr(snat_addr) ], null, rport, null, null, refredir);
+                                                       }
+                                               }
+                                       }
                                }
-
-                               break;
                        }
 
                        if (length(rip[0]) > 1 || length(rip[1]) > 1)
                                this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
 
+                       let has_ip4_addr = length(sip[0]) || length(dip[0]) || length(rip[0]),
+                           has_ip6_addr = length(sip[1]) || length(dip[1]) || length(rip[1]),
+                           has_any_addr = has_ip4_addr || has_ip6_addr;
+
                        /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
-                       if (!family && !length(sip[0]) && !length(sip[1]) && !length(dip[0]) && !length(dip[1]) && !length(rip[0]) && !length(rip[1])) {
+                       if (!family && !has_any_addr) {
                                /* for backwards compatibility, treat unspecified family as IPv4 unless user explicitly requested any (0) */
                                if (family == null)
                                        family = 4;
@@ -2687,13 +2861,13 @@ return {
 
                        /* we need to emit one or two AF specific rules */
                        else {
-                               if ((!family || family == 4) && (length(sip[0]) || length(dip[0]) || length(rip[0]))) {
+                               if ((!family || family == 4) && (!has_any_addr || has_ip4_addr)) {
                                        for (let saddrs in subnets_group_by_masking(sip[0]))
                                                for (let daddrs in subnets_group_by_masking(dip[0]))
                                                        add_rule(4, proto, saddrs, daddrs, rip[0], sport, dport, rport, ipset, redir);
                                }
 
-                               if ((!family || family == 6) && (length(sip[1]) || length(dip[1]) || length(rip[1]))) {
+                               if ((!family || family == 6) && (!has_any_addr || has_ip6_addr)) {
                                        for (let saddrs in subnets_group_by_masking(sip[1]))
                                                for (let daddrs in subnets_group_by_masking(dip[1]))
                                                        add_rule(6, proto, saddrs, daddrs, rip[1], sport, dport, rport, ipset, redir);
@@ -2707,7 +2881,7 @@ return {
                        enabled: [ "bool", "1" ],
 
                        name: [ "string", this.section_id(data[".name"]) ],
-                       family: [ "family", "4" ],
+                       family: [ "family" ],
 
                        src: [ "zone_ref" ],
                        device: [ "string" ],
@@ -2782,9 +2956,6 @@ return {
                        return;
                }
 
-               if (snat.src && snat.src.zone)
-                       snat.src.zone.dflags.snat = true;
-
                let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, snat) => {
                        let n = {
                                ...snat,
@@ -2834,19 +3005,21 @@ return {
                        if (length(rip[0]) > 1 || length(rip[1]) > 1)
                                this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
 
-                       /* inherit family restrictions from related zones */
-                       if (family === 0 || family === null) {
-                               let f = (rule.src && rule.src.zone) ? rule.src.zone.family : 0;
-
-                               if (f) {
-                                       this.warn_section(r,
-                                               sprintf("inheriting %s restriction from src %s",
-                                                       this.nfproto(f1, true), rule.src.zone.name));
+                       family = infer_family(family, [
+                               sip, "source IP",
+                               dip, "destination IP",
+                               rip, "rewrite IP",
+                               snat.src?.zone, "source zone"
+                       ]);
 
-                                       family = f;
-                               }
+                       if (type(family) == "string") {
+                               this.warn_section(data, family + ", skipping");
+                               continue;
                        }
 
+                       if (snat.src?.zone)
+                               snat.src.zone.dflags.snat = true;
+
                        /* if no family was configured, infer target family from IP addresses */
                        if (family === null) {
                                if ((length(sip[0]) || length(dip[0]) || length(rip[0])) && !length(sip[1]) && !length(dip[1]) && !length(rip[1]))
@@ -2854,7 +3027,7 @@ return {
                                else if ((length(sip[1]) || length(dip[1]) || length(rip[1])) && !length(sip[0]) && !length(dip[0]) && !length(rip[0]))
                                        family = 6;
                                else
-                                       family = 0;
+                                       family = 4; /* default to IPv4 only for backwards compatibility, unless an explict family any was configured */
                        }
 
                        /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */