Dm-crypt
Creating a crypt container with plain dm-crypt
Creating the container (100MB in the example below)
dd if=/dev/urandom of=container_file bs=1M count=100
As root, mount and initialize the container
NAME=c01
FREE_LOOP_DEV=$(losetup -f)
losetup $FREE_LOOP_DEV container_file
cryptsetup create $NAME $FREE_LOOP_DEV
# Enter the passphrase
mkfs.ext4 /dev/mapper/$NAME
# Then, mount the device
MOUNTPOINT=/mnt/cryptcontainer
mkdir -p $MOUNTPOINT
mount /dev/mapper/$NAME $MOUNTPOINT
# Access the data in $MOUNTPOINT
touch touch $MOUNTPOINT/MOUNT_FILE # To determine from scripts if the container is mounted
# When you're done, unmount:
umount $MOUNTPOINT
# And close the container
cryptsetup remove $NAME
# Finally close the loop device
losetup -d /dev/loop0
Use the following script to open the container
#!/bin/bash
function wrong_password(){
su -c "echo 'Opening the crypt container failed!'"
su -c "cryptsetup remove $NAME"
su -c "losetup -d $FREE_LOOP_DEV"
exit -1
}
CRYPTO_CONTAINERS_PATH=/srv/edr-data/cryptcontainers
CONTAINER_BASENAME=container
MOUNT_POINT_SUFFIX=_mtpt
CONTAINER_ID="${1:-01}"
CONTAINER_NAME=${CONTAINER_BASENAME}${CONTAINER_ID}
NAME=c${CONTAINER_ID}
OUTPUT_TARGET=/dev/null # Replace /dev/null by a filename to get debug output if things do not work
if [ ! -e ${CRYPTO_CONTAINERS_PATH}/${CONTAINER_NAME} ];then
echo "Container ${CONTAINER_NAME} does not exist!"
exit -1
fi
MOUNTPOINT=${CRYPTO_CONTAINERS_PATH}/${CONTAINER_NAME}${MOUNT_POINT_SUFFIX}
if [ ! -e ${MOUNTPOINT} ];then
echo "Mountpoint ${MOUNTPOINT} does not exist!"
exit -1
fi
FREE_LOOP_DEV=$(su -c "losetup -f")
su -c "losetup $FREE_LOOP_DEV ${CRYPTO_CONTAINERS_PATH}/${CONTAINER_NAME}" > $OUTPUT_TARGET
su -c "cryptsetup create $NAME $FREE_LOOP_DEV" > $OUTPUT_TARGET
# Enter the passphrase
su -c "mount /dev/mapper/$NAME $MOUNTPOINT" > $OUTPUT_TARGET
if [ ! -e $MOUNTPOINT/MOUNT_FILE ];then
wrong_password
fi
exit
And the following to unmount
#!/bin/bash
CRYPTO_CONTAINERS_PATH=/srv/edr-data/cryptcontainers
CONTAINER_BASENAME=container
MOUNT_POINT_SUFFIX=_mtpt
CONTAINER_ID="${1:-01}"
CONTAINER_NAME=${CONTAINER_BASENAME}${CONTAINER_ID}
NAME=c${CONTAINER_ID}
if [ ! -e ${CRYPTO_CONTAINERS_PATH}/${CONTAINER_NAME} ];then
echo "Container ${CONTAINER_NAME} does not exist!"
exit -1
fi
MOUNTPOINT=${CRYPTO_CONTAINERS_PATH}/${CONTAINER_NAME}${MOUNT_POINT_SUFFIX}
if [ ! -e ${MOUNTPOINT} ];then
echo "Mountpoint ${MOUNTPOINT} does not exist!"
exit -1
fi
LOOP_DEV=$(su -c 'losetup -a' | grep ${CONTAINER_NAME} | grep -o "/dev/loop[0-9]")
su -c "umount $MOUNTPOINT "
if [ -e /dev/mapper/$NAME ];then
su -c "cryptsetup remove $NAME"
fi
if [ ! -z $LOOP_DEV ];then
su -c "losetup -d $LOOP_DEV"
fi
If you allow the script for password free execution using sudo you can run it as normal user.