diff --git a/README.md b/README.md index 53b902c..ffca1be 100644 --- a/README.md +++ b/README.md @@ -31,3 +31,16 @@ Used to upload a directory of ssh keys to bitwarden, placing public key in the n 3. Run script like this: ```/home/$USER/scripts/bw-ssh-uploader.sh /path/to/directory/of/keys $COLLECTIONID $ORGID``` + +## bw-ssh.sh + +Used to fetch a private key from bitwarden, add it to ssh-agent, and login to a host + +### Usage Instructions + +1. Copy the file to a location of your choosing, I use `/home/$USER/scripts` + +2. Mark it as executable + +3. Run the script like this: +```/home/$USER/scripts/bw-ssh.sh $KEYNAME $USERNAME $HOSTNAME``` \ No newline at end of file diff --git a/bw-ssh.sh b/bw-ssh.sh new file mode 100755 index 0000000..bb90d0f --- /dev/null +++ b/bw-ssh.sh @@ -0,0 +1,48 @@ +#!/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