Initramfs for encrypted root using GPG encrypted random keys

Cha! The most tricky part is comming. I spent 2 days to make this work. There are several tutorials on the internet but you will still need a lot of thinking and patience.

This tutorial is a continuation of:

So we are still in a Gentoo LiveCD environment and we have following hard drives:

  • /dev/sda
    • decrypted as /dev/mapper/vault
    • mounted as /mnt/gentoo
  • /dev/sdb
    • decrypted as /dev/mapper/crypted-home
    • mounted as /mnt/gentoo/home
  • /dev/sdh1
    • mounted as /mnt/gentoo/boot 
    • containing chroot script /mnt/gentoo/boot/chrootenv
    • containing gpg keys in /mnt/gentoo/boot/keys/*.gpg
We are chrooted in our existing installation environment.

Compiling Kernel

Just follow the Configuring the Kernel tutorial. We will be using genkernel method. It’s the easiest one. So in shortcut:

# emerge -av gentoo-sources
# eselect kernel list
# eselect kernel set [X]
# emerge -av genkernel

I’ve create myself a script again to short down the process in case it will needed to be repeated. And it will be! A lot of times! Believe me! You have been warned.

Since we are in our fixed installation environment we can create following script in /usr/local/bin/makegenkernel:

#!/bin/bash
SPLASH_THEME="livecd-2007.0"
SPLASH_RES="1920x1080"
KERNEL_VERSION=`file /usr/src/linux | awk '{print $5}' | cut -d- -f2`

cd /usr/src/linux
genkernel --splash=${SPLASH_THEME} --splash-res=${SPLASH_RES} --dmraid --luks --disklabel --no-clean --no-mrproper --menuconfig all
cp /usr/src/linux/.config /usr/src/kernel.config.`date +%Y-%m-%d-%H-%M-%S`

You might want to change the first 2 variables to fit your needs. It also backups the kernel configuration between every compile. You will find it useful at some point 🙂

So run:

# makegenkernel

This tutorial will not fully cover what modules you will need to include in your kernel since it differs depending on the hardware. You can lookup:

In my case it was something like:
General setup  --->
  [*] Initial RAM filesystem and RAM disk (initramfs/initrd) support
Processor type and features
  [*] Symmetric multi-processing support
Device Drivers  --->
  Generic Driver Options  --->
    [*] Maintain a devtmpfs filesystem to mount at /dev
  Block devices  --->
    [*] RAM disk support
    (8192) Default RAM disk size (kbytes) // Might need even more
    [*] Initial RAM disk (initramfs/initrd) support
    Multi-device support (RAID and LVM)  --->
      [M] RAID support
      [*] Device mapper support
      [*] Crypt target support
  Graphics support  --->
    [*] Support for frame buffer devices
    Console display driver support  --->
      [*] Framebuffer Console support
      [ ] Enable Tile Blitting Support
      [*] Support for the Framebuffer Console Decorations
  Input Device Support  --->
    [*] Event Interface
USB support  --->
    [*] Support for Host-side USB
    [*] USB Mass Storage support
    [*] EHCI HCD (USB 2.0) support
    [*] OHCI HCD support
    [*] UHCI HCD (most Intel and VIA) support
    [*] HID Devices
    [*] USB Human Interface Device (full HID) support
File system  --->
  [*] Second extended fs support
  [*] Ext3 journalling file system support
  [*] The Extended 4 (ext4) filesystem
  Pseudo Filesystems  --->
    [*] /proc file system support
    [*] Virtual memory file system support (former shm fs)
    [*] GPT partition label support
    [*] Advanced partition selection  --->
      [*] EFI GUID Partition support
Cryptographic options  --->
  [*] SHA256 digest algorithm
  [*] SHA384 and SHA512 digest algorithms
  [*] Blowfish cipher algorithm
  [*] Twofish cipher algorithm
  [*] Serpent cipher algorithm
  [*] AES cipher algorithms (x86_64)
  [*] XTS

Uncompressing INITRAMFS made by genkernel

Now we have the genkernel and the according initramfs in /boot. We will need some modifications to the default genkernel. First unpack it to /usr/src/:

# cd /usr/src
# mkdir initramfs
# zcat /boot/initramfs-genkernel-x86_64-3.3.8-gentoo | cpio -i -d --no-absolute-filenames

Updating INIT script in INITRAMFS

I changes the followind scripts in the initramfs:

  • /usr/src/initramfs/init 
#!/bin/sh

. /etc/initrd.defaults
. /etc/initrd.scripts

splash() {
	return 0
}

[ -e /etc/initrd.splash ] && . /etc/initrd.splash

# Clean input/output
exec >${CONSOLE} &1

if [ "$$" != '1' ]
then
	echo '/linuxrc has to be run as the init process as the one'
	echo 'with a PID of 1. Try adding init="/linuxrc" to the'
	echo 'kernel command line or running "exec /linuxrc".'
	exit 1
fi

mount -t proc -o noexec,nosuid,nodev proc /proc >/dev/null 2>&1
mount -o remount,rw / >/dev/null 2>&1

# Set up symlinks
/bin/busybox --install -s

if [ "$0" = '/init' ]
then
	[ -e /linuxrc ] && rm /linuxrc
fi

quiet_kmsg

CMDLINE=$(cat /proc/cmdline)
# Scan CMDLINE for any specified real_root= or cdroot arguments
FAKE_ROOT=''
REAL_ROOTFLAGS=''
ROOTFSTYPE='auto'
CRYPT_SILENT=0
for x in ${CMDLINE}
do
	case "${x}" in
		real_root=*)
			REAL_ROOT=${x#*=}
		;;
		root=*)
			FAKE_ROOT=${x#*=}
		;;
		subdir=*)
			SUBDIR=${x#*=}
		;;
		real_init=*)
			REAL_INIT=${x#*=}
		;;
		init_opts=*)
			INIT_OPTS=${x#*=}
		;;
		# Start livecd loop, looptype options
		loop=*)
			LOOP=${x#*=}
		;;
		looptype=*)
			LOOPTYPE=${x#*=}
		;;
		isoboot=*)
			ISOBOOT=${x#*=}
		;;
		# Start Volume manager options
		dolvm)
			USE_LVM_NORMAL=1
		;;
		dolvm2)
			bad_msg 'Using dolvm2 is deprecated, use dolvm, instead.'
			USE_LVM_NORMAL=1
		;;
		domdadm)
			USE_MDADM=1
		;;
		dodmraid)
			USE_DMRAID_NORMAL=1
		;;
		dodmraid=*)
			DMRAID_OPTS=${x#*=}
			USE_DMRAID_NORMAL=1
		;;
		# Debug Options
		debug)
			DEBUG='yes'
		;;
		# Scan delay options
		scandelay=*)
			SDELAY=${x#*=}
		;;
		scandelay)
			SDELAY=3
		;;
		# Module no-loads
		doload=*)
			MDOLIST=${x#*=}
			MDOLIST=$(echo ${MDOLIST} | sed -e 's/,/ /g')
		;;
		nodetect)
			NODETECT=1
		;;
		noload=*)
			MLIST=${x#*=}
			MLIST="$(echo ${MLIST} | sed -e 's/,/ /g')"
			export MLIST
		;;
		# Redirect output to a specific tty
		CONSOLE=*|console=*)
			CONSOLE=${x#*=}
			CONSOLE=$(basename ${CONSOLE})
#			exec >${CONSOLE} &1
		;;
		# /dev/md
		lvmraid=*)
			RAID_DEVICES="${x#*=}"
			RAID_DEVICES="$(echo ${RAID_DEVICES} | sed -e 's/,/ /g')"
			USE_LVM_NORMAL=1
		;;
		part=*)
			MDPART=${x#*=}
		;;
		# NFS
		ip=*)
			IP=${x#*=}
		;;
		nfsroot=*)
			NFSROOT=${x#*=}
		;;
		# iSCSI
		iscsi_initiatorname=*)
			ISCSI_INITIATORNAME=${x#*=}
		;;
		iscsi_target=*)
			ISCSI_TARGET=${x#*=}
		;;
		iscsi_tgpt=*)
			ISCSI_TGPT=${x#*=}
		;;
		iscsi_address=*)
			ISCSI_ADDRESS=${x#*=}
		;;
		iscsi_port=*)
			ISCSI_PORT=${x#*=}
		;;
		iscsi_username=*)
			ISCSI_USERNAME=${x#*=}
		;;
		iscsi_password=*)
			ISCSI_PASSWORD=${x#*=}
		;;
		iscsi_username_in=*)
			ISCSI_USERNAME_IN=${x#*=}
		;;
		iscsi_password_in=*)
			ISCSI_PASSWORD_IN=${x#*=}
		;;
		iscsi_debug=*)
			ISCSI_DEBUG=${x#*=}
		;;
		iscsi_noibft)
			ISCSI_NOIBFT=1
		;;
		# Crypto
		crypt_root=*)
			CRYPT_ROOT=${x#*=}
		;;
		crypt_swap=*)
			CRYPT_SWAP=${x#*=}
		;;
		root_key=*)
			CRYPT_ROOT_KEY=${x#*=}
		;;
		root_keydev=*)
			CRYPT_ROOT_KEYDEV=${x#*=}
		;;
		root_trim=*)
			CRYPT_ROOT_TRIM=${x#*=}
		;;

		swap_key=*)
			CRYPT_SWAP_KEY=${x#*=}
		;;
		swap_keydev=*)
			CRYPT_SWAP_KEYDEV=${x#*=}
		;;
		real_resume=*|resume=*)
			REAL_RESUME=${x#*=}
		;;
		noresume)
			NORESUME=1
		;;
		crypt_silent)
			CRYPT_SILENT=1
		;;
		real_rootflags=*)
			REAL_ROOTFLAGS=${x#*=}
		;;
		rootfstype=*)
			ROOTFSTYPE=${x#*=}
		;;
		keymap=*)
			keymap=${x#*=}
		;;
		aufs)
			USE_AUFS_NORMAL=1
		;;
		unionfs)
			if [ ! -x /sbin/unionfs ]
			then
				USE_UNIONFS_NORMAL=0
				bad_msg 'unionfs binary not found: aborting use of unionfs!'
			else
				USE_UNIONFS_NORMAL=1
			fi
			;;
		nounionfs)
			USE_UNIONFS_NORMAL=0
			;;
		pretend)
			PRETEND=1
			;;
	esac
done

if [ -z "${REAL_ROOT}" -a \( "${CDROOT}" = '0' \)  -a \( "${FAKE_ROOT}" != "/dev/ram0" \) ]; then
	REAL_ROOT="${FAKE_ROOT}"
fi

splash 'init'

cmdline_hwopts

# Mount sysfs
mount_sysfs

# Setup hotplugging for firmware loading
setup_hotplug

# Load modules listed in MY_HWOPTS if /lib/modules exists for the running kernel
if [ -z "${DO_modules}" ]
then
	good_msg 'Skipping module load; disabled via commandline'
elif [ -d "/lib/modules/${KV}" ]
then
	good_msg 'Loading modules'
	# Load appropriate kernel modules
	if [ "${NODETECT}" != '1' ]
	then
		for modules in ${MY_HWOPTS}
		do
			modules_scan ${modules}
		done
	fi
	# Always eval doload=...
	modules_load ${MDOLIST}
else
	good_msg 'Skipping module load; no modules in the ramdisk!'
fi

# Apply scan delay if specified
sdelay

# Setup slow USB bits
setup_slowusb

# Start device manager
start_dev_mgr

# if doslowusb is passed, pause other 10 seconds here, after mdev load
[ "${DO_slowusb}" ] && sleep 10

# Start iSCSI
if [ -e /bin/iscsistart ]
then
	startiscsi
fi

# Setup btrfs, see bug 303529
setup_btrfsctl

# Setup md device nodes if they dont exist
setup_md_device

# Scan volumes
startVolumes

setup_keymap

startLUKS
if [ "${NORESUME}" != '1' ] && [ -n "${REAL_RESUME}" ]; then
	getRealDevice ${REAL_RESUME}
	REAL_RESUME=${DETECTED_REAL_DEVICE}
	do_resume
fi

mkdir -p "${NEW_ROOT}"
CHROOT="${NEW_ROOT}"

# Run debug shell if requested
rundebugshell

# Determine root device
good_msg 'Determining root device...'
while true
do
	while [ "${got_good_root}" != '1' ]
	do
		case "${REAL_ROOT}" in
			LABEL=*|UUID=*)

				ROOT_DEV=""
				retval=1

				if [ ${retval} -ne 0 ]; then
					ROOT_DEV=$(findfs "${REAL_ROOT}" 2>/dev/null)
					retval=$?
				fi

				if [ ${retval} -ne 0 ]; then
					ROOT_DEV=$(busybox findfs "${REAL_ROOT}" 2>/dev/null)
					retval=$?
				fi

				if [ ${retval} -ne 0 ]; then
					ROOT_DEV=$(blkid -l -t "${REAL_ROOT}" | cut -d ":" -f 1 2>/dev/null)
					retval=$?
				fi

				if [ ${retval} -eq 0 ] && [ -n "${ROOT_DEV}" ]; then
					good_msg "Detected real_root=${ROOT_DEV}"
					REAL_ROOT="${ROOT_DEV}"
				else
					prompt_user "REAL_ROOT" "root block device"
					got_good_root=0
					continue
				fi
				;;
		esac

		if [ "${REAL_ROOT}" = '' ]
		then
			# No REAL_ROOT determined/specified. Prompt user for root block device.
			prompt_user "REAL_ROOT" "root block device"
			got_good_root=0

		# Check for a block device or /dev/nfs
		elif [ -b "${REAL_ROOT}" ] || [ "${REAL_ROOT}" = "/dev/nfs" ]
		then
			got_good_root=1

		else
			bad_msg "Block device ${REAL_ROOT} is not a valid root device..."
			REAL_ROOT=""
			got_good_root=0
		fi
	done

	if [ "${LOOPTYPE}" = "sgimips" ]; then
		# sgimips mounts the livecd root partition directly
		# there is no isofs filesystem to worry about
		break
	else
		good_msg "Mounting root..."

		# Try to mount the device as ${NEW_ROOT}
		if [ "${REAL_ROOT}" = '/dev/nfs' ]; then
			findnfsmount
		else
			# mount ro so fsck doesn't barf later
			if [ "${REAL_ROOTFLAGS}" = '' ]; then
				good_msg "Using mount -t ${ROOTFSTYPE} -o ro"
				mount -t ${ROOTFSTYPE} -o ro ${REAL_ROOT} ${NEW_ROOT}
			else
				good_msg "Using mount -t ${ROOTFSTYPE} -o ro,${REAL_ROOTFLAGS}"
				mount -t ${ROOTFSTYPE} -o ro,${REAL_ROOTFLAGS} ${REAL_ROOT} ${NEW_ROOT}
			fi
		fi

		# If mount is successful break out of the loop
		# else not a good root and start over.
		if [ "$?" = '0' ]
		then
			if [ -d ${NEW_ROOT}/dev -a -x ${NEW_ROOT}/sbin/init ] || [ "${REAL_ROOT}" = "/dev/nfs" ]
			then
				break
			else
				bad_msg "The filesystem mounted at ${REAL_ROOT} does not appear to be a valid /, try again"
				got_good_root=0
				REAL_ROOT=''
			fi
		else
			bad_msg "Could not mount specified ROOT, try again"
			got_good_root=0
			REAL_ROOT=''
		fi
	fi
done
# End determine root device

#verbose_kmsg

if [ "${USE_UNIONFS_NORMAL}" = '1' ]; then
	mkdir /union_changes
	mount -t tmpfs tmpfs /union_changes
	setup_unionfs /union_changes ${NEW_ROOT}
	mkdir -p ${UNION}/tmp/.initrd
fi

# Mount the additional things as required by udev & systemd
if [ -f ${NEW_ROOT}/etc/initramfs.mounts ]; then
	fslist=$(get_mounts_list)
else
	# Disabled until the new OpenRC is ready to go.
	# Otherwise users will get /usr mounted RO, and it will NOT transition to
	# RW correctly.
	#fslist="/usr"
	fslist=""
fi

for fs in $fslist; do
	dev=$(get_mount_device $fs)
	# In this case, it's probably part of the filesystem
	# and not a mountpoint
	[ -z "$dev" ] && continue
	opts="ro,$(get_mount_options \"$fs\")"
	if ! mount -o ${opts} $dev ${NEW_ROOT}${fs}; then
		rescue_shell "Unable to mount $dev on $fs"
	fi
done

if [ "${SUBDIR}" != '' -a -e "${CHROOT}/${SUBDIR}" ]; then
	good_msg "Entering ${SUBDIR} to boot"
	CHROOT="${CHROOT}/${SUBDIR}"
fi

verbose_kmsg

echo -ne "${GOOD}>>${NORMAL}${BOLD} Booting (initramfs)${NORMAL}"

cd "${CHROOT}"
mkdir "${CHROOT}/proc" "${CHROOT}/sys" 2>/dev/null
echo -ne "${BOLD}.${NORMAL}"

# If devtmpfs is mounted, try move it to the new root
# If that fails, try to unmount all possible mounts of devtmpfs as stuff breaks otherwise
for fs in /dev /sys /proc
do
	if grep -qs "$fs" /proc/mounts
	then
		if ! mount --move $fs "${CHROOT}"$fs
		then
			umount $fs || echo '*: Failed to move and unmount the ramdisk $fs!'
		fi
	fi
done

if [ ! -e "${CHROOT}/dev/console" ] || [ ! -e "${CHROOT}/dev/null" ]
then
	echo -ne "${BAD}>>${NORMAL}${BOLD} ERROR: your real /dev is missing files required to boot (console and null)${NORMAL}"
elif [ -e /etc/initrd.splash -a ! -e "${CHROOT}/dev/tty1" ]
then
	echo -ne "${BAD}>>${NORMAL}${BOLD} ERROR: your real /dev is missing tty1, which is required for splash${NORMAL}"
fi

echo -e "${BOLD}.${NORMAL}"

if [ "${PRETEND}" = '1' ]; then
  echo
  echo "JUST PRETENDING :o) ... That's all folks."
  echo
else
  echo ${INIT_OPTS}
  exec /sbin/switch_root -c "/dev/console" "${CHROOT}" "${REAL_INIT:-/sbin/init}" "${INIT_OPTS}"
fi

# If we get here, something bad has happened
splash 'verbose'

echo "A fatal error has probably occured since ${REAL_INIT:-/sbin/init} did not"
echo "boot correctly. Trying to open a shell..."
echo
#exec /bin/bash
#exec /bin/sh
exec /bin/ash
#exec /bin/dash
#exec sh
  • /usr/src/initramfs/etc/initrd.defaults
#!/bin/ash

PATH="/usr/sbin:/usr/bin:/sbin:/bin"

# Insert ctrl character
# ctrl-V then esc will print ^[
# ctrl-V then ctrl-shift-m will print ^M
BACK_UP="\033[1K\033[0G"
NORMAL="\033[0m"
WARN="\033[33;1m"
BAD="\033[31;1m"
BOLD="\033[1m"
GOOD="\033[32;1m"

# From KNOPPIX LINUXRC
# Reset fb color mode
RESET="]R"
# ANSI COLORS
# Erase to end of line
CRE="
"
# Clear and reset Screen
CLEAR="c"
# Normal color
NORMAL=""
# RED: Failure or error message
RED=""
# GREEN: Success message
GREEN=""
# YELLOW: Descriptions
YELLOW=""
# BLUE: System mesages
BLUE=""
# MAGENTA: Found devices or drivers
MAGENTA=""
# CYAN: Questions
CYAN=""
# BOLD WHITE: Hint
WHITE=""

# Clear screen with colormode reset
# echo "$CLEAR$RESET"
# echo "$CLEAR"
# Just go to the top of the screen
# echo -n ""

KV=`uname -r`
KMAJOR=`echo $KV | cut -f1 -d.`
KMINOR=`echo $KV | cut -f2 -d.`
KVER="${KMAJOR}.${KMINOR}"
MISCOPTS='debug detect'

if [ "${KMAJOR}" -ge 3 ] || [ "${KMAJOR}" -eq 2 -a "${KMINOR}" -eq '6' ]
then
	KV_2_6_OR_GREATER="yes"
fi

QUIET='1'
ROOT_LINKS='bin sbin lib lib32 lib64 boot usr opt emul'
ROOT_TREES='etc root home var'
INSMOD='insmod'
if [ "${KMAJOR}" -ge 3 ] || [ "${KMAJOR}" -eq 2 -a "${KMINOR}" -gt '4' ]
then
	KSUFF='.ko'
else
	KSUFF='.o'
fi

REAL_ROOT=''
PRETENT='0'
CDROOT='0'
CDROOT_DEV=''
CDROOT_TYPE='auto'
NEW_ROOT='/newroot'
CDROOT_PATH='/mnt/cdrom'
CONSOLE='/dev/console'

LOOPS='/livecd.loop /zisofs /livecd.squashfs /image.squashfs /livecd.gcloop'

DEFAULT_NFSOPTIONS="ro,nolock,rsize=1024,wsize=1024"

# Only sections that are in by default or those that
# are not module groups need to be defined here...
HWOPTS='keymap cache modules pata sata scsi usb firewire waitscan slowusb lvm dmraid mdadm fs net'
MY_HWOPTS='modules pata sata scsi slowusb usb firewire waitscan dmraid mdadm fs net iscsi crypto'
HWOPTS="$HWOPTS ataraid crypto dmraid firewire fs iscsi lvm mdadm net pata pcmcia sata scsi usb waitscan "
  • /usr/src/initramfs/etc/initrd.scripts
#!/bin/ash

. /etc/initrd.defaults

backup() {
	echo -ne "\033[0G\033[0K"
}

modules_load() {
	for module in $*
	do
		echo ${module} >> /etc/modules/extra_load
	done

	modules_scan extra_load
}

modules_scan() {
	local MODS
	[ -d "/etc/modules/${1}" ] || touch /etc/modules/${1}

	[ -f "/etc/modules/${1}" ] && MODS=`cat /etc/modules/${1}`
	for x in ${MODS}
	do
		MLOAD=`echo ${MLIST} | sed -e "s/.*${x}.*/${x}/"`
		if [ "${MLOAD}" = "${x}" ] # Only module to no-load
		then
			echo -e "${BOLD}   ::${NORMAL} Skipping ${x}..."
		elif [ "${MLOAD}" = "${MLIST}" ] # == No change == No specified no-load
		then
			[ -n "${DEBUG}" ] && echo -e "${BOLD}   ::${NORMAL} Checking for ${x}..."
			# find -name does not work since the return status is always zero
			if find /lib/modules/${KV} | grep /"${x}${KSUFF}" >/dev/null 2>&1
			then
				echo -ne "${BOLD}   ::${NORMAL} Scanning for ${x}..."
				modprobe ${x} -n
				backup
				echo -ne "${NORMAL}"
			fi
		else
			echo -e "${BOLD}   ::${NORMAL} Skipping ${x}..."
		fi
	done
}

