nixos-configs/configurations/nos/modules/qbittorrent/wireguard.nix

79 lines
2.1 KiB
Nix
Raw Normal View History

{
config,
pkgs,
...
}: let
inherit (config.sops) secrets;
2024-10-21 11:34:14 -04:00
wgPort = 51820;
clientIP = "10.2.0.2";
serverIP = "146.70.198.2";
in {
networking.wireguard = {
enable = true;
interfaces = {
wg0 = {
interfaceNamespace = "wg";
2024-10-21 11:34:14 -04:00
ips = ["${clientIP}/32"];
2024-10-21 11:34:14 -04:00
listenPort = wgPort;
generatePrivateKeyFile = false;
privateKeyFile = secrets.vpn.path;
peers = [
{
publicKey = "aQ2NoOYEObG9tDMwdc4VxK6hjW+eA0PLfgbH7ffmagU=";
allowedIPs = ["0.0.0.0/0"];
2024-10-21 11:34:14 -04:00
endpoint = "${serverIP}:${toString wgPort}";
}
];
};
};
};
systemd.services = let
joinWgNamespace = {
2024-03-11 22:25:32 -04:00
bindsTo = ["netns@wg.service"];
requires = ["network-online.target"];
after = ["wireguard-wg0.service"];
unitConfig.JoinsNamespaceOf = "netns@wg.service";
serviceConfig.NetworkNamespacePath = "/var/run/netns/wg";
};
mkPortRoute = service: port: {
description = "Forward to ${service} in wireguard namespace";
requires = ["${service}.service"];
after = ["${service}.service"];
2024-02-27 03:54:21 -05:00
partOf = ["${service}.service"];
serviceConfig = {
Restart = "on-failure";
TimeoutStopSec = 300;
};
wantedBy = ["multi-user.target"];
script = ''
${pkgs.iproute2}/bin/ip netns exec wg ${pkgs.iproute2}/bin/ip link set dev lo up
2024-10-21 11:34:14 -04:00
${pkgs.socat}/bin/socat tcp-listen:${port},fork,reuseaddr exec:'${pkgs.iproute2}/bin/ip netns exec wg ${pkgs.socat}/bin/socat STDIO "tcp-connect:${clientIP}:${port}"',nofork
'';
};
in {
# Create namespace for Wireguard
# This allows us to isolate specific programs to Wireguard
"netns@" = {
description = "%I network namespace";
before = ["network.target"];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${pkgs.iproute2}/bin/ip netns add %I";
ExecStop = "${pkgs.iproute2}/bin/ip netns del %I";
};
};
"wireguard-wg0".wants = ["netns@wg.service"];
2024-02-27 03:54:21 -05:00
"qbittorrent" = joinWgNamespace;
"qbittorrent-port-route" = mkPortRoute "qbittorrent" "8080";
};
}