Unknown SSH key on a Linux server: audit authorized_keys and sshd for backdoor access
A key in authorized_keys is a permanent door that survives password changes. Attackers add one right after getting in. Check every user, not just root, and also the sshd settings that can add access in other ways.
List every authorized key
Show the keys of all users, with the file's last change time. A key you cannot name is a suspect.
for f in /root/.ssh/authorized_keys /home/*/.ssh/authorized_keys; do echo "== $f"; sudo stat -c '%y' "$f" 2>/dev/null; sudo cat "$f" 2>/dev/null | cut -c1-90; doneLook at other places keys can come from
sshd can read keys from other files or from a command. Check the effective configuration.
sudo sshd -T | grep -Ei 'authorizedkeys|authorizedprincipals|permitrootlogin|passwordauthentication|allowusers' ls /etc/ssh/sshd_config.d/See which key was used to log in
The authentication log records the fingerprint of the key. Match fingerprints to keys.
sudo grep 'Accepted publickey' /var/log/auth.log | tail -n 30 ssh-keygen -lf /home/USER/.ssh/authorized_keysRemove keys you do not recognise
Keep a copy of the file for evidence, then remove only the lines you cannot account for, and check the file is not immutable or recreated.
sudo cp /home/USER/.ssh/authorized_keys /root/ak-evidence-USER sudo lsattr /home/USER/.ssh/authorized_keysEnd the sessions that are open now
Find and end sessions from unknown addresses.
w sudo ss -tnp | grep ':22 ' sudo pkill -KILL -t pts/N # replace N with the terminal to endRotate your own keys and lock SSH down
If an attacker had access, treat your keys as seen: make new ones, use keys only, and limit who can log in.
sudo sshd -T | grep -E 'passwordauthentication|permitrootlogin' # want: no, prohibit-password or no
Common mistakes
- Checking only root's file and missing the other users.
- Removing the key but not asking how it got there: the way in is probably still open.
- Closing all your sessions at once with a mistyped sshd change: keep one session open and test a new login.
How to undo it
Put back a legitimate key from your copy of the file, and revert any sshd_config change from the backup in /etc/ssh, testing with sshd -t before reloading.
Sources
Commands are for Debian and Ubuntu unless noted. Test on a copy first and keep a backup: you are responsible for changes on your own systems.