Skip to content

Instantly share code, notes, and snippets.

@larvanitis
Last active September 20, 2017 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larvanitis/99cc3d665a324d0ba05bbf564874df6c to your computer and use it in GitHub Desktop.
Save larvanitis/99cc3d665a324d0ba05bbf564874df6c to your computer and use it in GitHub Desktop.
Encrypted file container
#!/bin/sh
echo "Not a script..." >&2 && exit 1
# This is more or less a TL;DR; procedure to create and use an encrypted volume contained in a file instead of a physical drive/partition.
# The encryption options are set to sane (and IMHO secure) values. The device will be (un)locked using a password.
# The mounting is done manually by the root and all users can access the mounted filesystem.
################
# REQUIREMENTS #
################
# 1) Programs: dd, losetup, cryptsetup, mkfs.ext4
# ...on Arch Linux that is: coreutils, util-linux, cryptsetup, e2fsprogs
# 2) Root access (user must be root or sudoer)
# See also: https://wiki.archlinux.org/index.php/Dm-crypt/Encrypting_a_non-root_file_system#Loop_device
#############
# PROCEDURE #
#############
# WARNING: The following commands assume that the first loopback device is unused (/dev/loop0).
# If you already have other devices mapped use a higher number (eg. `/dev/loop1`)
# You can check this with `losetup -a` which should list all currently used devices.
# IF YOU DON'T USE A FREE LOOP DEVICE YOU WILL DESTROY YOUR SYSTEM, YOUR HOME AND PROBABLY YOUR MARRIAGE!
# Create volume file
sudo dd if=/dev/urandom of=/PATH/TO/ENCRYPTED.VOL bs=1M count=SIZE_IN_MB
# eg. `sudo dd if=/dev/urandom of=/my_encrypted_container.img bs=1M count=1024`
# Mount loopback device
sudo losetup /dev/loop0 /PATH/TO/ENCRYPTED.VOL
# Encrypt device
sudo cryptsetup -v --cipher aes-xts-plain64 --key-size 512 --hash sha512 --iter-time 5000 --use-urandom --verify-passphrase luksFormat /dev/loop0
# Open (unencrypt) encrypted device
sudo cryptsetup open /dev/loop0 MAPPER_LABEL
# Create the filesystem
sudo mkfs -t ext4 -m 0 -L FS_LABEL /dev/mapper/MAPPER_LABEL
# Close the device and unmount the loopback device (cleanup)
sudo cryptsetup close MAPPER_LABEL && sudo losetup -d /dev/loop0
# Create the mounting point
sudo mkdir -p -m 755 /PATH/TO/MOUNT_DIR
# At this point you are set...
#########
# USAGE #
#########
# Open and mount the encrypted volume
sudo cryptsetup luksOpen /PATH/TO/ENCRYPTED.VOL MAPPER_LABEL && sudo mount /dev/mapper/MAPPER_LABEL /PATH/TO/MOUNT_DIR
# Unmount and close the encrypted volume
sudo umount /dev/mapper/MAPPER_LABEL && sudo cryptsetup luksClose MAPPER_LABEL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment