如何让kexec从initramfs运行新内核?

时间:2019-04-23 20:06:56

标签: encryption linux-kernel sh initrd

我正在尝试进行设置,以便可以使用USB initramfs引导包含/ boot的完整加密系统。我编写了一个脚本,该脚本将解锁根文件系统,然后将dmsetup表传递给新的initramfs,然后使用kexec -e进行引导。但是,每次我运行kexec -e时,它都会崩溃而没有任何错误消息。

我也尝试使用systemctl,但是现在出现错误:

#systemctl start kexec.target
System has not been booted with systemd as init system (PID 1)

这是我脚本的下半部分。此时,目标系统分区已在/ dev / mapper / crypttarget上解锁并挂载到/ root。这里的想法是,它使用dmsetup表,将其加密为一个特殊文件,并将其传递给下一个内核的自定义initrd。

#!/bin/sh
set -x
mount=/root
USE_GRUB_CONFIG=false       


#Generate a large random file, while hashing it simultaneously and return the hash
gen_random(){
dd if=/dev/zero bs=1048576 count=64 | \
gpg --passphrase-file /dev/urandom --symmetric --batch --s2k-mode 1 --cipher-algo AES256 | \
tee key | sha512sum | head -c 128
}

error(){
   echo $*
   exit
}

if [ ! -e $mount/boot ]; then
    error "Can't find /boot"
fi

if [ ! -e $mount/boot/grub/grub.cfg ]; then
    error "Can't find grub.cfg"
fi

grub=$(cat $mount/boot/grub/grub.cfg | grep vmlinuz | head -n 1)
kernel=$(echo $grub | sed 's/.*\/boot/\/root\/boot/;s/ .*//')
version=$(echo $kernel | sed 's/.*vmlinuz-//')
uuid=$(blkid | grep mapper | head -n 1 | cut -d ' ' -f 2)
cmdline="root=$uuid ro quiet"

if [ -z "$grub" ]; then
    error "Can't find vmlinuz in grub.cfg"
fi

#Create a temporary directory and subfolder and copy initrd into it.
tempdir=$(mktemp -d keydir.XXXXXX)
cd $tempdir

#Encrypt the table with the hash of the file key.
#The entire table must be hashed to get the table back which makes it easy to destroy in ram.
dmsetup table --showkeys | gpg --cipher-algo AES256 --passphrase $(gen_random) --symmetric --batch --s2k-mode 1 > table

#Add a short decryptor script into the custom.sh file of the new initramfs
if [ -z "$BOOT_IMAGE" ]; then
    error "Not running in initramfs"
fi
echo '''
#!/bin/sh

PREREQ="cryptroot-prepare"
prereqs()
{
        echo "$PREREQ"
}

case $1 in
prereqs)
        prereqs
        exit 0
        ;;
esac

cd $(find . -name keydir.* -type d)
ls -l
sha512sum key | head -c 128 | gpg --passphrase-fd 0 --batch --decrypt table | dmsetup create root && echo Unlocked!
shred -n 1 -u key table
''' > $0
chmod 700 $0
ls -l


#Create a new initrd and shred the old files    
find . -type f | cpio -o -c | gzip -1 > /initrd.img
initrd=/initrd.img
shred -n 1 -u key table

kexec -l $kernel --initrd=$initrd --command-line="$cmdline" || error "kexec load failed"
kexec -e

0 个答案:

没有答案