ce34965471aa5ea9f292514a2fe66dbd29872b1f
[cmccabe-bin] / passtool.sh
1 #!/usr/bin/env bash
2
3 die() {
4     echo $1
5     exit 1
6 }
7
8 usage() 
9 {
10     cat <<EOF
11 $0: a tool for dealing with passwords.
12
13 Flags:
14 -f [path]: specify the password file to use.
15 -h: this help message.
16 -p: the input file is plaintext, and we should encrypt it.
17 -s [pattern]: search for the given pattern
18
19 Environment variables:
20 EDITOR: the editor to use.
21 EOF
22 }
23
24 TEMPDIR="/dev/shm/passtool.$$.$RANDOM"
25 EDITOR=${EDITOR:-vi}
26 mkdir -p "${TEMPDIR}" || die "failed to mkdir ${TEMPDIR}"
27 TEMPFILE="${TEMPDIR}/temp"
28 TEMPFILE_ENC="${TEMPDIR}/temp.nc"
29 trap "rm -rf ${TEMPDIR}; exit" EXIT
30 #chmod 007 "${TEMPDIR}" || die "failed to chmod ${TEMPDIR}"
31
32 encrypt_new_file() {
33     echo
34     encrypt_file "${TEMPFILE}" "${PASSWORD_PATH}"
35     [[ $? -ne 0 ]] && die "Failed to encrypt ${PASSWORD_PATH}"
36     mv -f "${TEMPFILE}" "${PASSWORD_PATH}" || \
37         die "Failed to replace ${PASSWORD_PATH}"
38     exit 0
39 }
40
41 search_existing_file() {
42     echo
43     decrypt_file "${TEMPFILE}" "${PASSWORD_PATH}"
44     [[ $? -ne 0 ]] && \
45         die "Failed to decrypt ${PASSWORD_PATH}.  Was the password correct?"
46     egrep ${SEARCH_PATTERN} "${TEMPFILE}"
47 }
48
49 edit_existing_file() {
50     echo
51     decrypt_file "${TEMPFILE}" "${PASSWORD_PATH}"
52     [[ $? -ne 0 ]] && \
53         die "Failed to decrypt ${PASSWORD_PATH}.  Was the password correct?"
54     ${EDITOR} "${TEMPFILE}"
55     encrypt_file "${PASSWORD_PATH}" "${TEMPFILE}" 
56     [[ $? -ne 0 ]] && \
57             die "failed to move ${TEMPFILE_ENC} to ${PASSWORD_PATH}: changes lost."
58     exit 0
59 }
60
61 encrypt_file() {
62     dest="${1}"
63     src="${2}"
64     openssl enc -aes-256-ecb -k "${PASSWORD}" -salt < "${src}" > "${dest}"
65 }
66
67 decrypt_file() {
68     dest="${1}"
69     src="${2}"
70     openssl enc -d -aes-256-ecb -k "${PASSWORD}" < "${src}" > "${dest}"
71 }
72
73 SEARCH_PATTERN=""
74 PLAINTEXT=0
75 while getopts  "f:hps:" flag; do
76     case $flag in
77         f)  PASSWORD_PATH="${OPTARG}";;
78         h)  usage; exit 0;;
79         p)  PLAINTEXT=1;;
80         s)  SEARCH_PATTERN="${OPTARG}";;
81         *)  echo; usage; exit 1;;
82     esac
83 done
84
85 [[ -z ${PASSWORD_PATH} ]] && die "You must specify a password file path with -f"
86 [[ -f ${PASSWORD_PATH} ]] || die "No regular file found at ${PASSWORD_PATH}"
87
88 if [[ -z ${PASSWORD} ]]; then
89     read -s -p "enter password: " PASSWORD
90 fi
91 if [[ ${PLAINTEXT} -eq 1 ]]; then
92     if [[ ${SEARCH_PATTERN} != "" ]]; then
93         die "You may not specify both -s and -p."
94     fi
95     encrypt_new_file
96 elif [[ ${SEARCH_PATTERN} != "" ]]; then
97     search_existing_file
98 else
99     edit_existing_file
100 fi
101