FedoraRHEL Based

How To Enable SSH Login Alerts on Fedora 42

Enable SSH Login Alerts on Fedora 42

Monitoring SSH access to your Fedora 42 server is essential for maintaining robust security and detecting unauthorized login attempts. SSH login alerts provide real-time notifications whenever someone accesses your system, helping you identify suspicious activity before it escalates into a security breach. This comprehensive guide walks you through multiple methods to configure SSH login notifications on Fedora 42, from simple email alerts to advanced PAM-based monitoring and instant messaging integrations.

Whether you manage a production server, development environment, or multi-user system, implementing SSH login alerts enhances your server security posture significantly. You’ll learn how to set up email notifications, configure PAM modules for reliable alerting, integrate Telegram bots for instant mobile notifications, and troubleshoot common issues. By the end of this tutorial, you’ll have a fully functional SSH monitoring system tailored to your specific requirements.

Prerequisites

Before configuring SSH login alerts on your Fedora 42 server, ensure you have the following requirements in place:

  • Root or sudo privileges on your Fedora 42 system
  • OpenSSH server installed and running properly
  • Basic command-line interface knowledge
  • Familiarity with text editors like nano or vi
  • Mail transfer agent configured (for email notifications)
  • Active internet connection for sending notifications

Verify that SSH is already installed on your Fedora 42 system by running systemctl status sshd. If SSH isn’t installed, you can install it using sudo dnf install openssh-server. Additionally, you’ll need either a working email configuration or a Telegram account depending on which notification method you choose to implement.

Understanding SSH Login Alerts

What Are SSH Login Alerts

SSH login alerts are automated notifications triggered whenever a user successfully authenticates to your server via SSH protocol. These alerts provide critical information about login events, including the username, source IP address, timestamp, and hostname. Real-time monitoring through SSH alerts helps system administrators detect unauthorized access attempts, track user activity, and maintain comprehensive audit logs for compliance requirements.

The notification system works by hooking into the SSH authentication process or user session initialization. When someone logs in, a script executes automatically, collecting connection details and sending them through your chosen notification channel. This proactive approach allows you to respond immediately to suspicious login patterns or unauthorized access attempts.

Common Notification Methods

Several notification methods exist for SSH login alerts, each with distinct advantages. Email notifications remain the most traditional approach, sending detailed login information to your inbox for review. Instant messaging platforms like Telegram, Discord, and Signal offer real-time push notifications directly to your mobile device. System logging tools provide comprehensive audit trails that integrate with centralized monitoring solutions.

Push notification services such as Pushover and Gotify deliver alerts with customizable priorities and sound profiles. Each method has specific use cases. Email works well for less critical systems where delayed notifications are acceptable. Instant messaging excels in production environments requiring immediate awareness. Choose the notification method that aligns with your operational requirements and response time expectations.

When to Use SSH Login Alerts

Implement SSH login alerts in multi-user server environments where multiple administrators access the same system. Production and critical servers handling sensitive data benefit significantly from real-time access monitoring. Organizations with compliance requirements often mandate SSH access logging for audit trails and security incident investigations.

Development teams working on shared infrastructure use SSH alerts to track which team members are actively connected. Personal VPS hosting and cloud servers exposed to the internet require login monitoring to detect brute-force attacks and unauthorized access attempts. Any server accessible from untrusted networks should implement SSH login alerts as part of a comprehensive security strategy.

Method 1: Email-Based SSH Login Alerts Using .bashrc

Installing Mail Utilities on Fedora 42

The first step involves installing mail command-line utilities on your Fedora 42 system. Run the following command to install mailx, the standard email client for Linux systems:

sudo dnf install mailx

This package provides the mail command that enables your server to send email notifications. After installation, verify the mail functionality by sending a test email:

echo "Test email from Fedora 42" | mail -s "Test Subject" your-email@example.com

