dotfiles/modules/services/wireguard.nix

69 lines
1.9 KiB
Nix
Raw Normal View History

{ config, pkgs, lib, ... }: {
2022-10-09 14:12:31 +00:00
options.networking.wireguard = {
2022-10-09 14:12:31 +00:00
encryptedPrivateKey = lib.mkOption {
type = lib.types.path;
description = "Nix path to age-encrypted client private key";
default = ../../private/wireguard.age;
};
2022-10-09 14:12:31 +00:00
};
2022-10-09 14:12:31 +00:00
config = {
2022-10-09 14:12:31 +00:00
networking.wireguard = {
enable = true;
interfaces = {
wg0 = {
2022-10-09 14:12:31 +00:00
# Establishes identity of this machine
generatePrivateKeyFile = false;
privateKeyFile = "/private/wireguard/wg0";
2022-10-09 14:12:31 +00:00
# Move to network namespace for isolating programs
interfaceNamespace = "wg";
2022-10-09 14:12:31 +00:00
};
2022-06-04 14:29:36 +00:00
};
2022-05-29 16:00:19 +00:00
};
2022-10-09 14:12:31 +00:00
# Create namespace for Wireguard
# This allows us to isolate specific programs to Wireguard
systemd.services."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";
};
2022-10-09 14:12:31 +00:00
};
# Create private key file for wireguard
systemd.services.wireguard-private-key = {
wantedBy = [ "wireguard-wg0.service" ];
requiredBy = [ "wireguard-wg0.service" ];
before = [ "wireguard-wg0.service" ];
serviceConfig = { Type = "oneshot"; };
script = let
encryptedPrivateKey = config.networking.wireguard.encryptedPrivateKey;
privateKeyFile =
config.networking.wireguard.interfaces.wg0.privateKeyFile;
in ''
mkdir --parents --mode 0755 ${builtins.dirOf privateKeyFile}
if [ ! -f "${privateKeyFile}" ]; then
${pkgs.age}/bin/age --decrypt \
--identity ${config.identityFile} \
--output ${privateKeyFile} \
${builtins.toString encryptedPrivateKey}
chmod 0700 ${privateKeyFile}
fi
'';
2022-10-09 14:12:31 +00:00
};
2022-10-09 14:12:31 +00:00
};
2022-05-29 16:00:19 +00:00
}