How to change SSH port in Linux

How to Change SSH Port in Linux: A Complete Security Guide SSH (Secure Shell) is one of the most fundamental tools for remote server administration in Linux environments. While the default SSH port 22 is universally recognized, keeping it unchanged can make your server a target for automated attacks and port scanners. Changing your SSH port is a simple yet effective security measure that can significantly reduce unwanted connection attempts. In this comprehensive guide, we'll walk you through the entire process of changing your SSH port in Linux, from initial configuration to testing and troubleshooting. Whether you're managing a personal VPS or enterprise servers, this guide will help you implement this important security enhancement safely and effectively. Why Change the Default SSH Port? Security Benefits The default SSH port 22 is well-known to attackers and automated scripts that constantly scan the internet for vulnerable servers. By changing to a non-standard port, you can: - Reduce brute force attacks: Automated bots typically target port 22 - Minimize log noise: Fewer failed connection attempts in your logs - Implement security through obscurity: An additional layer of protection - Decrease server load: Fewer connection attempts mean less processing overhead Common Use Cases - Web servers: Protecting production environments from constant scanning - Development servers: Securing staging and testing environments - Personal VPS: Enhancing home lab or personal project security - Corporate compliance: Meeting security requirements for remote access Prerequisites and Preparation Before changing your SSH port, ensure you have: Required Access - Root or sudo privileges on the target system - Current SSH access to the server - Physical access or alternative remote access method (as backup) System Requirements - Linux distribution with SSH server installed - Text editor (nano, vim, or emacs) - Firewall management tools (iptables, ufw, or firewalld) Important Safety Note ⚠️ Warning: Always maintain an active SSH session while making these changes. If something goes wrong, you'll need this connection to fix the configuration. Step 1: Choose Your New SSH Port Port Selection Guidelines When selecting a new SSH port, consider these best practices: Recommended Port Ranges: - 1024-49151: Registered ports (good choice for SSH) - 49152-65535: Dynamic/private ports (also acceptable) Ports to Avoid: - 1-1023: Well-known ports reserved for system services - Common service ports: 80 (HTTP), 443 (HTTPS), 25 (SMTP), etc. - Already in use: Check with `netstat -tuln` or `ss -tuln` Check Port Availability Before proceeding, verify your chosen port isn't already in use: ```bash Check if port 2222 is available sudo netstat -tuln | grep :2222 Alternative method using ss sudo ss -tuln | grep :2222 Check for any service using the port sudo lsof -i :2222 ``` If no output is returned, the port is available for use. Step 2: Backup Current SSH Configuration Creating a backup is crucial for quick recovery if issues arise: ```bash Create a backup of the SSH configuration sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup Verify backup was created ls -la /etc/ssh/sshd_config* ``` You should see both the original file and the backup: ``` -rw-r--r-- 1 root root 3264 Oct 15 10:30 /etc/ssh/sshd_config -rw-r--r-- 1 root root 3264 Oct 15 10:25 /etc/ssh/sshd_config.backup ``` Step 3: Modify SSH Configuration Locate and Edit the Configuration File The main SSH daemon configuration file is located at `/etc/ssh/sshd_config`. Open it with your preferred text editor: ```bash Using nano (beginner-friendly) sudo nano /etc/ssh/sshd_config Using vim (advanced users) sudo vim /etc/ssh/sshd_config Using emacs sudo emacs /etc/ssh/sshd_config ``` Find the Port Configuration Look for the line that specifies the port. It might appear as: ```bash #Port 22 ``` or ```bash Port 22 ``` Update the Port Number Replace the existing port configuration with your chosen port. For example, to change to port 2222: ```bash Port 2222 ``` Important Notes: - Remove the `#` if the line was commented out - Ensure there are no spaces before "Port" - Save the file after making changes Example Configuration Section Here's how the relevant section of your `sshd_config` file should look: ```bash What ports, IPs and protocols we listen for Port 2222 Use these options to restrict which interfaces/protocols sshd will bind to #ListenAddress :: #ListenAddress 0.0.0.0 Protocol 2 ``` Step 4: Configure Firewall Rules For UFW (Ubuntu Firewall) If you're using UFW, add a rule for your new SSH port before removing the old one: ```bash Add rule for new SSH port sudo ufw allow 2222/tcp Verify the rule was added sudo ufw status After testing, remove the old SSH port rule sudo ufw delete allow 22/tcp ``` For iptables For systems using iptables directly: ```bash Add rule for new SSH port sudo iptables -A INPUT -p tcp --dport 2222 -j ACCEPT Save iptables rules (command varies by distribution) For CentOS/RHEL: sudo service iptables save For Debian/Ubuntu: sudo iptables-save > /etc/iptables/rules.v4 ``` For firewalld (CentOS/RHEL/Fedora) For systems using firewalld: ```bash Add the new SSH port sudo firewall-cmd --permanent --add-port=2222/tcp Reload firewall configuration sudo firewall-cmd --reload Verify the rule was added sudo firewall-cmd --list-ports ``` Step 5: Test and Restart SSH Service Validate Configuration Syntax Before restarting SSH, test the configuration syntax: ```bash Test SSH configuration for syntax errors sudo sshd -t If successful, no output is displayed If there are errors, they will be shown here ``` Restart SSH Service The command to restart SSH varies by Linux distribution: For systemd-based systems (Ubuntu 16+, CentOS 7+, etc.): ```bash sudo systemctl restart sshd or sudo systemctl restart ssh ``` For SysV init systems: ```bash sudo service sshd restart or sudo service ssh restart ``` Verify SSH is Running on New Port Check that SSH is now listening on your new port: ```bash Check if SSH is listening on the new port sudo netstat -tuln | grep :2222 Alternative using ss sudo ss -tuln | grep :2222 Check SSH service status sudo systemctl status sshd ``` Expected output should show: ``` tcp 0 0 0.0.0.0:2222 0.0.0.0:* LISTEN ``` Step 6: Test the New Configuration Test from Current Session While maintaining your current SSH session, open a new terminal and test the connection: ```bash Test connection with new port ssh -p 2222 username@your-server-ip Example ssh -p 2222 john@192.168.1.100 ``` Test from Remote Location If possible, test the connection from a different location to ensure external access works: ```bash Test from external network ssh -p 2222 username@your-public-ip ``` Verify Old Port is Closed Confirm that the old port 22 is no longer accessible: ```bash This should fail or timeout ssh -p 22 username@your-server-ip ``` Advanced Configuration Options Running SSH on Multiple Ports You can configure SSH to listen on multiple ports simultaneously by adding multiple Port directives: ```bash Port 22 Port 2222 Port 3333 ``` This approach allows for a gradual transition and provides backup access methods. Restricting Access by IP Combine port changes with IP restrictions for enhanced security: ```bash In sshd_config Port 2222 AllowUsers username@192.168.1.* DenyUsers @ ``` Using Port Knocking For advanced users, consider implementing port knocking alongside custom SSH ports: ```bash Example port knocking sequence Client must connect to ports 1234, 5678, 9012 before SSH port opens ``` Troubleshooting Common Issues Issue 1: SSH Service Won't Start Symptoms: - SSH service fails to restart - Error messages in system logs Solutions: ```bash Check SSH configuration syntax sudo sshd -t View detailed error logs sudo journalctl -u sshd Check if port is already in use sudo netstat -tuln | grep :2222 Verify firewall isn't blocking the port sudo ufw status verbose ``` Issue 2: Cannot Connect to New Port Symptoms: - Connection timeouts - "Connection refused" errors Diagnostic Steps: ```bash Verify SSH is listening on correct port sudo ss -tuln | grep :2222 Check firewall rules sudo iptables -L -n Test local connection ssh -p 2222 localhost ``` Solutions: - Ensure firewall allows the new port - Verify SSH service restarted successfully - Check network connectivity Issue 3: Authentication Failures Symptoms: - "Permission denied" errors - Authentication timeouts Solutions: ```bash Check SSH logs for detailed error messages sudo tail -f /var/log/auth.log Verify user permissions sudo grep "username" /etc/passwd Check SSH key permissions ls -la ~/.ssh/ ``` Issue 4: SELinux Blocking Custom Port For CentOS/RHEL with SELinux enabled: ```bash Allow SSH on custom port in SELinux sudo semanage port -a -t ssh_port_t -p tcp 2222 Verify SELinux policy sudo semanage port -l | grep ssh ``` Security Best Practices Additional SSH Hardening While changing the SSH port improves security, consider these additional measures: ```bash Disable root login PermitRootLogin no Use key-based authentication only PasswordAuthentication no PubkeyAuthentication yes Limit login attempts MaxAuthTries 3 Set idle timeout ClientAliveInterval 300 ClientAliveCountMax 2 ``` Regular Security Auditing ```bash Monitor SSH access attempts sudo grep "Failed password" /var/log/auth.log Check for successful logins sudo grep "Accepted" /var/log/auth.log Monitor current SSH connections sudo who ``` Automated Security Updates Keep your SSH server updated: ```bash For Ubuntu/Debian sudo apt update && sudo apt upgrade openssh-server For CentOS/RHEL sudo yum update openssh-server ``` Creating Client Configuration SSH Client Configuration File To avoid specifying the port each time, create a client configuration: ```bash Edit or create SSH client config nano ~/.ssh/config ``` Add the following configuration: ```bash Host myserver HostName your-server-ip Port 2222 User your-username Host production HostName prod.example.com Port 2222 User deploy IdentityFile ~/.ssh/production_key ``` Now you can connect using: ```bash ssh myserver Instead of: ssh -p 2222 username@your-server-ip ``` Monitoring and Maintenance Log Monitoring Set up log monitoring to track SSH access: ```bash Create a script to monitor SSH logs sudo nano /usr/local/bin/ssh-monitor.sh ``` ```bash #!/bin/bash SSH connection monitoring script tail -f /var/log/auth.log | grep --line-buffered "sshd.Accepted\|sshd.Failed" ``` Automated Port Checking Create a monitoring script to ensure SSH is running on the correct port: ```bash #!/bin/bash SSH port monitoring script PORT=2222 if ! netstat -tuln | grep -q ":$PORT "; then echo "SSH is not listening on port $PORT" systemctl restart sshd fi ``` Conclusion Changing your SSH port in Linux is a straightforward but effective security measure that can significantly reduce automated attacks on your server. While it shouldn't be your only security measure, it's an excellent first step in hardening your SSH configuration. Remember these key points: 1. Always backup your SSH configuration before making changes 2. Keep an active SSH session open while testing new configurations 3. Update firewall rules to allow your new SSH port 4. Test thoroughly from multiple locations and methods 5. Document changes for future reference and team members By following this guide, you've not only changed your SSH port but also learned valuable troubleshooting techniques and security best practices. Consider implementing additional SSH hardening measures such as key-based authentication, fail2ban, and regular security audits to further protect your Linux servers. The security of your Linux systems is an ongoing process, and changing the SSH port is just the beginning. Stay vigilant, keep your systems updated, and regularly review your security configurations to maintain a robust defense against potential threats.