Check your inbox to confirm the test email arrived successfully. If emails don’t arrive, you may need to configure a mail relay or SMTP server settings in /etc/mail.rc. Some cloud providers block outbound port 25 by default, requiring alternative SMTP configurations.

Configuring Email Alerts for Root User

Access the root user’s home directory and edit the .bash_profile file to trigger notifications on login. Execute these commands:

sudo su -
cd /root
nano .bash_profile

Add the following script at the end of the file:

echo "SSH Login Alert - Root Access
Server: $(hostname)
User: $(whoami)
IP Address: $(echo $SSH_CONNECTION | awk '{print $1}')
Date: $(date)
" | mail -s "Root SSH Login Alert - $(hostname)" your-email@example.com

Replace your-email@example.com with your actual email address. This script extracts the connecting IP address from the $SSH_CONNECTION environment variable and includes the server hostname and timestamp. Save the file and exit the editor.

The notification triggers automatically whenever root logs in via SSH. The email subject line clearly identifies root access events, making them easy to filter in your inbox. Customize the message body to include additional information like system load or active users if needed.

Setting Up Alerts for Regular Users

For individual users, modify their respective .bashrc files in their home directories. Navigate to the user’s home directory:

sudo nano /home/username/.bashrc

Add the same notification script, adjusting the email subject to distinguish regular users from root access:

echo "SSH Login Alert - Regular User
Server: $(hostname)
User: $(whoami)
IP Address: $(echo $SSH_CONNECTION | awk '{print $1}')
Date: $(date)
" | mail -s "User SSH Login - $(whoami)@$(hostname)" your-email@example.com

For system-wide configuration affecting all users, edit /etc/bashrc instead. This approach applies notifications to every user account without modifying individual profile files. However, users with custom shell configurations might override these settings, making this method less reliable than PAM-based approaches.

Ensure proper file permissions after editing user configuration files:

sudo chown username:username /home/username/.bashrc
sudo chmod 644 /home/username/.bashrc

Testing Email Notifications

Initiate a new SSH session to your Fedora 42 server from another terminal or computer. Log in using the configured user account:

ssh username@your-fedora-server-ip

Check your email inbox for the login notification. The email should arrive within seconds to a few minutes, depending on your mail server configuration. If notifications don’t appear, verify these common issues:

Check the mail service status with systemctl status postfix or your configured MTA. Review mail logs at /var/log/maillog for delivery errors. Ensure your firewall allows outbound SMTP traffic. Test mail functionality manually using the command echo "test" | mail -s "test" your-email@example.com.

Method 2: PAM Module Configuration (Most Reliable)

Understanding PAM (Pluggable Authentication Module)

PAM (Pluggable Authentication Module) provides the most reliable method for SSH login notifications because it integrates directly into the authentication process. Unlike shell-based methods that execute after the user’s shell initializes, PAM hooks trigger during the authentication phase itself. This ensures notifications occur even if users bypass standard shell initialization or use custom shell configurations.

PAM operates as a modular authentication framework used by most Linux distributions, including Fedora 42. When SSH receives a connection request, PAM modules execute in sequence to verify credentials, establish sessions, and perform additional actions. The pam_exec.so module allows running custom scripts at specific authentication events. This architecture makes PAM notifications virtually impossible to bypass, providing superior reliability compared to .bashrc methods.

Creating the PAM Notification Script

Create a dedicated script that PAM will execute upon SSH login events. Use your preferred text editor to create the notification script:

sudo nano /usr/local/bin/ssh-login-notify.sh

Add the following content to the script:

#!/bin/bash

# Only execute on session open, not close
if [ "$PAM_TYPE" != "close_session" ]; then
    # Extract connection details
    HOST=$(hostname)
    SUBJECT="SSH Login: $PAM_USER from $PAM_RHOST on $HOST"
    MESSAGE="SSH Login Details:
Server: $HOST
User: $PAM_USER
Source IP: $PAM_RHOST
Service: $PAM_SERVICE
Date: $(date)
TTY: $PAM_TTY"

    # Send email notification
    echo "$MESSAGE" | mail -s "$SUBJECT" your-email@example.com
fi

The script utilizes special PAM environment variables that provide authentication context:

  • $PAM_USER: The username attempting to log in
  • $PAM_RHOST: The remote hostname or IP address
  • $PAM_TYPE: The PAM operation type (open_session or close_session)
  • $PAM_SERVICE: The service name (sshd)
  • $PAM_TTY: The terminal identifier

Make the script executable with proper permissions:

sudo chmod +x /usr/local/bin/ssh-login-notify.sh
sudo chown root:root /usr/local/bin/ssh-login-notify.sh

Configuring /etc/pam.d/sshd

Edit the PAM configuration file for SSH to integrate the notification script:

sudo nano /etc/pam.d/sshd

Add the following line after the existing session entries, typically near the end of the file:

session optional pam_exec.so seteuid /usr/local/bin/ssh-login-notify.sh

This configuration tells PAM to execute the script as an optional session component. The optional keyword ensures that SSH logins succeed even if the notification script fails, preventing lockouts. The seteuid option runs the script with the effective user ID of the connecting user, providing additional security context.

Position the PAM module correctly within the configuration file. Place it after authentication and account modules but before the session closes. Incorrect placement may cause notifications to fire at the wrong time or not at all.

Save the file and exit. No SSH service restart is required because PAM reads this configuration file for each new connection.

Script Customization Options

Customize the notification script to include additional system information or filter specific users. Add system metrics like current load average:

LOAD=$(uptime | awk -F'load average:' '{print $2}')
MESSAGE="$MESSAGE
System Load: $LOAD"

Filter notifications to exclude specific trusted users or local connections:

# Skip notifications for specific users
if [ "$PAM_USER" = "monitoring" ] || [ "$PAM_USER" = "backup" ]; then
    exit 0
fi

# Skip localhost connections
if [ "$PAM_RHOST" = "localhost" ] || [ "$PAM_RHOST" = "127.0.0.1" ]; then
    exit 0
fi

Implement logging for troubleshooting notification issues:

# Log notification attempts
echo "$(date): SSH login by $PAM_USER from $PAM_RHOST" >> /var/log/ssh-notifications.log

Create the log file with appropriate permissions:

sudo touch /var/log/ssh-notifications.log
sudo chmod 644 /var/log/ssh-notifications.log

Testing PAM-Based Notifications

Open a new SSH session to your Fedora 42 server from a different terminal:

ssh username@fedora-server-ip

The notification email should arrive within moments of successful authentication. Check your inbox for the detailed login alert containing all extracted connection information.

If notifications don’t arrive, examine PAM logs for errors:

sudo journalctl -u sshd -n 50

Look for entries related to pam_exec or the notification script. Common issues include incorrect script permissions, missing mail utilities, or syntax errors in the bash script. Test the script manually by setting PAM environment variables:

sudo PAM_TYPE="open_session" PAM_USER="testuser" PAM_RHOST="192.168.1.100" /usr/local/bin/ssh-login-notify.sh

Verify that the test email arrives successfully.

Method 3: Telegram Bot Integration for Instant Alerts

Setting Up Telegram Bot

Telegram bots provide instant push notifications directly to your mobile device with minimal latency. Start by creating a bot through Telegram’s BotFather:

Open Telegram and search for @BotFather. Start a conversation and send the command /newbot. Follow the prompts to choose a name and username for your bot. BotFather will provide an API token that looks like 123456789:ABCdefGHIjklMNOpqrsTUVwxyz. Save this token securely as you’ll need it for the notification script.

Create a new Telegram group for receiving SSH notifications. Add your newly created bot to this group. To find your chat ID, open Telegram in a web browser and navigate to your group. The URL will contain your group ID after the # symbol, including the minus sign. For example: https://web.telegram.org/#-4250408318 means your chat ID is -4250408318.

