system/modules/nixos/services/vpn/wireguard/client.nix

76 lines
2.2 KiB
Nix
Raw Normal View History

{ config, lib, pkgs, ... }:
2023-03-02 16:00:19 +03:00
let
2024-04-16 02:51:46 +03:00
cfg = config.local.services.vpn.wireguard;
2023-03-02 16:00:19 +03:00
in
{
2024-04-16 02:51:46 +03:00
options.local.services.vpn.wireguard = with lib; {
2023-03-02 18:57:38 +03:00
enable = mkEnableOption "Enable wireguard vpn";
2023-03-02 16:00:19 +03:00
ip = mkOption {
type = types.str;
example = "10.100.0.1/24";
};
privateKeyFile = mkOption {
type = types.str;
};
2024-04-16 02:51:46 +03:00
server = {
addr = mkOption {
type = types.str;
};
port = mkOption {
type = types.int;
};
publicKey = mkOption {
type = types.str;
};
};
2023-03-02 16:00:19 +03:00
};
config = lib.mkIf cfg.enable {
networking.firewall = {
2024-04-16 02:51:46 +03:00
allowedUDPPorts = [ cfg.server.port ]; # Clients and peers can use the same port, see listenport
2023-03-02 16:00:19 +03:00
};
# Enable WireGuard
2023-07-28 17:08:13 +03:00
networking.wg-quick.interfaces = {
2023-03-02 16:00:19 +03:00
# "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.
2023-07-28 17:08:13 +03:00
address = [ cfg.ip ];
2023-08-01 12:54:35 +03:00
dns = [ "10.20.30.1" ];
2023-07-28 17:08:13 +03:00
2024-04-16 02:51:46 +03:00
listenPort = cfg.server.port; # to match firewall allowedUDPPorts (without this wg uses random port numbers)
2023-03-02 16:00:19 +03:00
# Path to the private key file.
privateKeyFile = cfg.privateKeyFile;
postUp = ''
addr=`${pkgs.iproute}/bin/ip route | ${pkgs.gawk}/bin/awk '/default/ {print $3; exit}'`
interface=`${pkgs.iproute}/bin/ip route | ${pkgs.gawk}/bin/awk '/default/ {print $5; exit}'`
# don't use wg with cache.nixos.org
${pkgs.iproute}/bin/ip route add 151.101.86.217/32 via $addr dev $interface
'';
2023-03-02 16:00:19 +03:00
peers = [
# For a client configuration, one peer entry for the server will suffice.
{
# Public key of the server (not a file path).
2024-04-16 02:51:46 +03:00
publicKey = cfg.server.publicKey;
2023-03-02 16:00:19 +03:00
# 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.
2024-04-16 02:51:46 +03:00
endpoint = "${cfg.server.addr}:${toString cfg.server.port}";
2023-03-02 16:00:19 +03:00
# Send keepalives every 25 seconds. Important to keep NAT tables alive.
2023-03-20 23:32:29 +03:00
persistentKeepalive = 15;
2023-03-02 16:00:19 +03:00
}
];
};
};
};
}