Ssh – Send an email any time an SSH key is used

key-authenticationlogsscpssh

I have about 30 nearly-identical CentOS 6 servers that I need to be able to push out updated config files automatically using an rsa key to log in as root. Usually this will just be rsync, but sometimes might have to run commands on the servers, so it needs ssh too. Since this will be run as a script to update all 30 servers, I don't want to have a passphrase on the key.

I have that part all working fine. I created the rsa key, added it to authorized_keys for root, so I can ssh or rsync to the servers without needing to type a password.

I have authorized_keys set to only accept the key from a single hostname, which should make this setup relatively secure. However, I'm still not totally comfortable with it, so would like to set it up to send an email to our shared tech mailbox every time this key is used.

There's lots of times that I'll be logging into these servers as myself, and su'ing to give myself root. This is fine, and don't want to spam the tech mailbox every time one of us logs in. I only want to get the emails when the SSH key is used.

Here's what I have so far, on server1[through 30].example.com:

cat /root/.ssh/authorized_keys
from="pusher.example.com",environment="SSHKEY=1" ssh-rsa AAAAB3NzaIwAAAxetcetc== root@pusher

tail -n 3 /root/.bash_profile
if [[ "${SSHKEY}" == "1" ]] ; then
echo 'Either we are getting hacked, or somebody used the SSH key on pusher to push something out to ' `hostname` ' at ' `date` | mail -s "WARNING - ROOT SSH KEY USED ON `hostname`!" techs@example.com
fi

This works perfectly for SSH – If I putty in as myself and run su to get root, I don't get the email, but if I log into pusher, and run:

ssh -i /root/.ssh/server1.pri server1.example.com

I get an email. The problem is pushing files. If I run either of:

scp -i /root/.ssh/server1.pri /tmp/file.txt server1.example.com:/tmp/
rsync -e 'ssh -i /root/.ssh/server1.pri' /tmp/test.txt server1.example.com:/tmp/

I still don't get the email.

Is there a way, rather than relying on bash_profile, to set this up to send an email any time the key is used, for anything? (Or alternatively, only if it's used for scp or rsync, and I'll restrict the key to only run those?)

Best Answer

You can misuse /root/.ssh/rc for your purpose (see man sshd) and include a mailx command there.

Related Question