To improve security on your Linux server it’s useful to know when someone gains root privileges on a Linux machine via SSH. For example, if a hacker gained root access to a server you will be notified via email and can take prompt action. Having this setup will also help with incident management as emails will provide you with the IP address of the machine that used root and timestamp.
Here is a simple bash script that will email you an alert when someone logs in via SSH as root, this will work for direct root logins as well as elevating/switching users via ‘su’.
To implement email alerts on root login:
echo 'ALERT - Root Shell Login:' `date` `who` | mail -s "Alert: Root Login from `who | cut -d"(" -f2 | cut -d")" -f1`" firstname.lastname@example.org
Just amend the email address at the end of the line to your old email and save changes to the file.
Simply log out as root and back in and you should get an email alert straight into your inbox!
Don’t forget to whitelist the email address so it doesn’t end up in your Junk mailbox.
This will work on pretty much all Linux distributions, CentOS, Redhat, Ubuntu, FreeBSD etc.