uppercase(){
	# needs tr on busybox
	echo $1 | tr 'a-z' 'A-Z'
}

findmediamount() {
	# $1 = mount dir name / media name
	# $2 = recognition file
	# $3 = variable to have the device path
	# $4 = actual mount dir path (full path)
	# args remaining are possible devices

	local media=$1 recon=$2 vrbl=$3 mntdir=$4
	shift 4

	good_msg "Looking for the ${media}" ${CRYPT_SILENT}

	if [ "$#" -gt "0" ]
	then
		[ ! -d "${mntdir}" ] && mkdir -p ${mntdir} 2>/dev/null >/dev/null
		if [ -n "${ISOBOOT}" ]
		then
			mntcddir="${mntdir%${media}}iso"
			if [ ! -f ${mntcddir} ]
			then
				mkdir ${mntcddir}
			fi
		else
			mntcddir=${mntdir}
		fi

		for x in $*
		do
			# Check for a block device to mount
			if [ -b "${x}" ]
			then
				skip=0
				bsn=`basename "${x}"`
				#
				# If disk and it has at least one partition, skip.
				# We use /sys/block/${bsn}/${bsn}[0-9]* to make sure that we
				# don't skip device mapper devices. Even the craziest scenario
				# deserves a fair chance.
				#
				for part in `ls /sys/block/${bsn}/${bsn}[0-9]* 2>/dev/null`
				do
					skip=1
					break;
				done
				if [ ${skip} -eq 1 ]
				then
					continue
				fi
				good_msg "Attempting to mount media:- ${x}" ${CRYPT_SILENT}

				mount -r -t ${CDROOT_TYPE} ${x} ${mntcddir} >/dev/null 2>&1
				if [ "$?" = '0' ]
				then
					if [ -n "${ISOBOOT}" ]; then
						if [ -f ${mntcddir}/${ISOBOOT} ]; then
							mount -o loop ${mntcddir}/${ISOBOOT} ${mntdir}
							if [ "$?" = "0" ]; then
								good_msg "iso mounted on ${mntdir}"
							fi
						fi
					fi

					# Check for the media
					if [ -f "${mntdir}/${recon}" ]
					then
						#set REAL_ROOT, CRYPT_ROOT_KEYDEV or whatever ${vrbl} is
						eval ${vrbl}'='"${x}"
						good_msg "Media found on ${x}" ${CRYPT_SILENT}
						break
					else
						umount ${mntcddir}
					fi
				fi
			fi
		done
	fi

	eval local result='$'${vrbl}

	[ -n "${result}" ] || bad_msg "Media not found" ${CRYPT_SILENT}
}

