2016-07-21 13:48:49 +00:00
|
|
|
#!/bin/bash
|
|
|
|
|
|
|
|
COLOR_RED="\033[0;31m"
|
|
|
|
COLOR_GREEN="\033[0;32m"
|
|
|
|
COLOR_CYAN="\033[0;36m"
|
|
|
|
COLOR_PLAIN="\033[0m"
|
|
|
|
|
|
|
|
function error {
|
|
|
|
echo -e "${COLOR_RED}$@${COLOR_PLAIN}"
|
|
|
|
}
|
|
|
|
|
|
|
|
function success {
|
|
|
|
echo -e "${COLOR_GREEN}$@${COLOR_PLAIN}"
|
|
|
|
}
|
|
|
|
|
|
|
|
function info {
|
|
|
|
echo -e "${COLOR_CYAN}$@${COLOR_PLAIN}"
|
|
|
|
}
|
|
|
|
|
|
|
|
if ! ( which vault > /dev/null ); then
|
|
|
|
error "vault is required."
|
|
|
|
exit 2
|
|
|
|
fi
|
|
|
|
|
|
|
|
# Require something to be passed to this command
|
|
|
|
if [ $# -eq 0 ]; then
|
|
|
|
error "You need to specify a key name."
|
|
|
|
exit 2
|
|
|
|
fi
|
|
|
|
|
2016-12-29 12:43:45 +00:00
|
|
|
# Create a helper script to send STDIN data to ssh-add
|
|
|
|
HELPER=$(tempfile -m 0700)
|
|
|
|
trap "rm ${HELPER}" EXIT
|
2016-07-21 13:48:49 +00:00
|
|
|
|
2016-12-29 12:43:45 +00:00
|
|
|
cat -s <<EOF > ${HELPER}
|
|
|
|
#!/bin/bash
|
|
|
|
vault read -field=private "/secret/ssh-key/\$1" | exec ssh-add -
|
|
|
|
EOF
|
2016-07-21 13:48:49 +00:00
|
|
|
|
2016-12-29 12:43:45 +00:00
|
|
|
for KEY_NAME in $@; do
|
2016-07-21 13:48:49 +00:00
|
|
|
# If this key is already in the agent we don't need to do anything
|
|
|
|
if ( ssh-add -l | grep -q "${KEY_NAME}" ); then
|
2016-12-29 12:43:45 +00:00
|
|
|
info "[${KEY_NAME}] Key already present."
|
2016-07-21 13:48:49 +00:00
|
|
|
continue
|
|
|
|
fi
|
|
|
|
|
|
|
|
# Retrieve key from LastPass
|
2016-12-29 12:43:45 +00:00
|
|
|
PWD=$(vault read -field=passphrase "/secret/ssh-key/${KEY_NAME}")
|
2016-07-21 13:48:49 +00:00
|
|
|
# In case LastPass exitted non-zero we have no password
|
|
|
|
if ! [ $? -eq 0 ]; then
|
2016-12-29 12:43:45 +00:00
|
|
|
error "[${KEY_NAME}] Unable to get password. Not trying to unlock."
|
2016-07-21 13:48:49 +00:00
|
|
|
continue
|
|
|
|
fi
|
|
|
|
|
|
|
|
# Fill password to ssh-add utility
|
|
|
|
expect <<EOF >/dev/null
|
2016-12-29 12:43:45 +00:00
|
|
|
spawn ${HELPER} ${KEY_NAME}
|
|
|
|
|
2016-07-21 13:48:49 +00:00
|
|
|
expect "Enter passphrase"
|
|
|
|
send "$PWD\n"
|
2016-12-29 12:43:45 +00:00
|
|
|
|
|
|
|
expect "added:" {exit 0} timeout {exit 1}
|
2016-07-21 13:48:49 +00:00
|
|
|
EOF
|
|
|
|
|
2016-12-29 12:43:45 +00:00
|
|
|
if [ $? -eq 0 ]; then
|
|
|
|
info "[${KEY_NAME}] Should be loaded by now."
|
2016-07-21 13:48:49 +00:00
|
|
|
else
|
2016-12-29 12:43:45 +00:00
|
|
|
error "[${KEY_NAME}] Was not added successfully."
|
2016-07-21 13:48:49 +00:00
|
|
|
fi
|
|
|
|
|
|
|
|
done
|