+
alpine
atom
+
+
+
bundler
&&
c#
+
asm
crystal
termux
+
+
+
gatsby
=>
+
prettier
//
+
ios
+
aws
+
+
suse
+
+
+
phoenix
argocd
prometheus
+
delphi
+
+
!=
raspbian
pytest
lit
%
+
+
+
torch
influxdb
couchdb
+
centos
axum
+
+
r
+
+
+
parcel
ubuntu
+
+
clion
htmx
weaviate
bash
xcode
+
+
+
+
+
+
cypress
+
+
+
+
ractive
+
websocket
laravel
koa
+
+
raspbian
Back to Blog
🔒 Configuring Secure Shell SSH Hardening on Alpine Linux: Complete Guide
Alpine Linux SSH Security

🔒 Configuring Secure Shell SSH Hardening on Alpine Linux: Complete Guide

Published Jun 18, 2025

Advanced tutorial for system administrators to secure SSH access on Alpine Linux. Perfect for production servers with comprehensive security hardening and best practices.

13 min read
0 views
Table of Contents

🔒 Configuring Secure Shell SSH Hardening on Alpine Linux: Complete Guide

Let’s secure your SSH access on Alpine Linux! 🛡️ This comprehensive tutorial shows you how to harden SSH configuration, implement key-based authentication, and protect against common attacks. Essential for production servers and security-conscious administrators! 😊

🤔 What is SSH Hardening?

SSH hardening is the process of securing your SSH server against attacks and unauthorized access! It involves configuring advanced security settings and implementing best practices.

SSH hardening is like:

  • 🔐 Adding multiple locks and security systems to your house
  • 🛡️ Creating barriers that make it extremely difficult for attackers to break in
  • 💡 Implementing monitoring and detection systems for suspicious activity

🎯 What You Need

Before we start, you need:

  • ✅ Alpine Linux server with SSH access
  • ✅ Root or sudo privileges for configuration changes
  • ✅ Basic understanding of SSH and Linux security
  • ✅ Another way to access the server (console/KVM) in case SSH breaks

📋 Step 1: Initial SSH Setup and Assessment

Install and Enable OpenSSH

Let’s make sure SSH is properly installed and running! 😊

What we’re doing: Installing OpenSSH server and enabling it for secure remote access.

# Install OpenSSH server
apk update
apk add openssh openssh-server

# Enable SSH service
rc-update add sshd default

# Start SSH service
rc-service sshd start

# Check SSH status
rc-service sshd status

# Verify SSH is listening
netstat -tuln | grep :22

What this does: 📖 Installs and starts the SSH server for remote access.

Example output:

sshd                                                          [started]
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
tcp6       0      0 :::22                   :::*                    LISTEN

What this means: SSH server is running and accepting connections! ✅

Backup Original Configuration

Let’s backup the SSH configuration before making changes! This is crucial! 🎯

What we’re doing: Creating backups of SSH configuration files for easy recovery.

# Create backup directory
mkdir -p /root/ssh-backups/$(date +%Y%m%d-%H%M%S)

# Backup SSH configuration
cp /etc/ssh/sshd_config /root/ssh-backups/$(date +%Y%m%d-%H%M%S)/
cp -r /etc/ssh/ /root/ssh-backups/$(date +%Y%m%d-%H%M%S)/ssh-complete

# Verify backups
ls -la /root/ssh-backups/$(date +%Y%m%d)/

# Create restore script
cat > /root/restore-ssh.sh << 'EOF'
#!/bin/sh
echo "🚨 Restoring original SSH configuration..."
BACKUP_DIR=$(ls -1t /root/ssh-backups/ | head -1)
cp "/root/ssh-backups/$BACKUP_DIR/sshd_config" /etc/ssh/
rc-service sshd restart
echo "✅ SSH configuration restored from $BACKUP_DIR"
EOF

chmod +x /root/restore-ssh.sh
echo "SSH configuration backed up! 💾"

What this means: You can safely restore SSH configuration if something goes wrong! 🌟

💡 Important Tips

Tip: Always keep console access available when modifying SSH! 💡

Warning: Test SSH changes in a separate session before closing your current one! ⚠️

🛠️ Step 2: Basic SSH Hardening Configuration

Secure Basic SSH Settings

Let’s configure fundamental SSH security settings! 😊

What we’re doing: Modifying basic SSH configuration to improve security and reduce attack surface.

# Create hardened SSH configuration
cat > /etc/ssh/sshd_config << 'EOF'
# Basic SSH Security Configuration
Port 2222
Protocol 2
AddressFamily inet

# Authentication Settings
PermitRootLogin no
MaxAuthTries 3
MaxSessions 2
LoginGraceTime 30

# Password Authentication
PasswordAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no

# Key-based Authentication
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys

# Host-based Authentication
HostbasedAuthentication no
IgnoreRhosts yes

# Forwarding and Tunneling
AllowTcpForwarding no
X11Forwarding no
AllowAgentForwarding no
GatewayPorts no

# Session Settings
ClientAliveInterval 300
ClientAliveCountMax 2
TCPKeepAlive no

# Logging
SyslogFacility AUTHPRIV
LogLevel VERBOSE

# Banner and Messages
Banner /etc/ssh/banner
PrintMotd no
EOF

echo "Basic SSH hardening applied! 🔒"

Code explanation:

  • Port 2222: Changes SSH from default port 22 to reduce automated attacks
  • PermitRootLogin no: Prevents direct root login attempts
  • PasswordAuthentication no: Forces key-based authentication only
  • MaxAuthTries 3: Limits login attempts to prevent brute force
  • X11Forwarding no: Disables potentially insecure GUI forwarding

What this means: SSH is now significantly more secure! 🎉

Create SSH Security Banner

Let’s add a warning banner for SSH connections! 🚀

What we’re doing: Creating a legal/security banner that appears before login.

# Create SSH banner
cat > /etc/ssh/banner << 'EOF'
#############################################################################
#                           AUTHORIZED ACCESS ONLY                         #
#############################################################################
#                                                                           #
#  This system is for authorized users only. All activities are logged     #
#  and monitored. Unauthorized access is strictly prohibited and will      #
#  be prosecuted to the full extent of the law.                           #
#                                                                           #
#  By continuing, you acknowledge that you are an authorized user and      #
#  agree to comply with all applicable policies and procedures.            #
#                                                                           #
#############################################################################
EOF

# Set proper permissions
chmod 644 /etc/ssh/banner

# Test banner (will show when connecting)
echo "SSH banner created! ⚠️"

What this does: Displays a legal warning to anyone attempting to connect! ✅

Configure User Access Controls

Let’s set up granular user access controls! 🎮

What we’re doing: Configuring which users and groups can access SSH.

# Add SSH user access configuration to sshd_config
cat >> /etc/ssh/sshd_config << 'EOF'

# User and Group Access Controls
AllowUsers sshuser admin
DenyUsers root guest nobody
AllowGroups ssh-users wheel

# Host-based Access Controls
# Allow from specific networks only
#AllowUsers [email protected].*
#AllowUsers [email protected].*

# Deny from specific networks
#DenyUsers *@192.168.100.*
EOF

# Create SSH users group
addgroup ssh-users

# Create a dedicated SSH user (example)
adduser -D -s /bin/ash sshuser
addgroup sshuser ssh-users
addgroup sshuser wheel

# Set password for new user (temporary - will use keys later)
echo "sshuser:$(openssl rand -base64 32)" | chpasswd

echo "User access controls configured! 👥"

What this means: Only specific users and groups can access SSH! 🌟

🔧 Step 3: Implement Key-Based Authentication

Generate SSH Key Pairs

Let’s set up secure key-based authentication! This is the gold standard! 😊

What we’re doing: Creating strong SSH key pairs for passwordless authentication.

# Generate SSH keys for the SSH user
sudo -u sshuser ssh-keygen -t ed25519 -b 4096 -f /home/sshuser/.ssh/id_ed25519 -N ""

# Alternative: Generate RSA keys (if ed25519 not supported)
sudo -u sshuser ssh-keygen -t rsa -b 4096 -f /home/sshuser/.ssh/id_rsa -N ""

# Set proper permissions on SSH directory
chmod 700 /home/sshuser/.ssh
chmod 600 /home/sshuser/.ssh/id_ed25519
chmod 644 /home/sshuser/.ssh/id_ed25519.pub
chown -R sshuser:sshuser /home/sshuser/.ssh

# Create authorized_keys file
touch /home/sshuser/.ssh/authorized_keys
chmod 600 /home/sshuser/.ssh/authorized_keys
chown sshuser:sshuser /home/sshuser/.ssh/authorized_keys

echo "SSH keys generated! 🔑"

What these key types mean:

  • ed25519: Modern, fast, and secure elliptic curve algorithm
  • rsa 4096: Traditional but robust RSA with 4096-bit key size
  • Both are considered highly secure for SSH authentication

What this means: You have strong cryptographic keys for secure authentication! 🎉

Configure Key Authentication

Let’s set up the authorized keys properly! 🎯

What we’re doing: Adding public keys to authorized_keys with security restrictions.

# Example: Add a public key with restrictions
cat >> /home/sshuser/.ssh/authorized_keys << 'EOF'
# Restricted SSH key with security options
restrict,command="/usr/local/bin/user-shell.sh",from="192.168.1.0/24" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExampleKeyDataHere user@workstation

# Standard SSH key (less restrictive)
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAnotherExampleKeyHere admin@laptop
EOF

# Create restricted shell script
cat > /usr/local/bin/user-shell.sh << 'EOF'
#!/bin/sh
echo "🔒 Welcome to restricted SSH environment"
echo "Available commands: ls, cat, grep, less, tail"

# Allow only specific commands
case "$SSH_ORIGINAL_COMMAND" in
    "ls"*|"cat"*|"grep"*|"less"*|"tail"*)
        eval "$SSH_ORIGINAL_COMMAND"
        ;;
    "")
        echo "Interactive shell disabled. Use specific commands only."
        ;;
    *)
        echo "Command not allowed: $SSH_ORIGINAL_COMMAND"
        exit 1
        ;;
esac
EOF

chmod +x /usr/local/bin/user-shell.sh

echo "Key authentication configured with restrictions! 🛡️"

Key restriction options explained:

  • restrict: Applies all restrictions by default
  • command=: Forces execution of specific command only
  • from=: Limits connections to specific IP addresses/networks
  • no-port-forwarding: Disables port forwarding for this key

What this means: SSH keys are configured with fine-grained security controls! 🌟

Test Key Authentication

Let’s verify key authentication is working! 😊

What we’re doing: Testing SSH key authentication from a secure location.

# Display public key for copying to client
echo "📋 Copy this public key to your SSH client:"
cat /home/sshuser/.ssh/id_ed25519.pub

# Test SSH configuration syntax
sshd -t

# Restart SSH service with new configuration
rc-service sshd restart

# Test local SSH connection (from another terminal)
# ssh -p 2222 -i /path/to/private/key sshuser@localhost

# Create connection test script
cat > /root/test-ssh.sh << 'EOF'
#!/bin/sh
echo "🧪 Testing SSH configuration..."

# Test SSH syntax
if sshd -t; then
    echo "✅ SSH configuration syntax is valid"
else
    echo "❌ SSH configuration has errors!"
    exit 1
fi

# Test SSH service status
if rc-service sshd status | grep -q "started"; then
    echo "✅ SSH service is running"
else
    echo "❌ SSH service is not running!"
    exit 1
fi

# Test SSH port listening
if netstat -tuln | grep -q ":2222"; then
    echo "✅ SSH is listening on port 2222"
else
    echo "❌ SSH is not listening on port 2222!"
    exit 1
fi

echo "🎉 SSH hardening tests completed!"
EOF

chmod +x /root/test-ssh.sh
/root/test-ssh.sh

What this means: Your SSH hardening is properly configured and functional! 🎉

🔍 Step 4: Advanced Security Measures

Configure Fail2Ban for SSH Protection

Let’s set up automated protection against brute force attacks! 🚀

What we’re doing: Installing and configuring Fail2Ban to automatically block suspicious SSH activity.

# Install Fail2Ban
apk add fail2ban

# Create Fail2Ban configuration for SSH
cat > /etc/fail2ban/jail.d/sshd.conf << 'EOF'
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
backend = auto
maxretry = 3
findtime = 600
bantime = 3600
ignoreip = 127.0.0.1/8 192.168.1.0/24

[sshd-ddos]
enabled = true
port = 2222
filter = sshd-ddos
logpath = /var/log/auth.log
maxretry = 6
findtime = 60
bantime = 300
EOF

# Enable and start Fail2Ban
rc-update add fail2ban default
rc-service fail2ban start

# Check Fail2Ban status
fail2ban-client status sshd

echo "Fail2Ban configured for SSH protection! 🛡️"

What Fail2Ban does:

  • Monitors SSH log files for failed login attempts
  • Automatically blocks IP addresses after specified failed attempts
  • Provides temporary and permanent banning capabilities
  • Protects against brute force and DDoS attacks

What this means: Your SSH server is now protected against automated attacks! 🌟

Implement Two-Factor Authentication

Let’s add two-factor authentication for extra security! 🎮

What we’re doing: Setting up Google Authenticator or similar TOTP for SSH login.

# Install Google Authenticator PAM module
apk add google-authenticator-libpam

# Configure PAM for SSH 2FA
cat > /etc/pam.d/sshd << 'EOF'
# PAM configuration for SSH with 2FA
auth required pam_google_authenticator.so nullok
auth include system-remote-login
account include system-remote-login
password include system-remote-login
session include system-remote-login
EOF

# Update SSH configuration for 2FA
cat >> /etc/ssh/sshd_config << 'EOF'

# Two-Factor Authentication
AuthenticationMethods publickey,keyboard-interactive
ChallengeResponseAuthentication yes
UsePAM yes
EOF

# Generate 2FA codes for user
sudo -u sshuser google-authenticator -t -d -W -f -r 3 -R 30 -Q UTF8

# Create 2FA setup script for users
cat > /usr/local/bin/setup-2fa.sh << 'EOF'
#!/bin/sh
echo "🔐 Setting up Two-Factor Authentication"
echo "======================================"

if [ "$(whoami)" = "root" ]; then
    echo "❌ Run this as the SSH user, not root"
    exit 1
fi

echo "📱 Follow the prompts to set up Google Authenticator..."
google-authenticator -t -d -W -f -r 3 -R 30 -Q UTF8

echo "✅ Two-Factor Authentication configured!"
echo "📋 Add the secret key to your authenticator app"
echo "🔑 Save the backup codes in a secure location"
EOF

chmod +x /usr/local/bin/setup-2fa.sh

echo "Two-Factor Authentication configured! 🔐"

What this means: SSH now requires both a key AND a time-based code! 🎉

Set Up SSH Monitoring and Alerting

Let’s create monitoring for SSH activity! 😊

What we’re doing: Setting up logging and alerting for SSH security events.

# Configure enhanced SSH logging
cat >> /etc/ssh/sshd_config << 'EOF'

# Enhanced Logging Configuration
LogLevel VERBOSE
SyslogFacility AUTH
EOF

# Create SSH monitoring script
cat > /usr/local/bin/ssh-monitor.sh << 'EOF'
#!/bin/sh
# SSH Security Monitoring Script

LOG_FILE="/var/log/auth.log"
ALERT_EMAIL="[email protected]"
TEMP_DIR="/tmp/ssh-monitor"

mkdir -p "$TEMP_DIR"

echo "🔍 SSH Security Monitor - $(date)"
echo "=================================="

# Check for successful logins
echo "📊 Recent successful SSH logins:"
grep "Accepted" "$LOG_FILE" | tail -5

# Check for failed login attempts
echo "⚠️ Recent failed SSH attempts:"
grep "Failed" "$LOG_FILE" | tail -5

# Check for unusual connection patterns
echo "🚨 Connections from new IPs today:"
grep "$(date '+%b %d')" "$LOG_FILE" | grep "Accepted" | \
awk '{print $11}' | sort -u > "$TEMP_DIR/today_ips"

if [ -f "$TEMP_DIR/known_ips" ]; then
    comm -23 "$TEMP_DIR/today_ips" "$TEMP_DIR/known_ips" | \
    while read ip; do
        echo "🔍 New IP: $ip"
    done
fi

# Update known IPs list
cat "$TEMP_DIR/today_ips" >> "$TEMP_DIR/known_ips"
sort -u "$TEMP_DIR/known_ips" -o "$TEMP_DIR/known_ips"

# Check Fail2Ban status
echo "🛡️ Fail2Ban SSH jail status:"
fail2ban-client status sshd 2>/dev/null || echo "Fail2Ban not active"

# Check active SSH sessions
echo "👥 Current SSH sessions:"
who | grep pts

echo "✅ SSH monitoring completed at $(date)"
EOF

chmod +x /usr/local/bin/ssh-monitor.sh

# Create daily monitoring cron job
echo "0 9 * * * /usr/local/bin/ssh-monitor.sh > /var/log/ssh-daily-report.log 2>&1" | crontab -

echo "SSH monitoring and alerting configured! 📊"

What this means: You’ll have comprehensive monitoring of all SSH activity! 🌟

📊 Quick SSH Security Commands Table

CommandPurposeResult
🔧 sshd -tTest SSH config✅ Validate configuration
🔍 fail2ban-client status sshdCheck ban status✅ View blocked IPs
📋 ssh-keygen -t ed25519Generate SSH key✅ Create secure key pair
🛡️ journalctl -u sshdView SSH logs✅ Monitor SSH activity

🎮 Practice Time!

Let’s practice what you learned! Try these security scenarios:

Example 1: Emergency SSH Access Recovery 🟢

What we’re doing: Creating emergency access procedures in case SSH lockout occurs.

# Create emergency SSH recovery script
cat > /root/emergency-ssh-recovery.sh << 'EOF'
#!/bin/sh
echo "🚨 EMERGENCY SSH RECOVERY PROCEDURE"
echo "================================="

# Enable emergency SSH access temporarily
echo "⚠️ Enabling emergency SSH access..."

# Backup current config
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.emergency-backup

# Create temporary emergency config
cat > /etc/ssh/sshd_config.emergency << 'EOF'
Port 22
PermitRootLogin yes
PasswordAuthentication yes
PubkeyAuthentication yes
MaxAuthTries 6
UsePAM no
EOF

# Apply emergency config
cp /etc/ssh/sshd_config.emergency /etc/ssh/sshd_config
rc-service sshd restart

echo "✅ Emergency SSH access enabled on port 22"
echo "🔄 Restore hardened config with: /root/restore-ssh.sh"
echo "⏰ Remember to re-harden after fixing issues!"
EOF

chmod +x /root/emergency-ssh-recovery.sh

# Test recovery procedure (don't run in production!)
echo "Emergency recovery procedure created! 🚨"

What this does: Provides a way to recover SSH access if configuration goes wrong! 🌟

Example 2: SSH Security Audit 🟡

What we’re doing: Creating a comprehensive SSH security audit script.

# Create SSH security audit script
cat > /usr/local/bin/ssh-security-audit.sh << 'EOF'
#!/bin/sh
echo "🔍 SSH Security Audit Report"
echo "============================"
echo "Generated: $(date)"
echo ""

# Check SSH service status
echo "📊 SSH Service Status:"
rc-service sshd status | head -1
echo ""

# Check SSH configuration
echo "🔧 SSH Configuration Analysis:"
echo "Port: $(grep '^Port' /etc/ssh/sshd_config | awk '{print $2}')"
echo "Root Login: $(grep '^PermitRootLogin' /etc/ssh/sshd_config | awk '{print $2}')"
echo "Password Auth: $(grep '^PasswordAuthentication' /etc/ssh/sshd_config | awk '{print $2}')"
echo "Key Auth: $(grep '^PubkeyAuthentication' /etc/ssh/sshd_config | awk '{print $2}')"
echo ""

# Check authorized keys
echo "🔑 SSH Keys Analysis:"
for user_home in /home/*; do
    if [ -d "$user_home/.ssh" ]; then
        user=$(basename "$user_home")
        key_count=$(wc -l < "$user_home/.ssh/authorized_keys" 2>/dev/null || echo "0")
        echo "User $user: $key_count authorized keys"
    fi
done
echo ""

# Check recent activity
echo "📈 Recent SSH Activity (last 24 hours):"
grep "$(date -d '1 day ago' '+%b %d')" /var/log/auth.log | grep -E "(Accepted|Failed)" | wc -l | xargs echo "Total attempts:"
grep "$(date '+%b %d')" /var/log/auth.log | grep "Accepted" | wc -l | xargs echo "Successful logins:"
grep "$(date '+%b %d')" /var/log/auth.log | grep "Failed" | wc -l | xargs echo "Failed attempts:"
echo ""

# Check Fail2Ban status
echo "🛡️ Fail2Ban Protection:"
if command -v fail2ban-client >/dev/null; then
    fail2ban-client status sshd 2>/dev/null || echo "Fail2Ban not configured for SSH"
else
    echo "Fail2Ban not installed"
fi
echo ""

# Security recommendations
echo "💡 Security Recommendations:"
if grep -q "^Port 22" /etc/ssh/sshd_config; then
    echo "⚠️ Consider changing SSH port from default 22"
fi
if grep -q "^PermitRootLogin yes" /etc/ssh/sshd_config; then
    echo "🚨 Root login is enabled - consider disabling"
fi
if grep -q "^PasswordAuthentication yes" /etc/ssh/sshd_config; then
    echo "⚠️ Password authentication enabled - consider key-only auth"
fi
echo ""

echo "✅ SSH Security Audit Completed"
EOF

chmod +x /usr/local/bin/ssh-security-audit.sh

# Run the audit
/usr/local/bin/ssh-security-audit.sh

echo "SSH security audit completed! 📚"

What this does: Provides a comprehensive security assessment of your SSH configuration! 📚

🚨 Fix Common Problems

Problem 1: SSH connection refused after hardening ❌

What happened: Can’t connect to SSH after applying hardening configuration. How to fix it: Use console access to restore or fix configuration.

# From console/KVM access:
# 1. Check SSH service status
rc-service sshd status

# 2. Test SSH configuration
sshd -t

# 3. Check if SSH is listening on correct port
netstat -tuln | grep 2222

# 4. Restore from backup if needed
/root/restore-ssh.sh

# 5. Fix common issues
# Allow your IP in firewall
iptables -A INPUT -p tcp --dport 2222 -s YOUR_IP -j ACCEPT

# Check user permissions
ls -la /home/sshuser/.ssh/

Problem 2: SSH keys not working ❌

What happened: Key authentication fails despite proper setup. How to fix it: Check permissions and configuration.

# Fix SSH key permissions
chmod 700 /home/sshuser/.ssh
chmod 600 /home/sshuser/.ssh/authorized_keys
chown -R sshuser:sshuser /home/sshuser/.ssh

# Check SSH configuration
grep -E "(PubkeyAuthentication|AuthorizedKeysFile)" /etc/ssh/sshd_config

# Test key format
ssh-keygen -l -f /home/sshuser/.ssh/authorized_keys

# Enable debug logging temporarily
echo "LogLevel DEBUG" >> /etc/ssh/sshd_config
rc-service sshd restart
# Check logs: tail -f /var/log/auth.log

Don’t worry! SSH issues are usually configuration or permission problems that are easy to fix! 💪

💡 Simple Tips

  1. Always keep console access 📅 - Never rely only on SSH for server access
  2. Test changes gradually 🌱 - Apply hardening in steps, not all at once
  3. Monitor SSH logs regularly 🤝 - Stay aware of connection attempts and patterns
  4. Keep SSH keys secure 💪 - Protect private keys and rotate them periodically

✅ Check Everything Works

Let’s verify your SSH hardening is working perfectly:

# Complete SSH security verification
echo "=== SSH Security Hardening Verification ==="

echo "1. SSH service status:"
rc-service sshd status | grep -E "(started|stopped)"

echo "2. SSH configuration test:"
sshd -t && echo "✅ Configuration valid" || echo "❌ Configuration errors"

echo "3. SSH listening ports:"
netstat -tuln | grep ssh || netstat -tuln | grep :2222

echo "4. Security features enabled:"
grep -E "^(PermitRootLogin|PasswordAuthentication|PubkeyAuthentication)" /etc/ssh/sshd_config

echo "5. Fail2Ban status:"
fail2ban-client status sshd 2>/dev/null | grep "Currently banned" || echo "Fail2Ban not active"

echo "6. SSH user permissions:"
ls -la /home/*/\.ssh/ 2>/dev/null | head -5

