Include 'sys/sysmacros.h' for GCC-9
[platform/upstream/cryptsetup.git] / misc / luks-header-from-active
1 #!/bin/bash
2
3 # Try to get LUKS info and master key from active mapping and prepare parameters for cryptsetup.
4 #
5 # Copyright (C) 2010,2011,2012 Milan Broz <gmazyland@gmail.com>
6 #
7 # This copyrighted material is made available to anyone wishing to use,
8 # modify, copy, or redistribute it subject to the terms and conditions
9 # of the GNU General Public License v.2.
10 #
11 # You should have received a copy of the GNU General Public License
12 # along with this program; if not, write to the Free Software Foundation,
13 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
14 #
15 umask 0077
16
17 fail() { echo -e $1 ; exit 1 ; }
18 field() { echo $(dmsetup table --target crypt --showkeys $DEVICE | sed 's/.*: //' | cut -d' ' -f$1) ; }
19 field_uuid() { echo $(dmsetup info $1 --noheadings -c -o uuid) ; }
20 field_device() {
21         TEMP=$(readlink /sys/dev/block/$1 | sed -e 's/.*\///')
22         if [  ${TEMP:0:3} = "dm-" -a -e /sys/block/$TEMP/dm/name ] ; then
23                 TEMP=/dev/mapper/$(cat /sys/block/$TEMP/dm/name)
24         else
25                 TEMP=/dev/$TEMP
26         fi
27         echo $TEMP
28 }
29
30 which readlink >/dev/null || fail "You need readlink (part of coreutils package)."
31 which xxd >/dev/null || fail "You need xxd (part of vim package) installed to convert key."
32
33 [ -z "$2" ] && fail "Recover LUKS header from active mapping, use:\n $0 crypt_mapped_device mk_file_name"
34
35 DEVICE=$1
36 MK_FILE=$2
37
38 [ -z "$(field 4)" ] && fail "Mapping $1 not active or it is not crypt target."
39
40 CIPHER=$(field 4)
41 OFFSET=$(field 8)
42 SYS_DEVICE=$(field 7)
43 REAL_DEVICE=$(field_device $SYS_DEVICE)
44 KEY=$(field 5)
45 KEY_SIZE=$(( ${#KEY} / 2 * 8 ))
46 SYS_UUID=$(field_uuid $DEVICE)
47 UUID="${SYS_UUID:12:8}-${SYS_UUID:20:4}-${SYS_UUID:24:4}-${SYS_UUID:28:4}-${SYS_UUID:32:12}"
48
49 #echo "CIPHER=$CIPHER OFFSET=$OFFSET SYS_DEVICE=$SYS_DEVICE REAL_DEVICE=$REAL_DEVICE KEY_SIZE=$KEY_SIZE KEY=$KEY UUID=$UUID SYS_UUID=$SYS_UUID"
50
51 [ -z "$CIPHER" -o -z "$OFFSET" -o "$OFFSET" -le 383 -o \
52 -z "$KEY" -o -z "$UUID" -o -z "$REAL_DEVICE" -o "${SYS_UUID:0:12}" != "CRYPT-LUKS1-" ] && \
53 fail "Incompatible device, sorry."
54
55 echo "Generating master key to file $MK_FILE."
56 echo -E -n $KEY| xxd -r -p >$MK_FILE
57
58 echo "You can now try to reformat LUKS device using:"
59 echo "  cryptsetup luksFormat -c $CIPHER -s $KEY_SIZE --align-payload=$OFFSET --master-key-file=$MK_FILE --uuid=$UUID $REAL_DEVICE"