OpsSquad.ai
Blog/Security/·33 min read
Security

Secure SSH Port: Beyond Default 22 in 2026

Learn to secure your SSH port beyond default 22 in 2026. Manually harden SSH, then automate with OpsSqad's Security Squad for robust remote access.

Adir Semana

Founder of OpsSqaad.ai. Your AI on-call engineer — it connects to your servers, learns how they run, and helps your team resolve issues faster every time.

Share
Secure SSH Port: Beyond Default 22 in 2026

Secure SSH Port: Beyond Default 22 for Robust Remote Access in 2026

As remote work and distributed infrastructure become the norm in 2026, securing access to our servers is paramount. While SSH (Secure Shell) is the de facto standard for secure remote command-line access, its default configuration, particularly the use of port 22, presents a significant attack surface. This article delves into the critical practices for securing your SSH port, moving beyond basic configurations to implement a truly robust remote access strategy. We'll explore why changing the default port is just the first step, the importance of strong authentication, effective key management, network segmentation, and how modern platforms can simplify these complex security measures.

Key Takeaways

  • SSH port 22 receives millions of automated attack attempts daily, making it the most targeted service port in 2026.
  • Changing your SSH port to a non-standard number reduces automated attacks by up to 99%, though it's not a complete security solution.
  • Key-based authentication is exponentially more secure than passwords, with modern 4096-bit RSA keys being effectively unbreakable by brute-force.
  • Disabling root login and implementing fail2ban can prevent the majority of successful SSH compromises.
  • Bastion hosts provide centralized access control and reduce your attack surface by keeping internal servers off the public internet.
  • Modern reverse TCP architectures eliminate the need for inbound firewall rules entirely, fundamentally changing the security model.
  • Comprehensive audit logging is essential for compliance and incident response, capturing every command executed via SSH.

The Persistent Threat: Why SSH Port 22 is a Target

SSH port 22, designated by IANA and historically championed by figures like Jon Postel, has been the default for decades. This ubiquity, however, makes it a prime target for automated attacks. Brute-force attempts, credential stuffing, and vulnerability scanning are constantly directed at this well-known port. Understanding why it's a target is the first step in mitigating the risk.

The History and Ubiquity of SSH Port 22

The story of how SSH acquired port 22 is rooted in the early days of internet standardization. In 1995, when Tatu Ylönen developed SSH as a secure replacement for Telnet and rlogin, he needed an official port number assignment from IANA (Internet Assigned Numbers Authority). Jon Postel, who managed port assignments at the time, assigned port 22 to SSH, displacing an earlier, rarely-used protocol.

This assignment made port 22 the universal standard for SSH connections across all Unix-like systems, Windows servers, network devices, and embedded systems. By 2026, billions of devices worldwide listen on port 22 by default, creating a massive, predictable target for attackers.

The "open door" analogy perfectly captures the security implication: when every house on the street has its front door in the exact same location, burglars know exactly where to try the handle. Attackers don't need to scan for SSH services—they know port 22 will be SSH if it's open. This predictability enables mass-scale automated attacks that would be impractical if services were randomly distributed across port ranges.

Automated attack vectors specifically targeting port 22 have evolved into sophisticated, distributed campaigns. Brute-force login attempts systematically try common username/password combinations like root/password, admin/admin, or ubuntu/ubuntu. Dictionary attacks use wordlists containing millions of leaked passwords from previous breaches. Credential stuffing takes username/password pairs from one compromised service and tries them against SSH servers, exploiting the reality that many users reuse credentials.

Drive-by hacking and botnets represent the most persistent threat to SSH port 22 in 2026. Automated scripts continuously scan entire IP ranges, attempting to connect to port 22 on every address. When they find an open port, they immediately begin authentication attempts. A typical internet-facing server on port 22 receives hundreds to thousands of login attempts per day from these automated systems. Compromised IoT devices, servers, and home routers form botnets that distribute these attacks, making IP-based blocking increasingly ineffective.

Understanding the Risks of Default Configuration

Increased visibility is the fundamental problem with default port 22. Network scanners like Masscan can sweep the entire IPv4 address space in under six minutes, identifying every server listening on port 22. This means your server is cataloged in attacker databases within hours of being connected to the internet, regardless of whether you've advertised its existence.

The higher volume of attacks on port 22 creates operational challenges beyond security concerns. Server resources are consumed processing authentication attempts, even failed ones. System logs fill with thousands of failed login entries, creating noise that obscures legitimate security events. In extreme cases, the sheer volume of connection attempts can impact server performance or trigger rate limits that affect legitimate users.

Exploiting known vulnerabilities becomes easier when attackers know exactly which service is running on a port. When a new SSH vulnerability is disclosed, attackers immediately begin scanning port 22 across the internet for vulnerable versions. The 2016 OpenSSH vulnerability (CVE-2016-0777) and the 2018 username enumeration issue (CVE-2018-15473) were both exploited within hours of public disclosure, with attackers specifically targeting port 22.

Beyond Port 22: Strategic SSH Port Management

