1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7 cfg = config.boot.initrd.network.openvpn;
8
9in
10
11{
12
13 options = {
14
15 boot.initrd.network.openvpn.enable = mkOption {
16 type = types.bool;
17 default = false;
18 description = ''
19 Starts an OpenVPN client during initrd boot. It can be used to e.g.
20 remotely accessing the SSH service controlled by
21 <option>boot.initrd.network.ssh</option> or other network services
22 included. Service is killed when stage-1 boot is finished.
23 '';
24 };
25
26 boot.initrd.network.openvpn.configuration = mkOption {
27 type = types.path; # Same type as boot.initrd.secrets
28 description = ''
29 The configuration file for OpenVPN.
30
31 <warning>
32 <para>
33 Unless your bootloader supports initrd secrets, this configuration
34 is stored insecurely in the global Nix store.
35 </para>
36 </warning>
37 '';
38 example = literalExpression "./configuration.ovpn";
39 };
40
41 };
42
43 config = mkIf (config.boot.initrd.network.enable && cfg.enable) {
44 assertions = [
45 {
46 assertion = cfg.configuration != null;
47 message = "You should specify a configuration for initrd OpenVPN";
48 }
49 ];
50
51 # Add kernel modules needed for OpenVPN
52 boot.initrd.kernelModules = [ "tun" "tap" ];
53
54 # Add openvpn and ip binaries to the initrd
55 # The shared libraries are required for DNS resolution
56 boot.initrd.extraUtilsCommands = ''
57 copy_bin_and_libs ${pkgs.openvpn}/bin/openvpn
58 copy_bin_and_libs ${pkgs.iproute2}/bin/ip
59
60 cp -pv ${pkgs.glibc}/lib/libresolv.so.2 $out/lib
61 cp -pv ${pkgs.glibc}/lib/libnss_dns.so.2 $out/lib
62 '';
63
64 boot.initrd.secrets = {
65 "/etc/initrd.ovpn" = cfg.configuration;
66 };
67
68 # openvpn --version would exit with 1 instead of 0
69 boot.initrd.extraUtilsCommandsTest = ''
70 $out/bin/openvpn --show-gateway
71 '';
72
73 # Add `iproute /bin/ip` to the config, to ensure that openvpn
74 # is able to set the routes
75 boot.initrd.network.postCommands = ''
76 (cat /etc/initrd.ovpn; echo -e '\niproute /bin/ip') | \
77 openvpn /dev/stdin &
78 '';
79 };
80
81}