flake/modules/nixos/server/wireguard.nix
2024-09-20 15:00:45 +00:00

93 lines
3.1 KiB
Nix

{ pkgs, lib, config, ... }: {
options.mods.server.wireguard = {
enable = lib.mkEnableOption {
default = false;
description = "enables wireguard server";
};
};
config = lib.mkIf config.mods.server.wireguard.enable {
networking.nat = {
enable = true;
enableIPv6 = true;
externalInterface = "ens3";
internalInterfaces = [ "wg0" ];
};
networking.firewall = {
allowedTCPPorts = [ 53 ];
allowedUDPPorts = [ 53 51820 ];
};
networking.wg-quick.interfaces = {
# "wg0" is the network interface name. You can name the interface arbitrarily.
wg0 = {
# Determines the IP/IPv6 address and subnet of the client's end of the tunnel interface
address = [ "10.0.0.1/24" "fdc9:281f:04d7:9ee9::1/64" ];
# The port that WireGuard listens to - recommended that this be changed from default
listenPort = 51820;
# Path to the server's private key
privateKeyFile = "/home/muon/wireguard-keys/private";
# This allows the wireguard server to route your traffic to the internet and hence be like a VPN
postUp = ''
${pkgs.iptables}/bin/iptables -A FORWARD -i wg0 -j ACCEPT
${pkgs.iptables}/bin/iptables -t nat -A POSTROUTING -s 10.0.0.1/24 -o ens3 -j MASQUERADE
${pkgs.iptables}/bin/ip6tables -A FORWARD -i wg0 -j ACCEPT
${pkgs.iptables}/bin/ip6tables -t nat -A POSTROUTING -s fdc9:281f:04d7:9ee9::1/64 -o ens3 -j MASQUERADE
'';
# Undo the above
preDown = ''
${pkgs.iptables}/bin/iptables -D FORWARD -i wg0 -j ACCEPT
${pkgs.iptables}/bin/iptables -t nat -D POSTROUTING -s 10.0.0.1/24 -o ens3 -j MASQUERADE
${pkgs.iptables}/bin/ip6tables -D FORWARD -i wg0 -j ACCEPT
${pkgs.iptables}/bin/ip6tables -t nat -D POSTROUTING -s fdc9:281f:04d7:9ee9::1/64 -o ens3 -j MASQUERADE
'';
peers = [{ # peer0
publicKey = "MDBdADwP/SE/T9cadXB1Mup7Dr3x+l6gBFBN83BU4Dg=";
presharedKeyFile = "/home/muon/wireguard-keys/psk-muon";
allowedIPs = [ "10.0.0.2/32" "fdc9:281f:04d7:9ee9::2/128" ];
}
# More peers can be added here.
];
};
};
services.dnsmasq = {
enable = true;
settings.bind-interfaces = true;
settings.interface = "wg0";
# extraConfig = ''
# interface=wg0
# '';
};
# networking.wireguard.interfaces = {
# wg0 = {
# ips = [ "10.100.0.1/24" ];
# listenPort = 51820;
# postSetup = ''
# ${pkgs.iptables}/bin/iptables -t nat -A POSTROUTING -s 10.100.0.0/24 -o eth0 -j MASQUERADE
# '';
# # This undoes the above command
# postShutdown = ''
# ${pkgs.iptables}/bin/iptables -t nat -D POSTROUTING -s 10.100.0.0/24 -o eth0 -j MASQUERADE
# '';
# privateKeyFile = "/home/muon/wireguard-keys/private";
# peers = [
# {
# publicKey = "MDBdADwP/SE/T9cadXB1Mup7Dr3x+l6gBFBN83BU4Dg=";
# allowedIPs = [ "10.100.0.2/32" ];
# }
# ];
# };
# };
};
}