summary refs log tree commit diff
path: root/nixos/modules/tasks/encrypted-devices.nix
blob: 331531cee15121a35a4b75e266846e2116a179a1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
{ config, lib, ... }:

with lib;

let
  fileSystems = attrValues config.fileSystems ++ config.swapDevices;
  encDevs = filter (dev: dev.encrypted.enable) fileSystems;
  keyedEncDevs = filter (dev: dev.encrypted.keyFile != null) encDevs;
  keylessEncDevs = filter (dev: dev.encrypted.keyFile == null) encDevs;
  isIn = needle: haystack: filter (p: p == needle) haystack != [];
  anyEncrypted =
    fold (j: v: v || j.encrypted.enable) false encDevs;

  encryptedFSOptions = {

    encrypted = {
      enable = mkOption {
        default = false;
        type = types.bool;
        description = "The block device is backed by an encrypted one, adds this device as a initrd luks entry.";
      };

      blkDev = mkOption {
        default = null;
        example = "/dev/sda1";
        type = types.nullOr types.str;
        description = "Location of the backing encrypted device.";
      };

      label = mkOption {
        default = null;
        example = "rootfs";
        type = types.uniq (types.nullOr types.str);
        description = "Label of the unlocked encrypted device. Set <literal>fileSystems.&lt;name?&gt;.device</literal> to <literal>/dev/mapper/&lt;label&gt;</literal> to mount the unlocked device.";
      };

      keyFile = mkOption {
        default = null;
        example = "/root/.swapkey";
        type = types.nullOr types.str;
        description = "File system location of keyfile. This unlocks the drive after the root has been mounted to <literal>/mnt-root</literal>.";
      };
    };
  };
in

{

  options = {
    fileSystems = mkOption {
      options = [encryptedFSOptions];
    };
    swapDevices = mkOption {
      options = [encryptedFSOptions];
    };
  };

  config = mkIf anyEncrypted {
    boot.initrd = {
      luks = {
        devices =
          map (dev: { name = dev.encrypted.label; device = dev.encrypted.blkDev; } ) keylessEncDevs;
        cryptoModules = [ "aes" "sha256" "sha1" "xts" ];
      };
      postMountCommands =
        concatMapStrings (dev: "cryptsetup luksOpen --key-file ${dev.encrypted.keyFile} ${dev.encrypted.blkDev} ${dev.encrypted.label};\n") keyedEncDevs;
    };
  };
}