devicelist(){
	# Locate the cdrom device with our media on it.
	# CDROM DEVICES
	local DEVICES="/dev/cdroms/* /dev/ide/cd/* /dev/sr*"
	# USB Keychain/Storage
	DEVICES="$DEVICES /dev/sd*"
	# IDE devices
	DEVICES="$DEVICES /dev/hd*"
	# USB using the USB Block Driver
	DEVICES="$DEVICES /dev/ubd* /dev/ubd/*"
	# iSeries devices
	DEVICES="$DEVICES /dev/iseries/vcd*"
	echo ${DEVICES}
}

bootstrapKey() {
	# $1 = ROOT/SWAP
	local KEYDEVS=`devicelist`
	eval local keyloc='"${CRYPT_'${1}'_KEY}"'

	findmediamount "key" "${keyloc}" "CRYPT_${1}_KEYDEV" "/mnt/key" ${KEYDEVS}
}

mount_sysfs() {
	mount -t sysfs sysfs /sys -o noexec,nosuid,nodev >/dev/null 2>&1
	ret=$?
	[ ${ret} -eq 0 ] || bad_msg "Failed to mount /sys!"
}

findnfsmount() {
	if [ "${IP}" != '' ] || busybox udhcpc -n -T 15 -q
	then
		[ -e /rootpath ] && NFSROOT=`cat /rootpath`

		if [ "${NFSROOT}" = '' ]
		then
			# Obtain NFSIP
			OPTIONS=`busybox dmesg | grep rootserver | sed -e "s/,/ /g"`
			for OPTION in $OPTIONS
			do
				if [ `echo $OPTION | sed -e "s/=/ /g" | cut -d " " -f 1` = 'rootserver' ]
				then
					NFSIP=`echo $OPTION | sed -e "s/=/ /g" | cut -d " " -f 2`
				fi
			done

			# Obtain NFSPATH
			OPTIONS=`busybox dmesg | grep rootpath | sed -e "s/,/ /g"`
			for OPTION in $OPTIONS
			do
				if [ `echo $OPTION | sed -e "s/=/ /g" | cut -d " " -f 1` = 'rootpath' ]
				then
					NFSPATH=`echo $OPTION | sed -e "s/=/ /g" | cut -d " " -f 2`
		 		fi
			done

			# Setup NFSROOT
			if [ "${NFSIP}" != '' ] && [ "$NFSPATH" != '' ]
			then
				NFSROOT="${NFSIP}:${NFSPATH}"
			else
				bad_msg "The DHCP Server did not send a valid root-path."
				bad_msg "Please check your DHCP setup, or provide a nfsroot= parameter."
			fi
		fi

		if [ "${NFSROOT}" != '' ]
		then
			NFSOPTIONS=${NFSROOT#*,}
			NFSROOT=${NFSROOT%%,*}
			if [ "${NFSOPTIONS}" = "${NFSROOT}" ]
			then
				NFSOPTIONS=$DEFAULT_NFSOPTIONS
			else
				NFSOPTIONS="${DEFAULT_NFSOPTIONS},${NFSOPTIONS}"
			fi

			good_msg "Attempting to mount NFS root on ${NFSROOT} with options ${NFSOPTIONS}"
			mount -t nfs -o ${NFSOPTIONS} ${NFSROOT} ${NEW_ROOT}
			if [ "$?" = '0' ]
			then
				REAL_ROOT="/dev/nfs"
			else
				bad_msg "NFS Mounting failed. Is the path correct ?"
			fi
			# FIXME: Need to start portmap and the other rpc daemons in
			# order to remount rw.
		fi
	fi
}

run_shell() {
	/bin/ash
}

runmdev() {
	# Use devtmpfs if enabled in kernel,
	# else tmpfs. Always run mdev just in case
	devfs=tmpfs
	if grep -qs devtmpfs /proc/filesystems ; then
		devfs=devtmpfs
	fi

	# Options copied from /etc/init.d/udev-mount, should probably be kept in sync
	mount -t $devfs -o "exec,nosuid,mode=0755,size=10M" udev /dev \
		|| bad_msg "Failed to mount /dev as ${devfs}"

	# http://git.busybox.net/busybox/plain/docs/mdev.txt
	mkdir -m 0755 /dev/pts
	mount -t devpts -o gid=5,mode=0620 devpts /dev/pts  || bad_msg "Failed to mount /dev/pts"
	mdev -s  || bad_msg "Failed to receive dynamic updates from mdev"
}

test_success() {
	retcode=$?
	# If last command failed send error message and fall back to a shell
	if [ "$retcode" != '0' ]
	then
		error_string=$1
		error_string="${error_string:-run command}"
		bad_msg 'Failed to $1; failing back to the shell...'
		run_shell
	fi
}

# msg functions arguments
# $1 string
# $2 hide flag

good_msg() {
	msg_string=$1
	msg_string="${msg_string:-...}"
	[ "$2" != 1 ] && echo -e "${GOOD}>>${NORMAL}${BOLD} ${msg_string} ${NORMAL}"
}

bad_msg() {
	msg_string=$1
	msg_string="${msg_string:-...}"
	if [ "$2" != 1 ]
	then
		splash 'verbose' > /dev/null &
		echo -e "${BAD}!!${NORMAL}${BOLD} ${msg_string} ${NORMAL}"
	fi
}

warn_msg() {
	msg_string=$1
	msg_string="${msg_string:-...}"
	[ "$2" != 1 ] && echo -e "${WARN}**${NORMAL}${BOLD} ${msg_string} ${NORMAL}"
}

crypt_filter() {
	if [ "${CRYPT_SILENT}" = '1' ]
	then
		eval $1 >/dev/null 2>/dev/null
	else
		splash 'verbose' > /dev/null &
		eval $1
		res=$?
		if [ ${res} -eq 0 ]
		then
			splash set_msg 'Disk unlocked.'
		fi
		return ${res}
	fi
}

prompt_user(){
	# $1 = variable whose value is the path (examples: "REAL_ROOT",
	#      "LUKS_KEYDEV")
	# $2 = label
	# $3 = optional explanations for failure

	eval local oldvalue='$'${1}

	[ \( $# != 2 \) -a \( $# != 3 \) ] && \
		bad_msg "Bad invocation of function prompt_user, please file a bug \
		report with this message" && exit 1
	[ -n "${3}" ] && local explnt=" or : ${3}" || local explnt="."

	bad_msg "Could not find the ${2} in ${oldvalue}${explnt}"
	echo '   Please specify another value or: press Enter for the same, type "shell" for a shell, or "q" to skip...'
	echo -n "${2}(${oldvalue}) :: "
	read ${1}
	case `eval echo '$'${1}` in
		'q')
			eval ${1}'='${oldvalue}
			warn_msg "Skipping step, this will likely cause a boot failure."
			break
			;;
		'shell')
			eval ${1}'='${oldvalue}
			echo "To leave and try again just press +D"
			run_shell
			;;
		'')
			eval ${1}'='${oldvalue}
			;;
	esac
}

setup_hotplug() {
	if [ "${KV_2_6_OR_GREATER}" ]
	then
		echo /sbin/mdev > /proc/sys/kernel/hotplug
	fi
}

setup_slowusb() {
	# This function removes unset DO_slowusb if there is no usb-storage attached.
	# If noslowusb is set, skip this function
	[ "${DO_slowusb}" ] || return

	# Unset DO_slowusb, so we can set it again if usb-storage has something attached
	unset DO_slowusb

	local usb_storage_dir="/sys/bus/usb/drivers/usb-storage"
	if [ ! -d "${usb_storage_dir}" ]
	then
		# no automated slowusb required. no usb-storage devices attached.
		return
	fi
	for x in "${usb_storage_dir}"/*
	do
		[ -d "${x}" ]  && [ "${x}" != "${usb_storage_dir}/module" ] \
			&& { DO_slowusb="1" ; break ; }
	done
}

start_dev_mgr() {
	if [ "${KV_2_6_OR_GREATER}" ]
	then
		cd /sys
		good_msg 'Activating mdev'
		runmdev
		cd /
	fi
}

cmdline_hwopts() {
	# Scan CMDLINE for any "doscsi" or "noscsi"-type arguments
	local FOUND
	local TMP_HWOPTS

	for x in $HWOPTS
	do
		for y in $CMDLINE
		do
			if [ "${y}" = "do${x}" ]
			then
				MY_HWOPTS="${MY_HWOPTS} $x"
			elif [ "${y}" = "no${x}" ]
			then
				MY_HWOPTS="`echo ${MY_HWOPTS} | sed -e \"s/${x}//g\" -`"
			fi
			if [ "$(echo ${y} | cut -b -7)" = "keymap=" ]
			then
				MY_HWOPTS="${MY_HWOPTS} keymap"
			fi
		done
	done

	# Shouldnt need to sort this as the following loop should figure out the
	# duplicates and strip them out
	#MY_HWOPTS=`echo ${MY_HWOPTS}|  sort`

	for x in ${MY_HWOPTS}
	do
		FOUND=0
		for y in ${TMP_HWOPTS}
		do
			if [ "${y}" = "${x}" ]
			then
				continue 2
			fi
		done
		TMP_HWOPTS="${TMP_HWOPTS} ${x}"
		eval DO_`echo ${x} | sed 's/-//'`=1
	done

	MY_HWOPTS=${TMP_HWOPTS}
}

load_modules() {
	# Load modules listed in MY_HWOPTS if /lib/modules exists for the running
	# kernel version
	if [ -d "/lib/modules/${KV}" ]
	then
		good_msg 'Loading modules'
		# Load appropriate kernel modules
		for modules in $MY_HWOPTS
		do
			modules_scan $modules
		done
	else
		good_msg 'Skipping module load; no modules in the ramdisk!'
	fi
}

setup_keymap() {
	if [ "${DO_keymap}" ]
	then
		if [ ! -e /dev/vc/0 -a ! -e /dev/tty0 ]
		then
			DEVBIND=1
			mount -o bind ${NEW_ROOT}/dev /dev
		fi
		[ ! -e /dev/tty0 ] && ln -s /dev/tty1 /dev/tty0

		[ -f /lib/keymaps/keymapList ] && chooseKeymap

		[ "${DEVBIND}" = '1' ] && umount /dev
	fi
}

chooseKeymap() {
	good_msg "Loading keymaps"
	if [ -z "${keymap}" ]
	then
		splash 'verbose' > /dev/null &
		cat /lib/keymaps/keymapList
		read -t 10 -p '<< Load keymap (Enter for default): ' keymap
		case ${keymap} in
			1|azerty) keymap=azerty ;;
			2|be) keymap=be ;;
			3|bg) keymap=bg ;;
			4|br-a) keymap=br-a ;;
			5|br-l) keymap=br-l ;;
			6|by) keymap=by ;;
			7|cf) keymap=cf ;;
			8|croat) keymap=croat ;;
			9|cz) keymap=cz ;;
			10|de) keymap=de ;;
			11|dk) keymap=dk ;;
			12|dvorak) keymap=dvorak ;;
			13|es) keymap=es ;;
			14|et) keymap=et ;;
			15|fi) keymap=fi ;;
			16|fr) keymap=fr ;;
			17|gr) keymap=gr ;;
			18|hu) keymap=hu ;;
			19|il) keymap=il ;;
			20|is) keymap=is ;;
			21|it) keymap=it ;;
			22|jp) keymap=jp ;;
			23|la) keymap=la ;;
			24|lt) keymap=lt ;;
			25|mk) keymap=mk ;;
			26|nl) keymap=nl ;;
			27|no) keymap=no ;;
			28|pl) keymap=pl ;;
			29|pt) keymap=pt ;;
			30|ro) keymap=ro ;;
			31|ru) keymap=ru ;;
			32|se) keymap=se ;;
			33|sg) keymap=sg ;;
			34|sk-y) keymap=sk-y ;;
			35|sk-z) keymap=sk-z ;;
			36|slovene) keymap=slovene ;;
			37|trf) keymap=trf ;;
			38|trq) keymap=trq ;;
			39|ua) keymap=ua ;;
			40|uk) keymap=uk ;;
			41|us) keymap=us ;;
			42|wangbe) keymap=wangbe ;;
		esac
	fi
	if [ -e /lib/keymaps/${keymap}.map ]
	then
		good_msg "Loading the ''${keymap}'' keymap"
		loadkmap < /lib/keymaps/${keymap}.map #		xkeymap=${keymap} #		echo ${keymap} | egrep -e "[0-9]+" >/dev/null 2>&1
#		if [ $? -eq 0 ]
#		then
#			xkeymap=`tail -n 7 /lib/keymaps/keymapList | grep ${keymap} | sed -r "s/.*\s+${keymap}\s+([a-z-]+).*/\1/g" | egrep -v 1`
#		fi
		mkdir -p /etc/sysconfig
#		echo "XKEYBOARD=${xkeymap}" > /etc/sysconfig/keyboard
		echo "XKEYBOARD=${keymap}" > /etc/sysconfig/keyboard
		splash set_msg "Set keymap to ${keymap}"
	elif [ -z "${keymap}" ]
	then
		echo
		good_msg "Keeping default keymap"
		splash set_msg "Keeping default keymap"
	else
		bad_msg "Sorry, but keymap ''${keymap}'' is invalid!"
		unset keymap
		chooseKeymap
	fi
}

