Receive notification by email when someone accesses as root by SSH

Those of us who administer servers must keep the strictest possible control over everything that happens on the server, one of the things that we often need to know is when a user connects via SSH (root included), for this with a package and a line would reach our email notifications.

Can you imagine that every time someone connects via SSH with root they get an email that says?

In other words, they would receive an email that would say something like this:

[miserver] Alert: Root Terminal access on: 2014/01/21 (200.55.51.151)

That is:

[$ NOMBRE_VPS] Alert: Access to Root Terminal on: $ DATE ($ IP_DE_WHO_S_CONNECT)

To achieve this they must first install a package called mailx.

Assuming your server uses Debian or some distro based on it (I recommend only Debian, not Ubuntu or similar for servers) it would be:

apt-get install mailx

Note: The previous command is executed as root directly on the server, as it is a VPS, sudo should not be used unless it is strictly necessary.

Then we must put the following line in the root .bashrc:

echo 'ALERTA - Acceso a Terminal de Root en:' `hostname` 'el:' `date +'%Y/%m/%d'` `who | grep -v localhost` | mail -s "[ `hostname` ] Alerta: Acceso a Terminal de Root el: `date +'%Y/%m/%d'` `who | grep -v localhost | awk {'print $5'}`" mi@email.com

To edit /root/.bashrc use some editor in terminal like nano:

nano /root/.bashrc

Remember that you must specify your email at the end of the line, simply change my@email.com to the email you want the notifications to reach

After putting (anywhere in the file) the line that I put before, we save the file with Ctrl + O (Or bear) and we left it with Ctrl + X

Ready, every time someone enters the root terminal the .bashrc file will be loaded, which is something that is always done by default, and when the file is loaded, the line that sends the email will be executed, leaving something in our inbox as:

email-notification-ssh

The explanation of the line is something really simple:

  1. Through mailx I send the mail, with the parameter -s «_____» I specify the subject, and I pass it with echo «____» and a pipe the content of the body.
  2. `hostname` with this I get the hostname or hostname, that is, the name of the VPS.
  3. `date + '% Y /% m /% d'` the date command shows me the system date, the rest of the letters simply indicate how I want the date to be displayed.
  4. who | grep -v localhost` If you run who on your computer it will show you the active users, with a grep -v localhost I make sure that it only shows those that have connected from a different location to the server itself, that is, basically SSH
  5. `who | grep -v localhost | awk {'print $ 5'} `What differentiates this line from the previous one is the awk, through the awk and the printing of the 5th column is that I get the IP from where they connected to SSH

Anyway, the line is somewhat long and may seem complex to understand, however there are many strange characters but everything is quite simple 🙂

As always, I hope you have found it of interest.

regards


Leave a Comment

Your email address will not be published. Required fields are marked with *

*

*

  1. Responsible for the data: Miguel Ángel Gatón
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.

  1.   manuelperez said

    A question, with which mail server is it sent? Do you have to configure a shipping account?

    1.    KZKG ^ Gaara said

      You must have the mailx package installed 😉
      Once this is done, it is sent without the need to configure anything else on the server.

      1.    manuelperez said

        I will try it, but I think my email will not accept receiving email from an unauthenticated source ...

        1.    yomismo said

          I use exim4 with a 'gmail' account to send emails and it works fine
          - Except for the FROM TO and REPLY TO headers, which gmail puts what it wants but they arrive well -.
          To configure gmail with exim4 use this info:
          http://dajul.com/2009/06/08/configurar-exim4-con-gmail-o-google-apps/

          1.    KZKG ^ Gaara said

            Interesting, thank you very much 🙂

      2.    Israel said

        Friend @ KZKG ^ Gaara I have installed the package and I have made the manual step by step, the only thing that when I send it I have the local mail, I never got out, can you help me with that ?? …… well I really need have this theme configured on my servers, salu2s.

        1.    KZKG ^ Gaara said

          By your IP I assume that you are from my country 😉
          The "problem" with our networks rarely have real IPs as such, that is, we are subnetted under a ministry proxy network, or something like that. In other words, possibly the problem is that the web server alone cannot get an email from the network or something like that, maybe you need this: https://blog.desdelinux.net/enviar-emails-por-consola-con-sendmail/

  2.   truko22 said

    interesting and if it is placed in «/ etc / profile» will it give the warning when any user connects?

    1.    KZKG ^ Gaara said

      It would be necessary to try, it had not occurred to me 😀

  3.   Nebuchadnezzar said

    Call me paranoid, but put a script that a stranger suggests me in an important part of my system where I keep account passwords, data such as birth certificates, personal documents and work documents (thus exposing my clients as well) etc etc, and that implies also exposing my email account (!!!)… well, it's something dangerous, I think.

    1.    yomismo said

      The danger of the presented script is inversely proportional to the understanding of it.

      And for paranoia, stop installing NON-FREE repositories, as it is possible that someone enters a malicious code that steals your shopping cart.

    2.    KZKG ^ Gaara said

      I explained what each part of the command line does, however if you think I am deceiving someone, the script or commands are right there in the post, it does not have any hidden or secret code, you are welcome to review the commands as thoroughly as you want that runs, if you find something suspicious please comment it right here 😉

  4.   browsons said

    Is appreciated.

  5.   thisnameisfalse said

    Very interesting.

    Perhaps the ~ / .bashrc or / etc / profile files are not the most suitable in the event that we access by SSH with a normal user and execute a specific command as root. Or if we export the X11 from our remote VPS, each time we open an xterm we would have a new email.

    For the mailx hack, I think we should use the files ~ / .ssh / rc (individual for each user) or / etc / ssh / sshrc

    PostData: _NEVER_ access by SSH as root user. _NEVER_ access by SSH using password. _ALWAYS_ use private keys.

    1.    truko22 said

      interesting → ~ / .ssh / rc I'll find more information about it thanks 😀

  6.   chinoloco said

    Hello, very good tutor!
    Could you make one to enter via ssh from any ip, outside the local network?
    thank you!

  7.   vidagnu said

    This script works if the mail server we send to does not verify that the source mail comes from an authentic server, in this case it would be from the root @ localhost source, most servers will take it as spam.

    What I do is configure sendmail as an MTA, and then use the mail that comes in all distros to send emails.

    http://vidagnu.blogspot.com/2009/02/configurar-sendmail-como-cliente-de.html

  8.   Algave said

    Thanks for the tip I'll have it in to test it:]

  9.   kuk said

    very useful thanks

  10.   Israel said

    Thanks a million for the advice friend @ KZKG ^ Gaara, I'm going to take a look at sendmail, I hope to solve, salu2s.

  11.   joskar said

    Great! Thanks for the input!

  12.   Juan C said

    And what happens, if for example the script is sending too many emails, for example someone enters the root terminal at 8:00 am and sent about 40 emails, then someone entered at another time and more than 23 emails were sent and then someone comes in at another time and more than 150 emails were sent, what could it be?