Listen to this Post

Introduction:
The debate over changing the default SSH port from 22 to a non‑standard number is one of the most polarising discussions in system administration. On one side, purists dismiss it as “security through obscurity” – a superficial trick that offers no real protection against a determined attacker. On the other, seasoned practitioners swear by it as the single most effective way to slash log noise, reduce brute‑force attempts, and reclaim sanity in server management. The truth, as always, lies somewhere in the middle – and missing that nuance can leave your infrastructure dangerously exposed.
Learning Objectives:
- Understand the difference between security through obscurity and defence in depth in the context of SSH hardening.
- Learn how to implement a layered SSH security strategy that includes port changes, key‑based authentication, fail2ban, and port knocking.
- Acquire practical Linux and Windows commands to harden SSH configurations and monitor for malicious activity.
You Should Know:
- Changing the SSH Port – The Great Obscurity Debate
Changing the default SSH port from 22 to a high, ephemeral port (e.g., 49222) is one of the oldest tricks in the sysadmin playbook. Attackers use automated port scanners to find SSH services on port 22, and moving to a custom port can reduce the number of random attack attempts from thousands per day to just a few dozen. This reduction in noise is not trivial – it decreases log clutter, reduces CPU overhead from connection attempts, and can even improve the performance of services that share the same host.
However, it is critical to understand that changing the port does not provide real security against a targeted adversary. A simple `nmap -p 1-65535
Step‑by‑step guide – Changing the SSH port on Linux:
1. Backup the SSH configuration sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.ORIG <ol> <li>Edit the configuration file sudo nano /etc/ssh/sshd_config</p></li> <li><p>Find the line 'Port 22' and change it to your desired port Port 49222</p></li> <li><p>Save the file and restart the SSH service sudo systemctl restart sshd</p></li> <li><p>Update the firewall to allow the new port (example with UFW) sudo ufw allow 49222/tcp</p></li> <li><p>Remove the old port 22 rule (if you no longer need it) sudo ufw delete allow 22/tcp</p></li> <li><p>Test the new connection before closing your current session ssh -p 49222 user@your-server-ip
On Windows (OpenSSH Server):
- Edit `%ProgramData%\ssh\sshd_config` in Notepad as Administrator.
- Change `Port 22` to
Port 49222. - Restart the service: `Restart-Service sshd` in PowerShell.
- Update Windows Defender Firewall with a new inbound rule for port 49222.
2. Key‑Based Authentication – The Real Game Changer
If you only implement one SSH hardening measure, make it key‑based authentication and disable password logins. Passwords can be guessed, brute‑forced, or stolen; private keys, when properly managed, are virtually impossible to crack. This is the single most impactful step you can take to secure SSH, regardless of which port you use.
Step‑by‑step guide – Generate and deploy SSH keys:
On your local machine, generate an ED25519 key pair (recommended over RSA) ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519 Copy the public key to your server ssh-copy-id -p 49222 user@your-server-ip Alternatively, manually append the key cat ~/.ssh/id_ed25519.pub | ssh -p 49222 user@your-server-ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys" Set correct permissions on the server ssh -p 49222 user@your-server-ip "chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys" Now, disable password authentication in /etc/ssh/sshd_config sudo nano /etc/ssh/sshd_config Set: PasswordAuthentication no PermitRootLogin no ChallengeResponseAuthentication no UsePAM no Restart SSH sudo systemctl restart sshd
On Windows (PowerShell as Admin):
Generate key pair ssh-keygen -t ed25519 -f $env:USERPROFILE.ssh\id_ed25519 Copy public key to server (Linux or Windows) type $env:USERPROFILE.ssh\id_ed25519.pub | ssh -p 49222 user@server "cat >> .ssh/authorized_keys"
3. Fail2Ban – Automatically Block the Bad Guys
Fail2ban is an intrusion prevention framework that monitors log files for repeated failed login attempts and dynamically adds firewall rules to ban offending IPs. It is lightweight, highly configurable, and works seamlessly with both standard and non‑standard SSH ports. When combined with a changed SSH port, fail2ban provides a powerful one‑two punch: the port change reduces the volume of attacks, and fail2ban automatically deals with any that do get through.
Step‑by‑step guide – Install and configure Fail2ban:
Install Fail2ban (Ubuntu/Debian) sudo apt update && sudo apt install fail2ban -y Create a local configuration file (to avoid overwrites on package updates) sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local Edit the local configuration sudo nano /etc/fail2ban/jail.local Find the [bash] section and set: [bash] enabled = true port = 49222 Change to your custom SSH port filter = sshd logpath = /var/log/auth.log maxretry = 5 bantime = 3600 Ban for 1 hour Restart and enable Fail2ban sudo systemctl enable --1ow fail2ban Check the status sudo fail2ban-client status sshd View banned IPs sudo fail2ban-client banned
To unban an IP:
sudo fail2ban-client set sshd unbanip 192.168.1.100
On CentOS/RHEL (using firewalld):
sudo dnf install fail2ban -y Configure similarly, but ensure the firewall action uses firewalld
4. Port Knocking – The Ultimate Stealth Layer
For environments that demand maximum stealth, port knocking takes obscurity to the next level. This technique keeps the SSH port completely closed by default and only opens it temporarily when a client sends a specific sequence of connection attempts to predefined ports. A port scanner will see no open ports, effectively making your SSH service invisible to automated reconnaissance. This is not a replacement for strong authentication, but an additional layer that significantly raises the bar for attackers.
Step‑by‑step guide – Set up port knocking with `knockd` (Ubuntu):
Install knockd on the server sudo apt install knockd -y Configure the network interface (find your interface name with <code>ip a</code>) sudo nano /etc/default/knockd Set: KNOCKD_OPTS="-i eth0" Replace eth0 with your interface Edit the knockd configuration sudo nano /etc/knockd.conf Example configuration: [bash] logfile = /var/log/knockd.log [bash] sequence = 7000,8000,9000 seq_timeout = 15 command = /sbin/iptables -I INPUT -s %IP% -p tcp --dport 49222 -j ACCEPT tcpflags = syn [bash] sequence = 9000,8000,7000 seq_timeout = 15 command = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 49222 -j ACCEPT tcpflags = syn Start and enable knockd sudo systemctl enable --1ow knockd On the client machine, install knock utility sudo apt install knockd -y or just the knock client To "knock" and open the SSH port: knock your-server-ip 7000 8000 9000 Now connect via SSH (within the timeout window) ssh -p 49222 user@your-server-ip After finishing, close the port: knock your-server-ip 9000 8000 7000
Important: Ensure your firewall (iptables/UFW) has a default DROP policy for the SSH port, and that the `knockd` commands are correctly modifying the firewall rules. For production, consider using `fwknop` which implements encrypted port knocking for additional security.
5. Additional Hardening – The Defence‑in‑Depth Checklist
Beyond the techniques above, a comprehensive SSH hardening strategy includes several other critical measures:
- Disable Root Login: Set `PermitRootLogin no` in
sshd_config. This forces attackers to guess both a username and a password, dramatically reducing risk. - Use Strong Ciphers and MACs: Restrict SSH to modern, secure algorithms. Add to
sshd_config:Ciphers [email protected],[email protected] MACs [email protected],[email protected]
- Set Idle Timeout: `ClientAliveInterval 300` and `ClientAliveCountMax 0` will disconnect idle sessions after 5 minutes.
- Limit Access with
hosts.allow: Restrict SSH access to specific IP ranges using/etc/hosts.allow:sshd: 192.168.1.0/24, 10.0.0.0/8
- Monitor with
auditd: Set up auditing for SSH login attempts and configuration changes. - Regular Updates: Keep OpenSSH and the entire system patched. Vulnerabilities like CVE-2024-6387 (regreSSHion) highlight the importance of timely updates.
Windows‑specific hardening:
- Use Windows Defender Firewall to restrict SSH access to specific IPs.
- Enable `Set-Service -1ame sshd -StartupType ‘Automatic’` and consider using `sshd_config` with similar restrictions.
- For enterprise environments, integrate with Active Directory and use Group Policy to enforce key‑based authentication.
What Undercode Say:
- Key Takeaway 1: Changing the SSH port is not a security measure – it is a noise‑reduction tactic. It does not stop a targeted attacker, but it dramatically reduces the volume of automated scans and brute‑force attempts, which in turn lowers log clutter, reduces CPU load, and allows security teams to focus on genuine threats. The real security comes from key‑based authentication, fail2ban, and regular patching.
-
Key Takeaway 2: The debate is not “security vs. obscurity” – it is “obscurity as a layer within defence in depth”. When combined with strong authentication, automated blocking, and network‑level controls like port knocking, changing the port becomes a valuable part of a resilient security posture. The nuance that many miss is that security is never about a single control; it is about layers that slow, detect, and mitigate attacks at every stage.
Analysis: The SSH port debate perfectly illustrates a broader truth in cybersecurity: absolute security is a myth, and every control has trade‑offs. Moving SSH off port 22 is a low‑effort, high‑impact change that improves operational hygiene and reduces exposure to opportunistic threats. However, it should never be the only measure. The real failure occurs when administrators rely on port changes as a substitute for proper authentication, patching, and monitoring. In the DevSecOps era, where infrastructure is ephemeral and attack surfaces are constantly shifting, the principle of defence in depth is non‑negotiable. Embrace obscurity as a tactical tool, but never mistake it for a strategic solution.
Prediction:
- +1 As AI‑driven reconnaissance tools become more sophisticated, the effectiveness of simple port changes will diminish. However, the underlying principle of reducing attack surface will remain critical, with organisations adopting dynamic, time‑based port obfuscation techniques that automatically rotate listening ports.
- +1 The integration of port knocking with zero‑trust architectures and identity‑aware proxies will become mainstream, allowing SSH access to be granted only after multi‑factor authentication and device posture checks, effectively rendering static port changes obsolete.
- -1 The continued reliance on security through obscurity alone will lead to more breaches, as attackers increasingly use full‑port scans and service fingerprinting that easily bypass simple port changes. Organisations that fail to implement key‑based authentication and automated threat blocking will remain vulnerable despite changing ports.
- +1 Fail2ban and similar tools will evolve to leverage threat intelligence feeds, enabling real‑time blocking of known malicious IPs before they even attempt a connection, further reducing the need for port changes as a primary defence.
- -1 The growing complexity of multi‑cloud and hybrid environments will make consistent SSH hardening more challenging, leading to misconfigurations and exposed services on non‑standard ports that are still discoverable through cloud metadata services and internal scanning.
▶️ Related Video (66% Match):
https://www.youtube.com/watch?v=-VH1PXmXroA
🎯Let’s Practice For Free:
🎓 Live Courses & Certifications:
Join Undercode Academy for Verified Certifications
🚀 Request a Custom Project:
Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
[email protected]
💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands
IT/Security Reporter URL:
Reported By: Stephanerobert1 Devsecops – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


