How To Enable SSH Login Alerts on Debian 13
Monitoring SSH access is a critical security practice for any Debian 13 server. Every time someone logs into your system via SSH, you should know about it immediately. SSH login alerts provide real-time notifications whenever authentication occurs, giving administrators instant visibility into who’s accessing their servers and from where. This comprehensive guide walks through multiple methods to configure SSH login notifications on Debian 13, from basic email alerts to advanced integrations with platforms like Telegram and Discord.
Unauthorized SSH access remains one of the most common vectors for server compromise. Attackers constantly scan the internet for vulnerable SSH services, attempting brute-force attacks and credential stuffing. By implementing automated login notifications, system administrators gain a powerful early warning system that detects both legitimate access and potential security breaches the moment they happen.
This tutorial covers three proven methods: the PAM-based approach (most reliable), the .bashrc method (user-specific), and alternative notification channels for modern workflows. Each method has been tested on Debian 13 (trixie) and includes complete configuration steps, troubleshooting guidance, and security best practices.
Why SSH Login Alerts Matter for Server Security
SSH serves as the primary remote access method for Linux servers. Without proper monitoring, unauthorized access can go undetected for days or weeks, giving attackers ample time to compromise data, install backdoors, or pivot to other systems.
Understanding SSH Access Threats
Modern servers face constant SSH attacks. Automated bots scan IP ranges looking for open SSH ports, then launch dictionary attacks using common username and password combinations. Even with strong passwords, compromised credentials from data breaches can give attackers legitimate-looking access to your systems.
Real-time login alerts transform passive logging into active monitoring. Instead of discovering a breach weeks later during a routine audit, administrators receive immediate notifications that trigger investigation protocols. This rapid response capability dramatically reduces the window of opportunity for attackers.
Benefits of Automated Login Notifications
SSH login alerts provide multiple security advantages. First, they create instant awareness of all access events, whether from team members or potential intruders. Second, they establish an audit trail that satisfies compliance requirements for industries like healthcare, finance, and government. Third, they enable rapid detection of compromised credentials before attackers cause significant damage.
Multi-user environments particularly benefit from login notifications. When multiple administrators share server access, tracking who logged in when becomes essential for accountability and troubleshooting. Automated alerts eliminate guesswork and provide concrete evidence of access patterns.
Prerequisites and Requirements
Before configuring SSH login alerts, ensure your Debian 13 system meets the following requirements. You need a functioning Debian 13 (trixie) installation with SSH already installed and configured. The OpenSSH server package typically comes pre-installed, but you can verify with systemctl status ssh
.
Root access or sudo privileges are mandatory for system-wide alert configuration. You’ll modify system files and PAM configurations that require elevated permissions. Basic command-line familiarity helps, particularly with text editors like nano or vi.
For email-based notifications, you need a working mail transfer agent (MTA) such as Postfix or Exim4, or at minimum the mailutils package. An active internet connection is required for installing packages and sending notifications.
Optional components include email accounts for receiving alerts, Telegram bot credentials for mobile notifications, or Discord webhooks for team channels. Before making any changes, create backups of configuration files—a best practice that saves headaches if something goes wrong.
Understanding How SSH Login Alerts Work
SSH login alerts leverage Linux’s authentication infrastructure to trigger notifications. Two primary mechanisms exist: PAM (Pluggable Authentication Module) hooks and shell profile scripts.
The Technical Foundation
PAM provides a flexible authentication framework that sits between applications and the underlying authentication mechanisms. When users authenticate via SSH, PAM modules execute in sequence, performing various checks and actions. By adding a custom PAM module configuration, administrators can trigger scripts at specific authentication stages.
The PAM approach intercepts login events at the system level, before user shells initialize. This early execution ensures alerts fire regardless of shell type, user configuration, or session duration. Even if a connection drops immediately after authentication, the alert still sends.
Shell profile scripts like .bashrc offer an alternative approach. These files execute when interactive shells start, making them ideal for user-specific configurations. However, they only trigger for interactive sessions—SFTP connections and non-interactive commands bypass shell profiles entirely.
Alert Methods Comparison
The PAM method provides the most reliable monitoring because it operates at the authentication layer. It captures all SSH authentication events, works for all users automatically, and cannot be bypassed by individual user configurations. Performance impact is negligible since the script runs asynchronously.
The .bashrc method offers simplicity and doesn’t require PAM modifications. Users can implement it in their own accounts without administrative access. However, it has limitations: it doesn’t capture SFTP sessions, users can modify their own scripts, and it requires configuration for each account separately.
Alternative notification channels like Telegram, Discord, or Slack provide modern, mobile-friendly alert delivery. These platforms offer better notification management, searchable histories, and team-wide visibility compared to email.
Method 1: Enable SSH Alerts Using PAM (Recommended)
The PAM-based approach represents the gold standard for SSH login monitoring on Debian 13. It integrates directly with the authentication system, ensuring reliable alert delivery regardless of shell configuration or connection type.
Why PAM Method is Most Reliable
PAM’s system-level integration provides several critical advantages. The module executes during the authentication phase, before user shells initialize. This early trigger point ensures alerts fire even if sessions terminate prematurely or use non-interactive protocols like SFTP.
Unlike user-configurable files, PAM configurations require root access to modify. Individual users cannot disable or circumvent PAM modules, making this method tamper-resistant. Enterprise environments and production servers benefit from this enterprise-grade security approach.
Step 1: Install Required Email Utilities
Begin by installing the mailutils package, which provides email sending capabilities. Open a terminal and update package lists:
sudo apt update
Install mailutils with all dependencies:
sudo apt install mailutils -y
During installation, Debian presents a configuration wizard. Choose the mail configuration that matches your environment. For most standalone servers, select “Internet Site” to send mail directly. Enter your server’s fully qualified domain name when prompted.
Test mail functionality immediately to verify configuration:
echo "Test email from Debian 13 server" | mail -s "Mail Test" your@email.com
Replace your@email.com
with your actual email address. Check your inbox and spam folder. If the test email arrives, mail configuration is working correctly. If not, troubleshoot your MTA configuration before proceeding.
Step 2: Create the SSH Login Alert Script
Create a dedicated script that handles notification logic. This script receives authentication data from PAM and formats it into a meaningful alert message.
Navigate to the system binary directory and create the script:
sudo nano /usr/local/bin/ssh-login-alert.sh
Enter the following script content:
#!/bin/bash
# SSH Login Alert Script for Debian 13
# Capture login details from PAM variables
IPADDR=${PAM_RHOST}
USERNAME=${PAM_USER}
HOSTNAME=$(hostname)
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
# Email configuration
EMAIL="admin@yourdomain.com"
SUBJECT="SSH Login Alert: ${USERNAME}@${HOSTNAME}"
# Message body
MESSAGE="SSH Login Detected
-----------------
Server: ${HOSTNAME}
User: ${USERNAME}
IP Address: ${IPADDR}
Time: ${TIMESTAMP}
-----------------
This is an automated security alert."
# Send email notification
echo "${MESSAGE}" | mail -s "${SUBJECT}" "${EMAIL}"
exit 0
This script uses PAM environment variables that are automatically populated during authentication. The PAM_RHOST
variable contains the connecting IP address, while PAM_USER
holds the authenticated username. These variables provide reliable data without requiring complex parsing.
Customize the EMAIL
variable with your actual email address. The script formats a clear, informative message that includes all relevant security details: server hostname, authenticated user, source IP, and precise timestamp.
Save the file (Ctrl+O, Enter) and exit nano (Ctrl+X). Make the script executable:
sudo chmod +x /usr/local/bin/ssh-login-alert.sh
Verify permissions are correct:
ls -l /usr/local/bin/ssh-login-alert.sh
The output should show -rwxr-xr-x
permissions with root ownership. These restrictive permissions prevent unauthorized users from modifying the alert script, maintaining security integrity.
Step 3: Configure PAM to Execute the Script
Now integrate the script into SSH’s PAM configuration. Open the SSH PAM configuration file:
sudo nano /etc/pam.d/sshd
Scroll to the session section where session-related PAM modules are configured. Add the following line after existing session entries:
session optional pam_exec.so /usr/local/bin/ssh-login-alert.sh
This line instructs PAM to execute your alert script during the session initialization phase. The optional
keyword is crucial—it tells PAM to continue authentication even if the script fails. Using required
instead would block logins if the notification script encounters errors, potentially locking administrators out of their own systems.
The pam_exec.so
module provides the functionality to execute external programs from within PAM. It passes relevant authentication details through environment variables, which your script captures and uses.
Save the file and exit. PAM configurations take effect immediately without requiring service restarts. This design ensures security updates apply instantly without disrupting active sessions.
Step 4: Test the PAM Configuration
Testing validates that alerts trigger correctly. Open a new terminal window or use a different machine to SSH into your server:
ssh username@your-server-ip
Authenticate normally. Within seconds, check the configured email address. You should receive an alert email containing the login details: server hostname, your username, source IP address, and login timestamp.
If the email doesn’t arrive, begin troubleshooting systematically. First, verify the mail system works by sending another test email manually. Second, check that the script has execute permissions. Third, review the PAM configuration syntax for typos. Fourth, examine /var/log/auth.log
for any error messages related to PAM or script execution.
Check mail logs for delivery issues:
sudo tail -f /var/log/mail.log
This command displays mail system activity in real-time, revealing any delivery failures or configuration problems.
Method 2: Enable SSH Alerts Using .bashrc Method
The .bashrc approach offers a simpler alternative that doesn’t modify system authentication infrastructure. This method places notification commands directly in user shell initialization files.
When to Use the .bashrc Method
Choose .bashrc-based alerts when PAM modifications aren’t suitable for your environment. Shared hosting platforms often restrict PAM configuration, making shell-based alerts the only option. Individual users without root access can implement their own notifications this way.
User-specific monitoring scenarios also benefit from this approach. If you need different notification destinations for different users, .bashrc provides granular control. However, remember that this method only captures interactive shell sessions—SFTP and non-interactive SSH commands won’t trigger alerts.
Step 1: Configure Root User SSH Alerts
Start with root user monitoring since root access represents the highest security priority. Navigate to root’s home directory:
cd /root
Open root’s .bashrc file:
sudo nano /root/.bashrc
Scroll to the end of the file and add this notification code:
# SSH Login Alert
if [ -n "$SSH_CONNECTION" ]; then
IPADDR=$(echo $SSH_CONNECTION | awk '{print $1}')
HOSTNAME=$(hostname)
USERNAME=$(whoami)
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
echo "SSH Login Alert: Root access on ${HOSTNAME} from ${IPADDR} at ${TIMESTAMP}" | \
mail -s "Root SSH Login: ${HOSTNAME}" admin@yourdomain.com
fi
This code checks if SSH_CONNECTION
exists, confirming an SSH session rather than local console access. The SSH_CONNECTION
variable contains four space-separated values: client IP, client port, server IP, and server port. Using awk
extracts just the client IP address.
Save the file and test immediately. Log out of the current root session and log back in. The alert should arrive within moments.
Step 2: Configure Normal User SSH Alerts
Repeat the process for regular user accounts. Switch to a standard user and edit their .bashrc:
su - username
nano ~/.bashrc
Add the same notification code, customizing the email subject to distinguish user logins from root logins:
# SSH Login Alert
if [ -n "$SSH_CONNECTION" ]; then
IPADDR=$(echo $SSH_CONNECTION | awk '{print $1}')
HOSTNAME=$(hostname)
USERNAME=$(whoami)
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
echo "SSH Login Alert: User ${USERNAME} on ${HOSTNAME} from ${IPADDR} at ${TIMESTAMP}" | \
mail -s "User SSH Login: ${USERNAME}@${HOSTNAME}" admin@yourdomain.com
fi
User-level monitoring matters in multi-user environments where multiple administrators access the same server. Tracking individual user activity helps with accountability, troubleshooting, and security auditing.
Step 3: Understanding .bashrc Execution
The .bashrc file executes when Bash starts as an interactive, non-login shell. SSH sessions typically trigger .bashrc execution, making it suitable for login monitoring. However, the execution happens after authentication completes and shell initialization begins.
Debian and Ubuntu systems use .bashrc by default, while Red Hat-based distributions often use .bash_profile instead. Debian 13 follows the .bashrc convention, ensuring compatibility with this tutorial.
Non-interactive shells don’t execute .bashrc. When SSH sessions run commands without spawning an interactive shell (like ssh user@host ls /tmp
), .bashrc doesn’t execute and alerts don’t trigger. This limitation represents a significant gap compared to PAM-based monitoring.
Limitations of .bashrc Method
Several constraints affect .bashrc-based monitoring. SFTP connections bypass shell initialization entirely since they don’t require interactive shells. Users who modify their own .bashrc files can disable notifications, either intentionally or accidentally. Failed authentication attempts never reach shell initialization, remaining invisible to this monitoring method.
Multi-user systems require configuration for each user account individually. New users created after initial setup won’t have monitoring until administrators manually add notification code to their .bashrc files. This administrative overhead makes PAM-based monitoring more scalable for larger environments.
Method 3: Alternative Notification Channels
Modern infrastructure teams often prefer centralized notification platforms over traditional email. Telegram, Discord, and Slack provide real-time mobile alerts with better organization and searchability.
Telegram Bot Notifications
Telegram offers excellent mobile push notifications and works worldwide without SMS fees. Creating a Telegram bot takes minutes and provides instant mobile alerts.
First, create a bot using Telegram’s BotFather. Open Telegram and search for @BotFather. Send /newbot
and follow the prompts to name your bot. BotFather provides a bot token—save this securely.
Next, get your chat ID. Message your new bot, then visit this URL in a browser:
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
Replace <YOUR_BOT_TOKEN>
with your actual token. The response contains your chat ID in the JSON output.
Modify the alert script to use Telegram:
#!/bin/bash
BOT_TOKEN="your_bot_token_here"
CHAT_ID="your_chat_id_here"
IPADDR=${PAM_RHOST}
USERNAME=${PAM_USER}
HOSTNAME=$(hostname)
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
MESSAGE=" SSH Login Alert%0A%0AServer: ${HOSTNAME}%0AUser: ${USERNAME}%0AIP: ${IPADDR}%0ATime: ${TIMESTAMP}"
curl -s -X POST "https://api.telegram.org/bot${BOT_TOKEN}/sendMessage" \
-d chat_id="${CHAT_ID}" \
-d text="${MESSAGE}" \
-d parse_mode="HTML" > /dev/null 2>&1
exit 0
The %0A
sequences create line breaks in Telegram messages. Install curl if not already present: sudo apt install curl
. Test by executing the script manually with environment variables set.
Discord Webhook Integration
Discord webhooks provide team-based notifications with organized channels and permanent message history. Create a webhook in Discord server settings under Integrations. Copy the webhook URL provided.
Modify the alert script for Discord:
#!/bin/bash
WEBHOOK_URL="your_discord_webhook_url_here"
IPADDR=${PAM_RHOST}
USERNAME=${PAM_USER}
HOSTNAME=$(hostname)
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
JSON_PAYLOAD=$(cat <<EOF
{
"content": " **SSH Login Alert**",
"embeds": [{
"title": "Server Access Detected",
"color": 15258703,
"fields": [
{"name": "Server", "value": "${HOSTNAME}", "inline": true},
{"name": "User", "value": "${USERNAME}", "inline": true},
{"name": "IP Address", "value": "${IPADDR}", "inline": false},
{"name": "Timestamp", "value": "${TIMESTAMP}", "inline": false}
]
}]
}
EOF
)
curl -H "Content-Type: application/json" \
-d "${JSON_PAYLOAD}" \
"${WEBHOOK_URL}" > /dev/null 2>&1
exit 0
Discord’s embed format creates visually appealing notifications with structured fields. The color value (15258703) produces an orange accent, distinguishing security alerts from other messages.
Slack Integration
Slack incoming webhooks work similarly to Discord. In Slack workspace settings, add an incoming webhook integration and select the target channel. Slack provides a webhook URL that accepts JSON payloads.
Slack makes sense for teams already using it for operations. The permanent searchable history helps during security investigations when reviewing login patterns over time.
SMS Notifications (Advanced)
Critical production servers might warrant SMS notifications via services like Twilio. SMS ensures alerts arrive even without internet connectivity on mobile devices. However, SMS services incur per-message costs, making them best suited for high-priority alerts only. Configure SMS for root logins or connections from unexpected IP ranges while using email or messaging apps for routine notifications.
Configuring Email Alerts (Detailed Setup)
Email remains the most universal notification method, working across all platforms without requiring third-party accounts or API access.
Installing and Configuring Mailutils
Install the mailutils package along with a mail transfer agent:
sudo apt update
sudo apt install mailutils postfix -y
The Postfix installation wizard presents configuration options. Most servers should select “Internet Site” for direct mail delivery. Enter your server’s fully qualified domain name (FQDN) when prompted—this becomes the sending domain for alert emails.
For “Internet with smarthost” configuration, specify a relay server like your ISP’s mail server. This option helps if your server’s IP has poor email reputation.
Setting Up Gmail SMTP Relay (Optional)
Many administrators prefer routing alert emails through Gmail for better deliverability. Configure Postfix to use Gmail as an SMTP relay.
Install the SASL authentication library:
sudo apt install libsasl2-modules
Edit Postfix main configuration:
sudo nano /etc/postfix/main.cf
Add these lines at the end:
relayhost = [smtp.gmail.com]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = encrypt
Create the password file:
sudo nano /etc/postfix/sasl_passwd
Add your Gmail credentials:
[smtp.gmail.com]:587 youremail@gmail.com:your-app-password
Use Gmail app-specific passwords rather than your main password for security. Generate app passwords in Gmail security settings.
Hash the password file and set restrictive permissions:
sudo postmap /etc/postfix/sasl_passwd
sudo chmod 600 /etc/postfix/sasl_passwd*
Restart Postfix:
sudo systemctl restart postfix
Test Gmail relay functionality with a test message.
Email Formatting Best Practices
Craft clear, actionable subject lines that facilitate email filtering. Include the server hostname and event type: “SSH Login Alert: web-server-01” works better than generic “Login Notification.”
Essential information belongs in the message body: server name, authenticated username, source IP address, and exact timestamp. Additional context like SSH protocol version or public key fingerprints enhances security analysis capabilities. Keep formatting clean and consistent for easy scanning when multiple alerts arrive.
Testing and Verification
Thorough testing ensures alerts function correctly before relying on them for security monitoring.
Testing PAM-Based Alerts
Test from multiple source IP addresses to verify IP detection works correctly. Use a different computer, mobile device, or cloud instance to generate SSH connections. Each login should trigger an alert containing the correct source IP.
Test both root and regular user accounts to confirm system-wide coverage. If only root generates alerts, review the PAM configuration and script permissions. All users should trigger notifications equally.
Email delivery should occur within seconds of authentication. Delays longer than 30 seconds suggest mail system problems. Check mail logs and test direct mail delivery outside the alert system.
Testing .bashrc Alerts
Test normal SSH sessions with interactive shells first. These should trigger alerts reliably. Then test SFTP connections—these won’t generate alerts, confirming the known limitation.
Try both key-based and password authentication to ensure the method doesn’t affect alert delivery. The authentication type shouldn’t impact notification functionality since alerts trigger post-authentication.
Log Verification
Review /var/log/auth.log
to confirm SSH connections appear in system logs:
sudo tail -50 /var/log/auth.log | grep sshd
Verify that successful authentications show in system logs before expecting alert scripts to work. If SSH connections don’t log properly, address that fundamental issue first.
Check for script execution errors in system logs:
sudo journalctl -xe | grep ssh-login-alert
Error messages here reveal script problems or permission issues.
Troubleshooting Common Issues
Even well-configured systems sometimes encounter problems. Systematic troubleshooting isolates issues quickly.
Emails Not Being Received
Test the mail system independently of the alert script:
echo "Direct mail test" | mail -s "Test Subject" your@email.com
If this test fails, the problem lies with mail configuration rather than the alert system. Reconfigure Postfix or Exim4 before proceeding.
Check spam and junk folders thoroughly. Mail servers sometimes flag automated messages as spam, especially from new or unrecognized sending domains. Whitelist your server’s domain in email settings.
Review mail logs for delivery attempts and failures:
sudo tail -100 /var/log/mail.log
Look for bounce messages, connection failures, or authentication errors. These logs pinpoint exactly where delivery fails.
Verify the alert script has execute permissions:
ls -l /usr/local/bin/ssh-login-alert.sh
The file must have execute permission (the ‘x’ in permissions). If missing, add it: sudo chmod +x /usr/local/bin/ssh-login-alert.sh
.
Check PAM configuration syntax carefully:
sudo cat /etc/pam.d/sshd | grep pam_exec
Typos in the path or module name prevent script execution. The line should read exactly: session optional pam_exec.so /usr/local/bin/ssh-login-alert.sh
.
Alerts Not Triggering
Verify PAM configuration placement within /etc/pam.d/sshd
. The session line must appear in the session section, not in auth or account sections. PAM processes modules in order, so placement matters.
Double-check the script path is absolute and correct. Relative paths don’t work in PAM configurations. Use the full path: /usr/local/bin/ssh-login-alert.sh
.
Confirm PAM environment variables are accessible within the script. Test manually:
sudo PAM_USER=testuser PAM_RHOST=192.168.1.100 /usr/local/bin/ssh-login-alert.sh
This command simulates PAM execution with environment variables set. If the test email arrives, the script works correctly and the issue lies in PAM configuration.
Multiple Alerts Per Login
Receiving duplicate alerts per login indicates multiple trigger points. Check for duplicate lines in /etc/pam.d/sshd
. Multiple pam_exec.so
entries cause multiple script executions.
Review .bashrc
files for duplicate notification blocks. If both PAM and .bashrc contain alert code, each login generates two notifications. Choose one method and remove the other.
Examine PAM configuration for conflicts with other modules. Some PAM modules trigger multiple times during authentication. If duplicates persist, adjust the PAM configuration line to use different trigger points.
Script Permission Errors
Scripts must have appropriate execute permissions. Set permissions correctly:
sudo chmod 755 /usr/local/bin/ssh-login-alert.sh
Verify ownership is root:
sudo chown root:root /usr/local/bin/ssh-login-alert.sh
Non-root ownership might cause execution problems in some configurations.
Check SELinux or AppArmor policies if they’re active on your Debian 13 system. Security modules sometimes restrict PAM script execution. Review audit logs for denial messages and adjust policies accordingly.
Security Best Practices and Considerations
Alert systems themselves require security hardening to prevent tampering or circumvention.
Protecting the Alert System
Secure notification scripts from unauthorized modification. Use restrictive permissions (700 or 755) that prevent regular users from editing alert scripts:
sudo chmod 700 /usr/local/bin/ssh-login-alert.sh
sudo chown root:root /usr/local/bin/ssh-login-alert.sh
Store sensitive credentials like API keys, webhook URLs, and passwords securely. Never hard-code production credentials in scripts stored in world-readable locations. Consider environment variables stored in protected files or dedicated credential vaults.
Use secure file permissions on credential files:
sudo chmod 600 /etc/postfix/sasl_passwd
Only root should read files containing passwords or API tokens.
Complementary Security Measures
SSH login alerts form one layer of defense-in-depth. Combine notifications with proactive security controls for comprehensive protection.
Implement Fail2ban to automatically block IP addresses after repeated failed login attempts. Fail2ban monitors authentication logs and creates temporary firewall rules blocking hostile IPs. Install and configure it alongside alert systems.
Use SSH key authentication instead of password authentication. Key-based auth eliminates brute-force password attacks entirely. Generate strong SSH keys and disable password authentication in sshd_config
.
Disable root SSH login after establishing sudo access for regular users. Edit /etc/ssh/sshd_config
and set PermitRootLogin no
. This prevents direct root compromise even if credentials leak.
Change the default SSH port from 22 to a non-standard port. While not foolproof, this reduces automated attack traffic significantly. Update firewall rules accordingly.
Implement two-factor authentication using Google Authenticator PAM module. 2FA adds another security layer, requiring possession of a physical device in addition to credentials.
Conduct regular security audits and log reviews. Automated alerts catch events as they happen, but periodic log analysis reveals patterns and trends that inform security posture improvements.
Monitoring Failed Login Attempts
Successful login alerts represent only half the picture. Failed authentication attempts often indicate active attacks.
Use tools like Logwatch for comprehensive SSH monitoring. Logwatch analyzes log files and generates daily reports summarizing authentication activity, including failed attempts.
Configure alerts specifically for failed authentication attempts:
sudo apt install fail2ban
Fail2ban can send email notifications when it bans IP addresses. Configure notification recipients in /etc/fail2ban/jail.local
.
Monitor /var/log/auth.log
for suspicious patterns like repeated failures from single IPs or authentication attempts for non-existent users. These patterns reveal reconnaissance or active attack campaigns.
Advanced Configurations
Production environments often require sophisticated monitoring capabilities beyond basic alerts.
Multi-User Environment Setup
Deploy alerts system-wide using PAM for consistent coverage across all user accounts. The PAM approach automatically protects new accounts without additional configuration.
Configure different notification channels for different users in multi-tenant environments. Modify the alert script to check username and route notifications accordingly:
if [ "$PAM_USER" == "admin" ]; then
EMAIL="admin@example.com"
elif [ "$PAM_USER" == "developer" ]; then
EMAIL="dev-team@example.com"
fi
Centralized logging helps manage large deployments. Forward SSH login data to log aggregation platforms like ELK Stack (Elasticsearch, Logstash, Kibana) or Splunk for analysis across multiple servers.
Alert Filtering and Priority
Not all logins warrant immediate attention. Filter alerts based on source IP to reduce noise. Whitelist trusted IP ranges like office networks or VPN endpoints:
# In alert script
TRUSTED_IPS=("192.168.1.0/24" "10.0.0.0/8")
# Check if IPADDR matches trusted ranges
# Only send alert if not from trusted network
Priority notifications distinguish root access from regular user logins. Send root login alerts to SMS or high-priority notification channels while routing regular user alerts to email or team chat.
Implement time-based alert suppression for scheduled maintenance windows. Before maintenance, temporarily disable alerts to prevent notification floods during expected access patterns.
Integration with SIEM Systems
Enterprise environments benefit from forwarding SSH login data to security information and event management (SIEM) platforms. SIEM systems correlate SSH access with other security events, revealing complex attack patterns.
Configure syslog forwarding to send authentication logs to SIEM collectors. Most SIEM platforms ingest syslog data natively. Set up correlation rules that trigger investigations when unusual patterns emerge.
Implement automated response workflows that integrate alerts with orchestration platforms. For example, trigger automated account locks when suspicious login patterns occur, or initiate incident response playbooks automatically.
Congratulations! You have successfully setup SSH Login Alerts. Thanks for using this tutorial to configure SSH Login Alerts on Debian 13 “Trixie” system. For additional help or useful information, we recommend you check the official Debian website.