Thursday, February 18, 2016

Setup SSH Login Email Alert on Ubuntu 14.04 or Debian

Anytime one enables ssh server, the machine will be at great risk from random attempts all around the world. It may be wise to setup an alert mail when someone logs into the machine remotely. In this post, we will look into how to do so.

I will make use of mail.mailutils program to send emails out here, but there are many other alternative mail out packages.
$ sudo apt-get install -y mailutils postfix
When prompted with postfix configuration, just choose the default setting, which is Internet Site.

Next, create a bash script file that will be executed when someone logs in remotely. In this example, I will place it in the /etc/ssh directory.
$ sudo vim /etc/ssh/ssh_alert.sh

Add the following content to the file
#!/bin/bash
# replace with sender's email address
sender="sender_address@some_mail.com"
# replace with recipient's email address
recipient="recipient_address@some_mail.com"
time=$(date)
if [ "$PAM_TYPE" != "close_session" ]; then
# replace with host name
host="ubuntu-server"
subject="SSH Login: $PAM_USER from $PAM_RHOST on $host at $time"

message="SSH login $PAM_USER from $PAM_RHOST at $time on $host"
echo "$message" | mail.mailutils -r "$sender" -s "$subject" "$recipient"
fi

Next, enable execute
$ sudo chmod u+x /etc/ssh/ssh_alert.sh

Now, we need to make sure that the script actually works. To do so, simply run it
$ sudo /etc/ssh/ssh_alert.sh

If you see a message saying that the email was sent successfully, then you can set it up so that a ssh remote login will execute the script and allow the remote login only if the email was successfully sent. To see whether the execution returns successful, type in
$ echo $?
The output of 0 means successful.

When the mail out is successful, open up /etc/pam.d/sshd
$ sudo vim /etc/pam.d/sshd

Add the following line to /etc/pam/sshd
session required pam_exec.so seteuid /etc/ssh/ssh_alert.sh

That's it. You should now receive the email when someone logs into the server through ssh.

No comments:

Post a Comment