nixos-module/container/upstream: fix SNAT by adding a staticIpv4Address option

This commit is contained in:
Astro 2021-09-06 22:58:52 +02:00
parent fd4c8ad65b
commit 1b4f761de8
3 changed files with 35 additions and 25 deletions

View File

@ -149,6 +149,7 @@ in
upstream1.interfaces.up1.upstream = {
provider = "vodafone";
staticIpv4Address = "24.134.104.53";
noNat.subnets6 = [
"2a02:8106:208:5200::/56"
];
@ -165,6 +166,7 @@ in
upstream = {
provider = "dsi";
link = "up4";
staticIpv4Address = "81.201.149.152";
upBandwidth = 98000;
noNat.subnets6 = [
"2a00:8180:2000:37::1/128"

View File

@ -111,6 +111,9 @@ let
default = null;
description = "Underlying interface name for eg. PPPoE";
};
staticIpv4Address = mkOption {
type = with types; nullOr str;
};
upBandwidth = mkOption {
type = with types; nullOr int;
default = null;

View File

@ -77,32 +77,37 @@ in
-j ${net}_nat
'') (builtins.attrNames upstreamInterfaces)
) +
# Do SNAT on connection attempts so that the actual return path
# won't matter. Forwarded ports will work from internal networks
# and on services that have Internet through another upstream routers.
builtins.concatStringsSep "\n" (
map ({ proto, destination, sourcePort, ... }:
# Do SNAT on connection attempts so that forwarded ports will
# work from internal networks.
''
iptables -w -t nat -N nixos-nat-post-forward 2>/dev/null || \
iptables -w -t nat -F nixos-nat-post-forward
${lib.concatMapStringsSep "\n" (net:
let
ds = builtins.split ":" destination;
ds' =
if builtins.length ds == 3
then {
dest = lib.elemAt ds 0;
port = lib.elemAt ds 2;
}
else if builtins.length ds == 1
then {
dest = lib.elemAt ds 0;
port = toString sourcePort;
}
else throw "Too many colons in a forwardPorts destination";
inherit (ds') dest port;
in ''
iptables -t nat -A nixos-nat-post \
-p ${proto} --dest ${dest} --dport ${port} \
-j SNAT --to-source ${config.site.net.core.hosts4.${hostName}}
'') hostConf.forwardPorts
);
inherit (upstreamInterfaces.${net}.upstream) staticIpv4Address;
in lib.optionalString (staticIpv4Address != null) ''
iptables -w -t nat -A nixos-nat-post \
--source 172.20.0.0/14 \
--dest ${staticIpv4Address}/32 \
-j nixos-nat-post-forward
'') (builtins.attrNames upstreamInterfaces)}
${lib.concatMapStringsSep "\n" ({ proto, destination, sourcePort, ... }:
let
ds = builtins.split ":" destination;
port =
if builtins.length ds == 3
then lib.elemAt ds 2
else if builtins.length ds == 1
then toString sourcePort
else throw "Too many colons in a forwardPorts destination";
in ''
iptables -t nat -A nixos-nat-post-forward \
-p ${proto} --dport ${port} \
-j SNAT --to-source ${config.site.net.core.hosts4.${hostName}}
'') hostConf.forwardPorts}
'';
extraStopCommands =
builtins.concatStringsSep "\n" (
map (net: ''