While changing the SSH port is a common recommendation, it's crucial to understand its limitations and how to implement it effectively. This section explores the practicalities of port modification and the considerations for choosing a new port.

The Benefits and Drawbacks of Changing the SSH Port

Deflecting automated scans is the immediate benefit of moving SSH to a non-standard port. Mass scanning operations typically target only the most common ports to maximize efficiency. By moving to port 2222, 2200, or any non-standard port above 1024, you immediately drop off the radar of 99% of automated attacks. Your SSH logs will transform from thousands of daily failed attempts to perhaps a handful per week.

Reducing noise in logs has practical operational value. When your auth.log isn't filled with failed root login attempts from Chinese IP addresses, you can actually spot the legitimate security concern: that unusual login from a new IP address at 3 AM, or the failed authentication from an account that should be using key-based auth. Clean logs enable effective security monitoring.

The "security through obscurity" debate is worth addressing directly. Changing your SSH port is obscurity, not security. A determined attacker who specifically targets your server will run a full port scan and find SSH regardless of which port it's on. However, this misses the point: you're not trying to hide from targeted attacks—you're eliminating the constant background radiation of automated attacks that waste resources and create opportunities for exploitation.

Potential for misconfiguration is a real risk when changing ports. Choosing a port that conflicts with another service can create connectivity issues. Selecting a port in the well-known range (1-1023) may require root privileges for the SSH daemon and could conflict with standard services. Choosing a port that's commonly scanned (like 8080 or 3389) reduces the effectiveness of the change.

Choosing and Implementing a New SSH Port

Selecting a non-standard port requires balancing obscurity with practicality. The port range from 1024 to 49151 represents "registered ports" that are less likely to conflict with system services but aren't in the ephemeral range used by client connections.

Range considerations should guide your selection. Ports above 1024 don't require root privileges for binding, simplifying configuration. Ports below 49151 avoid the dynamic/private range that operating systems use for outbound connections. Avoid commonly used application ports: 8080 (HTTP alternate), 8443 (HTTPS alternate), 3306 (MySQL), 5432 (PostgreSQL), 6379 (Redis), and 27017 (MongoDB).

Good choices for SSH ports include: 2222 (easy to remember, commonly used for SSH alternate), 2200-2299 (SSH-related range), 22000-22999 (clearly SSH-related but obscure), or any random port between 10000-40000 that doesn't conflict with your other services.

IANA and reserved ports should be checked before finalizing your choice. While you're unlikely to run into conflicts with officially registered ports in practice, checking the IANA registry can prevent future issues. Avoid ports officially assigned to common protocols.

Modifying the SSH daemon configuration requires editing the sshd_config file. This file controls all aspects of the SSH server's behavior, including which port it listens on.

Locating the configuration file is straightforward on most systems:

# On most Linux distributions
ls -l /etc/ssh/sshd_config
 
# Verify the file exists and check permissions
-rw-r--r-- 1 root root 3289 Jan 15 10:23 /etc/ssh/sshd_config

Editing the Port directive involves uncommenting and modifying a single line:

# Open the configuration file with your preferred editor
sudo nano /etc/ssh/sshd_config
 
# Find the line that reads:
# Port 22
 
# Change it to your chosen port (removing the # comment):
Port 2222
 
# Save and exit (Ctrl+X, then Y, then Enter in nano)

Warning: Before restarting SSH, ensure you have a backup access method (console access via your hosting provider, or a second active SSH session) to avoid locking yourself out if something goes wrong.

Restarting the SSH service applies your configuration changes:

# For systemd-based systems (Ubuntu 16.04+, Debian 8+, CentOS 7+, RHEL 7+)
sudo systemctl restart sshd
 
# Verify the service restarted successfully
sudo systemctl status sshd
 
# For older init-based systems
sudo service ssh restart
 
# Verify SSH is listening on the new port
sudo ss -tlnp | grep sshd

Expected output showing SSH listening on port 2222:

LISTEN 0      128          0.0.0.0:2222       0.0.0.0:*    users:(("sshd",pid=1234,fd=3))
LISTEN 0      128             [::]:2222          [::]:*    users:(("sshd",pid=1234,fd=4))

Specifying the SSH port on the command line requires the -p flag:

# Connecting to a server with SSH on port 2222
ssh username@your_server_ip -p 2222
 
# Example with actual values
ssh [email protected] -p 2222

Configuring SSH client via ~/.ssh/config eliminates the need to specify the port every time:

# Edit or create your SSH config file
nano ~/.ssh/config
 
# Add an entry for your server
Host my-secure-server
    Hostname 192.168.1.100
    User admin
    Port 2222
    IdentityFile ~/.ssh/id_rsa
 
# Now you can simply connect with:
ssh my-secure-server

This configuration accepts all standard SSH config directives, allowing you to customize connection behavior, specify keys, set connection timeouts, and configure proxy commands.

Securing SSH Access Through Firewalls

The role of firewalls in SSH security cannot be overstated. Firewalls act as gatekeepers, controlling which network traffic reaches your SSH daemon. Even with a changed port and strong authentication, an improperly configured firewall can expose your server to unnecessary risk.

