Skip to content

Instantly share code, notes, and snippets.

@sinewalker
Last active February 9, 2024 22:10
Show Gist options
  • Save sinewalker/91d74a0d19a93f373e2071e5ba2ced2e to your computer and use it in GitHub Desktop.
Save sinewalker/91d74a0d19a93f373e2071e5ba2ced2e to your computer and use it in GitHub Desktop.
ssh-pass: add an SSH key to your agent with passphrase from password store, no clipboard
#!/bin/bash
#Add specified SSH keys to the SSH Agent, using SSH_ASKPASS to retrieve
#each key's passphrase from the Unix password store (pass).
#This relies upon the keys having the same names in both your key directory
#and your password store.
if [[ -z ${1} ]]; then
echo "$(basename ${0}): no SSH key specified" 1>&2
exit 1;
fi
KEY_DIR=${HOME}/key
export DISPLAY=dummy
for KEY in ${@}; do
export SSH_ASKPASS=$(mktemp -t ssh-askpass)
cat > ${SSH_ASKPASS} << EOF
#!/bin/sh
pass ${KEY}|head -1
EOF
chmod +x ${SSH_ASKPASS}
ssh-add ${KEY_DIR}/${KEY} < /dev/null
rm ${SSH_ASKPASS}
done
@sinewalker
Copy link
Author

Blogged at milosophical.me, and since improved a bit by adding the for loop to handle multiple keys (each still has the same naming constraint).

@CodeIter
Copy link

CodeIter commented Feb 9, 2024

Automatically load ssh keys :
Add to .bashrc and configure environment variable.

export SSH_DIR="${HOME}/.ssh"
command mkdir -p "${SSH_DIR}"
eval "$(ssh-agent -s)" >/dev/null 2>&1
export SSH_AUTH_SOCK="${SSH_AUTH_SOCK}"
export SSH_AGENT_LIFE=14400 # 4 hours
export SSHADD_OPTS=""
export PASS_SSH_ENTRY_PREFIX="_ssh"
if command -v pass &>/dev/null \
&& command -v gpg &>/dev/null \
; then
  for _public_key in "${SSH_DIR}"/*.pub ; do
    _private_key="${_public_key%.pub}"
    _entry="$(basename "${_private_key}")"
    if command pass ls "${PASS_SSH_ENTRY_PREFIX}/${_entry}" &>/dev/null ; then
      if ! command ssh-add -l | command grep -qF -- "$(command ssh-keygen -lf "${_public_key}")" &>/dev/null ; then
        _ask="${SSH_DIR}/ssh-askpass.sh"
        (\
          echo '#!/usr/bin/env -S bash -euo pipefail' ; \
          echo ; \
          echo "command pass '${PASS_SSH_ENTRY_PREFIX}/${_entry}/password' | command head -n 1" \
        ) > "${_ask}"
        command chmod u+x "${_ask}"
        DISPLAY="${DISPLAY:-dummy}" \
        SSH_ASKPASS_REQUIRE=force \
        SSH_ASKPASS="${_ask}" \
        command ssh-add -t "${SSH_AGENT_LIFE}" ${SSHADD_OPTS:-} "${_private_key}"
      fi
    fi
  done
  command rm -f "${_ask}"
  unset _public_key _private_key _entry _ask
  #echo ; ssh-add -l
fi

My pass ssh entries:
$ pass _ssh/

_ssh
└── id_termux
    ├── cipher
    ├── note
    ├── password
    ├── privateKey.priv
    └── publicKey.pub
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment