system/machines/modules/wireguard-client.nix

73 lines
2.2 KiB
Nix
Raw Normal View History

2023-03-02 16:00:19 +03:00
{ config, lib, pkgs, ... }:
let
cfg = config.local.wireguard;
port = 51820;
serverAddr = (import ../canigou/data.secret.nix).addr;
2023-03-02 17:36:05 +03:00
# Run `ip route` to show gateway
2023-03-02 16:00:19 +03:00
defaultGateway = "192.168.0.1";
in
{
options.local.wireguard = with lib; {
enable = mkOption {
type = types.bool;
default = false;
description = "Enable wireguard vpn";
};
ip = mkOption {
type = types.str;
description = "10.100.0.<num>/24";
example = "10.100.0.1/24";
};
privateKeyFile = mkOption {
type = types.str;
};
};
config = lib.mkIf cfg.enable {
networking.firewall = {
allowedUDPPorts = [ port ]; # Clients and peers can use the same port, see listenport
};
# Enable WireGuard
networking.wireguard.interfaces = {
# "wg0" is the network interface name. You can name the interface arbitrarily.
wg0 = {
# Determines the IP address and subnet of the client's end of the tunnel interface.
ips = [ cfg.ip ];
listenPort = port; # to match firewall allowedUDPPorts (without this wg uses random port numbers)
# Path to the private key file.
privateKeyFile = cfg.privateKeyFile;
2023-03-02 17:36:05 +03:00
# Add a more specific ip route allowing trafgfic to the VPN via the default gateway
# Source: https://discourse.nixos.org/t/route-all-traffic-through-wireguard-interface/1480/18
2023-03-02 16:00:19 +03:00
postSetup = "${pkgs.iproute}/bin/ip route add ${serverAddr} via ${defaultGateway}";
postShutdown = "${pkgs.iproute}/bin/ip route del ${serverAddr} via ${defaultGateway}";
peers = [
# For a client configuration, one peer entry for the server will suffice.
{
# Public key of the server (not a file path).
publicKey = "nFqvL30dkKkhOt+fLJ+EJNmp9GjkXVjmpz1WRI1pG0A=";
# Forward all the traffic via VPN.
allowedIPs = [ "0.0.0.0/0" ];
# Or forward only particular subnets
# allowedIPs = [ "192.168.0.0/24" ];
# Set this to the server IP and port.
endpoint = "${serverAddr}:${toString port}";
# Send keepalives every 25 seconds. Important to keep NAT tables alive.
persistentKeepalive = 25;
}
];
};
};
};
}