Configuring firewall rules with iptables provides fine-grained control over SSH access:

# Allow incoming connections on your custom SSH port
sudo iptables -A INPUT -p tcp --dport 2222 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -p tcp --sport 2222 -m conntrack --ctstate ESTABLISHED -j ACCEPT
 
# Block the default SSH port to prevent confusion
sudo iptables -A INPUT -p tcp --dport 22 -j DROP
 
# Optionally, restrict SSH access to specific IP addresses
sudo iptables -A INPUT -p tcp -s 203.0.113.0/24 --dport 2222 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 2222 -j DROP

Saving iptables rules ensures they persist across reboots:

# On Ubuntu/Debian systems
sudo apt install iptables-persistent
sudo netfilter-persistent save
 
# On CentOS/RHEL systems
sudo service iptables save
 
# Alternatively, use iptables-save to export rules
sudo iptables-save > /etc/iptables/rules.v4

Pro tip: Always test firewall changes from a separate, active SSH session. Keep one session open while you make changes in another. If you lock yourself out, the existing session remains active and allows you to fix the problem. Set a cronjob to automatically flush firewall rules after 5 minutes as a safety net during testing:

# Create a temporary safety net
echo "sudo iptables -F" | at now + 5 minutes
 
# Make your firewall changes
# If successful, cancel the scheduled flush
atrm <job_number>

For servers using UFW (Uncomplicated Firewall), the process is more straightforward:

# Allow the new SSH port
sudo ufw allow 2222/tcp
 
# Deny the default SSH port
sudo ufw deny 22/tcp
 
# Enable UFW if not already active
sudo ufw enable
 
# Check status
sudo ufw status verbose

Enforcing Strong Authentication: The Core of SSH Security

Changing the port is a superficial fix if authentication remains weak. Strong authentication is the foundation of SSH security—without it, all other measures are merely speed bumps for determined attackers.

The Dangers of Password Authentication and Root Login

Password vulnerabilities represent the weakest link in most SSH configurations. Passwords are inherently limited by human memory, leading users to choose memorable (and therefore guessable) combinations. The average password in 2026 can be cracked in seconds using modern GPU-based cracking tools. Rainbow tables containing billions of pre-computed password hashes make dictionary attacks trivial.

Even "strong" passwords face systematic attacks. An 8-character password with mixed case, numbers, and symbols has approximately 6 quadrillion combinations—which sounds secure until you realize that modern cracking rigs can test billions of combinations per second. A password that would take years to crack via brute force in 2010 now falls in hours or days.

Disabling root login is one of the most critical SSH security measures. Direct root access via SSH means a successful authentication gives an attacker complete, unrestricted control over your system. There's no audit trail of privilege escalation, no opportunity for sudo logging, and no chance to implement command restrictions.

Modifying sshd_config to disable root login:

# Edit the SSH daemon configuration
sudo nano /etc/ssh/sshd_config
 
# Find and modify these directives:
PermitRootLogin no
 
# Also disable password authentication entirely (after setting up keys)
PasswordAuthentication no
 
# Disable empty passwords
PermitEmptyPasswords no
 
# Restart SSH to apply changes
sudo systemctl restart sshd

Guessable usernames compound password security problems. Using common usernames like admin, administrator, user, or ubuntu makes brute-force attacks significantly easier. Attackers don't need to guess both username and password—they can focus all their attempts on common usernames. Create non-obvious usernames for administrative accounts, and consider implementing AllowUsers or AllowGroups directives in sshd_config to explicitly whitelist permitted accounts.

The Power of SSH Key-Based Authentication

How SSH keys work is based on public-key cryptography, specifically asymmetric encryption. You generate a key pair: a private key that remains on your client machine (never shared) and a public key that you copy to servers you want to access. When you connect, the server uses your public key to create a challenge that only your private key can solve, proving your identity without transmitting any secret information over the network.

Benefits of key-based authentication are substantial. Modern SSH keys use 4096-bit RSA or Ed25519 cryptography, creating keys with computational complexity that makes brute-force attacks infeasible with current or foreseeable technology. A 4096-bit RSA key would take longer than the age of the universe to crack using all computing power on Earth.

Convenience is another major advantage. Once configured, SSH keys provide passwordless authentication—you connect without typing credentials. For servers you access frequently, this saves significant time. For automated processes, scripts, and CI/CD pipelines, key-based authentication is essential for secure automation.

Generating SSH key pairs with modern algorithms:

# Generate a 4096-bit RSA key pair (widely compatible)
ssh-keygen -t rsa -b 4096 -C "[email protected]"
 
# Or generate an Ed25519 key (more secure, smaller, faster)
ssh-keygen -t ed25519 -C "[email protected]"
 
# You'll be prompted for a file location (default is fine):
# Enter file in which to save the key (/home/username/.ssh/id_rsa):
 
# Enter a strong passphrase (highly recommended):
# Enter passphrase (empty for no passphrase):

Expected output:

