Thursday, September 18, 2008

Log ssh accesses

After that our mail server was hacked I've worked in order to increase security and controls of all our public servers.
One of the ideas that popped into my head was an alert that could notifies me every time someone successfully login into a public server. Searching the web I'd found a useful idea to put a line in bashrc that sends an email every time someone opens a session.
I've improved that line a bit and the result is a script that reads from an external file the patterns of addresses for which not to send emails (such as the IP of your desktop, for example).

The script is something like that:
# Send login alert
# This script is useful to send an alert email when someone log in with
# the monitored user
# Remember to alias the root account to a valid mail box
# Thinked by Simone Tregnago (

#this file provides the patterns of hosts for which you don't want to send messages
whologged=$(who -m | cut -d"(" -f2 | cut -d")" -f1)

if [ -z "$(echo $whologged | grep -f $acl_patterns )" ]; then
(echo "ALERT - Access to "$(hostname -f)" on:" $(date);echo;echo "who output:
";echo $(who -T)) | mail -s "Subject: Alert: access from "$whologged root

The acl_patterns is the file that contains the patterns parsed by grep. If the pattern matches the script exits without the alert.

For example:
will match for accesses made from or from ip under 10.1.x.x , so it doesn't sends alerts for this origins.

With those two files, following those simple steps, you can have emails alerts for every user:
- Put the script and the patterns files in a place accessible by the user that you want to monitor
- Set the script as executable
- Add a line in the .bashrc of the monitored user. This line will call the script, nothing else:
for example: ./
- Be sure that emails sent to root are forwarded to a valid user