Skip to content

Instantly share code, notes, and snippets.

@esolitos
Created August 12, 2017 10:48
Show Gist options
  • Save esolitos/f07ba34ca3e421e12ca4ca52e417feff to your computer and use it in GitHub Desktop.
Save esolitos/f07ba34ca3e421e12ca4ca52e417feff to your computer and use it in GitHub Desktop.
Useful functions to (un)lock and (un)mount a Lucks device (a USB in this example)
#!/bin/sh
# Open and close secure key
secureUSBOpen () {
luksDev="$1"
luksName="$2"
mountPoint="/media/USB/${luksName}"
# Check if we have the right args
if [ $# -ne 2 ]; then
echo "Error: You need to specify the device and LuksName" 1>&2
return 22
fi
# Check if the device exists and it's a mountable block device
if [ ! -b "$luksDev" ]; then
echo "Error: $luksDev is not a mountable device!" 1>&2
return 15
fi
if [ -e "$mountPoint" ]; then
echo "Error: Mount point already exists." 1>&2
return 17
fi
echo "Attempting to unlock $luksDev and mount to $mountPoint"
cryptsetup luksOpen $luksDev $luksName
if [ $? -ne 0 ]; then
echo "Error: luksOpen returned non-zero code. Stopping." 1>&2
return 1
fi
mkdir -p "$mountPoint"
mount "/dev/mapper/$luksName" "$mountPoint"
cd "$mountPoint"
}
secureUSBClose () {
luksName="$1"
mountPoint="/media/USB/${luksName}"
# Check if we have the right args
if [ $# -ne 1 ]; then
echo "Error: You need to specify the Luks device name" 1>&2
return 22
fi
if [ ! -d "$mountPoint" ]; then
echo "Error: Mount point doesn't exist, inconsistent state!" 1>&2
else
# Check for usage!
lsof "$mountPoint"
if [ $? -ne 0 ]; then
echo "Error: At the least one process is using $mountPoint" 1>2
else
umount "$mountPoint"
rmdir "$mountPoint"
cryptsetup luksClose "$luksName"
fi
fi
if [ "$(cryptsetup status "$luksName" | grep -c inactive)" -ne 1 ]; then
echo -E "\nError: $luksName doesn't seems to be inactive!!\n" 1>&2
return -1
else
echo -E "\n[OK] $luksName seems to be inactive"
return 0
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment