How to receive emails when logging in via SSH
When using a server, it is important to understand what is happening on them at the moment: who is accessing via SSH and when. This is especially true for security: if an attacker guesses a password and logs in as root, he will have unlimited rights — the consequences are obvious.
A good practice is to disable direct root login via SSH and work through a regular account with sudo. When you need superuser access, log in as a regular user and switch to root via su. And in order not to miss suspicious logins, you can set up simple email notifications — the letter will be sent to the specified address and contain the IP of the last login.
If you see an unknown IP, it is easy to block it in the firewall.
How to quickly block an IP with SSH access
iptables:
sudo iptables -A INPUT -s <IP_Address> -p tcp --dport ssh -j DROP
firewalld:
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="<IP_Address>" port protocol="tcp" port="22" reject'
sudo firewall-cmd --reload
UFW:
sudo ufw deny from <IP_Address> to any port 22
sudo ufw reload
Setting up email notifications for login via SSH
Here you will need root rights, minimal skills in nano or vi and an installed mail client mailx (aka mailutils on Debian-like systems) to send letters.
Install mailx on your system using one of the commands:
sudo apt install mailutils # Debian/Ubuntu/Mint
sudo yum install mailx # RHEL/CentOS/Fedora/Rocky/AlmaLinux
sudo emerge -a sys-apps/mailx # Gentoo
sudo apk add mailx # Alpine
sudo pacman -S mailx # Arch
sudo zypper install mailx # openSUSE
sudo pkg install mailx # FreeBSD
Letters when logging in as root
Log in as root and go to his home directory:
cd /root
Open the .bashrc file in your favorite editor. Please note that this is a hidden file — it can be seen with the ls -la command.
vi .bashrc
or
nano .bashrc
At the end of the file, add a line replacing ServerName with your server name and your@yourdomain.com with your email:
echo 'ALERT - Root Shell Access (ServerName) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d'(' -f2 | cut -d')' -f1`" your@yourdomain.com
Save the file, log out of the session and log in again via SSH. Each time root logs in, an email will be sent. Example notification:
ALERT — Root Shell Access (Database Replica) on: Thu Nov 28 16:59:40 IST 2023 tecmint pts/0 2023-11-28 16:59 (172.16.25.125)
Emails when a regular user logs in
Log in as the desired user (in the example — tecmint) and go to his home directory:
cd /home/tecmint
Open .bashrc and add the same line (substitute your server name and email):
vi .bashrc
or
nano .bashrc
echo ‘ALERT — Root Shell Access (ServerName) on:’ `date` `who` | mail -s «Alert: Root Access from `who | cut -d'(‘ -f2 | cut -d’)’ -f1`» your@yourdomain.com
Save, log out and log in again. Each time this user logs in, .bashrc will be executed and send an email with login details. You can similarly configure notifications for any account: edit the /home/username/.bashrc file and add the specified line.
Such a simple mechanism helps to quickly notice unexpected logins and quickly block unwanted IPs at the firewall level.
CONTENT:
Similar
Похожее
Все новости
Adaxa Suite: подробный обзор ERP-системы корпоративного класса
Adaxa Suite — комплексная ERP-платформа для компаний, которым уже тесно в рамках простых учётных систем, но которые при этом не готовы идти в сторону дорогих корпоративных решений уровня SAP или Oracle. Изначально продукт создавался для среднего бизнеса, которому нужна большой набор функций, сквозная автоматизация процессов и надёжная архитектура без чрезмерной стоимости владения. Архитектура и техническая […]
Как заказать дополнительные IP-адреса на UFO.Hosting: пошаговая инструкция
По мере роста проекта одного IP-адреса может стать недостаточно. Это типичная ситуация для компаний, которые масштабируют инфраструктуру, запускают новые сервисы или разделяют внутренние процессы. В UFO.Hosting подключение дополнительных IP-адресов выполняется через биллинговую панель и занимает всего несколько минут. Важно: возможность для заказа дополнительных IP-адресов доступна для тарифов VPS начиная с Haedus. Зачем нужны дополнительные IP-адреса […]