firewall: extract _share_iptables_set_masquerade() helper

When we configure iptables rules, we really do two independent
steps: enable masquerading and do some filtering.

As such, introduce a helper method _share_iptables_set_masquerade() for
the masquerading part.

nm_utils_share_rules_apply() is at the moment a bit odd, because
of the order in which we add/remove the rule. This will get better next.
This commit is contained in:
Thomas Haller 2021-05-05 16:45:21 +02:00
parent f5e12f3915
commit c752de2237
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728

View file

@ -1693,6 +1693,28 @@ _share_iptables_call_v(const char *const *argv)
return TRUE;
}
#define _share_iptables_call(...) _share_iptables_call_v(NM_MAKE_STRV(__VA_ARGS__))
static void
_share_iptables_set_masquerade(gboolean add, in_addr_t addr, guint8 plen)
{
char str_subnet[_SHARE_IPTABLES_SUBNET_TO_STR_LEN];
_share_iptables_subnet_to_str(str_subnet, addr, plen);
_share_iptables_call("" IPTABLES_PATH "",
"--table",
"nat",
add ? "--insert" : "--delete",
"POSTROUTING",
"--source",
str_subnet,
"!",
"--destination",
str_subnet,
"--jump",
"MASQUERADE");
}
struct _NMUtilsShareRules {
char * ip_iface;
in_addr_t addr;
@ -1774,18 +1796,6 @@ _share_rules_create_iptables(const char *ip_iface,
rules = g_array_new(FALSE, FALSE, sizeof(ShareRule));
g_array_set_clear_func(rules, nm_indirect_g_free);
shared_rules_add_iptables(rules,
shared,
"nat",
"POSTROUTING",
"--source",
addr_mask,
"!",
"--destination",
addr_mask,
"--jump",
"MASQUERADE");
shared_rules_add_iptables(rules,
shared,
"filter",
@ -1908,6 +1918,9 @@ nm_utils_share_rules_apply(NMUtilsShareRules *self, gboolean shared)
rules =
_share_rules_create_iptables(self->ip_iface, self->addr, self->plen, shared, gfree_keeper);
if (!shared)
_share_iptables_set_masquerade(FALSE, self->addr, self->plen);
/* depending on whether we share or unshare, we add/remote the rules
* in opposite order. */
if (shared)
@ -1930,6 +1943,9 @@ nm_utils_share_rules_apply(NMUtilsShareRules *self, gboolean shared)
break;
}
}
if (shared)
_share_iptables_set_masquerade(TRUE, self->addr, self->plen);
}
/*****************************************************************************/