config/modules/services/friendlyport/default.nix

60 lines
1.9 KiB
Nix
Raw Normal View History

2024-07-29 15:39:54 +03:00
{ config, lib, ... }:
2023-08-05 18:00:43 +03:00
{
2023-09-12 15:46:44 +03:00
options.mj.services.friendlyport = with lib.types; {
2023-08-06 00:47:32 +03:00
ports = lib.mkOption {
2023-10-01 23:14:05 +03:00
type = listOf (submodule {
options = {
2024-07-29 15:39:54 +03:00
subnets = lib.mkOption { type = listOf str; };
2023-10-01 23:14:05 +03:00
tcp = lib.mkOption {
type = listOf int;
2024-07-29 15:39:54 +03:00
default = [ ];
2023-09-12 15:46:44 +03:00
};
2023-10-01 23:14:05 +03:00
udp = lib.mkOption {
type = listOf int;
2024-07-29 15:39:54 +03:00
default = [ ];
2023-10-01 23:14:05 +03:00
};
};
});
2023-08-05 18:00:43 +03:00
};
};
2024-07-29 15:39:54 +03:00
config =
let
inherit (config.mj.services.friendlyport) ports;
2023-10-01 23:14:05 +03:00
2024-07-29 15:39:54 +03:00
mkAdd =
proto: subnets: ints:
let
subnetsS = builtins.concatStringsSep "," subnets;
intsS = builtins.concatStringsSep "," (map builtins.toString ints);
in
if builtins.length ints == 0 then
""
else
"iptables -A INPUT -p ${proto} --match multiport --dports ${intsS} --source ${subnetsS} -j ACCEPT";
2023-09-12 15:46:44 +03:00
2024-07-29 15:39:54 +03:00
startTCP = map (attr: mkAdd "tcp" attr.subnets attr.tcp) ports;
startUDP = map (attr: mkAdd "udp" attr.subnets attr.udp) ports;
2023-08-06 00:47:32 +03:00
2024-07-29 15:39:54 +03:00
# TODO: when stopping the firewall, systemd uses the old ports. So this is a two-phase process.
# How to stop the old one and start the new one?
mkDel =
proto: subnets: ints:
let
subnetsS = builtins.concatStringsSep "," subnets;
intsS = builtins.concatStringsSep "," (map builtins.toString ints);
in
if builtins.length ints == 0 then
""
else
"iptables -D INPUT -p ${proto} --match multiport --dports ${intsS} --source ${subnetsS} -j ACCEPT || :";
2023-09-12 15:46:44 +03:00
2024-07-29 15:39:54 +03:00
stopTCP = map (attr: mkDel "tcp" attr.subnets attr.tcp) ports;
stopUDP = map (attr: mkDel "udp" attr.subnets attr.udp) ports;
in
{
networking.firewall.extraCommands = lib.concatLines (startTCP ++ startUDP);
networking.firewall.extraStopCommands = lib.concatLines (stopTCP ++ stopUDP);
};
2023-08-05 18:00:43 +03:00
}