Fail2ban is dope and SSH is quite secure, but what if someone still manages to authenticate to your machine e.g. by using saved/harvested credentials? Receive email alerts on successful ssh logins based on a predefined IP whitelist OR a predefined IP country origin whitelist.
Essentially: IF (ssh successful authentication ip address NOT IN ip whitelist) OR (ssh successful authentication ip address country of origin NOT IN country whitelist); then send email notification;
Note: For a simpler version that requires only a gmail account see gmail-ssh-log-alert.
sudo apt install geoip-bin
- A domain name.
- A mailgun account.
- Edit variables
country_whitelist
ORip_whitelist
in ssh-log-alert.sh to your needs. - Edit the script and replace your mailgun API, domain name, from-address and to-address in function
mailgun_send_alert()
.
sudo chmod +x ssh-log-alert.sh
There are two ways to use this script:
- Simply run the script (as root) which will result in a live log of every succesfull ssh authentication as well as an indication of email alert trigger success/failure, when a condition is met (you should test it that way also).
./ssh-log-alert.sh
- Add script to the root crontab and have it run in the background when the machine starts:
crontab -e
then add line:
@reboot /bin/bash /path/to/ssh-log-alert/ssh-log-alert.sh
reboot the machine and you are good to go (reboot now
).
If you have never used it:
- You need to have a domain (you can purchase one from multiple services such as https://www.namecheap.com/).
- Create a mailgun account and upgrade it (you need to add payment data but the service is free of charge).
- After you upgrade, you'll need to update your DNS records according to the instructions provided by mailgun.