Send mail the first time an IP logs in over SSH

Fail2ban is useful for slowing down brute force attacks against SSH, and in the few days since I enabled it it’s become very clear that these attempts are happening all the time. I don’t want to disable password authentication for all users in case I find myself without my SSH keys, and even if I did it’s not impossible for SSH keys to be compromised. For the day when the walls are breached, I’ve put this in my /etc/ssh/sshrc:

IP="$(echo $SSH_CONNECTION | awk '{print $1}')"
KNOWN_IPS="$HOME/.ssh/known_ips"
if ! grep -Fqsx $IP $KNOWN_IPS; then
  echo $IP >> $KNOWN_IPS
  echo "$IP added to $KNOWN_IPS" | \
    mail -s "ssh $USER@$(hostname) from $IP" [email protected]
fi

It sends me an email the first time a particular IP successfully logs in over SSH. (If you use this, make sure that mail is configured correctly first: dpkg-reconfigure exim4-config in Debian.)

2 thoughts on “Send mail the first time an IP logs in over SSH

  1. This seems very sensible. But what if a well-prepared invader disables your MTA immediately on login? Is it possible to force sshd to wait for the mail to be delivered before starting the ssh session?

Comments are closed.