1 diff --git a/nixos/modules/module-list.nix b/nixos/modules/module-list.nix
2 index ff06a72ff9dd..022ad5bdb8c9 100644
3 --- a/nixos/modules/module-list.nix
4 +++ b/nixos/modules/module-list.nix
6 ./services/networking/netbird.nix
7 ./services/networking/networkd-dispatcher.nix
8 ./services/networking/networkmanager.nix
9 + ./services/networking/netns.nix
10 ./services/networking/nextdns.nix
11 ./services/networking/nftables.nix
12 ./services/networking/nghttpx/default.nix
13 diff --git a/nixos/modules/services/networking/netns.nix b/nixos/modules/services/networking/netns.nix
15 index 000000000000..b14aff993022
17 +++ b/nixos/modules/services/networking/netns.nix
19 +{ pkgs, lib, config, options, ... }:
22 + cfg = config.services.netns;
23 + inherit (config) networking;
24 + # Escape as required by: https://www.freedesktop.org/software/systemd/man/systemd.unit.html
25 + escapeUnitName = name:
26 + lib.concatMapStrings (s: if lib.isList s then "-" else s)
27 + (builtins.split "[^a-zA-Z0-9_.\\-]+" name);
30 +options.services.netns = {
31 + namespaces = mkOption {
32 + description = mdDoc ''
33 + Network namespaces to create.
35 + Other services can join a network namespace named `netns` with:
37 + PrivateNetwork=true;
38 + JoinsNamespaceOf="netns-''${netns}.service";
41 + So can `iproute` with: `ip -n ''${netns}`
44 + You should usually create (or update via your VPN configuration's up script)
45 + a file named `/etc/netns/''${netns}/resolv.conf`
46 + that will be bind-mounted by `ip -n ''${netns}` onto `/etc/resolv.conf`,
47 + which you'll also want to configure in the services joining this network namespace:
49 + BindReadOnlyPaths = ["/etc/netns/''${netns}/resolv.conf:/etc/resolv.conf"];
54 + type = types.attrsOf (types.submodule {
55 + options.nftables = mkOption {
56 + description = mdDoc "Nftables ruleset within the network namespace.";
58 + default = networking.nftables.ruleset;
59 + defaultText = "config.networking.nftables.ruleset";
61 + options.sysctl = options.boot.kernel.sysctl // {
62 + description = mdDoc "sysctl within the network namespace.";
63 + default = config.boot.kernel.sysctl;
64 + defaultText = literalMD "config.boot.kernel.sysctl";
66 + options.service = mkOption {
67 + description = mdDoc "Systemd configuration specific to this netns service";
75 + systemd.services = mapAttrs' (name: c:
76 + nameValuePair "netns-${escapeUnitName name}" (mkMerge [
77 + { description = "${name} network namespace";
78 + before = [ "network.target" ];
81 + RemainAfterExit = true;
82 + # Let systemd create the netns so that PrivateNetwork=true
83 + # with JoinsNamespaceOf="netns-${name}.service" works.
84 + PrivateNetwork = true;
86 + # For convenience, register the netns to the tracking mecanism of iproute,
87 + # and make sure resolv.conf can be used in BindReadOnlyPaths=
88 + # For propagating changes in that file to the services bind mounting it,
89 + # updating must not remove the file, but only truncate it.
90 + (pkgs.writeShellScript "ip-netns-attach" ''
91 + ${pkgs.iproute}/bin/ip netns attach ${escapeShellArg name} $$
92 + mkdir -p /etc/netns/${escapeShellArg name}
93 + touch /etc/netns/${escapeShellArg name}/resolv.conf
96 + # Bringing the loopback interface is almost always a good thing.
97 + "${pkgs.iproute}/bin/ip link set dev lo up"
99 + # Use --ignore because some keys may no longer exist in that new namespace,
100 + # like net.ipv6.conf.eth0.addr_gen_mode or net.core.rmem_max
101 + ''${pkgs.procps}/bin/sysctl --ignore -p ${pkgs.writeScript "sysctl"
102 + (concatStrings (mapAttrsToList (n: v:
103 + optionalString (v != null)
104 + "${n}=${if v == false then "0" else toString v}\n"
108 + # Load the nftables ruleset of this netns.
109 + optional networking.nftables.enable (pkgs.writeScript "nftables-ruleset" ''
110 + #!${pkgs.nftables}/bin/nft -f
114 + # Unregister the netns from the tracking mecanism of iproute.
115 + ExecStop = "${pkgs.iproute}/bin/ip netns delete ${escapeShellArg name}";
121 + meta.maintainers = with lib.maintainers; [ julm ];
124 diff --git a/nixos/modules/services/networking/openvpn.nix b/nixos/modules/services/networking/openvpn.nix
125 index 9a5866f2afd4..ace7409f9523 100644
126 --- a/nixos/modules/services/networking/openvpn.nix
127 +++ b/nixos/modules/services/networking/openvpn.nix
128 @@ -5,55 +5,205 @@ with lib;
131 cfg = config.services.openvpn;
132 + enabledServers = filterAttrs (name: srv: srv.enable) cfg.servers;
134 inherit (pkgs) openvpn;
136 + PATH = name: makeBinPath config.systemd.services."openvpn-${name}".path;
138 makeOpenVPNJob = cfg: name:
141 - path = makeBinPath (getAttr "openvpn-${name}" config.systemd.services).path;
142 + configFile = pkgs.writeText "openvpn-config-${name}" (
143 + generators.toKeyValue
145 + mkKeyValue = key: value:
146 + if hasAttr key scripts
147 + then "${key} " + pkgs.writeShellScript "openvpn-${name}-${key}" (scripts.${key} value)
148 + else if builtins.isBool value
149 + then optionalString value key
150 + else if builtins.isPath value
151 + then "${key} ${value}"
152 + else if builtins.isList value
153 + then concatMapStringsSep "\n" (v: "${key} ${generators.mkValueStringDefault {} v}") value
154 + else "${key} ${generators.mkValueStringDefault {} value}";
160 - export PATH=${path}
165 + export PATH=${PATH name}
167 - # For convenience in client scripts, extract the remote domain
168 - # name and name server.
169 - for var in ''${!foreign_option_*}; do
171 - if [ "''${x[0]}" = dhcp-option ]; then
172 - if [ "''${x[1]}" = DOMAIN ]; then domain="''${x[2]}"
173 - elif [ "''${x[1]}" = DNS ]; then nameserver="''${x[2]}"
177 + # For convenience in client scripts, extract the remote domain
178 + # name and name server.
179 + for var in ''${!foreign_option_*}; do
181 + if [ "''${x[0]}" = dhcp-option ]; then
182 + if [ "''${x[1]}" = DOMAIN ]; then domain="''${x[2]}"
183 + elif [ "''${x[1]}" = DNS ]; then nameserver="''${x[2]}"
189 - ${optionalString cfg.updateResolvConf
190 - "${pkgs.update-resolv-conf}/libexec/openvpn/update-resolv-conf"}
192 + ${optionalString cfg.updateResolvConf
193 + "${pkgs.update-resolv-conf}/libexec/openvpn/update-resolv-conf"}
195 + # Add DNS settings given in foreign DHCP options to the resolv.conf of the netns.
196 + # Note that JoinsNamespaceOf="netns-${cfg.netns}.service" will not
197 + # BindReadOnlyPaths=["/etc/netns/${cfg.netns}/resolv.conf:/etc/resolv.conf"];
198 + # this will have to be added in each service joining the namespace.
199 + setNetNSResolvConf = ''
200 + mkdir -p /etc/netns/${cfg.netns}
201 + # This file is normally created by netns-${cfg.netns}.service,
202 + # care must be taken to not delete it but to truncate it
203 + # in order to propagate the changes to bind-mounted versions.
204 + : > /etc/netns/${cfg.netns}/resolv.conf
205 + chmod 644 /etc/netns/${cfg.netns}/resolv.conf
206 + foreign_opt_domains=
207 + process_foreign_option () {
209 + dhcp-option:DNS) echo "nameserver $3" >>/etc/netns/'${cfg.netns}'/resolv.conf ;;
210 + dhcp-option:DOMAIN) foreign_opt_domains="$foreign_opt_domains $3" ;;
215 + eval opt=\"\''${foreign_option_$i-}\"
218 + process_foreign_option $opt
221 + for d in $foreign_opt_domains; do
222 + printf '%s\n' "domain $1" "search $*" \
223 + >>/etc/netns/'${cfg.netns}'/resolv.conf
227 + if cfg.netns == null
233 + export PATH=${PATH name}
235 + ${setNetNSResolvConf}
236 + ip link set dev '${cfg.settings.dev}' up netns '${cfg.netns}' mtu "$tun_mtu"
237 + ip netns exec '${cfg.netns}' ${pkgs.writeShellScript "openvpn-${name}-up-netns.sh" ''
240 + export PATH=${PATH name}
243 - export PATH=${path}
244 - ${optionalString cfg.updateResolvConf
245 - "${pkgs.update-resolv-conf}/libexec/openvpn/update-resolv-conf"}
248 + ip link set dev lo up
250 - configFile = pkgs.writeText "openvpn-config-${name}"
253 - ${optionalString (cfg.up != "" || cfg.down != "" || cfg.updateResolvConf) "script-security 2"}
255 - ${optionalString (cfg.up != "" || cfg.updateResolvConf)
256 - "up ${pkgs.writeShellScript "openvpn-${name}-up" upScript}"}
257 - ${optionalString (cfg.down != "" || cfg.updateResolvConf)
258 - "down ${pkgs.writeShellScript "openvpn-${name}-down" downScript}"}
259 - ${optionalString (cfg.authUserPass != null)
260 - "auth-user-pass ${pkgs.writeText "openvpn-credentials-${name}" ''
261 - ${cfg.authUserPass.username}
262 - ${cfg.authUserPass.password}
265 + netmask4="''${ifconfig_netmask:-30}"
266 + netbits6="''${ifconfig_ipv6_netbits:-112}"
267 + if [ -n "''${ifconfig_local-}" ]; then
268 + if [ -n "''${ifconfig_remote-}" ]; then
269 + ip -4 addr replace \
270 + local "$ifconfig_local" \
271 + peer "$ifconfig_remote/$netmask4" \
272 + ''${ifconfig_broadcast:+broadcast "$ifconfig_broadcast"} \
273 + dev '${cfg.settings.dev}'
275 + ip -4 addr replace \
276 + local "$ifconfig_local/$netmask4" \
277 + ''${ifconfig_broadcast:+broadcast "$ifconfig_broadcast"} \
278 + dev '${cfg.settings.dev}'
281 + if [ -n "''${ifconfig_ipv6_local-}" ]; then
282 + if [ -n "''${ifconfig_ipv6_remote-}" ]; then
283 + ip -6 addr replace \
284 + local "$ifconfig_ipv6_local" \
285 + peer "$ifconfig_ipv6_remote/$netbits6" \
286 + dev '${cfg.settings.dev}'
288 + ip -6 addr replace \
289 + local "$ifconfig_ipv6_local/$netbits6" \
290 + dev '${cfg.settings.dev}'
298 + if cfg.netns == null
301 + export PATH=${PATH name}
303 + ip netns exec '${cfg.netns}' ${pkgs.writeShellScript "openvpn-${name}-route-up-netns" ''
304 + export PATH=${PATH name}
308 + eval net=\"\''${route_network_$i-}\"
309 + eval mask=\"\''${route_netmask_$i-}\"
310 + eval gw=\"\''${route_gateway_$i-}\"
311 + eval mtr=\"\''${route_metric_$i-}\"
314 + ip -4 route replace "$net/$mask" via "$gw" ''${mtr:+metric "$mtr"}
318 + if [ -n "''${route_vpn_gateway-}" ]; then
319 + ip -4 route replace default via "$route_vpn_gateway"
324 + # There doesn't seem to be $route_ipv6_metric_<n>
325 + # according to the manpage.
326 + eval net=\"\''${route_ipv6_network_$i-}\"
327 + eval gw=\"\''${route_ipv6_gateway_$i-}\"
330 + ip -6 route replace "$net" via "$gw" metric 100
334 + # There's no $route_vpn_gateway for IPv6. It's not
335 + # documented if OpenVPN includes default route in
336 + # $route_ipv6_*. Set default route to remote VPN
337 + # endpoint address if there is one. Use higher metric
338 + # than $route_ipv6_* routes to give preference to a
339 + # possible default route in them.
340 + if [ -n "''${ifconfig_ipv6_remote-}" ]; then
341 + ip -6 route replace default \
342 + via "$ifconfig_ipv6_remote" metric 200
350 + export PATH=${PATH name}
351 + ${optionalString cfg.updateResolvConf
352 + "${pkgs.update-resolv-conf}/libexec/openvpn/update-resolv-conf"}
355 + if cfg.netns == null
361 + export PATH=${PATH name}
362 + ip netns exec '${cfg.netns}' ${pkgs.writeShellScript "openvpn-${name}-down-netns.sh" ''
366 + rm -f /etc/netns/'${cfg.netns}'/resolv.conf
372 @@ -61,11 +211,14 @@ let
374 wantedBy = optional cfg.autoStart "multi-user.target";
375 after = [ "network.target" ];
376 + bindsTo = optional (cfg.netns != null) "netns-${cfg.netns}.service";
377 + requires = optional (cfg.netns != null) "netns-${cfg.netns}.service";
379 path = [ pkgs.iptables pkgs.iproute2 pkgs.nettools ];
381 serviceConfig.ExecStart = "@${openvpn}/sbin/openvpn openvpn --suppress-timestamps --config ${configFile}";
382 serviceConfig.Restart = "always";
383 + serviceConfig.RestartSec = "5s";
384 serviceConfig.Type = "notify";
387 @@ -96,30 +249,30 @@ in
388 example = literalExpression ''
393 # Simplest server configuration: https://community.openvpn.net/openvpn/wiki/StaticKeyMiniHowto
396 - ifconfig 10.8.0.1 10.8.0.2
397 - secret /root/static.key
399 - up = "ip route add ...";
400 - down = "ip route del ...";
402 + ifconfig = "10.8.0.1 10.8.0.2";
403 + secret = "/root/static.key";
404 + up = "ip route add ...";
405 + down = "ip route del ...";
412 - remote vpn.example.org
416 - ca /root/.vpn/ca.crt
417 - cert /root/.vpn/alice.crt
418 - key /root/.vpn/alice.key
420 - up = "echo nameserver $nameserver | ''${pkgs.openresolv}/sbin/resolvconf -m 0 -a $dev";
421 - down = "''${pkgs.openresolv}/sbin/resolvconf -d $dev";
424 + remote = "vpn.example.org";
426 + proto = "tcp-client";
428 + ca = "/root/.vpn/ca.crt";
429 + cert = "/root/.vpn/alice.crt";
430 + key = "/root/.vpn/alice.key";
431 + up = "echo nameserver $nameserver | ''${pkgs.openresolv}/sbin/resolvconf -m 0 -a $dev";
432 + down = "''${pkgs.openresolv}/sbin/resolvconf -d $dev";
437 @@ -133,36 +286,80 @@ in
441 - type = with types; attrsOf (submodule {
442 + type = with types; attrsOf (submodule ({ name, config, options, ... }: {
446 + enable = mkEnableOption (mdDoc "OpenVPN server") // { default = true; };
448 - config = mkOption {
449 - type = types.lines;
450 + settings = mkOption {
451 description = lib.mdDoc ''
452 Configuration of this OpenVPN instance. See
453 {manpage}`openvpn(8)`
456 To import an external config file, use the following definition:
457 - `config = "config /path/to/config.ovpn"`
463 - type = types.lines;
464 - description = lib.mdDoc ''
465 - Shell commands executed when the instance is starting.
471 - type = types.lines;
472 - description = lib.mdDoc ''
473 - Shell commands executed when the instance is shutting down.
474 + config = /path/to/config.ovpn;
477 + type = types.submodule {
478 + freeformType = with types;
486 + (listOf (oneOf [ bool int str path ]))
490 + options.dev = mkOption {
493 + description = lib.mdDoc ''
494 + Shell commands executed when the instance is starting.
497 + options.down = mkOption {
499 + type = types.lines;
500 + description = lib.mdDoc ''
501 + Shell commands executed when the instance is shutting down.
504 + options.errors-to-stderr = mkOption {
507 + description = lib.mdDoc ''
508 + Output errors to stderr instead of stdout
509 + unless log output is redirected by one of the `--log` options.
512 + options.route-up = mkOption {
514 + type = types.lines;
515 + description = lib.mdDoc ''
516 + Run command after routes are added.
519 + options.up = mkOption {
521 + type = types.lines;
522 + description = lib.mdDoc ''
523 + Shell commands executed when the instance is starting.
526 + options.script-security = mkOption {
528 + type = types.enum [ 1 2 3 ];
529 + description = lib.mdDoc ''
530 + - 1 — (Default) Only call built-in executables such as ifconfig, ip, route, or netsh.
531 + - 2 — Allow calling of built-in executables and user-defined scripts.
532 + - 3 — Allow passwords to be passed to scripts via environmental variables (potentially unsafe).
538 autoStart = mkOption {
539 @@ -171,6 +368,10 @@ in
540 description = lib.mdDoc "Whether this OpenVPN instance should be started automatically.";
544 + down = (elemAt settings.type.functor.payload.modules 0).options.down;
545 + up = (elemAt settings.type.functor.payload.modules 0).options.up;
547 updateResolvConf = mkOption {
550 @@ -204,9 +405,41 @@ in
557 + type = with types; nullOr str;
558 + description = lib.mdDoc "Network namespace.";
563 + config.settings = mkMerge
565 + (mkIf (config.netns != null) {
566 + # Useless to setup the interface
567 + # because moving it to the netns will reset it
568 + ifconfig-noexec = true;
569 + route-noexec = true;
570 + script-security = 2;
572 + (mkIf (config.authUserPass != null) {
573 + auth-user-pass = pkgs.writeText "openvpn-auth-user-pass-${name}" ''
574 + ${config.authUserPass.username}
575 + ${config.authUserPass.password}
578 + (mkIf config.updateResolvConf {
579 + script-security = 2;
582 + # Aliases legacy options
583 + down = modules.mkAliasAndWrapDefsWithPriority id (options.down or { });
584 + up = modules.mkAliasAndWrapDefsWithPriority id (options.up or { });
593 @@ -221,9 +454,9 @@ in
595 ###### implementation
597 - config = mkIf (cfg.servers != { }) {
598 + config = mkIf (enabledServers != { }) {
600 - systemd.services = (listToAttrs (mapAttrsFlatten (name: value: nameValuePair "openvpn-${name}" (makeOpenVPNJob value name)) cfg.servers))
601 + systemd.services = (listToAttrs (mapAttrsFlatten (name: value: nameValuePair "openvpn-${name}" (makeOpenVPNJob value name)) enabledServers))
604 environment.systemPackages = [ openvpn ];