Bart Simons

twilio

A 1 post collection


Send an SMS notification upon successful SSH authentication with Twilio

 •  Filed under ssh, sms, authentication, notification, twilio

Are your always curious about who logs into your server using SSH? Me too! Sometimes I am just a little paranoid and then I come up with these (crazy) ideas: sending an SMS when somebody successfully logs in over SSH. Why? Well: why not, right?

So, what do we need?

  • A server with an SSH daemon (duh...)
  • A Twilio account

So first of all, let me explain what Twilio is: it's an awesome company that makes placing and receiving calls, sending and receiving SMS and MMS, etcetera super simple. It operates over an API so that developers can create, integrate and automate telecommunication solutions into their applications.

Before continuing, make sure you have an account and make sure you write down your account SID and authentication token, both can be found on the Twilio console page.

Now, we need to prepare our server. Once any user successfully authenticates over SSH, we want to execute a script before any shell process gets spawned. This is how I did it:

First I created a script in the /opt directory called sshauthsms.sh with the following contents in it:

#!/bin/bash

curl -s -X POST 'https://api.twilio.com/2010-04-01/Accounts/YOURACCOUNTSIDGOESHERE/Messages.json' --data-urlencode 'To=+12345678901' --data-urlencode 'From=+15017250604' --data-urlencode 'Body=Somebody just succesfully SSHed into your server!' -u YOURACCOUNTSIDGOESHERE:YOURAUTHTOKENGOESHERE > /dev/null  

Make sure to replace the account SID and authentication token placeholders by the values stated in your Twilio console and replace the To and From phone numbers to your phone numbers. Also, don't forget to make the script executable:

chmod +x /opt/sshauthsms.sh  

There's only one more thing left to do: modifying the SSH daemon configuration file. For me (I use Ubuntu) it was located at /opt/ssh/sshd_config.

Just add the following line to the bottom of this file:

ForceCommand /opt/sshauthsms.sh; /bin/bash  

And restart your SSH server daemon with:

service sshd restart  

Try it out! For me it worked brilliantly:

It works!

Have a wonderful day! 🎉