Skip to content

Instantly share code, notes, and snippets.

@flxai
Last active January 4, 2022 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flxai/14ddcaf8c25979846cb159c8eff82e32 to your computer and use it in GitHub Desktop.
Save flxai/14ddcaf8c25979846cb159c8eff82e32 to your computer and use it in GitHub Desktop.
Unlock OpenSSH keys using passphrases from KeePassXC database

About

This script unlocks multiple OpenSSH keys that reside in a common directory, e.g. ~/.ssh/keys, using passphrases stored in a KeepassXC database, e.g. ~/.keepass.kdbx.

Installation

Download the script and make it executable, e.g. using

$ url="https://gist.githubusercontent.com/flxai/14ddcaf8c25979846cb159c8eff82e32/raw/59eb4b1d5716f19d54b7f2bc73fc88d152006cff/ssh-keyring"
$ wget "$url"
$ chmod +x "ssh-keyring"

Usage

Run the script, declaring the path ot the KeePassXC database and the OpenSSH key directory, i.e.

$ ./ssh-keyring $keepass_db $key_dir

e.g.

$ ./ssh-keyring ~/.keepass.kdbx ~/.ssh/keys
#!/usr/bin/env bash
# Unlock ssh keys using passwords stored in keepassxc database
if [[ $# -lt 2 ]]; then
echo -e "Usage:\n${0##*/} KEEPASS_DB KEY_DIR"
exit 1
fi
# Some variables
kpdb="$1"
key_dir="$2"
askpass="$0-ask"
c_red=$(tput setaf 1)
c_grn=$(tput setaf 2)
c_rst=$(tput sgr0)
# Ask for password
echo "Unlocking all ssh-keys..."
echo -n "Enter password: "
read -s dbpw
echo
key_fail() {
echo " ${c_red}$1${c_rst}"
}
key_success() {
echo " ${c_grn}$1${c_rst}"
}
# Trailing slash required for symlinks
key_files=$(find "$key_dir/" -type f -regex '.+/[^.]+')
for key_file in $key_files; do
# Skip unprotected
ssh-keygen -y -P "" -f "$key_file" &>/dev/null && continue
# Short name
key_name="${key_file##*/}"
# Get keepass item or continue silently
kpid=$(echo "$dbpw" | keepassxc-cli locate "$kpdb" "$key_name" 2>/dev/null)
[[ -z "$kpid" || "$kpid" == "" ]] && key_fail "$key_name (no such entry)" && continue
# Get item's password
key_pw=$(echo "$dbpw" | keepassxc-cli show "$kpdb" "$kpid" -a password 2>/dev/null)
# Use password to unlock key
SSH_ASKPASS="$askpass" ssh-add "$key_file" <<< "$key_pw" 2>/dev/null && key_success "$key_name" || key_fail "$key_name (wrong pw)"
unset key_pw
done
unset dbpw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment