Add passtool.sh
authorColin P. Mccabe <colin@cmccabe.xyz>
Mon, 2 Apr 2018 00:53:37 +0000 (17:53 -0700)
committerColin P. Mccabe <colin@cmccabe.xyz>
Mon, 2 Apr 2018 00:53:37 +0000 (17:53 -0700)
passtool.sh [new file with mode: 0755]

diff --git a/passtool.sh b/passtool.sh
new file mode 100755 (executable)
index 0000000..552568e
--- /dev/null
@@ -0,0 +1,62 @@
+#!/usr/bin/env bash
+
+die() {
+    echo $1
+    exit 1
+}
+
+usage() 
+{
+    cat <<EOF
+$0: a tool for dealing with passwords.
+
+Flags:
+-f [path]: specify the password file to use.
+-h: this help message.
+-s [pattern]: search for the given pattern
+
+Environment variables:
+EDITOR: the editor to use.
+EOF
+}
+
+TEMPDIR="/dev/shm/passtool.$$.$RANDOM"
+EDITOR=${EDITOR:-vi}
+mkdir -p "${TEMPDIR}" || die "failed to mkdir ${TEMPDIR}"
+TEMPFILE="${TEMPDIR}/temp"
+TEMPFILE_ENC="${TEMPDIR}/temp.nc"
+trap "rm -rf ${TEMPDIR}; exit" EXIT
+#chmod 007 "${TEMPDIR}" || die "failed to chmod ${TEMPDIR}"
+
+SEARCH_PATTERN=""
+while getopts  "f:hs:" flag; do
+    case $flag in
+        f)  PASSWORD_PATH="${OPTARG}";;
+        h)  usage; exit 0;;
+        s)  SEARCH_PATTERN="${OPTARG}";;
+        *)  echo; usage; exit 1;;
+    esac
+done
+
+[[ -z ${PASSWORD_PATH} ]] && die "You must specify a password file path with -f"
+[[ -f ${PASSWORD_PATH} ]] || die "No regular file found at ${PASSWORD_PATH}"
+
+if [[ -z ${PASSWORD} ]]; then
+    read -s -p "enter password: " PASSWORD
+fi
+if openssl enc -d -aes-256-ecb -k "${PASSWORD}" \
+        < "${PASSWORD_PATH}" > "${TEMPFILE}"; then
+    if [[ -z ${SEARCH_PATTERN} ]]; then
+        ${EDITOR} "${TEMPFILE}"
+        openssl enc -aes-256-ecb -k "${PASSWORD}" -salt \
+                    < "${TEMPFILE}" > "${TEMPFILE_ENC}" ||
+            die "Re-encryption failed.  Changes lost."
+        mv -f "${TEMPFILE_ENC}" "${PASSWORD_PATH}" || \
+            die "failed to move ${TEMPFILE_ENC} to ${PASSWORD_PATH}: changes lost."
+    else
+        echo
+        egrep ${SEARCH_PATTERN} "${TEMPFILE}"
+    fi
+else
+    die "Failed to decrypt ${PASSWORD_PATH}.  Was the password correct?"
+fi