startVolumes() {
	#good_msg 'Checking if volumes need to be started...'

	# Here, we check for /dev/device-mapper, and if it exists, we setup a
	# a symlink, which should hopefully fix bug #142775 and bug #147015
	if [ -e /dev/device-mapper ] && [ ! -e /dev/mapper/control ]
	then
		mkdir -p /dev/mapper
		ln -sf /dev/device-mapper /dev/mapper/control
	fi

	if [ "${USE_MDADM}" = '1' ]
	then
		/sbin/mdadm --assemble --scan
	fi

	if [ "${USE_DMRAID_NORMAL}" = '1' ]
	then
		if [ -e '/sbin/dmraid' ]
		then
			good_msg "Activating Device-Mapper RAID(s)"
			if [ '${DMRAID_OPTS}' = '' ]
			then
				/sbin/dmraid -ay
			else
				/sbin/dmraid -ay ${DMRAID_OPTS}
			fi
		fi
	fi

	if [ "${USE_LVM_NORMAL}" = '1' ]
	then
		if [ -e '/bin/lvm' ]
		then
			for dev in ${RAID_DEVICES}
			do
				setup_md_device "${dev}"
			done

			# This is needed for /bin/lvm to accept the following logic
			lvm_commands="#! /bin/lvm"

			# If there is a cahe, update it. Unbreak at least dmcrypt
			[ -d /etc/lvm/cache ] && lvm_commands="${lvm_commands} \nvgscan"

			# To activate volumegroups on all devices in the cache
			lvm_commands="${lvm_commands} \nvgchange -ay --sysinit"

			# To create symlinks so users can use real_root=/dev/vg/root
			# This needs to run after vgchange, using vgchange --mknodes is too
			# early.
			lvm_commands="${lvm_commands} \nvgmknodes --ignorelockingfailure"

			# And finally execute it all (/proc/... needed if lvm is compiled without readline)
			good_msg "Scanning for and activating Volume Groups"
			printf "%b\n" "${lvm_commands}" | /bin/lvm /proc/self/fd/0
		else
			bad_msg "vgscan or vgchange not found: skipping LVM volume group activation!"
		fi
	fi
}

