Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Notes on reacting to ssh key used to connect to server

The answers to https://unix.stackexchange.com/questions/15575/can-i-find-out- which-ssh-key-was-used-to-access-an-account provide some interesting details I've never seen before. You can specify a command to run in the ~/.ssh/authorized_keys file:

command="/usr/share/bgscripts/work/react-ssh.sh ; /bin/bash" ssh-rsa AAAAB3NgaC1yc2EAAAABJQAAANEAnYh0nq5dzOgIgfkh50Th68hZoX+zR[...output truncated...]

Inside my example react-ssh.sh file:

journalctl -n30 -u sshd.service 2>/dev/null | grep -E "sshd\[$( ps --noheaders -o ppid $( ps --noheaders -o ppid $( ps --noheaders -o ppid $$ ) ) | xargs )]: Accepted publickey for ${USER}" | tail -n1 | awk '{print $(NF-1),$NF}'

So when I log in with an ssh key, it will print it out for me:

[bgstack15@example1|/home/bgstack15]$ ssh example2
RSA SHA256:I3wuJRyf1dWCzeqdLl6mWfMl9wONJLk38/xUwLCiNgA
[bgstack15@example2 ~]$

Here is a script that could be called with a parameter to show the entire public key of the hash.

1
2
3
4
5
6
7
8
9
#!/bin/sh
# to show the full public key of the provided hash
test -z "${SFK_AUTHORIZED_KEYS}" && SFK_AUTHORIZED_KEYS=~/.ssh/authorized_keys

SFK_HASHES="$( ssh-keygen -l -f "${SFK_AUTHORIZED_KEYS}" )"
for word in $@ ;
do
   sed -n -r -e "$( echo "${SFK_HASHES}" | grep -hn "${word}" | awk -F':' '{print $1}' )p" "${SFK_AUTHORIZED_KEYS}"
done

Comments