DEV Community

jmc265
jmc265

Posted on • Originally published at jx0.uk

Using BitWarden and Chezmoi to manage SSH keys

I have recently started using Chezmoi to manage my dotfiles (and various other pieces software config) across multiple machines. The distribution is done via a git repo and therefore we should not check in secrets such as the private part of the SSH key. Using Bitwarden, we can store the key in a Secure Note and retrieve on the other machines.

Setup

The rest of this post assumes you already have Chezmoi installed and set up:

curl -sfL https://git.io/chezmoi | sh
chezmoi init

You will also need a pre-existing SSH key:

ssh_keygen -o

Store the key

The public key part of the SSH key can be stored in Chezmoi in plain text:

chezmoi add .ssh/id_rsa.pub

To store the private part we are going to need to install the bitwarden-cli and then login and unlock it:

bw login <EMAIL-ADDRESS>
bw unlock
export BW_SESSION="<SESSION-ID>"

Now, we get to the magic sauce. This line will store your SSH key (stored at ~/.ssh/id_rsa) in a secure note in Bitwarden:

echo "{\"organizationId\":null,\"folderId\":null,\"type\":2,\"name\":\"sshkey\",\"notes\":\"$(sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/\\\\n/g' ~/.ssh/id_rsa)\",\"favorite\":false,\"fields\":[],\"login\":null,\"secureNote\":{\"type\":0},\"card\":null,\"identity\":null}" | bw encode | bw create item

And finally, we need to tell chezmoi where to get the key from. Create a file in your chezmoi repo at this location: private_dot_ssh/private_id_rsa.tmpl and add this as the contents:

{{ (bitwarden "item" "sshkey").notes }}

(For OSX, this file needs a new line character at the end. For Linux, I believe it mustn't, so you might need to end the file with -}} instead)

Make sure all the files are committed and pushed to the origin.

Retrieve the key

On another machine where you want to retrieve the same key, make sure bitwarden-cli and Chezmoi are installed and first do the same login and unlock steps for Bitwarden as above. Then simplpy do:

chezmoi init --apply <GIT-REPO>

And that's it. Check your private key has made it safely to your machine by doing cat ~/.ssh/id_rsa.

You can see the full example of my chezmoi config here.

Top comments (2)

Collapse
 
darksinge profile image
Craig Blackburn

I ended up base64-encoding my ssh key because the sed command was leaving literal \n's in my ssh key.

NOTE=$(cat ~/.ssh/id_rsa | base64)
echo "{ ..., \"notes\":\"$NOTE", ... }" | bw encode | bw create item
Enter fullscreen mode Exit fullscreen mode

Then slightly modified private_dot_ssh/private_id_rsa.tmpl:

{{ (bitwarden "item" "sshkey").notes | b64dec }}
Enter fullscreen mode Exit fullscreen mode

This felt a little nicer than the sed command, so I thought I'd share :). Thanks for this guide, very straightforward!

Collapse
 
joshoram80 profile image
joshoram80

Sorry to necro an old post.
I've tried your solution but bw keeps complaining:
Error parsing the encoded request data.