Skip to content

Instantly share code, notes, and snippets.

@nelsonaloysio
Last active July 9, 2024 11:41
Show Gist options
  • Save nelsonaloysio/a79212effe709cda47a5357e24411147 to your computer and use it in GitHub Desktop.
Save nelsonaloysio/a79212effe709cda47a5357e24411147 to your computer and use it in GitHub Desktop.
SSH/SCP with GPG encryption.
#!/usr/bin/env bash
# sshx.sh - SSH/SCP with GPG encryption.
MY_PGP_KEY="XXXXX"
MY_SSH_TAR="/path/to/file.tar.gz.gpg"
function ssh-host () {(
# Reads ~/.ssh/config and returns the host entry for the given host.
h=$(
cat ~/.ssh/config |
grep -v \# |
sed "/^Host / s/ / Host /g" |
tr -d "\n" |
sed "s/Host Host/\nHost/g" |
tee |
sed 1d |
grep -v \* |
grep -E "(^|\s)Host \b($1)\s" --color=never |
sed 's:^Host ::;s: Host : :g'
)
[ -z "$h" ] &&
echo "error: host '$1' not found in config." ||
echo $h
)}
function scpx () {(
# Secure copy (scp) with automatic key loading.
for a in $@; do
[ $(echo "$a" | grep -c :) -gt 0 ] &&
h=$(echo "$a" | cut -f1 -d:) &&
break
done
[ $(grep -Ec "^Host.*\b(\s$h(\s|$))" ~/.ssh/config) -eq 0 ] &&
echo "error: host '$h' not found in config." ||
(sshx-load-hostkeys $h -q -t 15 && scp $@)
)}
function sshx () {
# Secure shell (ssh) with automatic key loading.
[ $(grep -Ec "^Host.*\b(\s$1(\s|$))" ~/.ssh/config) -eq 0 ] &&
echo "error: host '$1' not found in config." ||
(sshx-load-hostkeys $1 -q -t 15 && ssh $@)
}
function sshx-decrypt-keys() {
# Decrypts the SSH keys archive.
mkdir -p ~/.sshx
gpg -dq "$MY_SSH_TAR" |
tar -C ~/.sshx -zx &&
echo "Keys extracted to '~/.sshx'."
}
function sshx-encrypt-keys() {
tar=tar
# On MacOS, check if GNU tar is available.
if [ "$(uname -s)" = Darwin ]; then
[ -n "$(command -v gtar)" ] &&
tar=gtar
fi
# Encrypts the SSH keys archive.
[ -e ~/.sshx ] &&
[ -n "$(ls -1 ~/.sshx/)" ] &&
$tar -cz -C ~/.sshx -T - <<< `cd ~/.sshx && find . -type f | sed 's:./::'` |
gpg -er "$MY_PGP_KEY" > "$MY_SSH_TAR" &&
rm -rf ~/.sshx &&
echo "Keys compressed from '~/.sshx'."
}
function sshx-list-keys() {
# Lists the SSH keys in the archive.
gpg -dq "$MY_SSH_TAR" |
tar -zt |
grep -v .pub |
sort
}
function sshx-load-hostkeys() {(
# Loads required SSH keys for a given host, including ProxyJump hosts.
h=$1
shift
while true; do
k=$(
[ $(ssh-host $h | grep -c IdentityFile) = 1 ] &&
ssh-host $h |
sed 's:.*IdentityFile ::;s: .*::'
)
[ -n "$k" ] && [ $(basename $k) != id_rsa ] &&
sshx-load-key $k $@
h=$(
[ $(ssh-host $h | grep -c ProxyJump) = 1 ] &&
ssh-host $h |
sed 's:.*ProxyJump ::;s: .*::'
)
[ -z "$h" ] && break
done
)}
function sshx-load-key() {
# Loads an SSH key from the archive by name.
[ -z "$1" -o $(sshx-list-keys | grep -wc $1) -eq 0 ] &&
echo "error: key '$1' not found in archive." ||
gpg -dq "$MY_SSH_TAR" |
tar --to-stdout -zx $1 |
ssh-add $(shift && echo $@) -
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment