1 From 600839a7759be481904d029798e563e23df930db Mon Sep 17 00:00:00 2001
2 From: Julien Moutinho <julm+nixpkgs@sourcephile.fr>
3 Date: Sun, 17 Jan 2021 15:28:25 +0100
4 Subject: [PATCH 2/2] nixos/openvpn: add netns support
7 nixos/modules/services/networking/openvpn.nix | 395 ++++++++++++++----
8 1 file changed, 314 insertions(+), 81 deletions(-)
10 diff --git a/nixos/modules/services/networking/openvpn.nix b/nixos/modules/services/networking/openvpn.nix
11 index 56b1f6f5ab8f..9805099789b1 100644
12 --- a/nixos/modules/services/networking/openvpn.nix
13 +++ b/nixos/modules/services/networking/openvpn.nix
14 @@ -5,55 +5,205 @@ with lib;
17 cfg = config.services.openvpn;
18 + enabledServers = filterAttrs (name: srv: srv.enable) cfg.servers;
20 inherit (pkgs) openvpn;
22 + PATH = name: makeBinPath config.systemd.services."openvpn-${name}".path;
24 makeOpenVPNJob = cfg: name:
27 - path = makeBinPath (getAttr "openvpn-${name}" config.systemd.services).path;
28 + configFile = pkgs.writeText "openvpn-config-${name}" (
29 + generators.toKeyValue
31 + mkKeyValue = key: value:
32 + if hasAttr key scripts
33 + then "${key} " + pkgs.writeShellScript "openvpn-${name}-${key}" (scripts.${key} value)
34 + else if builtins.isBool value
35 + then optionalString value key
36 + else if builtins.isPath value
37 + then "${key} ${value}"
38 + else if builtins.isList value
39 + then concatMapStringsSep "\n" (v: "${key} ${generators.mkValueStringDefault {} v}") value
40 + else "${key} ${generators.mkValueStringDefault {} value}";
51 + export PATH=${PATH name}
53 - # For convenience in client scripts, extract the remote domain
54 - # name and name server.
55 - for var in ''${!foreign_option_*}; do
57 - if [ "''${x[0]}" = dhcp-option ]; then
58 - if [ "''${x[1]}" = DOMAIN ]; then domain="''${x[2]}"
59 - elif [ "''${x[1]}" = DNS ]; then nameserver="''${x[2]}"
63 + # For convenience in client scripts, extract the remote domain
64 + # name and name server.
65 + for var in ''${!foreign_option_*}; do
67 + if [ "''${x[0]}" = dhcp-option ]; then
68 + if [ "''${x[1]}" = DOMAIN ]; then domain="''${x[2]}"
69 + elif [ "''${x[1]}" = DNS ]; then nameserver="''${x[2]}"
75 - ${optionalString cfg.updateResolvConf
76 - "${pkgs.update-resolv-conf}/libexec/openvpn/update-resolv-conf"}
78 + ${optionalString cfg.updateResolvConf
79 + "${pkgs.update-resolv-conf}/libexec/openvpn/update-resolv-conf"}
81 + # Add DNS settings given in foreign DHCP options to the resolv.conf of the netns.
82 + # Note that JoinsNamespaceOf="netns-${cfg.netns}.service" will not
83 + # BindReadOnlyPaths=["/etc/netns/${cfg.netns}/resolv.conf:/etc/resolv.conf"];
84 + # this will have to be added in each service joining the namespace.
85 + setNetNSResolvConf = ''
86 + mkdir -p /etc/netns/${cfg.netns}
87 + # This file is normally created by netns-${cfg.netns}.service,
88 + # care must be taken to not delete it but to truncate it
89 + # in order to propagate the changes to bind-mounted versions.
90 + : > /etc/netns/${cfg.netns}/resolv.conf
91 + chmod 644 /etc/netns/${cfg.netns}/resolv.conf
92 + foreign_opt_domains=
93 + process_foreign_option () {
95 + dhcp-option:DNS) echo "nameserver $3" >>/etc/netns/'${cfg.netns}'/resolv.conf ;;
96 + dhcp-option:DOMAIN) foreign_opt_domains="$foreign_opt_domains $3" ;;
101 + eval opt=\"\''${foreign_option_$i-}\"
104 + process_foreign_option $opt
107 + for d in $foreign_opt_domains; do
108 + printf '%s\n' "domain $1" "search $*" \
109 + >>/etc/netns/'${cfg.netns}'/resolv.conf
113 + if cfg.netns == null
119 + export PATH=${PATH name}
121 + ${setNetNSResolvConf}
122 + ip link set dev '${cfg.settings.dev}' up netns '${cfg.netns}' mtu "$tun_mtu"
123 + ip netns exec '${cfg.netns}' ${pkgs.writeShellScript "openvpn-${name}-up-netns.sh" ''
126 + export PATH=${PATH name}
129 - export PATH=${path}
130 - ${optionalString cfg.updateResolvConf
131 - "${pkgs.update-resolv-conf}/libexec/openvpn/update-resolv-conf"}
134 + ip link set dev lo up
136 - configFile = pkgs.writeText "openvpn-config-${name}"
139 - ${optionalString (cfg.up != "" || cfg.down != "" || cfg.updateResolvConf) "script-security 2"}
141 - ${optionalString (cfg.up != "" || cfg.updateResolvConf)
142 - "up ${pkgs.writeShellScript "openvpn-${name}-up" upScript}"}
143 - ${optionalString (cfg.down != "" || cfg.updateResolvConf)
144 - "down ${pkgs.writeShellScript "openvpn-${name}-down" downScript}"}
145 - ${optionalString (cfg.authUserPass != null)
146 - "auth-user-pass ${pkgs.writeText "openvpn-credentials-${name}" ''
147 - ${cfg.authUserPass.username}
148 - ${cfg.authUserPass.password}
151 + netmask4="''${ifconfig_netmask:-30}"
152 + netbits6="''${ifconfig_ipv6_netbits:-112}"
153 + if [ -n "''${ifconfig_local-}" ]; then
154 + if [ -n "''${ifconfig_remote-}" ]; then
155 + ip -4 addr replace \
156 + local "$ifconfig_local" \
157 + peer "$ifconfig_remote/$netmask4" \
158 + ''${ifconfig_broadcast:+broadcast "$ifconfig_broadcast"} \
159 + dev '${cfg.settings.dev}'
161 + ip -4 addr replace \
162 + local "$ifconfig_local/$netmask4" \
163 + ''${ifconfig_broadcast:+broadcast "$ifconfig_broadcast"} \
164 + dev '${cfg.settings.dev}'
167 + if [ -n "''${ifconfig_ipv6_local-}" ]; then
168 + if [ -n "''${ifconfig_ipv6_remote-}" ]; then
169 + ip -6 addr replace \
170 + local "$ifconfig_ipv6_local" \
171 + peer "$ifconfig_ipv6_remote/$netbits6" \
172 + dev '${cfg.settings.dev}'
174 + ip -6 addr replace \
175 + local "$ifconfig_ipv6_local/$netbits6" \
176 + dev '${cfg.settings.dev}'
184 + if cfg.netns == null
187 + export PATH=${PATH name}
189 + ip netns exec '${cfg.netns}' ${pkgs.writeShellScript "openvpn-${name}-route-up-netns" ''
190 + export PATH=${PATH name}
194 + eval net=\"\''${route_network_$i-}\"
195 + eval mask=\"\''${route_netmask_$i-}\"
196 + eval gw=\"\''${route_gateway_$i-}\"
197 + eval mtr=\"\''${route_metric_$i-}\"
200 + ip -4 route replace "$net/$mask" via "$gw" ''${mtr:+metric "$mtr"}
204 + if [ -n "''${route_vpn_gateway-}" ]; then
205 + ip -4 route replace default via "$route_vpn_gateway"
210 + # There doesn't seem to be $route_ipv6_metric_<n>
211 + # according to the manpage.
212 + eval net=\"\''${route_ipv6_network_$i-}\"
213 + eval gw=\"\''${route_ipv6_gateway_$i-}\"
216 + ip -6 route replace "$net" via "$gw" metric 100
220 + # There's no $route_vpn_gateway for IPv6. It's not
221 + # documented if OpenVPN includes default route in
222 + # $route_ipv6_*. Set default route to remote VPN
223 + # endpoint address if there is one. Use higher metric
224 + # than $route_ipv6_* routes to give preference to a
225 + # possible default route in them.
226 + if [ -n "''${ifconfig_ipv6_remote-}" ]; then
227 + ip -6 route replace default \
228 + via "$ifconfig_ipv6_remote" metric 200
236 + export PATH=${PATH name}
237 + ${optionalString cfg.updateResolvConf
238 + "${pkgs.update-resolv-conf}/libexec/openvpn/update-resolv-conf"}
241 + if cfg.netns == null
247 + export PATH=${PATH name}
248 + ip netns exec '${cfg.netns}' ${pkgs.writeShellScript "openvpn-${name}-down-netns.sh" ''
252 + rm -f /etc/netns/'${cfg.netns}'/resolv.conf
258 @@ -61,11 +211,14 @@ let
260 wantedBy = optional cfg.autoStart "multi-user.target";
261 after = [ "network.target" ];
262 + bindsTo = optional (cfg.netns != null) "netns-${cfg.netns}.service";
263 + requires = optional (cfg.netns != null) "netns-${cfg.netns}.service";
265 path = [ pkgs.iptables pkgs.iproute2 pkgs.nettools ];
267 serviceConfig.ExecStart = "@${openvpn}/sbin/openvpn openvpn --suppress-timestamps --config ${configFile}";
268 serviceConfig.Restart = "always";
269 + serviceConfig.RestartSec = "5s";
270 serviceConfig.Type = "notify";
273 @@ -97,30 +250,30 @@ in
274 example = literalExpression ''
279 # Simplest server configuration: https://community.openvpn.net/openvpn/wiki/StaticKeyMiniHowto
282 - ifconfig 10.8.0.1 10.8.0.2
283 - secret /root/static.key
285 - up = "ip route add ...";
286 - down = "ip route del ...";
288 + ifconfig = "10.8.0.1 10.8.0.2";
289 + secret = "/root/static.key";
290 + up = "ip route add ...";
291 + down = "ip route del ...";
298 - remote vpn.example.org
302 - ca /root/.vpn/ca.crt
303 - cert /root/.vpn/alice.crt
304 - key /root/.vpn/alice.key
306 - up = "echo nameserver $nameserver | ''${pkgs.openresolv}/sbin/resolvconf -m 0 -a $dev";
307 - down = "''${pkgs.openresolv}/sbin/resolvconf -d $dev";
310 + remote = "vpn.example.org";
312 + proto = "tcp-client";
314 + ca = "/root/.vpn/ca.crt";
315 + cert = "/root/.vpn/alice.crt";
316 + key = "/root/.vpn/alice.key";
317 + up = "echo nameserver $nameserver | ''${pkgs.openresolv}/sbin/resolvconf -m 0 -a $dev";
318 + down = "''${pkgs.openresolv}/sbin/resolvconf -d $dev";
323 @@ -134,36 +287,80 @@ in
327 - type = with types; attrsOf (submodule {
328 + type = with types; attrsOf (submodule ({ name, config, options, ... }: {
332 + enable = mkEnableOption "OpenVPN server" // { default = true; };
334 - config = mkOption {
335 - type = types.lines;
336 + settings = mkOption {
338 Configuration of this OpenVPN instance. See
339 {manpage}`openvpn(8)`
342 To import an external config file, use the following definition:
343 - `config = "config /path/to/config.ovpn"`
349 - type = types.lines;
351 - Shell commands executed when the instance is starting.
357 - type = types.lines;
359 - Shell commands executed when the instance is shutting down.
360 + config = /path/to/config.ovpn;
363 + type = types.submodule {
364 + freeformType = with types;
372 + (listOf (oneOf [ bool int str path ]))
376 + options.dev = mkOption {
380 + Shell commands executed when the instance is starting.
383 + options.down = mkOption {
385 + type = types.lines;
387 + Shell commands executed when the instance is shutting down.
390 + options.errors-to-stderr = mkOption {
394 + Output errors to stderr instead of stdout
395 + unless log output is redirected by one of the `--log` options.
398 + options.route-up = mkOption {
400 + type = types.lines;
402 + Run command after routes are added.
405 + options.up = mkOption {
407 + type = types.lines;
409 + Shell commands executed when the instance is starting.
412 + options.script-security = mkOption {
414 + type = types.enum [ 1 2 3 ];
416 + - 1 — (Default) Only call built-in executables such as ifconfig, ip, route, or netsh.
417 + - 2 — Allow calling of built-in executables and user-defined scripts.
418 + - 3 — Allow passwords to be passed to scripts via environmental variables (potentially unsafe).
424 autoStart = mkOption {
425 @@ -172,6 +369,10 @@ in
426 description = "Whether this OpenVPN instance should be started automatically.";
430 + down = (elemAt settings.type.functor.payload.modules 0).options.down;
431 + up = (elemAt settings.type.functor.payload.modules 0).options.up;
433 updateResolvConf = mkOption {
436 @@ -205,9 +406,41 @@ in
443 + type = with types; nullOr str;
444 + description = "Network namespace.";
449 + config.settings = mkMerge
451 + (mkIf (config.netns != null) {
452 + # Useless to setup the interface
453 + # because moving it to the netns will reset it
454 + ifconfig-noexec = true;
455 + route-noexec = true;
456 + script-security = 2;
458 + (mkIf (config.authUserPass != null) {
459 + auth-user-pass = pkgs.writeText "openvpn-auth-user-pass-${name}" ''
460 + ${config.authUserPass.username}
461 + ${config.authUserPass.password}
464 + (mkIf config.updateResolvConf {
465 + script-security = 2;
468 + # Aliases legacy options
469 + down = modules.mkAliasAndWrapDefsWithPriority id (options.down or { });
470 + up = modules.mkAliasAndWrapDefsWithPriority id (options.up or { });
479 @@ -222,9 +455,9 @@ in
481 ###### implementation
483 - config = mkIf (cfg.servers != { }) {
484 + config = mkIf (enabledServers != { }) {
486 - systemd.services = (listToAttrs (mapAttrsToList (name: value: nameValuePair "openvpn-${name}" (makeOpenVPNJob value name)) cfg.servers))
487 + systemd.services = (listToAttrs (mapAttrsToList (name: value: nameValuePair "openvpn-${name}" (makeOpenVPNJob value name)) enabledServers))
490 environment.systemPackages = [ openvpn ];