Imported Upstream version 2.3.3
[platform/upstream/cryptsetup.git] / misc / dracut_90reencrypt / reencrypt.sh
1 #!/bin/sh
2 #
3 # $1=$device [$2=keyfile|none [$3=keyslot|any [$4=size]]]
4 #
5
6 [ -d /sys/module/dm_crypt ] || modprobe dm_crypt
7
8 [ -d /sys/module/loop ] || modprobe loop
9
10 [ -f /tmp/reencrypted ] && exit 0
11
12 . /lib/dracut-lib.sh
13
14 # if device name is /dev/dm-X, convert to /dev/mapper/name
15 if [ "${1##/dev/dm-}" != "$1" ]; then
16     device="/dev/mapper/$(dmsetup info -c --noheadings -o name "$1")"
17 else
18     device="$1"
19 fi
20
21 PARAMS="$device -T 1 --use-fsync --progress-frequency 5 -B 32"
22 if [ "$3" != "any" ]; then
23     PARAMS="$PARAMS -S $3"
24 fi
25
26 if [ -n "$4" ]; then
27     PARAMS="$PARAMS --device-size $4"
28 fi
29
30 reenc_readkey() {
31     keypath="${1#*:}"
32     keydev="${1%%:*}"
33
34     mntp="/tmp/reencrypted-mount-tmp"
35     mkdir "$mntp"
36     mount -r "$keydev" "$mntp" && cat "$mntp/$keypath"
37     umount "$mntp"
38     rm -r "$mntp"
39 }
40
41 # shellcheck disable=SC2086
42 # shellcheck disable=SC2164
43 reenc_run() {
44     cwd=$(pwd)
45     _prompt="LUKS password for REENCRYPTING $device"
46     cd /tmp
47     udevadm settle
48     if [ "$1" = "none" ] ; then
49         if [ "$2" != "any" ]; then
50                 _prompt="$_prompt, using keyslot $2"
51         fi
52         /bin/plymouth ask-for-password \
53         --prompt "$_prompt" \
54         --command="/sbin/cryptsetup-reencrypt-verbose $PARAMS"
55     else
56         info "REENCRYPT using key $1"
57         reenc_readkey "$1" | /sbin/cryptsetup-reencrypt-verbose -d - $PARAMS
58     fi
59     _ret=$?
60     cd $cwd
61 }
62
63 info "REENCRYPT $device requested"
64 # flock against other interactive activities
65 # shellcheck disable=SC2086
66 { flock -s 9;
67     reenc_run $2 $3
68 } 9>/.console_lock
69
70 if [ $_ret -eq 0 ]; then
71     # do not ask again
72     # shellcheck disable=SC2188
73     >> /tmp/reencrypted
74     warn "Reencryption of device $device has finished successfully. Use previous"
75     warn "initramfs image (without reencrypt module) to boot the system. When"
76     warn "you leave the emergency shell, the system will reboot."
77
78     emergency_shell -n "(reboot)"
79     [ -x /usr/bin/systemctl ] && /usr/bin/systemctl reboot
80     [ -x /sbin/shutdown ] && /sbin/shutdown -r now
81 fi
82
83 # panic the kernel otherwise
84 exit 1