echo "7. Recent SSH activity:"
grep "$(date '+%b %d')" /var/log/auth.log | grep -E "(Accepted|Failed)" | wc -l | xargs echo "Login attempts today:"

echo "8. SSH hardening score:"
SCORE=0
grep -q "^Port [0-9]" /etc/ssh/sshd_config && [ "$(grep '^Port' /etc/ssh/sshd_config | awk '{print $2}')" != "22" ] && SCORE=$((SCORE+1))
grep -q "^PermitRootLogin no" /etc/ssh/sshd_config && SCORE=$((SCORE+1))
grep -q "^PasswordAuthentication no" /etc/ssh/sshd_config && SCORE=$((SCORE+1))
grep -q "^PubkeyAuthentication yes" /etc/ssh/sshd_config && SCORE=$((SCORE+1))
command -v fail2ban-client >/dev/null && SCORE=$((SCORE+1))
echo "Security score: $SCORE/5"

echo "SSH hardening verification completed! ✅"

Good output shows:

=== SSH Security Hardening Verification ===
1. SSH service status:
sshd                                                          [started]

2. SSH configuration test:
✅ Configuration valid

3. SSH listening ports:
tcp        0      0 0.0.0.0:2222            0.0.0.0:*               LISTEN

4. Security features enabled:
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes

8. SSH hardening score:
Security score: 5/5

SSH hardening verification completed! ✅

🏆 What You Learned

Great job! Now you can:

  • ✅ Install and configure OpenSSH server securely on Alpine Linux
  • ✅ Implement comprehensive SSH hardening configurations
  • ✅ Set up key-based authentication with security restrictions
  • ✅ Configure Fail2Ban for automated attack protection
  • ✅ Implement two-factor authentication for SSH access
  • ✅ Create SSH monitoring and alerting systems
  • ✅ Handle emergency SSH access recovery procedures
  • ✅ Perform SSH security audits and assessments
  • ✅ Troubleshoot common SSH security issues

🎯 What’s Next?

Now you can try:

  • 📚 Implementing certificate-based SSH authentication (SSH CA)
  • 🛠️ Setting up SSH bastion hosts and jump servers
  • 🤝 Integrating SSH with centralized authentication systems (LDAP/AD)
  • 🌟 Exploring advanced SSH tunneling and port forwarding security!

Remember: SSH hardening is essential for server security! You’re now protecting your Alpine Linux systems like a pro! 🎉

Keep securing and you’ll become an SSH security expert! 💫