During a recent red-team engagement for a fintech startup in Bengaluru, I discovered that their primary jump host was susceptible to the 'regreSSHion' vulnerability (CVE-2024-6387). Despite having a perimeter firewall, the SSH daemon was exposed to the public internet to allow remote vendor access. This incident highlights a systemic failure in secure SSH access for teams: the reliance on default configurations in critical infrastructure. We successfully exploited the signal handler race condition in OpenSSH’s server (sshd) to gain unauthenticated remote code execution as root.
The Vulnerability Landscape: Why SSH is the Primary Target
We frequently observe that Indian SMEs and government contractors rely on legacy VPS instances from providers like Netmagic or BSNL Data Centers. These providers often use "Golden Images" that are significantly outdated. When these images are deployed, they carry legacy configurations and unpatched binaries that are trivial to exploit. The regreSSHion vulnerability specifically targets glibc-based Linux systems, making almost every default Ubuntu and Debian installation a high-priority target for automated botnets.
Analyzing CVE-2024-6387: The regreSSHion Risk
The regreSSHion vulnerability is a regression of a bug originally fixed in 2006. It exists because the SSH server's SIGALRM handler calls functions that are not async-signal-safe, such as syslog(). By timing the connection attempt to timeout exactly when the signal handler is executing, an attacker can manipulate the heap and gain root access. In our testing, we found that reducing the LoginGraceTime to 0 or 15 seconds significantly narrows the exploit window, though it does not eliminate the underlying flaw.
The Terrapin Attack and Handshake Manipulation
CVE-2023-48795, known as the Terrapin attack, targets the SSH transport layer. By manipulating sequence numbers during the handshake, an attacker can delete messages from the encrypted stream without the client or server noticing. This allows for the downgrade of connection security by disabling certain extensions like 'keystroke-timing obfuscation'. We recommend enforcing strictly authenticated encryption (AEAD) ciphers to mitigate this.
The Ultimate SSH Hardening Guide: Essential Configuration Steps
Securing sshd_config is the first step in moving toward a Zero-Trust architecture. We start by auditing the current configuration against modern cryptographic standards. I recommend moving away from RSA entirely and adopting Ed25519, which provides better security with smaller key sizes and faster performance.
Disabling Root Login and Password-Based Authentication
The most common entry point for brute-force attacks is the root account. We observed thousands of failed login attempts per hour on servers with PermitRootLogin yes enabled. Password-based authentication is equally dangerous due to credential stuffing and phishing.
# Check for current root login status
grep "PermitRootLogin" /etc/ssh/sshd_config
Disable password auth and root login
sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin no/' /etc/ssh/sshd_config sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
Implementing Robust SSH Key-Based Authentication
When generating keys, we avoid the default RSA 2048-bit keys. Instead, we use Ed25519 with a high iteration count for the Key Derivation Function (KDF) to protect the private key at rest. This makes offline brute-forcing of the passphrase significantly more difficult.
# Generate a high-entropy Ed25519 key
ssh-keygen -t ed25519 -a 100 -C "$(whoami)@$(hostname)-$(date +'%Y-%m-%d')"
Configuring Idle Timeout Intervals and Max Auth Tries
To prevent session hijacking and limit brute-force effectiveness, we must enforce strict timing and retry limits. MaxAuthTries should be set to 3 to disconnect any client that fails multiple times, while ClientAliveInterval ensures that inactive sessions are terminated.
# Edit /etc/ssh/sshd_config
Disconnect after 5 minutes of inactivity
ClientAliveInterval 300 ClientAliveCountMax 0
Limit authentication attempts
MaxAuthTries 3
Restricting User Access via AllowUsers and AllowGroups
By default, SSH allows any user with a valid shell to log in. In a production environment, we implement an allow-list approach. This is particularly important for compliance with India's DPDP Act 2023, which mandates strict access controls for any system handling personal data.
# Only allow specific users or members of the 'sysadmin' group
AllowGroups sysadmin AllowUsers krish_admin deepak_dev
Platform-Specific Best Practices: SSH Hardening for Ubuntu and Debian
Modern distributions have introduced new ways of managing the SSH daemon. Ubuntu 24.04, for instance, has moved toward systemd socket activation for SSH, which changes how we monitor and manage the service.
SSH Hardening in Ubuntu 24.04: New Security Features
Ubuntu 24.04 (Noble Numbat) uses systemd-socket-activated SSH by default. This means sshd is not running constantly; instead, systemd listens on port 22 and spawns a process only when a connection is received. While this saves resources, it requires a different approach for rate-limiting. We must modify the .socket file rather than just the sshd_config for certain networking parameters.
Hardening SSH on Debian Systems: A Step-by-Step Approach
Debian systems often include legacy ciphers for compatibility. We manually prune these to ensure only modern, quantum-resistant (to an extent) algorithms are used. I recommend running the following command to see what your current OpenSSH version supports:
# List supported ciphers and highlight secure ones
ssh -Q cipher | grep -E 'chacha20|poly1305|gcm'
Managing SSH Config Files in Modern Linux Distributions
Instead of modifying the main /etc/ssh/sshd_config directly, we now use the /etc/ssh/sshd_config.d/ directory. This allows for modular configurations that are not overwritten during package updates. We create a 00-hardening.conf file to ensure our settings take precedence.
# Create a modular hardening config
cat < /etc/ssh/sshd_config.d/00-hardening.conf
Enforce modern crypto
KexAlgorithms [email protected] Ciphers [email protected],[email protected] MACs [email protected],[email protected] EOF
Automating Security: SSH Hardening with Ansible and Scripts
Manual configuration is prone to human error. We use Ansible to enforce a consistent security baseline across hundreds of nodes. This ensures that no "shadow" servers are left with default configurations, which is as critical as detecting malicious extensions in the developer workspace.
Streamlining Security with SSH Hardening Ansible Playbooks
Our playbooks are designed to be idempotent. They check the current state of the sshd_config and only apply changes where necessary. This is critical for maintaining uptime in high-traffic environments.
- name: Harden SSH Configuration
hosts: all become: yes tasks: - name: Disable password authentication lineinfile: path: /etc/ssh/sshd_config regexp: '^PasswordAuthentication' line: 'PasswordAuthentication no' state: present - name: Disable root login lineinfile: path: /etc/ssh/sshd_config regexp: '^PermitRootLogin' line: 'PermitRootLogin no' state: present - name: Restart SSH service systemd: name: ssh state: restarted
Using an SSH Hardening Script for Rapid Deployment
For standalone servers or during initial provisioning, a bash script is more efficient. I use a script that not only configures sshd but also sets up basic firewall rules using ufw to limit SSH access to known IP ranges (e.g., the corporate VPN).
#!/bin/bash
Rapid SSH Hardening Script
set -e
Backup original config
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
Apply hardening settings
echo "Protocol 2" >> /etc/ssh/sshd_config echo "IgnoreRhosts yes" >> /etc/ssh/sshd_config echo "HostbasedAuthentication no" >> /etc/ssh/sshd_config echo "Banner /etc/issue.net" >> /etc/ssh/sshd_config
Set banner for legal compliance (DPDP Act)
echo "Authorized Access Only. All activities are logged." > /etc/issue.net
systemctl restart ssh echo "SSH Hardening Applied Successfully."
Top-Rated SSH Hardening Resources on GitHub
We frequently leverage community-vetted resources to stay updated. Projects like ssh-audit and the DevSec SSH Hardening Role are essential tools in our kit. We recommend integrating these into your CI/CD pipeline to test infrastructure code before deployment.
Validation and Compliance: Running an SSH Hardening Test
Configuration is only half the battle; validation is where we prove the security posture. We use ssh-audit to identify weak key exchange algorithms and outdated ciphers that might have been missed.
How to Perform a Comprehensive SSH Hardening Test
We start by running a remote scan against the target IP. This identifies the SSH version and the available algorithms without requiring local access.
# Install ssh-audit
pip3 install ssh-audit
Run a hardening audit against a server
ssh-audit --policy hardened 192.168.1.105
Auditing Your Configuration with Open-Source Security Tools
The output of ssh-audit provides a clear "Pass/Fail" for each algorithm. Any algorithm marked in red (like diffie-hellman-group1-sha1 or arcfour) must be disabled immediately. We also check for information leakage in the SSH banner, which can reveal the OS version to attackers.
Continuous Monitoring for SSH Configuration Drift
Configuration drift occurs when manual changes are made to a server after deployment. We use tools like Aide or Tripwire to monitor /etc/ssh/sshd_config for unauthorized changes. In an Indian context, where multiple outsourced vendors might have access, this monitoring is vital for accountability.
Advanced SSH Security Techniques
For high-security environments, standard hardening is not enough. We implement Zero-Trust principles by requiring multiple factors of authentication and moving away from static keys.
Implementing Multi-Factor Authentication (MFA) for SSH
We enforce MFA by combining SSH keys with Time-based One-Time Passwords (TOTP). This ensures that even if a developer's private key is stolen, the attacker cannot gain access without the TOTP code from a physical device.
# Install the Google Authenticator PAM module
sudo apt-get install libpam-google-authenticator
Configure /etc/pam.d/sshd
Add this line at the top
auth required pam_google_authenticator.so
In sshd_config, we must enable the challenge-response system to support PAM-based MFA:
# Enforce both Public Key AND TOTP
AuthenticationMethods publickey,keyboard-interactive KbdInteractiveAuthentication yes UsePAM yes
Using SSH Certificates for Enterprise-Level Access Control
Static SSH keys are a liability. In large Indian organizations, we see keys being shared via WhatsApp or stored in plain text on local machines. SSH Certificates solve this by using a Certificate Authority (CA) to sign short-lived keys. We use HashiCorp Vault or Smallstep to issue certificates that expire after 8 hours.
Setting up Fail2Ban to Prevent Brute Force Attacks
Fail2Ban monitors /var/log/auth.log for repeated failed attempts and dynamically updates firewall rules to ban the offending IP. This is a critical layer of defense against the constant background noise of internet-wide scans.
# Basic Fail2Ban jail for SSH
[sshd] enabled = true port = ssh filter = sshd logpath = /var/log/auth.log maxretry = 3 bantime = 3600
Zero-Trust and the DPDP Act 2023 Compliance
The Digital Personal Data Protection Act 2023 requires data fiduciaries to implement "reasonable security safeguards" to prevent personal data breaches. From a technical perspective, this means ensuring that every administrative access to a server is authenticated, authorized, and logged via a robust SIEM solution.
Non-Repudiation and Logging
By disabling shared accounts and enforcing AuthenticationMethods publickey,keyboard-interactive, we ensure non-repudiation. Every action taken on the server can be traced back to a specific individual. We also redirect SSH logs to a centralized, write-only logging server to prevent attackers from clearing their tracks.
# Increase logging verbosity in sshd_config
LogLevel VERBOSE
Preventing Lateral Movement
Attackers often use compromised SSH sessions to move laterally through a network. We disable features like X11 forwarding and agent forwarding unless they are specifically required for a task. Agent forwarding is particularly dangerous as it allows an attacker with root access on a remote host to use your local SSH agent to authenticate to other servers.
# Disable forwarding in /etc/ssh/sshd_config
X11Forwarding no AllowAgentForwarding no PermitTunnel no
Final Technical Observations
During our tests, we observed that many administrators forget to clean up the ~/.ssh/authorized_keys file. Old keys from former employees or decommissioned CI/CD runners often remain, providing a permanent "backdoor" into the system. We recommend a "Key Rotation Policy" where keys are replaced every 90 days, or better yet, moving entirely to the SSH Certificate model described above.
Technically, the most secure SSH configuration is one that minimizes the attack surface by restricting not just who can connect, but how they connect and what they can do once connected. The transition from legacy RSA/Password auth to Ed25519/MFA is not just a best practice; it is a fundamental requirement for modern infrastructure security.
# Final check: Test configuration for syntax errors before restarting
sshd -t
If sshd -t returns no output, the configuration is syntactically correct. We then apply the changes and monitor the logs for any legitimate users being blocked by the new, stricter policies.
Next Command: ssh -O check -S /tmp/ssh-session-socket user@host to verify the multiplexing and security state of your active control master sessions.
