bitwarden-helper-scripts/bw-ssh.sh

49 lines
1.3 KiB
Bash
Raw Normal View History

2020-07-08 15:19:57 -04:00
#!/bin/bash
# To ssh to a host using a key stored in Bitwarden
# Key must be stored as a Secure Note, with the private key as an attachment to the note
# Bitwarden vault must be unlocked prior to use
#Set variables
keyname="${1}"
username=${2}
hostname=${3}
keysavename=$(echo -e ${keyname} | tr -d '[:space:]' | awk -F"/" '{print $NF}')
keyfile=${keysavename}-$(date "+%s")
#Check to see if user is logged in to Bitwarden and vault is unlocked
#check_login()
#{
if bw status | grep -q "unlocked"; then
echo "Bitwarden Vault unlocked, continuing..."
else
echo "Please login with 'bw unlock'"
exit 1
fi
#}
#Fetch private key and place in /home/$user/.ssh/$keysavename_datetime
bw get attachment $(bw get item $keyname | jq ".attachments[] | select((.fileName == \"$keyname\")).id" -r) --output $HOME/$keyfile --itemid $(bw get item $keyname | jq -r .id)
chmod 0600 $HOME/$keyfile
mv $HOME/$keyfile $HOME/.ssh/
#store passphrase in a variable
sshpassphrase=$(bw get item $keyname | jq -r ".fields[] | select((.name == \"Passphrase\")).value")
#Add the key to ssh-agent
expect << EOF
spawn ssh-add -t 30 $HOME/.ssh/$keyfile
expect "Enter passphrase"
send "$sshpassphrase\r"
expect eof
EOF
#SSH to the host
ssh $username@$hostname
#Remove keyfile
rm -f $HOME/.ssh/$keyfile