--- title: Set up SSH login email notifications description: How to set up your server to send an email to you when someone logs into your server. We will use SMTP to send mails via our existing email account. level: beginner updated_at: 2022-01-03 slug: ssh-mail-login author_name: Philipp Bohk author_url: https://github.com/Homwer author_image: author_bio: tags: [shell, ssh, linux, sSMTP] netcup_product_url: https://www.netcup.com/en/server/root-server/rs-1000-g9.5-a1-iv language: en available_languages: [de, en] --- # Introduction This tutorial teaches you how to set up your server so it sends you an email when someone starts an SSH session by logging into your server. Please note that this should not serve as your main security protection but rather as a last case failsafe. This can also be useful if you are simply interested in being informed about who is accessing your server. We will use sSMTP so the server works as an email client using an existing email address. Therefore, we don’t need to run an email server by ourselves but can use netcup's email server. # Requirements You will need the following: - A VPS or ROOT server of any kind with root access. All machines from netcup will handle this task with ease. - An email account to send emails from; a netcup webhosting account works great for this [Webhosting Bestprice Classic](https://www.netcup.eu/bestellen/produkt.php?produkt=2899). This tutorial has been tested with the latest Ubuntu (20.10) and Debian (11). # Step 1 - Ordering the server At the time of writing (January 2022), the recommended product for this is a [RS 1000 G9.5](https://www.netcup.eu/bestellen/produkt.php?produkt=2899) or higher. Existing customers can add the product easily and quickly. # Step 2 - Basic configuration of the server Ensure that the server is up to date and upgrade the system: ``` sudo apt update && sudo apt dist-upgrade -y ``` Install the required package ssmtp: ``` sudo apt install ssmtp -y ``` # Step 3 - Configuration of sSMTP daemon In this step we will configure sSMTP to use our email account. Please create a new email address for this purpose. You will need the following data: - Username for the newly created email address - Password for the newly created email address - SMTP server for the newly created email address - SMTP port, this should be 25 by default. Create a configuration file for sSMTP: ``` sudo nano /etc/ssmtp/ssmtp.conf ``` Add the following lines and update the login information with the credentials for your newly created mail account: ``` #/etc/ssmtp/ssmtp.conf root=server@YourDomainFromNetcup.com mailhub= mx2f11.netcup.net:25 rewriteDomain=YourDomainFromNetcup.com AuthUser=YourDomainFromNetcup.com AuthPass=YourPasswordForTheEmailAccount FromLineOverride=YES ``` This will enable sSMTP to send emails from your email account. It is recommended to create a fresh email account for this purpose only! Don't use your daily account! # Step 4 – Create an email template The server is now able to send emails. To send an email whenever someone attempts to login, we must create an email template. We could just send a simple alert, but it is nice to get more information to identify a possible threat. Therefore, we will send an email that contains the username of the user, the IP address, the date and the time of the login attempt. Create a file for that purpose: ``` sudo nano /srv/mailatlogin.sh ``` Copy and paste the following lines into your file: ``` #!/bin/sh date=$(date '+%d.%m.%Y') host=$(hostname) ip=$(hostname -I) { echo To: Recipient@YourDomain.com echo From: SERVER YourDomainFromNetcup.com echo Subject: "SERVER LOGIN! from $PAM_USER on $host IP: $PAM_RHOST $date" echo echo "Login detected on the server $host from IP: $ip User: $PAM_USER If this is not you, act immediately!" } | ssmtp Recipient@YourDomain.com ``` Save and exit the editor. Make the script executable by running the following command: ``` sudo chmod +x /srv/mailatlogin.sh ``` The first line reads the information from your system and stores it into variables for later use. We get the date, hostname and IP address. Then we will add this information to your email. All content between the curly braces is the email. `Echo To` and `Echo From` must be replaced with your own data. `Echo Subject` is the subject of your email. It can be edited if needed. All values starting with `$` are variables. These will automatically be replaced with the corresponding values. The next echo is the content of the email. It can be edited or replaced if needed. Please be aware of the last line! Here you need to replace Recipient@YourDomain.com with your own email address! # Step 5 - Testing Test the script by running the following command: ``` sudo /srv/mailatlogin.sh ``` Now check your email address. You should have received a new email. Please be aware that the USER and the IP address will be empty while testing! These variables will be filled whenever someone attempts to login! # Step 6 - Add the script to your SSHD configuration Open the sshd.config with ``` sudo nano /etc/pam.d/sshd ``` and add the following line at the end: ``` session optional pam_exec.so /srv/mailatlogin.sh ``` Save and close the file and then restart the SSH daemon by running: ``` sudo systemctl restart ssh ``` # Step 7 - Log out and back in Log out of your system by running `exit` and log in again. Check your emails - you should have received a new email. # Step 8 - Errors you may detect - Check syslog for errors: ``` sudo tail -f /var/log/syslog ``` - Check the script for errors - Check the SPAM folder of your inbox - Check the sSMTP config `/etc/ssmtp/ssmtp.conf` Use this command to send a brief test email from the command line: ``` { echo To: Recipient@YourDomain.com echo From: SERVER YourDomainFromNetcup.com echo Subject: "Connection TEST" echo "TEST MAIL" } | ssmtp Recipient@YourDomain.com ``` Replace Recipient@YourDomain.com with your email address. # Conclusion Your server will now send you alert emails when someone is trying to log in. As mentioned before, this will not enhance the security of your server but it will keep you informed that something may be wrong and that you need to act immediately if you do not recognize the IP address or user trying to access the server. Please be aware that this script will react to all SSH sessions started. This includes scp, rsync and so on. # License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicence, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Contributor's Certificate of Origin By making a contribution to this project, I certify that: 1. The contribution was created in whole or in part by me and I have the right to submit it under the license indicated in the file; or 2. The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same license (unless I am permitted to submit under a different license), as indicated in the file; or 3. The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. 4. I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the license(s) involved.