如何配置 systemd 以激活加密的交换文件?

cjm*_*cjm 7 linux encryption swap systemd

之前的问题产生了添加加密交换文件的命令:

# One-time setup:
fallocate -l 4G /root/swapfile.crypt
chmod 600 /root/swapfile.crypt

# On every boot:
loop=$(losetup -f)
losetup ${loop} /root/swapfile.crypt
cryptsetup open --type plain --key-file /dev/urandom ${loop} swapfile
mkswap /dev/mapper/swapfile
swapon /dev/mapper/swapfile
Run Code Online (Sandbox Code Playgroud)

但是Arch Linux使用systemd,我无法弄清楚如何最好地让 systemd 自动激活我的交换文件。 systemd.swap建议我应该有一个dev-mapper-swapfile.swap看起来像这样的单元:

[Unit]
Description=Encrypted Swap File

[Swap]
What=/dev/mapper/swapfile
Run Code Online (Sandbox Code Playgroud)

那将执行swapon命令。但我不确定如何执行准备/dev/mapper/swapfile. 我认为dev-mapper-swapfile.swap应该声明对某个其他单元的依赖,但我不确定该单元应该是什么样子。

t-8*_*8ch 5

你可能想看看:

  • 密码表(5)
  • systemd-cryptsetup@.service(8)
  • systemd-cryptsetup-generator(8)

这些适用于由块设备支持的加密卷。它们也应该适用于文件支持的卷。

更新:

这对我有用:

# Automatically generated by systemd-cryptsetup-generator

[Unit]
Description=Cryptography Setup for %I
Documentation=man:systemd-cryptsetup@.service(8) man:crypttab(5)
SourcePath=/etc/crypttab
Conflicts=umount.target
DefaultDependencies=no
BindsTo=dev-mapper-%i.device
After=systemd-readahead-collect.service systemd-readahead-replay.service
Before=umount.target
Before=cryptsetup.target
After=systemd-random-seed-load.service

[Service]
Type=oneshot
RemainAfterExit=yes
TimeoutSec=0
ExecStart=/usr/lib/systemd/systemd-cryptsetup attach 'swap2' '/swap.test'     '/dev/urandom' 'swap'
ExecStop=/usr/lib/systemd/systemd-cryptsetup detach 'swap2'
ExecStartPost=/sbin/mkswap '/dev/mapper/swap2'
Run Code Online (Sandbox Code Playgroud)

获取此文件的步骤:

  • 在 /etc/crypttab 中创建一个条目: swap2 /swap.test /dev/urandom swap
  • 运行以下命令:/usr/lib/systemd/system-generators/systemd-cryptsetup-generator 这将在/tmp/目录中创建单元文件。
  • 搜索生成的单元文件。
  • 打开它并从和指令中删除条目。这很重要,因为根据定义,交换文件没有设备。这会阻止单元文件的启动。swap.test.deviceAfter=BindsTo=
  • 将单元文件复制到 /etc/systemd/system/
  • 为您最喜欢的目标激活它。