Under Linux, the connexion is handle by the PAM (Pluggable Authentication Modules) authentication system. As is name said it, the functionality are spread in different modules like authentication backend (like LDAP, NSS) or action to do at connexion (like folder mounting).

pam_exec

The pam_exec module allows to execute an arbitrary command while connecting. Therefore it is possible to do what ever we want.

To activate it you only need to add the following line in your /etc/pam.d/common-session file:

[...]
session    optional     pam_exec.so    command
[...]

Replace command by the name of the command to execute.

Several environments variables are set so that can be used inside the program:

  • $PAM_TYPE
  • $PAM_USER
  • $PAM_RUSER
  • $PAM_RHOST
  • $PAM_SERVICE
  • $PAM_TTY

Email notification of a connexion

One of the classical function of this module is to send an email notification while a user is login. For this we will create the /usr/local/bin/send-mail-on-login.sh> script with the following functionality : - only work at the opening of new connexions - only for a limited number of user (for example admin and root) - send by email the connexion information to the administrator (admin)

#!/bin/sh
if ([ "$PAM_TYPE" != "open_session" ] ||
    ([ "$PAM_USER" != "root" ] &&
     [ "$PAM_USER" != "admin" ]))
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

Do not forget to let the script executable by running the following command:

# chmod + x /usr/local/bin/send-mail-on-login.sh

And to modify /etc/pam.d/common-session file accordingly:

[...]
session    optional     pam_exec.so    /usr/local/bin/send-mail-on-login.sh
[...]

Now at each connexion of root or admin, an email will be send to the administrator. For example after a ssh connexion of admin the administrator will receive a email like the following one:

User: admin
Remote Host: dslb-000-000-000-000.pools.arcor-ip.net
Service: sshd
TTY: ssh
Date: mercredi 22 juin 2011, 22:46:38 (UTC+0200)
Server: Linux test 2.6.32-5-amd64 #1 SMP Mon Mar 7 21:35:22 UTC 2011 x86_64 GNU/Linux