Creating Telegram Notification Script

Create a directory for notification scripts and the main notification file:

sudo mkdir -p /opt/ssh-notifications
sudo nano /opt/ssh-notifications/login-notification.sh

Add the following script content:

#!/bin/bash

# Telegram Configuration
BOT_TOKEN="YOUR_BOT_TOKEN_HERE"
CHAT_ID="YOUR_CHAT_ID_HERE"

# Extract SSH connection details
if [ -n "$SSH_CONNECTION" ]; then
    SOURCE_IP=$(echo $SSH_CONNECTION | awk '{print $1}')
    SOURCE_PORT=$(echo $SSH_CONNECTION | awk '{print $2}')
else
    SOURCE_IP="Unknown"
    SOURCE_PORT="Unknown"
fi

# Prepare message
MESSAGE=" SSH Login Alert

Server: $(hostname)
User: $(whoami)
Source IP: $SOURCE_IP
Port: $SOURCE_PORT
Date: $(date '+%Y-%m-%d %H:%M:%S')"

# Send Telegram notification
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

Replace YOUR_BOT_TOKEN_HERE with your actual bot token and YOUR_CHAT_ID_HERE with your group chat ID. Make the script executable:

sudo chmod +x /opt/ssh-notifications/login-notification.sh

The script uses curl to send HTTP POST requests to Telegram’s API endpoint. Install curl if not already present:

sudo dnf install curl

Method 3A: Using /etc/ssh/sshrc

The sshrc file executes automatically when users log in via SSH. Create or edit the system-wide SSH rc file:

sudo nano /etc/ssh/sshrc

Add the notification script call:

#!/bin/bash
/opt/ssh-notifications/login-notification.sh

Set proper permissions and ownership:

sudo chmod 755 /etc/ssh/sshrc
sudo chown root:root /etc/ssh/sshrc

The sshrc method offers quick setup but has limitations. Users can override system-wide sshrc settings by creating their own ~/.ssh/rc file. Additionally, certain SSH connection types may bypass sshrc execution entirely. For production environments, the PAM-based approach provides superior reliability.

Method 3B: Using PAM with Telegram

Integrate the Telegram notification script with PAM for bulletproof execution. Modify your PAM notification script to call the Telegram notification instead of sending email:

sudo nano /usr/local/bin/ssh-telegram-notify.sh

Create a PAM-compatible Telegram script:

#!/bin/bash

BOT_TOKEN="YOUR_BOT_TOKEN_HERE"
CHAT_ID="YOUR_CHAT_ID_HERE"

if [ "$PAM_TYPE" != "close_session" ]; then
    MESSAGE=" SSH Login Alert

Server: $(hostname)
User: $PAM_USER
Source: $PAM_RHOST
Service: $PAM_SERVICE
Date: $(date '+%Y-%m-%d %H:%M:%S')"

    curl -s -X POST "https://api.telegram.org/bot${BOT_TOKEN}/sendMessage" \
        -d chat_id="${CHAT_ID}" \
        -d text="${MESSAGE}" > /dev/null 2>&1
fi

Make it executable:

sudo chmod +x /usr/local/bin/ssh-telegram-notify.sh

Edit /etc/pam.d/sshd to reference this script:

sudo nano /etc/pam.d/sshd

Add the PAM module line:

session optional pam_exec.so seteuid /usr/local/bin/ssh-telegram-notify.sh

This combination provides the reliability of PAM with the immediacy of Telegram notifications.

Testing Telegram Notifications

Establish a new SSH connection to your Fedora 42 server:

ssh username@fedora-server-ip

Check your Telegram group immediately for the login notification. The message should appear within seconds, displaying all connection details with emoji formatting.

If notifications don’t appear, troubleshoot systematically. Test the curl command manually from the command line:

curl -X POST "https://api.telegram.org/bot<BOT_TOKEN>/sendMessage" \
    -d chat_id="<CHAT_ID>" \
    -d text="Test notification"

Verify that your firewall allows outbound HTTPS connections on port 443. Check that the bot token and chat ID are correct. Examine script permissions and ensure the script is executable.

Method 4: Using /etc/ssh/sshrc for Quick Setup

What is sshrc

The sshrc file is a special script that the SSH daemon executes immediately after successful authentication but before starting the user’s shell. Two versions exist: the system-wide /etc/ssh/sshrc affecting all users, and user-specific ~/.ssh/rc files in individual home directories.

When SSH establishes a connection, it checks for these files in order: ~/.ssh/rc first, then /etc/ssh/sshrc if the user file doesn’t exist. The script runs with the user’s privileges and receives the X11 authentication data as input if X11 forwarding is enabled.

Implementing sshrc Notifications

Create the system-wide sshrc file if it doesn’t exist:

sudo nano /etc/ssh/sshrc

Add notification logic directly or call an external script:

#!/bin/bash

# Send email notification
echo "SSH Login on $(hostname)
User: $USER
IP: $(echo $SSH_CONNECTION | awk '{print $1}')
Time: $(date)" | mail -s "SSH Login: $USER@$(hostname)" admin@example.com

# Execute default X11 forwarding if needed
if [ -x /usr/bin/X11/xauth ]; then
    /usr/bin/X11/xauth -q -
fi

The script must handle X11 authentication if you use X11 forwarding. Include the xauth commands shown above to maintain X11 functionality.

Set proper permissions:

sudo chmod 755 /etc/ssh/sshrc

sshrc vs PAM Comparison

The sshrc method offers simplicity but lacks the robustness of PAM. Users can bypass system-wide sshrc by creating their own ~/.ssh/rc file that doesn’t include notification code. Certain SSH connection types, particularly those using forced commands or restricted shells, may skip sshrc execution entirely.

PAM-based notifications integrate at the authentication layer, making them virtually impossible to circumvent. PAM executes before the user gains shell access, ensuring notifications fire regardless of shell configuration. For security-critical systems, always choose PAM over sshrc.

Use sshrc for quick deployments on trusted systems where convenience outweighs security concerns. Implement PAM for production servers, compliance-required systems, or any environment where reliable monitoring is essential.

Configuring Firewall and SELinux on Fedora 42

Firewall Configuration

Fedora 42 uses firewalld as its default firewall management tool. Verify that SSH is permitted through the firewall:

sudo firewall-cmd --list-services

Ensure ssh appears in the output. If not, add it:

sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload

For custom SSH ports, specify the port number explicitly:

sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --reload

When using email notifications, verify that outbound SMTP traffic is allowed. Most configurations permit outbound connections by default, but restrictive policies may require explicit rules. Check your firewall zone configuration:

sudo firewall-cmd --get-active-zones
sudo firewall-cmd --zone=public --list-all

For Telegram or other API-based notifications, ensure outbound HTTPS (port 443) is permitted.

SELinux Considerations

Security-Enhanced Linux (SELinux) enforces mandatory access control policies on Fedora 42. Custom notification scripts may trigger SELinux denials if not properly configured. Check SELinux status:

sudo sestatus

When running SSH on non-standard ports, inform SELinux about the change:

sudo semanage port -a -t ssh_port_t -p tcp 2222

Verify the port was added:

sudo semanage port -l | grep ssh

For notification scripts, ensure proper SELinux context. Check current context:

ls -Z /usr/local/bin/ssh-login-notify.sh

If SELinux blocks script execution, examine audit logs:

sudo ausearch -m avc -ts recent

Grant necessary permissions or create custom SELinux policies based on denial messages. For testing purposes only, temporarily set SELinux to permissive mode:

sudo setenforce 0

Remember to re-enable enforcing mode after testing:

sudo setenforce 1

Advanced Configuration and Customization

Filtering Notifications by User

Reduce notification noise by excluding specific system accounts or trusted users. Modify your notification script to include filtering logic:

# List of users to exclude
EXCLUDED_USERS=("monitoring" "backup" "nagios" "prometheus")

# Check if current user is in exclusion list
for user in "${EXCLUDED_USERS[@]}"; do
    if [ "$PAM_USER" = "$user" ]; then
        exit 0
    fi
done

Create user-specific notification rules with different priority levels. Send high-priority alerts for root logins while using standard notifications for regular users:

if [ "$PAM_USER" = "root" ]; then
    SUBJECT=" CRITICAL: Root SSH Login on $(hostname)"
else
    SUBJECT="ℹ️ SSH Login: $PAM_USER on $(hostname)"
fi

Distinguish between root and regular user access in your email subject lines or Telegram message formatting.

Adding Geographic IP Information

Enhance notifications with geographic location data using IP geolocation services. Install the geoiplookup utility:

sudo dnf install GeoIP GeoIP-data

Modify your notification script to include location information:

# Get geographic information
if command -v geoiplookup &> /dev/null; then
    GEO_INFO=$(geoiplookup $PAM_RHOST | cut -d':' -f2-)
    MESSAGE="$MESSAGE
Location: $GEO_INFO"
fi

For more detailed geolocation, use external API services like ipinfo.io:

LOCATION=$(curl -s https://ipinfo.io/$PAM_RHOST/country)
MESSAGE="$MESSAGE
Country: $LOCATION"

Consider privacy and legal implications when collecting geolocation data. Ensure compliance with applicable data protection regulations in your jurisdiction.

Rich Notification Formatting

HTML email formatting improves readability and visual appeal. Configure your mail command to send HTML emails:

MESSAGE="<html><body>
<h2>SSH Login Alert</h2>
<table border='1' cellpadding='5'>
<tr><td>Server</td><td>$(hostname)</td></tr>
<tr><td>User</td><td>$PAM_USER</td></tr>
<tr><td>IP Address</td><td>$PAM_RHOST</td></tr>
<tr><td>Time</td><td>$(date)</td></tr>
</table>
</body></html>"

echo "$MESSAGE" | mail -a "Content-Type: text/html" -s "$SUBJECT" recipient@example.com

Telegram supports Markdown and HTML formatting for messages:

MESSAGE="<b> SSH Login Alert</b>

<b>Server:</b> $(hostname)
<b>User:</b> $PAM_USER
<b>Source:</b> $PAM_RHOST
<b>Time:</b> $(date '+%Y-%m-%d %H:%M:%S')"

curl -s -X POST "https://api.telegram.org/bot${BOT_TOKEN}/sendMessage" \
    -d chat_id="${CHAT_ID}" \
    -d text="${MESSAGE}" \
    -d parse_mode="HTML"

Include system metrics like CPU load and disk usage:

LOAD=$(cat /proc/loadavg | awk '{print $1,$2,$3}')
DISK=$(df -h / | awk 'NR==2 {print $5}')
MESSAGE="$MESSAGE
System Load: $LOAD
Disk Usage: $DISK"

Silent vs Priority Notifications

Implement intelligent notification rules based on connection patterns. Create a whitelist of trusted IP addresses that generate silent notifications:

TRUSTED_IPS=("192.168.1.100" "10.0.0.50")

for ip in "${TRUSTED_IPS[@]}"; do
    if [ "$PAM_RHOST" = "$ip" ]; then
        # Send low-priority notification or skip
        exit 0
    fi
done

Configure time-based notification rules to reduce alerts during maintenance windows:

HOUR=$(date +%H)
DAY=$(date +%u)

# Skip notifications during weekends or after-hours
if [ $DAY -gt 5 ] || [ $HOUR -lt 8 ] || [ $HOUR -gt 18 ]; then
    # Off-hours login - send high priority alert
    PRIORITY="HIGH"
else
    PRIORITY="NORMAL"
fi

Security Best Practices

SSH Hardening Recommendations

Combine SSH login alerts with comprehensive security measures for optimal protection. Disable direct root login to force attackers to compromise a regular user account first:

sudo nano /etc/ssh/sshd_config

Set these security parameters:

PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
PermitEmptyPasswords no
MaxAuthTries 3

Change the default SSH port to reduce automated scanning attempts:

Port 2222

Limit SSH access to specific users or groups:

AllowUsers alice bob admin

Or use groups:

AllowGroups sshadmins

Restart SSH to apply configuration changes:

sudo systemctl restart sshd

Notification Security

Protect API tokens and authentication credentials used in notification scripts. Store sensitive data in protected files with restricted permissions:

sudo nano /etc/ssh-notifications/config

Add your tokens:

BOT_TOKEN="your_telegram_token"
CHAT_ID="your_chat_id"

Set strict permissions:

sudo chmod 600 /etc/ssh-notifications/config
sudo chown root:root /etc/ssh-notifications/config

Source this configuration file in your notification script:

source /etc/ssh-notifications/config

Avoid including sensitive information like passwords or authentication tokens in notification messages. Limit notification content to connection metadata rather than detailed system information that could aid attackers.

Secure notification scripts themselves with appropriate ownership and permissions:

sudo chown root:root /usr/local/bin/*.sh
sudo chmod 755 /usr/local/bin/*.sh

Complementary Security Tools

Install Fail2Ban for automated intrusion prevention. Fail2Ban monitors authentication logs and bans IP addresses showing malicious behavior:

sudo dnf install fail2ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban

Configure Fail2Ban for SSH protection by editing /etc/fail2ban/jail.local:

[sshd]
enabled = true
port = ssh
logpath = /var/log/secure
maxretry = 5
bantime = 3600

Monitor SSH logs regularly using journalctl:

sudo journalctl -u sshd -f

Review failed login attempts:

sudo grep "Failed password" /var/log/secure

Conduct regular security audits examining user accounts, SSH configurations, and access patterns.

Troubleshooting Common Issues

Notifications Not Received

When notifications fail to arrive, systematically check each component. Verify script execution permissions:

ls -la /usr/local/bin/ssh-login-notify.sh

Ensure the script is executable and owned by root. Test the script manually by simulating PAM environment variables:

sudo PAM_TYPE="open_session" PAM_USER="testuser" PAM_RHOST="192.168.1.1" /usr/local/bin/ssh-login-notify.sh

For email notifications, check mail service status:

sudo systemctl status postfix

Review mail logs for delivery errors:

sudo tail -f /var/log/maillog

Test network connectivity for API-based notifications:

curl -v https://api.telegram.org

Examine PAM logs for script execution errors:

sudo journalctl -u sshd --since "10 minutes ago" | grep pam_exec

SELinux Blocking Scripts

SELinux may prevent notification scripts from executing or accessing required resources. Check for SELinux denials:

sudo ausearch -m avc -ts recent

If SELinux blocks your script, examine the denial message details. Create custom SELinux policies using audit2allow:

sudo ausearch -m avc -ts recent | audit2allow -M ssh_notify
sudo semodule -i ssh_notify.pp

For temporary testing, set SELinux to permissive mode:

sudo setenforce 0

Test your notifications, then re-enable enforcing mode:

sudo setenforce 1

Never leave SELinux permanently disabled in production environments.

Email Delivery Problems

Email notifications require proper mail relay configuration. Configure your mail transfer agent to use a valid SMTP server:

sudo nano /etc/mail.rc

Add SMTP settings:

set smtp=smtp.example.com:587
set smtp-use-starttls
set smtp-auth=login
set smtp-auth-user=username
set smtp-auth-password=password

Consider SPF and DKIM records for proper email delivery. Many mail providers mark server-generated emails as spam without proper sender authentication. Check spam folders if notifications don’t appear in the inbox.

Test mail delivery using verbose output:

echo "Test" | mail -v -s "Test" recipient@example.com

Telegram Bot Not Responding

Telegram notification failures often stem from incorrect bot tokens or chat IDs. Verify your bot token by testing the API manually:

curl https://api.telegram.org/bot<YOUR_TOKEN>/getMe

A successful response confirms the token is valid. Check your chat ID by sending a message to your bot or group, then query the API:

curl https://api.telegram.org/bot<YOUR_TOKEN>/getUpdates

Examine the JSON response for the correct chat ID. Ensure firewall rules allow outbound HTTPS connections:

sudo firewall-cmd --list-all | grep 443

Test the curl command manually from the command line:

curl -X POST "https://api.telegram.org/bot<TOKEN>/sendMessage" -d chat_id="<CHAT_ID>" -d text="Test"

Duplicate Notifications

Multiple notification triggers can cause duplicate alerts. Check for conflicting configurations in .bashrc, .bash_profile, /etc/profile.d/, and PAM simultaneously. Choose a single notification method to avoid redundancy.

List all notification sources:

sudo grep -r "mail.*SSH" /etc/profile.d/ /etc/bashrc /root/.bashrc
sudo grep "pam_exec" /etc/pam.d/sshd

Remove duplicate notification configurations, keeping only your preferred method.

Monitoring and Maintenance

Log Management

Review SSH logs regularly to identify unauthorized access attempts and security patterns. Fedora 42 stores SSH logs in the systemd journal and /var/log/secure:

sudo journalctl -u sshd | tail -100

Filter logs for specific events like failed logins:

sudo journalctl -u sshd | grep "Failed"

Set up log rotation to manage log file sizes:

sudo nano /etc/logrotate.d/sshd-notifications

Add rotation configuration:

/var/log/ssh-notifications.log {
    weekly
    rotate 4
    compress
    missingok
    notifempty
}

Query SSH logs using journalctl with time ranges:

sudo journalctl -u sshd --since "yesterday"
sudo journalctl -u sshd --since "2025-10-01" --until "2025-10-15"

Testing Notification Systems

Schedule periodic test notifications to verify the monitoring system remains functional. Create a cron job that sends test alerts:

sudo crontab -e

Add a weekly test:

0 9 * * 1 /usr/local/bin/ssh-login-notify.sh

Monitor notification delivery rates and response times. Track how long alerts take to arrive after login events occur. Document baseline performance metrics to detect degradation.

Keep notification scripts updated with security patches and functionality improvements. Review scripts quarterly to ensure they remain compatible with system updates.

Performance Considerations

Notification scripts add minimal overhead to SSH login time but optimization remains important. Heavy scripts executing synchronous operations can delay authentication. Run notification delivery in the background:

{
    # Notification code here
} &

Implement timeouts for external API calls to prevent hanging connections:

curl --max-time 5 -X POST "https://api.telegram.org/bot${BOT_TOKEN}/sendMessage" ...

For high-traffic servers with frequent logins, implement rate limiting to prevent notification flooding. Track notification timestamps and skip alerts that occur within defined intervals:

LAST_NOTIFICATION=$(cat /tmp/last_ssh_notification 2>/dev/null || echo 0)
CURRENT_TIME=$(date +%s)
TIME_DIFF=$((CURRENT_TIME - LAST_NOTIFICATION))

if [ $TIME_DIFF -gt 60 ]; then
    # Send notification
    echo $CURRENT_TIME > /tmp/last_ssh_notification
fi

Congratulations! You have successfully setup SSH Login Alerts. Thanks for using this tutorial to configure SSH Login Alerts on Fedora 42 Linux system. For additional help or useful information, we recommend you check the official Fedora website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button