Generating public/private rsa key pair.
Your identification has been saved in /home/username/.ssh/id_rsa
Your public key has been saved in /home/username/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:abc123def456ghi789jkl012mno345pqr678stu901vwx234yz [email protected]
The key's randomart image is:
+---[RSA 4096]----+
|    .o+*B=.      |
|     +=oB+       |
|    . .=+o       |
|       ==        |
|      o S        |
|     . = .       |
|      = o        |
|       o         |
|                 |
+----[SHA256]-----+

Deploying public keys to the server can be done automatically or manually:

# Automatic deployment using ssh-copy-id (requires password auth initially)
ssh-copy-id -p 2222 username@your_server_ip
 
# You'll be prompted for your password one last time
# The tool will copy your public key to ~/.ssh/authorized_keys on the server
 
# Manual deployment (if ssh-copy-id isn't available)
# First, display your public key
cat ~/.ssh/id_rsa.pub
 
# Copy the output, then SSH to your server and add it:
mkdir -p ~/.ssh
chmod 700 ~/.ssh
echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC..." >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

Securing your private key with a strong passphrase adds a critical layer of protection. If your laptop is stolen or your workstation is compromised, the private key file alone is useless without the passphrase. Use a passphrase of at least 20 characters, or better yet, a passphrase generated by a password manager.

# If you generated a key without a passphrase, you can add one:
ssh-keygen -p -f ~/.ssh/id_rsa
 
# You'll be prompted to enter the old passphrase (press Enter if none)
# Then enter your new passphrase twice

Implementing Two-Factor Authentication (2FA)

Adding an extra layer of security through two-factor authentication means even if an attacker obtains your private key and passphrase, they still cannot access your server without the second factor—typically a time-based one-time password (TOTP) from an authenticator app.

Integrating 2FA with SSH requires the Google Authenticator PAM module (despite the name, it works with any TOTP app):

# Install the Google Authenticator PAM module
# On Ubuntu/Debian:
sudo apt update
sudo apt install libpam-google-authenticator
 
# On CentOS/RHEL:
sudo yum install google-authenticator
 
# Run the setup as the user who will be logging in
google-authenticator
 
# Answer the prompts:
# Do you want authentication tokens to be time-based? (y/n) y
# Scan the QR code with your authenticator app
# Do you want me to update your "/home/username/.google_authenticator" file? (y/n) y
# Do you want to disallow multiple uses of the same token? (y/n) y
# Do you want to increase the time window? (y/n) n
# Do you want to enable rate-limiting? (y/n) y

Configure PAM to require the authenticator:

# Edit the SSH PAM configuration
sudo nano /etc/pam.d/sshd
 
# Add this line at the top of the file:
auth required pam_google_authenticator.so
 
# Edit sshd_config to enable challenge-response
sudo nano /etc/ssh/sshd_config
 
# Set these directives:
ChallengeResponseAuthentication yes
UsePAM yes
 
# Restart SSH
sudo systemctl restart sshd

Warning: When enabling 2FA, ensure you have an active SSH session open until you've verified that 2FA works correctly. Test logging in from a new session before closing your existing connection.

Advanced SSH Security: Bastion Hosts, Tunneling, and Auditing

Moving beyond basic configurations, implementing advanced security architectures provides defense-in-depth for critical infrastructure.

Understanding and Implementing SSH Bastion Hosts

The bastion host concept, also called a jump server or jump box, is a hardened server that acts as a single point of entry for accessing internal networks. Instead of exposing every server to the internet, only the bastion host accepts external SSH connections. All other servers accept SSH only from the bastion's internal IP address.

Benefits of a bastion host architecture are significant. Centralized access control means you configure, monitor, and audit SSH access in one place. Reduced attack surface keeps internal servers completely off the public internet—they don't need public IP addresses or open firewall ports. Enhanced monitoring and auditing becomes practical when all access flows through a single, heavily monitored system.

Securing the bastion host itself is critical since it becomes a high-value target. Implement all security measures discussed in this article: non-standard SSH port, key-based authentication only, 2FA, fail2ban, and restrictive firewall rules. Additionally, run only essential services—disable everything except SSH. Use a minimal OS installation. Enable comprehensive logging with log forwarding to a separate system. Implement automated security updates. Consider using a dedicated security-hardened OS distribution.

Connecting through a bastion requires SSH agent forwarding or ProxyJump:

# Using SSH agent forwarding (older method)
# First, add your key to the SSH agent on your local machine
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa
 
# Connect to the bastion with agent forwarding enabled
ssh -A username@bastion_ip -p 2222
 
# From the bastion, connect to internal servers
# Your key is forwarded, so no password is needed
ssh [email protected]
 
# Using ProxyJump (modern, more secure method)
# Connect directly to internal server via bastion in one command
ssh -J username@bastion_ip:2222 [email protected]
 
# Configure this permanently in ~/.ssh/config:
Host internal-server
    Hostname 10.0.1.50
    User internal_user
    ProxyJump username@bastion_ip:2222

