{ config, lib, pkgs, ... }: let cfg = config.local.services.vpn.wireguard; addrsViaDefaultInterface = [ # cache.nixos.org "151.101.86.217/32" # tbank.ru "178.248.236.218/32" ]; in { options.local.services.vpn.wireguard = with lib; { enable = mkEnableOption "Enable wireguard vpn"; ip = mkOption { type = types.str; example = "10.100.0.1/24"; }; privateKeyFile = mkOption { type = types.str; }; server = { addr = mkOption { type = types.str; }; port = mkOption { type = types.int; }; publicKey = mkOption { type = types.str; }; }; }; config = lib.mkIf cfg.enable { networking.firewall = { allowedUDPPorts = [ cfg.server.port ]; # Clients and peers can use the same port, see listenport }; # Enable WireGuard networking.wg-quick.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. address = [ cfg.ip ]; dns = [ "10.20.30.1" ]; listenPort = cfg.server.port; # to match firewall allowedUDPPorts (without this wg uses random port numbers) # Path to the private key file. privateKeyFile = cfg.privateKeyFile; postUp = '' addr=`${pkgs.iproute2}/bin/ip route | ${pkgs.gawk}/bin/awk '/default/ {print $3; exit}'` interface=`${pkgs.iproute2}/bin/ip route | ${pkgs.gawk}/bin/awk '/default/ {print $5; exit}'` '' + lib.concatLines (map (addr: "${pkgs.iproute2}/bin/ip route add ${addr} via $addr dev $interface || true") addrsViaDefaultInterface ); preDown = '' addr=`${pkgs.iproute2}/bin/ip route | ${pkgs.gawk}/bin/awk '/default/ {print $3; exit}'` interface=`${pkgs.iproute2}/bin/ip route | ${pkgs.gawk}/bin/awk '/default/ {print $5; exit}'` '' + lib.concatLines (map (addr: "${pkgs.iproute2}/bin/ip route del ${addr} via $addr dev $interface || true") addrsViaDefaultInterface ); peers = [ # For a client configuration, one peer entry for the server will suffice. { # Public key of the server (not a file path). publicKey = cfg.server.publicKey; # 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 = "${cfg.server.addr}:${toString cfg.server.port}"; # Send keepalives every 25 seconds. Important to keep NAT tables alive. persistentKeepalive = 15; } ]; }; }; }; }