startiscsi() {

	if [ ! -n "${ISCSI_NOIBFT}" ]
	then
		good_msg "Activating iSCSI via iBFT"
		iscsistart -b
	fi

	if [ -n "${ISCSI_INITIATORNAME}" ] && [ -n "${ISCSI_TARGET}" ] && [ -n "${ISCSI_ADDRESS}" ]
	then
		good_msg "Activating iSCSI via cmdline"

		if [ "${ISCSI_TGPT}" ]
		then
			ADDITIONAL="${ADDITIONAL} -g ${ISCSI_TGPT}"
		else
			ADDITIONAL="${ADDITIONAL} -g 1"
		fi

		if [ "${ISCSI_PORT}" ]
		then
			ADDITIONAL="${ADDITIONAL} -p ${ISCSI_PORT}"
		fi

		if [ "${ISCSI_USERNAME}" ]
		then
			ADDITIONAL="${ADDITIONAL} -u ${ISCSI_USERNAME}"
		fi

		if [ "${ISCSI_PASSWORD}" ]
		then
			ADDITIONAL="${ADDITIONAL} -w ${ISCSI_PASSWORD}"
		fi

		if [ "${ISCSI_USERNAME_IN}" ]
		then
			ADDITIONAL="${ADDITIONAL} -U ${ISCSI_USERNAME_IN}"
		fi

		if [ "${ISCSI_PASSWORD_IN}" ]
		then
			ADDITIONAL="${ADDITIONAL} -W ${ISCSI_PASSWORD_IN}"
		fi

		if [ "${ISCSI_DEBUG}" ]
		then
			ADDITIONAL="${ADDITIONAL} -d ${ISCSI_DEBUG}"
		fi

		iscsistart -i "${ISCSI_INITIATORNAME}" -t "${ISCSI_TARGET}" -a "${ISCSI_ADDRESS}" ${ADDITIONAL}

		# let iscsid settle - otherwise mounting the iSCSI-disk will fail (very rarely, though)
		sleep 1
	fi
}

DETECTED_REAL_DEVICE="";
getRealDevice() {
	DETECTED_REAL_DEVICE=$1
	case "${DETECTED_REAL_DEVICE}" in
		UUID\=*|LABEL\=*)
			local REAL_DEV=""
			local retval=1

			if [ "${retval}" -ne 0 ]; then
				REAL_DEV=`findfs "${DETECTED_REAL_DEVICE}" 2>/dev/null`
				retval=$?
			fi

			if [ "$retval" -ne 0 ]; then
				REAL_DEV=`busybox findfs "${DETECTED_REAL_DEVICE}" 2>/dev/null`
				retval=$?
			fi

			if [ "${retval}" -ne 0 ]; then
				REAL_DEV=`blkid -l -t "${DETECTED_REAL_DEVICE}" | cut -d ":" -f 1 2>/dev/null`
				retval=$?
			fi

			if [ "${retval}" -eq 0 ] && [ -n "${REAL_DEV}" ]; then
				good_msg "Detected device ${REAL_DEV}"
				DETECTED_REAL_DEVICE="${REAL_DEV}"
			fi
		;;
	esac
}

# Open a LUKS device
# It is either the root or a swap, other devices are supported in the scripts provided with sys-fs/cryptsetup-luks
# $1 - root/swap
openLUKS() {
	# please use 'tr' and this line, or remove it
	# eval local TYPE=`uppercase $1`

	case $1 in
		root)
			local TYPE=ROOT
			;;
		swap)
			local TYPE=SWAP
			;;
	esac

	eval local LUKS_DEVICE='"${CRYPT_'${TYPE}'}"' LUKS_NAME="$1" LUKS_KEY='"${CRYPT_'${TYPE}'_KEY}"' LUKS_KEYDEV='"${CRYPT_'${TYPE}'_KEYDEV}"' LUKS_TRIM='"${CRYPT_'${TYPE}'_TRIM}"'
	local DEV_ERROR=0 KEY_ERROR=0 KEYDEV_ERROR=0
	local mntkey="/mnt/key/" cryptsetup_options=''

	[ ! -e /sbin/cryptsetup ] && bad_msg "The ramdisk does not support LUKS" && exit 1
	while [ 1 ]
	do
		local gpg_cmd=""
		# if crypt_silent=1 and some error occurs, enter shell quietly
		if [ \( ${CRYPT_SILENT} -eq 1 \) -a \( \( \( ${DEV_ERROR} -eq 1 \) -o \( ${KEY_ERROR} -eq 1 \) \) -o \( ${KEYDEV_ERROR} -eq 1 \) \) ]
		then
			run_shell
		elif [ ${DEV_ERROR} -eq 1 ]
		then
			prompt_user "LUKS_DEVICE" "${LUKS_NAME}"
			DEV_ERROR=0
		elif [ ${KEY_ERROR} -eq 1 ]
		then
			prompt_user "LUKS_KEY" "${LUKS_NAME} key"
			KEY_ERROR=0
		elif [ ${KEYDEV_ERROR} -eq 1 ]
		then
			prompt_user "LUKS_KEYDEV" "${LUKS_NAME} key device"
			KEYDEV_ERROR=0
		else
			getRealDevice ${LUKS_DEVICE}
			LUKS_DEVICE=${DETECTED_REAL_DEVICE}
			getRealDevice ${LUKS_KEYDEV}
			LUKS_KEYDEV=${DETECTED_REAL_DEVICE}

			setup_md_device ${LUKS_DEVICE}
			cryptsetup isLuks ${LUKS_DEVICE}
			if [ $? -ne 0 ]
			then
				bad_msg "The LUKS device ${LUKS_DEVICE} does not contain a LUKS header" ${CRYPT_SILENT}
				DEV_ERROR=1
				continue
			else
				# Handle keys
				if [ "x${LUKS_TRIM}" = "xyes" ]
				then
					good_msg "Enabling TRIM support for ${LUKS_NAME}." ${CRYPT_SILENT}
					cryptsetup_options="${cryptsetup_options} --allow-discards"
				fi

				if [ -n "${LUKS_KEY}" ]
				then
					if [ ! -e "${mntkey}${LUKS_KEY}" ]
					then
						if [ -b "${LUKS_KEYDEV}" ]
						then good_msg "Using key device ${LUKS_KEYDEV}." ${CRYPT_SILENT}
						else
							good_msg "Please insert removable device ${LUKS_KEYDEV} for ${LUKS_NAME}" ${CRYPT_SILENT}
							# abort after 10 secs
							local count=10
							while [ ${count} -gt 0 ]
							do
								count=$((count-1))
								sleep 1
								if [ -b "${LUKS_KEYDEV}" ]
								then
									good_msg "Removable device ${LUKS_KEYDEV} detected." ${CRYPT_SILENT}
									break
								fi
							done
							if [ ! -b "${LUKS_KEYDEV}" ]
							then
								eval CRYPT_${TYPE}_KEY=${LUKS_KEY}
								bootstrapKey ${TYPE}
								eval LUKS_KEYDEV='"${CRYPT_'${TYPE}'_KEYDEV}"'
								if [ ! -b "${LUKS_KEYDEV}" ]; then
									KEYDEV_ERROR=1
									bad_msg "Removable device ${LUKS_KEYDEV} not found." ${CRYPT_SILENT}
									continue
								fi
								# continue otherwise will mount keydev which is mounted by bootstrap
								continue
							fi
						fi
						# At this point a device was recognized, now let's see if the key is there
						[ ! -d "$mntkey" ] && mkdir -p ${mntkey} 2>/dev/null >/dev/null

						mount -n -o ro ${LUKS_KEYDEV} ${mntkey} >/dev/null 2>/dev/null
						if [ "$?" != '0' ]
						then
							KEYDEV_ERROR=1
							bad_msg "Mounting of device ${LUKS_KEYDEV} failed." ${CRYPT_SILENT}
							continue
						else
							good_msg "Removable device ${LUKS_KEYDEV} mounted." ${CRYPT_SILENT}
							sleep 2
							# keyfile exists?
							if [ ! -e "${mntkey}${LUKS_KEY}" ]; then
								umount -n ${mntkey} 2>/dev/null >/dev/null
								KEY_ERROR=1
								KEYDEV_ERROR=1
								bad_msg "Key {LUKS_KEY} on device ${LUKS_KEYDEV} not found." ${CRYPT_SILENT}
								continue
							fi
						fi
					fi
					# At this point a candidate key exists (either mounted before or not)
					good_msg "${LUKS_KEY} on device ${LUKS_KEYDEV} found" ${CRYPT_SILENT}
					if [ "$(echo ${LUKS_KEY} | grep -o '.gpg$')" = ".gpg" ] && [ -e /sbin/gpg ] ; then
						[ -e /dev/tty ] && mv /dev/tty /dev/tty.org
						mknod /dev/tty c 5 1
						cryptsetup_options="" #"-d -"
						gpg_cmd="/sbin/gpg --logger-file /dev/null --quiet --decrypt ${mntkey}${LUKS_KEY} |"
					else
						cryptsetup_options="-d ${mntkey}${LUKS_KEY}"
					fi
				fi
				# At this point, keyfile or not, we're ready!
				crypt_filter "${gpg_cmd}cryptsetup ${cryptsetup_options} luksOpen ${LUKS_DEVICE} ${LUKS_NAME}"
				if [ $? -eq 0 ]
				then
					good_msg "LUKS device ${LUKS_DEVICE} opened" ${CRYPT_SILENT}
					break
				else
					bad_msg "Failed to open LUKS device ${LUKS_DEVICE}" ${CRYPT_SILENT}
					DEV_ERROR=1
					KEY_ERROR=1
					KEYDEV_ERROR=1
				fi
			fi
		fi
	done
	umount ${mntkey} 2>/dev/null >/dev/null
	rmdir -p ${mntkey} 2>/dev/null >/dev/null
}

startLUKS() {

	# if key is set but key device isn't, find it

	[ -n "${CRYPT_ROOT_KEY}" ] && [ -z "${CRYPT_ROOT_KEYDEV}" ] \
		&& sleep 6 && bootstrapKey "ROOT"

	if [ -n "${CRYPT_ROOT}" ]; then
		openLUKS "root"
		if [ -n "${REAL_ROOT}" ]
		then
			# Rescan volumes
			startVolumes
		else
			REAL_ROOT="/dev/mapper/root"
		fi
	fi

	# same for swap, but no need to sleep if root was unencrypted
	[ -n "${CRYPT_SWAP_KEY}" ] && [ -z "${CRYPT_SWAP_KEYDEV}" ] \
		&& { [ -z "${CRYPT_ROOT}" ] && sleep 6; bootstrapKey "SWAP"; }

	if [ -n "${CRYPT_SWAP}" ]; then
		openLUKS "swap"
		if [ -z "${REAL_RESUME}" ]
		then
			# Resume from swap as default
			REAL_RESUME="/dev/mapper/swap"
		fi
	fi
}

sdelay() {
	# Sleep a specific number of seconds if SDELAY is set
	if [ "${SDELAY}" ]
	then
		good_msg "Waiting ${SDELAY} seconds..."
		sleep ${SDELAY}
	else
		good_msg 'Hint: Use parameter scandelay[=seconds] if you need waiting here'
	fi
}

quiet_kmsg() {
	# if QUIET is set make the kernel less chatty
	[ -n "$QUIET" ] && echo '0' > /proc/sys/kernel/printk
}

verbose_kmsg() {
	# if QUIET is set make the kernel less chatty
	[ -n "$QUIET" ] && echo '6' > /proc/sys/kernel/printk
}

setup_btrfsctl() {
	# start BTRFS volume detection, if available
	[ -x /sbin/btrfsctl ] && /sbin/btrfsctl -a
}

setup_md_device() {
	local device

	[ -z "$1" ] && device="${REAL_ROOT}" || device="$1"
	[ -z "${device}" ] && return # LiveCD

	if [ `echo ${device}|sed -e 's#\(luks:\)\?\(/dev/md\)[[:digit:]]\+#\2#'` = "/dev/md" ]
	then
		good_msg 'Detected real_root as a md device. Setting up the device node...'
		MD_NUMBER=`echo ${device}|sed -e 's#\(luks:\)\?/dev/md\([[:digit:]]\+\)#\2#'`
		if [ ! -e /dev/md${MD_NUMBER} ]
		then
			mknod /dev/md${MD_NUMBER} b 9 ${MD_NUMBER} >/dev/null 2>&1
			[ $? -ne 0 ] && bad_msg "Creation of /dev/md${MD_NUMBER} failed..."
		fi
		mdstart ${MDPART} /dev/md${MD_NUMBER}
	fi
}

rundebugshell() {
	if [ -n "$DEBUG" ]
	then
		good_msg 'Starting debug shell as requested by "debug" option.'
		good_msg 'Type "exit" to continue with normal bootup.'
		[ -x /bin/sh ] && /bin/sh || /bin/ash
	fi
}

do_resume() {
	if [ -d /proc/suspend2 -o -d /sys/power/suspend2 -o -d /sys/power/tuxonice ]; then
		tuxonice_resume
	else
		swsusp_resume
	fi
}

swsusp_resume() {
	# determine swap resume partition
	local device=$(ls -lL "${REAL_RESUME}" | sed 's/\  */ /g' | cut -d \  -f 5-6 | sed 's/,\ */:/')
	[ -f /sys/power/resume ] && echo "${device}" > /sys/power/resume
}

tuxonice_resume() {
	local splash_theme
	if grep "splash=" /proc/cmdline > /dev/null 2>&1; then
		splash_theme=$(cat /proc/cmdline | sed 's/.*splash=/splash=/' | sed 's/ .*//' | sed 's/.*theme://' | sed 's/,.*//')
	fi

	local tuxonice_userui_program="/sys/power/tuxonice/user_interface/program"
	local tuxonice_do_resume="/sys/power/tuxonice/do_resume"
	local tuxonice_resumedev="/sys/power/tuxonice/resume"
	local tuxonice_replace_swsusp="/sys/power/tuxonice/replace_swsusp"

	#
	# Backward compatibility
	#
	if [ -e /sys/power/suspend2 ]; then
		tuxonice_userui_program="/sys/power/suspend2/user_interface/program"
		tuxonice_do_resume="/sys/power/suspend2/do_resume"
		tuxonice_resumedev="/sys/power/suspend2/resume"
		tuxonice_replace_swsusp="/sys/power/suspend2/replace_swsusp"
	elif [ -e /proc/suspend2 ]; then
		tuxonice_userui_program="/proc/suspend2/userui_program"
		tuxonice_do_resume="/proc/suspend2/do_resume"
		tuxonice_resumedev="/proc/suspend2/resume"
		tuxonice_replace_swsusp="/proc/suspend2/replace_swsusp"
	fi

	# if 'use_swsusp' is given, use swsusp instead
	if grep "use_swsusp" /proc/cmdline > /dev/null 2>&1; then
		echo 0 > ${tuxonice_replace_swsusp}
		swsusp_resume
		return
	fi

	modules_scan tuxonice

	# we both configure tuxonice and activate resuming,
	# however the kernel will resume only if an image is found

	if ! grep suspend_noui /proc/cmdline > /dev/null 2>&1; then
		which suspend2ui_text > /dev/null 2>&1 && which suspend2ui_text > "${tuxonice_userui_program}"
		which tuxoniceui_text > /dev/null 2>&1 && which tuxoniceui_text > "${tuxonice_userui_program}"

		if [ -n "${splash_theme}" ]; then
			ln -s /etc/splash/${splash_theme} /etc/splash/suspend2
			ln -s /etc/splash/${splash_theme} /etc/splash/tuxonice

			which suspend2ui_fbsplash > /dev/null 2>&1 && which suspend2ui_fbsplash > "${tuxonice_userui_program}"
			which tuxoniceui_fbsplash > /dev/null 2>&1 && which tuxoniceui_fbsplash > "${tuxonice_userui_program}"
		fi

	fi
	echo "${REAL_RESUME}" > "${tuxonice_resumedev}"
	echo > "${tuxonice_do_resume}"
}

getdvhoff() {
	echo $(( $(hexdump -n 4 -s $((316 + 12 * $2)) -e '"%i"' $1) * 512))
}

setup_unionfs() {
	local rw_dir=$1
	local ro_dir=$2
	if [ "${USE_UNIONFS_NORMAL}" = '1' ]
	then
		# Directory used for rw changes in union mount filesystem
		UNION=/union

		mkdir -p ${UNION}
		good_msg "Loading fuse module"
		modprobe fuse > /dev/null 2>&1

		mkdir /tmp
		mkdir -p ${UNION}
		good_msg "Creating union mount"
		unionfs -o allow_other,cow,noinitgroups,suid,dev,default_permissions,use_ino ${rw_dir}=RW:${ro_dir}=RO ${UNION} 2>/dev/null
		ret=$?
		if [ ${ret} -ne 0 ]
		then
			bad_msg "Can't setup union mount!"
			USE_UNIONFS_NORMAL=0
		fi
		[ ! -d "${NEW_ROOT}${CDROOT_PATH}" ] && mkdir -p "${NEW_ROOT}${CDROOT_PATH}"
		mount --bind "${CDROOT_PATH}" "${NEW_ROOT}${CDROOT_PATH}"
	else
		USE_UNIONFS_NORMAL=0
	fi
}

get_mounts_list()
{
	awk '
		/^[[:blank:]]*#/ { next }
		{ print $1 }
		' ${NEW_ROOT}/etc/initramfs.mounts
}

get_mount_options()
{
	awk -v fs="$1" '
		/^[[:blank:]]*#/ { next }
		$2 == fs { print $3 }
		' ${NEW_ROOT}/etc/fstab
}

get_mount_device()
{
	awk -v fs="$1" '
		/^[[:blank:]]*#/ { next }
		$2 == fs { print $1 }
		' ${NEW_ROOT}/etc/fstab
}
  • /usr/src/initramfs/etc/modules/crypto

Put modules depending on the cipher and modes you use for encrypting your root and for gpg.

aes_generic
xts
sha256_generic
cast5

Adding additional binaries

You will need to put following files to your /usr/src/initramfs, if not present:

/usr/src/initramfs
  |-- bin
  |    |-- lvm -> lvm.static
  |    |-- lvm.static*
  |-- etc
  |    |-- splash # your splash screen
  |-- lib
  |    |-- modules
  |    |    |-- 3.3.8-gentoo
  |    |    |    |-- kernel # additional modules u need
  |    |    |    |              # same structure as /lib/modules/3.3.8-gentoo/kernel
  |-- sbin
  |    |-- blkid
  |    |-- cryptsetup
  |    |-- dmraid
  |    |-- fbcondecor_helper
  |    |-- gpg
  |    |-- modprobe
  |    |-- splash_helper -> fbcondecor_helper
  |    |-- v86d
You have to copy a binary of gnupg-1.4.*. Gnupg-2.* will never work. If you have already gnupg-2.* do folowing:
# emerge --unmerge gnupg
# emerge -av "=app-crypt/gnupg-1.4.*"
# cp /usr/bin/gpg /usr/bin/gpg1
# cp /usr/bin/gpg /usr/src/initramfs/sbin/
# emerge -av gnupg

INITRAMFS build script

I also created a compilation script for the initramfs in /usr/local/bin/makeinitramfs with following content:

#!/bin/bash
KERNEL_VERSION=`file /usr/src/linux | awk '{print $5}' | cut -d- -f2`

if [ -z $1 ]; then
        echo -e "USAGE:"
        echo -e "\t${0} [suffix=custom] [src_dir=initramfs] [kernel_params]"
        SUFFIX="custom";
else
        SUFFIX=$1;
fi

if [ -z $2 ]; then
        SRC_DIR="initramfs";
else
        SRC_DIR=$2;
fi

if [ -z $3 ]; then
        KERNEL_PARAMS="root=/dev/ram0 real_root=LABEL=SystemRoot crypt_root=UUID=41f2edde-3e11-4fae-b932-66356f9a9eb0 root_key=/keys/rootkey.gpg root_keydev=LABEL=SystemBoot dolvm video=uvesafb:mtrr:2,ywrap,1920x1080-32@60 console=tty1 quiet splash=silent,fadein,theme:livecd-2007.0 pretend";
else
        KERNEL_PARAMS=$3;
fi

INITRAMFS="/boot/initramfs-genkernel-x86_64-${KERNEL_VERSION}-gentoo-${SUFFIX}"

rm ${INITRAMFS}
if [ -f ${INITRAMFS} ]; then
        while [ 1 ]; do
                echo -n "File ${INITRAMFS} exists! Delete? [y/N] "
                read response
                if [ "${response}" = "y" ]; then
                        rm ${INITRAMFS}
                        break
                else
                        exit
                fi
        done
fi

cd /usr/src/${SRC_DIR}
find . -print0 | cpio --null -ov --format=newc | gzip -9 > ${INITRAMFS}
echo "Testing with: ${KERNEL_PARAMS}"
modprobe kvm-intel
kvm -smp 4 -m 512 -kernel /boot/kernel-genkernel-x86_64-3.3.8-gentoo -initrd /boot/initramfs-genkernel-x86_64-3.3.8-gentoo-${SUFFIX} --append "${KERNEL_PARAMS}" /dev/sda &

Ignore the last two commands for now. They will be useful after we manage to bootup first time. The initramfs should be build using:

# makeinitramfs

Creating a bootable USB flash drive

Backup your key, make a Linux partition and mark it as bootable. 100MB is more than enought. Rest u can use for data partition for any purpose you usualy use your USB flash disks 😉

# mkdir /mnt/backup
# cp -R /boot/* /mnt/backup/
# umount /boot
#
# emerge sys-boot/syslinux
# cat /usr/share/syslinux/mbr.bin > /dev/sdh
# cfdisk /dev/sdh
# mkfs.ext2 /dev/sdh1
# mount /dev/sdh1 /boot
# extlinux --install /boot
# mv /mnt/backup/* /boot/
# rmdir /mnt/backup

Create /boot/extlinux.conf with following content:

DEFAULT gentoo
LABEL gentoo
# Gentoo Linux 3.3.8 [x86_64]
SAY Now booting Gentoo Linux 3.3.8 [x86_64] ...
KERNEL kernel-genkernel-x86_64-3.3.8-gentoo
APPEND ro root=/dev/ram0 real_root=LABEL=SystemRoot crypt_root=UUID=41f2edde-3e11-4fae-b932-66356f9a9eb0 root_key=/keys/rootkey.gpg root_keydev=LABEL=SystemBoot real_resume=LABEL=SystemHibernate video=uvesafb:mtrr:3,ywrap,1920x1080-24@60 splash=silent,fadein,theme:livecd-2007.0 console=tty1 quiet dolvm initrd=initramfs-genkernel-x86_64-3.3.8-gentoo-custom

Unmount everything and reboot. Try to boot from the USB flash disk. You should at least be able to get a shell from the initramfs. Manually load needed modules uncrypt disks and continue booting. As soon as you booted up first time (even manually) you have won.

This is the most annoying part. If you dont have all the binaries and necessary libraries in your initramfs you will need to boot in the LiveCD environment again, chroot an fix the problem by rebuilding the initramfs and possibly also the kernel. Every such reboot takes some time so try to fix as much as possible.

Optimizing and debugging INITRAMFS

Now you should be booted in your new system. If so the last two lines of the /usr/local/bin/makeinitramfs script will be useful. If you run the script the initramfs will be rebuild and booted in a virtual machine. The virtual machine will have RAW access to your disks so you should be able to debug and optimize the initramfs to the state it is usabe without workarounds every boot. After you manage to do that you can reboot to test if its really working and you are done.

Copy the content of KERNEL_PARAMS from the /usr/local/bin/makeintramfs script to your /boot/extlinux.conf without the pretend parameter.

You will also need to setup adjust your system, i.e. /etc/fstab etc…

Leave a Reply

Your email address will not be published. Required fields are marked *