Friday, 8 October 2010

Email me when someone logs in remotely via ssh?

I like to be able to ssh into my home Ubuntu server. I've got the server locked up pretty tight (I hope) and have Fail2Ban installed to lock out repeated (failed) ssh attempts.

However if anyone does log in (including me) I'd like to know about it asap, just in case someone does find a way in. My aim is to receive an email as soon as anyone logs in via ssh (since I'm the only one who ever logs in my server there shouldn't bee too many emails).This is easily done with the log-monitoring tool Tenshi.

First install Tenshi with sudo apt-get install tenshi

Note, there is a conf file provided with Tenshi for ssh, but it doesn't work with the format of log lines produced in Ubuntu (at least for 10.04 Lucid Lynx). However it's easy to write ones that do match. All you need are the following two lines in your tenshi.conf (ignore the wrapping, this should be just two lines):

  • set queue critical tenshi root@localhost [now] tenshi CRITICAL report
  • critical ^sshd: pam_unix\(sshd:session\): session opened for user (?:.+)

Note, in the "set queue" line, ensure the from-address is a fully qualified name (tenshi@abc.com) or, as I did, just a username (tenshi). I found from-addresses in the form tenshi@localhost didn't work with my Postfix install (although a to-address of root@localhost is fine).

The second conf-line (above) watches for a log-line that indicates someone has logged in, and if found adds it to Tenshi's critical queue. The first conf-line specifies that additions to the critical queue should be sent immediately ([now]) to the root@localhost address. In my set-up this address is then forward by Postfix to my personal gmail account (as explained in an earlier post).

No comments: