The best & the only appropriate approach is to Disable Root SSH Login. No need for email alerts. If something bad happens, it'd be already too late when you finally read the email notification. That is already explained in the article you were following:
So it’s not a good practice to allow direct root login via SSH
session and recommend to create non root accounts with sudo
access.
Whenever root access needed, first logged in as normal user and then
use su
to switch over to root user. To disable direct SSH root logins,
follow our below [Disable SSH Root Login and Limit SSH Access] article that shows how to disable and limit root
login in SSH.
If you are still willing to use email alerts instead...
The .bashrc
solution seems to be very popular, but has some problems. It gets to run (always and only) when bash
is launched. It stops to work if replaced by any other shell, or shell not launched (e.g. login only used for tunneling on SFTP), and it also runs even when SSH is not involved. An attacker could modify the .bashrc
before invoking bash
in order to circumvent your alert.
Since you probably don't use SSH internally, using ~/.ssh/rc
would meet the desired conditions, e.g.
ip=`echo $SSH_CONNECTION | cut -d " " -f 1`
echo "Root login from $ip" | mail -s "Alert: SSH root login from $ip" your@example.com
Then, for global SSH login alerts I wouldn't use anything in users home ~/
as the user can easily modify it. The ~/.ssh/rc
can be made a global default by using /etc/ssh/sshrc
, and any user can override the settings by using own ~/.ssh/rc
, with an easy fallback by removing the file.
If you need to enforce the alert in a way a user cannot override, you could use /etc/pam.d/sshd
: add line session optional pam_exec.so seteuid /path/to/login-notify.sh
where the .sh
script sends you (or the user) email.