Note: Agent forwarding (-A) has security implications. If the bastion host is compromised while you're connected, an attacker could use your forwarded agent to authenticate to other servers. ProxyJump is more secure as it doesn't forward your agent—it simply tunnels your connection through the bastion.

Securing SSH Tunneling and Port Forwarding

SSH tunneling explained: SSH can create encrypted tunnels for other network traffic, forwarding ports from your local machine to remote servers (local forwarding), from remote servers to your local machine (remote forwarding), or creating a SOCKS proxy for dynamic application-level forwarding.

Security risks of tunneling are often underestimated. Misconfigured tunnels can expose internal services to the internet, creating backdoors into your network. An attacker who compromises an account with forwarding privileges can tunnel malicious traffic through your infrastructure, bypassing firewall rules and security monitoring.

Mitigation strategies for tunnel security:

# Restrict forwarding in sshd_config if not needed
sudo nano /etc/ssh/sshd_config
 
# Disable all forwarding for maximum security
AllowTcpForwarding no
X11Forwarding no
AllowStreamLocalForwarding no
GatewayPorts no
 
# Or allow forwarding only for specific users/groups
Match User developer
    AllowTcpForwarding yes
    
Match User admin
    AllowTcpForwarding no

Binding to specific interfaces prevents unintended exposure:

# When creating a local forward, bind to localhost only
ssh -L 127.0.0.1:8080:internal_server:80 user@bastion
 
# This makes port 8080 available only on your local machine
# NOT accessible from other machines on your network

Auditing tunnel usage requires monitoring SSH logs for forwarding activities:

# Enable verbose logging in sshd_config
LogLevel VERBOSE
 
# Monitor for forwarding in logs
sudo grep -i "forwarding" /var/log/auth.log
 
# Example log entries showing tunnel creation:
# Accepted publickey for user from 203.0.113.50 port 54321 ssh2
# Accepted forwarding request for 127.0.0.1:8080

Monitoring and Auditing SSH Activities

The importance of logging cannot be overstated for security, compliance, and incident response. Comprehensive SSH logging captures successful logins, failed login attempts, user activity, and command execution. This audit trail is essential for detecting breaches, investigating incidents, and meeting regulatory requirements like SOC 2, PCI DSS, or HIPAA.

Key information to log includes authentication attempts (successful and failed), source IP addresses, usernames attempted, public keys used, session duration, port forwarding requests, and ideally, commands executed during sessions.

Tools for monitoring and auditing SSH activities:

auth.log and secure.log are the primary SSH log files on Linux systems:

# On Ubuntu/Debian systems
sudo tail -f /var/log/auth.log
 
# On CentOS/RHEL systems
sudo tail -f /var/log/secure
 
# Search for failed login attempts
sudo grep "Failed password" /var/log/auth.log
 
# Search for successful logins
sudo grep "Accepted publickey" /var/log/auth.log
 
# Find login attempts from a specific IP
sudo grep "203.0.113.50" /var/log/auth.log

fail2ban automatically monitors log files for malicious patterns and updates firewall rules to block offending IP addresses:

# Install fail2ban
# On Ubuntu/Debian:
sudo apt update
sudo apt install fail2ban
 
# On CentOS/RHEL:
sudo yum install epel-release
sudo yum install fail2ban
 
# Create a local configuration file (don't edit jail.conf directly)
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local
 
# Configure the SSH jail for your custom port:
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
findtime = 600
bantime = 3600
 
# Start and enable fail2ban
sudo systemctl start fail2ban
sudo systemctl enable fail2ban
 
# Check status and banned IPs
sudo fail2ban-client status sshd

Expected output from fail2ban-client status sshd:

