@@ -16,6 +16,9 @@
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
+#include <net/if.h>
+#include <sys/ioctl.h>
+
#include "zones.h"
#include "ubus.h"
#include "helpers.h"
@@ -98,6 +101,39 @@ const struct fw3_option fw3_zone_opts[] = {
{ }
};
+static bool
+check_loopback_addr(struct fw3_address *addr)
+{
+ if (addr->family == FW3_FAMILY_V4 &&
+ (ntohl(addr->address.v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
+ return true;
+
+ if (addr->family == FW3_FAMILY_V6 && !addr->range &&
+ fw3_netmask2bitlen(FW3_FAMILY_V6, &addr->mask.v6) == 128 &&
+ IN6_IS_ADDR_LOOPBACK(&addr->address.v6))
+ return true;
+
+ return false;
+}
+
+static bool
+check_loopback_dev(const char *name)
+{
+ struct ifreq ifr;
+ int s = socket(AF_LOCAL, SOCK_DGRAM, 0);
+ bool rv = false;
+
+ memset(&ifr, 0, sizeof(ifr));
+ strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name) - 1);
+
+ if (s < 0 || ioctl(s, SIOCGIFFLAGS, &ifr) < 0)
+ goto out;
+
+ if (ifr.ifr_flags & IFF_LOOPBACK)
+ rv = true;
+out:
+ return rv;
+}
static void
check_policy(struct uci_element *e, enum fw3_flag *pol, enum fw3_flag def,
@@ -557,22 +593,27 @@ print_interface_rule(struct fw3_ipt_handle *handle, struct fw3_state *state,
}
else if (handle->table == FW3_TABLE_RAW)
{
+ bool loopback_dev = (dev != NULL && !dev->any &&
+ !dev->invert && check_loopback_dev(dev->name));
+ char *chain = loopback_dev || (sub != NULL && !sub->invert && check_loopback_addr(sub)) ?
+ "OUTPUT" : "PREROUTING";
+
if (has(zone->flags, handle->family, FW3_FLAG_HELPER))
{
- r = fw3_ipt_rule_create(handle, NULL, dev, NULL, sub, NULL);
+ r = fw3_ipt_rule_create(handle, NULL, loopback_dev ? NULL : dev, NULL, sub, NULL);
fw3_ipt_rule_comment(r, "%s CT helper assignment", zone->name);
fw3_ipt_rule_target(r, "zone_%s_helper", zone->name);
fw3_ipt_rule_extra(r, zone->extra_src);
- fw3_ipt_rule_replace(r, "PREROUTING");
+ fw3_ipt_rule_replace(r, chain);
}
if (has(zone->flags, handle->family, FW3_FLAG_NOTRACK))
{
- r = fw3_ipt_rule_create(handle, NULL, dev, NULL, sub, NULL);
+ r = fw3_ipt_rule_create(handle, NULL, loopback_dev ? NULL : dev, NULL, sub, NULL);
fw3_ipt_rule_comment(r, "%s CT bypass", zone->name);
fw3_ipt_rule_target(r, "zone_%s_notrack", zone->name);
fw3_ipt_rule_extra(r, zone->extra_src);
- fw3_ipt_rule_replace(r, "PREROUTING");
+ fw3_ipt_rule_replace(r, chain);
}
}
}