The task is to send an email alert when SSH-login was made from a not whitelisted IPs.
Will use Monit here.
Install it:
Configure email settings: set localhost (we have a local exim
here), email’s format and email’s receiver.
Edit the /etc/monit/monitrc
file:
... set mailserver localhost set mail-format { from: Monit <monit@$HOST> subject: monit alert -- $EVENT $SERVICE message: $EVENT Service $SERVICE Date: $DATE Action: $ACTION Host: $HOST Description: $DESCRIPTION Your faithful employee, Monit } ... set alert user@example.com
Now add the rules file /etc/monit/conf.d/ssh_alerts.conf
:
check file ssh_logins with path /var/log/auth.log ignore match "/etc/monit/whitelist_ips.txt" if match "Accepted publickey" then alert
Check the documentation about IGNORE
If instead of key-based authorization password-based is used – change “Accepted publickey” to “Accepted password“.
Now in the /etc/monit/whitelist_ips.txt
file add the 1.1.1.1 IP – after testing will set a real one(s):
Restart the monit
service:
Check how it’s working – login to a server:
Check Monit’s logs:
And an email:
Obviously – such an approach may be used for anything just by changing the if match
conditions.
For example – I have one site which is inaccessible for all excluding myself, so I added another rule:
check file nginx_web_access with path /var/log/nginx/example.com-access.log ignore match "/etc/monit/whitelist_ips.txt" if match "GET" then alert
Here on any GET
-request from an IP not added to the white list – I’ll get an email alert.
The /etc/monit/whitelist_ips.txt
may look like next:
Here is one IP of my job’s network and another one – my home.
Done.