Skip to content

Instantly share code, notes, and snippets.

@DrSpeedy
Last active June 19, 2023 17:28
Show Gist options
  • Save DrSpeedy/074149c723ba225e7b9251641b9603e7 to your computer and use it in GitHub Desktop.
Save DrSpeedy/074149c723ba225e7b9251641b9603e7 to your computer and use it in GitHub Desktop.
Prototype linux directory locker
#!/bin/bash
# dLocker.sh by Brian Wilson
#
# Quick and dirty prototype for a directory locker
#
# Initialization Example:
# $ cd dLocker
# $ ls
# dLocker/ dLocker.sh
# $ ./dLocker.sh --init
#
# This will compress ./dLocker/dLocker into a gzipped tarball
# and encrypt it with gpg2 as ./dLocker.lk
# From here usage of the script is fairly straight forward.
# Simply use ./dLocker.sh -u to unlock the archive.
#
# NOTE: Any changes made to the unlocked directory are stored in /tmp/dLocker,
# so if the system were to go down before the directory is locked again, all data
# would be lost.
#
# REPEAT: The only way to save data at this moment, is to relock the directory!
BASE=$(basename $PWD)
TMPDIR="/tmp/$BASE"
# Name for GPG key in keyring
USER="Brian Wilson"
# Lock the files up
lock() {
if [ -d "$TMPDIR" ]; then
echo "[OK] $TMPDIR exists"
echo "Archiving data..."
if tar -C /tmp -czf $TMPDIR.tar.gz $BASE; then
echo "[OK] Archiving successful"
echo "Encrypting for user: $USER..."
if gpg2 -o $BASE.lk -se -r "$USER" $TMPDIR.tar.gz; then
echo "[OK] Encryption successful"
echo "Cleaning up..."
#TODO: Find a better way to remove files. Recursively zero them maybe
rm -rf $TMPDIR
rm $TMPDIR.tar.gz
# $ rm -rf $BASE is used when the --init argument is used
unlink $BASE 2> /dev/null || rm -rf $BASE
else
echo "[ERROR] Encryption failed!"
exit -1
fi
fi
else
echo "[ERROR] Data has not been initialized yet..."
echo "[ERROR] Please use $0 --init"
exit -1
fi
}
unlock() {
if [ -f $BASE.lk ]; then
if gpg2 -d $BASE.lk > $TMPDIR.tar.gz; then
echo "[OK] Decryption successful"
echo "Extracting archive..."
if tar -C /tmp -xzf $TMPDIR.tar.gz; then
echo "[OK] Extraction successful"
echo "Soft linking to current directory..."
ln -s $TMPDIR $PWD/$BASE
echo "[OK] Done!"
else
echo "[ERROR] Extraction failed!"
fi
else
echo "[ERROR] Decryption failed!"
fi
else
echo "[ERROR] Could not find $PWD/$BASE.lk!"
fi
}
init() {
if [ -d $BASE ]; then
cp -R $BASE $TMPDIR
if lock; then
echo "[OK] Initialization complete"
echo "Use $0 --unlock to use your files"
# ./$BASE still needs to be zeroed
fi
fi
}
showHelp() {
echo "Welcome to $0! Here are the available commands:"
printf "\t--init, -i\tInitialize a new locked directory\n"
printf "\t--lock, -l\tLock an existing unlocked directory\n"
printf "\t--unlock, -u\tUnlock an existing locked directory\n"
}
case "$1" in
--init | -i)
init ;;
--lock | -l)
lock ;;
--unlock | -u)
unlock ;;
*)
showHelp ;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment