Email yourself when you log in…

Posted by: Robert  :  Category: Administration

Ok for the past couple of days, we’ve been trying to help harden your server a little bit to prevent break ins… But if there is one, you want to know as quickly as possible! So setup your login to email you whenever you login. But, you say, wouldn’t they just disable that when they login? They could if they think to… but that first email should have already gone out. And by all means PLEASE make sure it goes to an off server email address. And you do use different passwords for each account right?? I thought so.

Login to your server. You should be in your home directory, if not go there with ‘cd ~’
vi (or pico, vim, etc.) .bash_profile

At the end add this:

# User specific environment and startup programs

# Email admin when user logs in as root
rootalert() {
  echo ‘ALERT – Root Shell Login’
  echo
  echo ‘Server: ‘`hostname`
  echo ‘Time: ‘`date`
  echo ‘User: ‘`who | awk ‘{ print $1 }’`
  echo ‘TTY: ‘`who | awk ‘{ print $2 }’`
  echo ‘Source: ‘`who | awk ‘{ print $5 }’`
  echo
  echo
  echo ‘This email is an alert automatically created by your server telling you that someone, even if it is you, logged into SSH as the root user.  If you or someone you know and trust logged in as root, disregard this email.  If you or someone you know and trust did not login to the server as root, then you may have a hack attempt in progress on your server.’
}
rootalert | mail -s “Alert: `who | awk ‘{ print $1 }’` Login [`hostname`]” (your OFFSITE email address)

By the way those wierd looking single quotes are the one on the key to the left of the 1 key on the top row of the keyboard. They tell the shell to execute the command between taking their output for the line it’s on. In this case, printing out pieces of login information. So go ahead and save and close the file.  Before logging out  type ‘sh .bash_profile’   and check that it execute cleanly, and emails you like it should.

So now if someone logs into your account, you will get an email. If it happens when you weren’t expecting it (as when you didn’t login yourself), you will know about it… Plus you’ll have the ip address they were on when they did… well, you’ll have the ip address of the last machine before they reached you as they will often go from one machine to the next. But it’s more than you had. And if you didn’t know, who knows how long they could hide out there and what damage they could cause.

About: Robert:
Robert Porter holds MCSE, A+, Net+, Security+, and multiple CIW certifications. He has been in the hosting industry for more than a decade and is founder of Lagniappe Internet L.L.C., a privately owned, completely debt free, hosting company based out of New Orleans. Robert's background includes 25+ years in programming, databases, networking and systems administration.

Leave a Reply