Sending email notifications of SSH logins on a system

There are some setups where it's beneficial to get a notice of user logins on a system. Here's one way to do it.

Create /usr/local/sbin/notify-login-mail.sh:

#!/bin/sh
if [ "$PAM_TYPE" != "open_session" ]
then
  exit 0
else
  {
    echo "User: $PAM_USER"
    echo "Remote host: $PAM_RHOST"
    echo "Service: $PAM_SERVICE"
    echo "TTY: $PAM_TTY"
    echo "Date: `date`"
    echo "Server: `uname -a`"
  } | mail -s "$PAM_SERVICE login on `hostname -s` for account $PAM_USER" root
fi
exit 0
# chmod 500 /usr/local/sbin/notify-login-mail.sh

Append the execution trigger to certain files, e.g. /etc/pam.d/[sshd|su|sudo]:

session    optional     pam_exec.so /usr/local/sbin/notify-login-mail.sh

For example the following triggers the notification from SSH logins, and successful su's and sudo's:

echo "session    optional     pam_exec.so /usr/local/sbin/notify-login-mail.sh" >> /etc/pam.d/sshd 
echo "session    optional     pam_exec.so /usr/local/sbin/notify-login-mail.sh" >> /etc/pam.d/su
echo "session    optional     pam_exec.so /usr/local/sbin/notify-login-mail.sh" >> /etc/pam.d/sudo

Check that mail exists; if not, it's in the package mailx:

# yum install mailx

Check the root account mail has been sensibly forwarded (e.g. /etc/aliases). Ensure there's a local MTA installed.

SSH: Allow only certain users to login with password

I got tired of the SSH failed login spam most public servers get. Allowing password login only for the users who really need it is an easy way to reduce login spam and also shrink the server's attack surface somewhat.

Create the specified user group and add users to it:

# groupadd -r password
# usermod -G password <user>

Append to /etc/ssh/sshd_config:

# Can't login with a password if not a member of the group "password"
PasswordAuthentication no
Match group password
    PasswordAuthentication yes

Also check that there are no other PasswordAuthentication directives effective in the file. Restart sshd. Test the login before killing existing connections.

Etaoin shrdlu

Sorry to disappoint, but there isn't really much yet. See you with better content later. Meanwhile, have some tasty lorem ipsum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

No comments