How to change SSH port for security

How to Change SSH Port for Security: A Complete Guide Table of Contents 1. [Introduction](#introduction) 2. [Why Change the Default SSH Port?](#why-change-the-default-ssh-port) 3. [Prerequisites](#prerequisites) 4. [Step-by-Step Guide to Changing SSH Port](#step-by-step-guide-to-changing-ssh-port) 5. [Testing the New SSH Configuration](#testing-the-new-ssh-configuration) 6. [Configuring Firewall Rules](#configuring-firewall-rules) 7. [Common Issues and Troubleshooting](#common-issues-and-troubleshooting) 8. [Best Practices for SSH Security](#best-practices-for-ssh-security) 9. [Advanced Configuration Options](#advanced-configuration-options) 10. [Conclusion](#conclusion) Introduction Secure Shell (SSH) is a fundamental protocol for remote server administration, providing encrypted communication between clients and servers. By default, SSH operates on port 22, which is well-known to both legitimate administrators and malicious actors. Changing the SSH port is one of the first security measures administrators implement to reduce automated attacks and improve overall server security. This comprehensive guide will walk you through the process of changing your SSH port, from initial configuration to advanced security practices. Whether you're managing a single server or multiple systems, understanding how to properly modify SSH settings is crucial for maintaining a secure infrastructure. Why Change the Default SSH Port? Security Through Obscurity While security through obscurity shouldn't be your only defense mechanism, changing the default SSH port provides several benefits: - Reduced Automated Attacks: Most automated scanning tools and bots target port 22 by default - Lower Log Noise: Fewer failed login attempts in your system logs - Additional Security Layer: Part of a comprehensive security strategy - Compliance Requirements: Some security frameworks recommend changing default ports Attack Vector Reduction Port 22 is constantly scanned by automated tools looking for vulnerable SSH services. By moving to a non-standard port, you significantly reduce the number of brute-force attempts and automated attacks targeting your server. Prerequisites Before proceeding with changing your SSH port, ensure you have: System Requirements - Root or sudo access to the server - Active SSH connection to the server - Basic understanding of command-line operations - Text editor familiarity (nano, vim, or emacs) Important Considerations - Backup Access: Ensure you have alternative access methods (console access, VNC, etc.) - Firewall Status: Know your current firewall configuration - Service Dependencies: Identify any services that depend on SSH port 22 - Documentation: Record the new port number securely Supported Operating Systems This guide covers: - Ubuntu/Debian systems - CentOS/RHEL/Fedora systems - Other Linux distributions - Basic principles apply to Unix-like systems Step-by-Step Guide to Changing SSH Port Step 1: Choose Your New Port Number Select a port number between 1024 and 65535 (unprivileged port range). Avoid commonly used ports: Recommended Port Ranges: - 2200-2299 (commonly used for SSH alternatives) - 10000-10099 (often used for administrative services) - 22000-22999 (SSH-related services) Ports to Avoid: - 80, 443 (HTTP/HTTPS) - 21 (FTP) - 25 (SMTP) - 53 (DNS) - 3306 (MySQL) - 5432 (PostgreSQL) Step 2: Backup Current SSH Configuration Before making any changes, create a backup of your SSH configuration: ```bash sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup.$(date +%Y%m%d) ``` Verify the backup was created: ```bash ls -la /etc/ssh/sshd_config* ``` Step 3: Edit SSH Configuration File Open the SSH daemon configuration file: ```bash sudo nano /etc/ssh/sshd_config ``` For vim users: ```bash sudo vim /etc/ssh/sshd_config ``` Step 4: Modify Port Configuration Locate the line that specifies the port (usually near the top of the file): ```bash #Port 22 ``` Uncomment and change it to your chosen port: ```bash Port 2222 ``` Alternative Method - Multiple Ports: You can temporarily run SSH on both ports during transition: ```bash Port 22 Port 2222 ``` This allows you to test the new port while maintaining access through the original port. Step 5: Additional Security Configurations While editing the SSH configuration, consider implementing these security enhancements: ```bash Disable root login PermitRootLogin no Use SSH protocol version 2 only Protocol 2 Limit user access AllowUsers yourusername Disable password authentication (if using key-based auth) PasswordAuthentication no Disable empty passwords PermitEmptyPasswords no Set login grace time LoginGraceTime 60 Limit authentication attempts MaxAuthTries 3 Enable public key authentication PubkeyAuthentication yes ``` Step 6: Validate Configuration Syntax Before restarting SSH, validate your configuration: ```bash sudo sshd -t ``` If there are no errors, you'll see no output. If there are syntax errors, they'll be displayed for correction. Step 7: Restart SSH Service For systemd systems (Ubuntu 16.04+, CentOS 7+, Debian 8+): ```bash sudo systemctl restart sshd ``` For SysV init systems (older distributions): ```bash sudo service ssh restart or sudo /etc/init.d/ssh restart ``` Verify SSH service status: ```bash sudo systemctl status sshd ``` Testing the New SSH Configuration Step 8: Test New Port Connection Important: Do not close your current SSH session until you've verified the new configuration works. Open a new terminal window and test the connection: ```bash ssh -p 2222 username@your-server-ip ``` Example with specific options: ```bash ssh -p 2222 -o ConnectTimeout=10 username@192.168.1.100 ``` Step 9: Verify Port Listening Status Check that SSH is listening on the new port: ```bash sudo netstat -tlnp | grep :2222 ``` Alternative using ss command: ```bash sudo ss -tlnp | grep :2222 ``` Expected output should show: ``` tcp 0 0 0.0.0.0:2222 0.0.0.0:* LISTEN 1234/sshd ``` Configuring Firewall Rules UFW (Ubuntu Firewall) If you're using UFW, add the new port and remove the old one: ```bash Add new SSH port sudo ufw allow 2222/tcp Remove old SSH port (only after confirming new port works) sudo ufw delete allow 22/tcp Check UFW status sudo ufw status ``` iptables For systems using iptables directly: ```bash Add rule for new port sudo iptables -A INPUT -p tcp --dport 2222 -j ACCEPT Save iptables rules (method varies by distribution) sudo iptables-save > /etc/iptables/rules.v4 ``` firewalld (CentOS/RHEL/Fedora) For systems using firewalld: ```bash Add new port sudo firewall-cmd --permanent --add-port=2222/tcp Remove old port (after testing) sudo firewall-cmd --permanent --remove-port=22/tcp Reload firewall sudo firewall-cmd --reload Verify configuration sudo firewall-cmd --list-ports ``` Cloud Provider Security Groups If using cloud services (AWS, Google Cloud, Azure), update security group rules: AWS Security Groups: - Add inbound rule for TCP port 2222 - Source: Your IP or appropriate CIDR block - Remove port 22 rule after testing Google Cloud Firewall Rules: ```bash gcloud compute firewall-rules create allow-ssh-2222 \ --allow tcp:2222 \ --source-ranges 0.0.0.0/0 \ --description "SSH on port 2222" ``` Common Issues and Troubleshooting Issue 1: Connection Refused Symptoms: ``` ssh: connect to host server.example.com port 2222: Connection refused ``` Troubleshooting Steps: 1. Verify SSH service is running: ```bash sudo systemctl status sshd ``` 2. Check if port is listening: ```bash sudo netstat -tlnp | grep sshd ``` 3. Review SSH logs: ```bash sudo tail -f /var/log/auth.log or on some systems: sudo tail -f /var/log/secure ``` 4. Check configuration syntax: ```bash sudo sshd -t ``` Issue 2: Permission Denied Symptoms: ``` Permission denied (publickey,password) ``` Solutions: 1. Verify user exists and has correct permissions: ```bash id username ``` 2. Check SSH key permissions: ```bash chmod 600 ~/.ssh/id_rsa chmod 644 ~/.ssh/id_rsa.pub chmod 700 ~/.ssh/ ``` 3. Verify authorized_keys file: ```bash chmod 600 ~/.ssh/authorized_keys ``` Issue 3: Firewall Blocking Connection Symptoms: Connection attempts timeout without error message. Solutions: 1. Temporarily disable firewall for testing: ```bash sudo ufw disable or sudo systemctl stop firewalld ``` 2. Check iptables rules: ```bash sudo iptables -L -n ``` 3. Verify cloud security group settings Issue 4: SELinux Issues (CentOS/RHEL) Symptoms: SSH fails to bind to new port on SELinux-enabled systems. Solutions: 1. Check SELinux status: ```bash sestatus ``` 2. Allow SSH on new port: ```bash sudo semanage port -a -t ssh_port_t -p tcp 2222 ``` 3. Verify SELinux port configuration: ```bash sudo semanage port -l | grep ssh ``` Issue 5: Service Won't Start Symptoms: SSH service fails to start after configuration change. Troubleshooting: 1. Check systemd journal: ```bash sudo journalctl -u sshd -f ``` 2. Test configuration in debug mode: ```bash sudo /usr/sbin/sshd -D -p 2222 ``` 3. Restore backup configuration: ```bash sudo cp /etc/ssh/sshd_config.backup.* /etc/ssh/sshd_config sudo systemctl restart sshd ``` Best Practices for SSH Security 1. Use Key-Based Authentication Generate and use SSH keys instead of passwords: ```bash Generate SSH key pair ssh-keygen -t rsa -b 4096 -C "your_email@example.com" Copy public key to server ssh-copy-id -p 2222 username@server-ip ``` 2. Implement Fail2Ban Install and configure Fail2Ban to automatically ban IP addresses with failed login attempts: ```bash sudo apt install fail2ban or sudo yum install fail2ban ``` Configure Fail2Ban for custom SSH port: ```bash sudo nano /etc/fail2ban/jail.local ``` Add: ```ini [sshd] enabled = true port = 2222 filter = sshd logpath = /var/log/auth.log maxretry = 3 bantime = 3600 ``` 3. Regular Security Updates Keep your system updated: ```bash Ubuntu/Debian sudo apt update && sudo apt upgrade CentOS/RHEL sudo yum update or on newer versions sudo dnf update ``` 4. Monitor SSH Logs Regularly review SSH access logs: ```bash Recent SSH login attempts sudo grep "sshd" /var/log/auth.log | tail -20 Failed login attempts sudo grep "Failed password" /var/log/auth.log ``` 5. Use SSH Configuration Files Create SSH client configuration for easier connections: ```bash nano ~/.ssh/config ``` Add: ``` Host myserver HostName server.example.com Port 2222 User yourusername IdentityFile ~/.ssh/id_rsa ``` Now connect simply with: ```bash ssh myserver ``` 6. Implement Two-Factor Authentication Consider implementing 2FA with Google Authenticator: ```bash sudo apt install libpam-google-authenticator ``` Advanced Configuration Options Port Knocking Implement port knocking for additional security: ```bash sudo apt install knockd ``` Configure knockd to open SSH port only after correct sequence: ```bash sudo nano /etc/knockd.conf ``` SSH Tunneling and Jump Hosts Configure SSH jump hosts for accessing internal servers: ```bash SSH config for jump host Host internal-server HostName 10.0.1.100 Port 2222 ProxyJump jump-host.example.com:2222 ``` Custom SSH Banners Create informative login banners: ```bash sudo nano /etc/ssh/banner.txt ``` Add to sshd_config: ```bash Banner /etc/ssh/banner.txt ``` Logging and Auditing Enhanced logging configuration: ```bash In /etc/ssh/sshd_config LogLevel VERBOSE SyslogFacility AUTHPRIV ``` Connection Limits Limit concurrent connections: ```bash MaxStartups 10:30:60 MaxSessions 4 ``` Maintenance and Monitoring Regular Security Audits Perform regular SSH security audits: ```bash Check for weak configurations sudo ssh-audit localhost -p 2222 Review active SSH sessions who w ``` Backup and Recovery Procedures Maintain SSH configuration backups: ```bash Automated backup script #!/bin/bash DATE=$(date +%Y%m%d_%H%M%S) cp /etc/ssh/sshd_config /backup/sshd_config_$DATE ``` Documentation Maintain documentation of: - SSH port numbers for each server - Key locations and purposes - Firewall rule configurations - Emergency access procedures Conclusion Changing your SSH port from the default 22 is a simple yet effective security measure that significantly reduces automated attacks and improves your server's security posture. While this guide has covered the technical aspects of changing SSH ports, remember that this is just one component of a comprehensive security strategy. Key Takeaways 1. Always maintain backup access before making SSH configuration changes 2. Test thoroughly before removing old configurations 3. Update firewall rules to match your new SSH port 4. Document changes for future reference and team members 5. Combine with other security measures like key-based authentication and fail2ban Next Steps After successfully changing your SSH port, consider implementing: - SSH key-based authentication to eliminate password-based attacks - Two-factor authentication for additional security layers - Regular security audits to identify potential vulnerabilities - Automated monitoring to track access attempts and system changes - Backup and disaster recovery procedures to ensure continued access Final Security Reminders Remember that changing the SSH port is security through obscurity and should be part of a broader security strategy. Continue to: - Keep your system updated with security patches - Monitor logs for suspicious activity - Regularly review and update SSH configurations - Maintain secure backup procedures - Train team members on secure SSH practices By following this comprehensive guide, you've taken an important step toward securing your server infrastructure. The techniques and best practices outlined here will serve as a foundation for maintaining robust SSH security across your systems.