Status for the jail: sshd
|- Filter
|  |- Currently failed: 2
|  |- Total failed:     47
|  `- File list:        /var/log/auth.log
`- Actions
   |- Currently banned: 5
   |- Total banned:     23
   `- Banned IP list:   203.0.113.45 198.51.100.23 192.0.2.67 198.51.100.89 203.0.113.12

Centralized logging sends SSH logs to a Security Information and Event Management (SIEM) system or centralized log server for correlation with other security events, long-term retention, and advanced analytics:

# Example: Configure rsyslog to forward auth logs to a remote server
sudo nano /etc/rsyslog.d/50-default.conf
 
# Add this line to forward auth logs
auth,authpriv.* @@log-server.example.com:514
 
# Restart rsyslog
sudo systemctl restart rsyslog

Addressing Content Gaps: Deeper Dives into SSH Security

Understanding SSH security requires going beyond basic configuration to examine specific vulnerabilities and alternative approaches.

Beyond Port Changes: Deep Dive into SSH Vulnerabilities and Exploits

Specific CVEs and exploits demonstrate why keeping SSH updated is critical. CVE-2016-0777 and CVE-2016-0778 affected OpenSSH versions 5.4 through 7.1, allowing information disclosure and potential buffer overflow. Attackers could exploit these vulnerabilities to leak private key information or execute arbitrary code. CVE-2018-15473 allowed username enumeration, letting attackers determine valid usernames without authentication—significantly reducing the search space for brute-force attacks.

More recently, CVE-2023-38408 in OpenSSH 9.3 allowed remote code execution under specific conditions. While SSH itself is generally secure, vulnerabilities do occur, and internet-facing SSH servers are immediately targeted when new CVEs are disclosed.

Cipher suite weaknesses can undermine SSH security even with strong authentication. Older cipher suites like arcfour, CBC-mode ciphers, and MD5-based MACs have known weaknesses. Modern SSH configurations should use only strong, current algorithms.

Configuring strong ciphers and MACs in sshd_config:

sudo nano /etc/ssh/sshd_config
 
# Add or modify these directives to use only modern, secure algorithms:
 
# Ciphers (encryption algorithms)
Ciphers [email protected],[email protected],[email protected],aes256-ctr,aes192-ctr,aes128-ctr
 
# MACs (message authentication codes)
MACs [email protected],[email protected],hmac-sha2-512,hmac-sha2-256
 
# Key exchange algorithms
KexAlgorithms curve25519-sha256,[email protected],diffie-hellman-group-exchange-sha256
 
# Host key algorithms
HostKeyAlgorithms ssh-ed25519,rsa-sha2-512,rsa-sha2-256
 
# Restart SSH to apply
sudo systemctl restart sshd

Note: Before implementing restrictive cipher configurations, verify that your SSH clients support these algorithms. Very old clients may not be able to connect.

SSH client security is often overlooked. A compromised client machine can expose private keys, capture passphrases via keyloggers, or be used to pivot into your infrastructure. Secure your SSH clients by storing private keys on encrypted drives, using hardware security keys (like YubiKey) for authentication, keeping client software updated, using dedicated bastion/jump hosts rather than connecting directly from workstations, and implementing endpoint detection and response (EDR) solutions.

Exploring Alternative Secure Remote Access Methods

Tailscale SSH represents a modern approach to secure remote access, using WireGuard-based mesh networking to create encrypted peer-to-peer connections without exposing SSH ports to the internet. Each machine runs the Tailscale client, joining a private network where SSH connections flow through encrypted WireGuard tunnels. This eliminates the need for port forwarding, dynamic DNS, or VPN servers.

Zero Trust Network Access (ZTNA) fundamentally changes the security model from "trust but verify" to "never trust, always verify." Instead of granting network access based on location (inside or outside the firewall), ZTNA authenticates and authorizes every connection based on identity, device posture, and context. Users and services are never trusted by default, regardless of network location.

Managed SSH gateways like Teleport, Boundary, or StrongDM provide centralized SSH access with advanced features: single sign-on (SSO) integration, session recording, just-in-time access provisioning, granular role-based access control, and comprehensive audit logging. These solutions are particularly valuable for enterprises with compliance requirements or complex multi-cloud environments.

Skip the Manual Work: How OpsSqad's Security Squad Solves This For You

Managing SSH security across a fleet of servers is time-consuming and error-prone. Between changing ports, deploying keys, configuring fail2ban, hardening sshd_config, and maintaining audit logs, a typical server hardening process consumes 15-30 minutes per server—and that's assuming you don't make mistakes that require troubleshooting.

OpsSqad's AI-powered platform with its dedicated Security Squad automates these complex security tasks, allowing you to harden SSH configurations across your entire infrastructure via simple chat commands. No more SSHing into each server, editing configuration files, and hoping you didn't break anything.

The OpsSqad Approach to Secure Remote Access

OpsSqad's reverse TCP architecture fundamentally changes the remote access security model. Instead of opening inbound firewall ports (creating attack surface), you install a lightweight node on your server that establishes a secure, outbound connection to the OpsSqad cloud. This means your server never accepts inbound connections—it only makes outbound connections to OpsSqad's infrastructure.

AI agents organized into specialized Squads (like the Security Squad) execute commands remotely through a chat interface. Every command runs through a whitelisting system—only pre-approved, safe commands can execute. Commands run in a sandboxed environment with comprehensive audit logging, capturing every action for compliance and incident response.

Your 5-Step Journey to Simplified SSH Security with OpsSqad

Step 1: Create Your Free Account and Deploy a Node

Visit app.opssquad.ai and sign up for a free account. Navigate to the "Nodes" section in the dashboard and create a new node with a descriptive name like "production-web-01". The dashboard will generate a unique Node ID and authentication token.

SSH to your server and install the OpsSqad agent:

# Download and run the installation script
curl -fsSL https://install.opssquad.ai/install.sh | bash
 
# Install the node using credentials from your dashboard
opssquad node install --node-id=node_abc123xyz --token=tok_def456uvw
 
# Start the node (establishes reverse TCP connection)
opssquad node start

The node establishes an outbound connection to OpsSqad cloud. Your firewall requires no inbound rule changes—the connection is entirely outbound.

Step 2: Deploy the Security Squad

In the OpsSqad dashboard, navigate to the Squad Marketplace. Browse available Squads and select "Security Squad." Click "Deploy Squad" to create a private instance with all security-focused agents pre-configured and ready to execute security hardening tasks.

Step 3: Link Agents to Your Nodes

Open your deployed Security Squad and navigate to the "Agents" tab. Select the agents you want to grant access to your infrastructure. Choose the nodes each agent can interact with—this grants permission for agents to execute whitelisted commands on your servers. This granular permission model ensures agents only access what they need.

Step 4: Secure Your SSH Port via Chat

Navigate to chat.opssquad.ai and select your Security Squad. Start a conversation with the AI agents:

You: "Security Squad, I need to harden SSH on production-web-01. Change the SSH port to 2222, disable root login, disable password authentication, and configure fail2ban to protect the new port."

Security Squad: "I'll help you secure SSH on production-web-01. Let me execute these tasks:

1. Backing up current sshd_config
2. Changing SSH port to 2222
3. Disabling root login (PermitRootLogin no)
4. Disabling password authentication (PasswordAuthentication no)
5. Installing and configuring fail2ban for port 2222
6. Restarting SSH service

Executing commands...

✓ Backup created: /etc/ssh/sshd_config.backup.2026-03-06
✓ SSH port changed to 2222
✓ Root login disabled
✓ Password authentication disabled
✓ fail2ban installed and configured for port 2222
✓ SSH service restarted successfully
✓ SSH is listening on port 2222 (verified with ss -tlnp)

SSH hardening complete. Your server is now significantly more secure. 
Remember to update your SSH client configuration to use port 2222."

You: "Great! Can you also review the current cipher configuration and update it to use only modern, secure algorithms?"

Security Squad: "Analyzing current cipher configuration on production-web-01...

Current configuration uses some weak ciphers. I'll update to modern algorithms:

✓ Updated Ciphers directive to: [email protected],[email protected],aes256-ctr
✓ Updated MACs directive to: [email protected],[email protected]
✓ Updated KexAlgorithms to: curve25519-sha256,diffie-hellman-group-exchange-sha256
✓ SSH service restarted

Configuration updated. All weak ciphers removed."

Step 5: Automate Key Management and Ongoing Auditing

The Security Squad can handle ongoing security tasks:

You: "Generate a new SSH key pair for the admin user and deploy it to production-web-01 and production-web-02."

Security Squad: "Generating 4096-bit RSA key pair...

✓ Key pair generated
✓ Public key deployed to production-web-01 (~/.ssh/authorized_keys)
✓ Public key deployed to production-web-02 (~/.ssh/authorized_keys)
✓ Permissions set correctly (600 on authorized_keys, 700 on .ssh)

Private key (keep secure):
[displays private key for you to save securely]

You can now authenticate to both servers using this key pair."

You: "Check SSH logs on all production servers for failed login attempts in the last 24 hours."

Security Squad: "Analyzing SSH logs across 5 production nodes...

production-web-01: 127 failed attempts (87 unique IPs)
production-web-02: 94 failed attempts (62 unique IPs)
production-web-03: 203 failed attempts (143 unique IPs)
production-db-01: 45 failed attempts (31 unique IPs)
production-db-02: 38 failed attempts (24 unique IPs)

Top attacking IPs:
- 203.0.113.45: 47 attempts across 3 servers
- 198.51.100.67: 32 attempts across 2 servers
- 192.0.2.89: 28 attempts across 4 servers

Would you like me to add these IPs to fail2ban's permanent ban list?"

The OpsSqad Advantage

No Inbound Firewall Changes: The reverse TCP architecture means you never open inbound ports. Your servers connect outbound to OpsSqad, eliminating the most common attack vector.

Whitelisted Commands & Sandboxing: Every command executed by an AI agent must be on the pre-approved whitelist. Commands run in sandboxed environments, preventing accidental or malicious system damage.

Comprehensive Audit Logging: Every interaction, every command, and every result is logged with full context. You have a complete audit trail for compliance frameworks like SOC 2, ISO 27001, or HIPAA.

Time Savings: What took 15-30 minutes of manual SSH configuration, editing files, and restarting services now takes 90 seconds via chat. Multiply this across dozens or hundreds of servers, and the time savings become substantial.

Prevention and Best Practices: A Holistic Approach to SSH Security

Implementing robust SSH security requires a comprehensive, layered approach. No single measure provides complete protection—security comes from defense-in-depth.

A Checklist for Secure SSH in 2026

Security MeasurePriorityImplementation DifficultyImpact
Change default port from 22HighLowReduces automated attacks by 99%
Disable root loginCriticalLowPrevents direct root compromise
Enforce key-based authenticationCriticalMediumEliminates password vulnerabilities
Use strong passphrases for private keysHighLowProtects keys if client compromised
Implement 2FAHighMediumAdds critical second factor
Configure fail2banHighMediumAutomates attack response
Use modern cipher suitesMediumLowPrevents cryptographic attacks
Deploy bastion hostMediumHighCentralizes access control
Implement strict firewall rulesHighMediumControls network access
Enable comprehensive loggingCriticalLowEssential for detection and compliance
Regular security updatesCriticalLowPatches known vulnerabilities
Principle of least privilegeHighMediumLimits breach impact
Regular security auditsMediumMediumIdentifies configuration drift

Change Default Port: Move SSH away from port 22 to a non-standard port above 1024 and below 49151. Avoid commonly used ports like 8080, 3389, or 3306.

Disable Root Login: Set PermitRootLogin no in sshd_config. Require users to authenticate as regular users and use sudo for privileged operations.

Enforce Key-Based Authentication: Generate 4096-bit RSA or Ed25519 keys. Deploy public keys to servers. Set PasswordAuthentication no in sshd_config.

Use Strong Passphrases for Private Keys: Protect private keys with passphrases of at least 20 characters. Use password managers to generate and store complex passphrases.

Implement Two-Factor Authentication (2FA): Use PAM modules like google-authenticator to add TOTP-based second-factor authentication.

Utilize a Bastion Host: For production environments with multiple servers, implement a hardened jump server as the single point of entry.

Configure Firewall Rules: Use iptables, ufw, or cloud security groups to restrict SSH access to known IP ranges. Block port 22 entirely if using a custom port.

Install and Configure fail2ban: Automatically ban IP addresses after repeated failed authentication attempts. Configure jails for your custom SSH port.

Keep SSH Software Updated: Enable automatic security updates or regularly check for and apply SSH daemon and client updates.

Use Modern Cipher Suites: Configure sshd_config to use only strong, current encryption algorithms. Disable weak ciphers, MACs, and key exchange algorithms.

Monitor SSH Logs: Regularly review /var/log/auth.log or /var/log/secure for suspicious activity. Consider forwarding logs to a SIEM system.

Principle of Least Privilege: Grant users only the minimum permissions necessary. Use AllowUsers or AllowGroups directives to explicitly whitelist accounts.

Regular Security Audits: Periodically review SSH configurations, user accounts, authorized keys, and access logs. Remove unused accounts and revoke unnecessary access.

Frequently Asked Questions

Why is SSH port 22 so heavily targeted by attackers?

SSH port 22 is the IANA-designated default port for SSH services, making it universally predictable across billions of devices worldwide. Attackers know that any server listening on port 22 is running SSH, eliminating the need for service detection. This predictability enables mass-scale automated attacks—botnets continuously scan entire IP ranges attempting to connect to port 22, then immediately begin brute-force authentication attempts. A typical internet-facing server on port 22 receives hundreds to thousands of automated attack attempts daily.

Does changing the SSH port actually improve security?

Changing the SSH port from 22 to a non-standard port immediately reduces exposure to automated attacks by approximately 99%, as most mass-scanning operations only target well-known ports. However, this is security through obscurity—a determined attacker who specifically targets your server will run a full port scan and find SSH regardless of port. The real value is eliminating the constant background noise of automated attacks, which reduces log clutter, conserves server resources, and decreases the probability of successful brute-force attacks over time.

What makes key-based authentication more secure than passwords?

Key-based authentication uses asymmetric cryptography with key lengths of 2048-4096 bits for RSA or 256 bits for Ed25519, creating computational complexity that makes brute-force attacks infeasible with current or foreseeable technology. A 4096-bit RSA key has approximately 2^4096 possible values, compared to even a strong 12-character password with about 2^79 possibilities. Additionally, the private key never traverses the network—authentication uses a challenge-response mechanism where the server verifies you possess the private key without ever seeing it, eliminating interception vulnerabilities.

How does a bastion host improve SSH security?

A bastion host acts as a hardened, single point of entry for accessing internal infrastructure, meaning internal servers never accept SSH connections from the internet—only from the bastion's internal IP address. This architecture reduces attack surface by limiting public SSH exposure to one heavily monitored, frequently updated, and strictly controlled server. All access flows through the bastion, enabling centralized logging, monitoring, and access control, making it significantly easier to detect and respond to unauthorized access attempts.

What is fail2ban and how does it protect SSH?

Fail2ban is an intrusion prevention tool that monitors log files for malicious patterns—specifically, repeated failed authentication attempts—and automatically updates firewall rules to block offending IP addresses. When fail2ban detects multiple failed SSH login attempts from the same IP within a defined time window (typically 3-5 failures within 10 minutes), it adds a temporary or permanent firewall rule blocking all traffic from that IP, effectively stopping brute-force attacks in progress and preventing further attempts from compromised systems or botnets.

Conclusion

Securing SSH access in 2026 requires moving beyond default configurations to implement layered security measures. Changing from port 22 deflects automated attacks, but true security comes from strong authentication, key-based access, 2FA, comprehensive monitoring, and architectural patterns like bastion hosts. Each layer of defense compounds the difficulty for attackers while the operational burden of managing these configurations across multiple servers can be substantial.

If you want to automate this entire workflow—from changing SSH ports to deploying keys, configuring fail2ban, and maintaining audit logs—OpsSqad's Security Squad can execute these tasks across your entire infrastructure via simple chat commands. The reverse TCP architecture eliminates inbound firewall exposure entirely, while whitelisted commands and comprehensive audit logging ensure security and compliance. Create your free account at app.opssquad.ai and secure your SSH infrastructure in minutes instead of hours.