Changing SSH Port for Enhanced Security
Table of Contents
1. [Introduction](#introduction) 2. [Why Change the Default SSH Port](#why-change-the-default-ssh-port) 3. [Security Considerations](#security-considerations) 4. [Prerequisites](#prerequisites) 5. [Step-by-Step Guide](#step-by-step-guide) 6. [Configuration Files and Parameters](#configuration-files-and-parameters) 7. [Firewall Configuration](#firewall-configuration) 8. [Testing and Verification](#testing-and-verification) 9. [Troubleshooting](#troubleshooting) 10. [Best Practices](#best-practices) 11. [Advanced Configurations](#advanced-configurations)Introduction
SSH (Secure Shell) is a cryptographic network protocol that provides secure communication between two networked computers. By default, SSH operates on port 22, which is well-known and frequently targeted by automated attacks and malicious actors. Changing the SSH port from its default value is a fundamental security practice known as "security through obscurity" that can significantly reduce unauthorized access attempts.
This comprehensive guide covers the complete process of changing the SSH port on various Linux distributions, including configuration modifications, firewall adjustments, and security considerations.
Why Change the Default SSH Port
Attack Vector Reduction
The default SSH port 22 is constantly scanned by automated bots and attackers worldwide. By changing to a non-standard port, you immediately reduce the number of automated attacks targeting your server.
Benefits Overview
| Benefit | Description | Impact Level | |---------|-------------|--------------| | Reduced Bot Attacks | Automated scanners typically target port 22 | High | | Log File Cleanliness | Fewer failed login attempts in logs | Medium | | Network Stealth | Less visible to casual port scans | Medium | | Compliance Requirements | Some security policies require non-standard ports | Variable | | Administrative Overhead | Easier to identify legitimate vs malicious traffic | Low |
Security Statistics
Studies show that changing the SSH port can reduce automated attack attempts by up to 99%. However, it's important to note that this is not a complete security solution but rather one layer in a comprehensive security strategy.
Security Considerations
Port Selection Guidelines
When selecting a new SSH port, consider the following factors:
| Port Range | Description | Recommendation | |------------|-------------|----------------| | 1-1023 | Well-known ports (require root privileges) | Avoid | | 1024-49151 | Registered ports (assigned by IANA) | Use with caution | | 49152-65535 | Dynamic/Private ports | Recommended |
Common Port Conflicts
Avoid these commonly used ports when selecting your new SSH port:
`
Port 80 - HTTP
Port 443 - HTTPS
Port 25 - SMTP
Port 53 - DNS
Port 110 - POP3
Port 143 - IMAP
Port 993 - IMAPS
Port 995 - POP3S
Port 3306 - MySQL
Port 5432 - PostgreSQL
`
Prerequisites
System Requirements
Before proceeding with the SSH port change, ensure you have:
- Root or sudo access to the server - Alternative access method (console, KVM, or physical access) - Basic understanding of text editors (nano, vim, or emacs) - Knowledge of your current network configuration - Backup of current SSH configuration
Required Packages
Verify that the necessary packages are installed:
`bash
Check SSH daemon status
systemctl status sshor
systemctl status sshdVerify SSH package installation
dpkg -l | grep ssh # Debian/Ubuntu rpm -qa | grep ssh # RHEL/CentOS/Fedora`Step-by-Step Guide
Step 1: Backup Current Configuration
Before making any changes, create a backup of the current SSH configuration:
`bash
Create backup directory
sudo mkdir -p /etc/ssh/backupBackup the main configuration file
sudo cp /etc/ssh/sshd_config /etc/ssh/backup/sshd_config.$(date +%Y%m%d_%H%M%S)Verify backup creation
ls -la /etc/ssh/backup/`Step 2: Edit SSH Configuration File
Open the SSH daemon configuration file for editing:
`bash
Using nano editor
sudo nano /etc/ssh/sshd_configUsing vim editor
sudo vim /etc/ssh/sshd_configUsing emacs editor
sudo emacs /etc/ssh/sshd_config`Step 3: Modify Port Configuration
Locate the port configuration line and modify it:
`bash
Find the current port setting (usually commented out)
Default configuration shows:
#Port 22Change to your desired port (example: 2222)
Port 2222`Important Notes: - Remove the hash symbol (#) to uncomment the line - Choose a port number between 1024 and 65535 - Avoid well-known ports used by other services - Document your chosen port for future reference
Step 4: Additional Security Configurations
While editing the SSH configuration, consider implementing these additional security measures:
`bash
Disable root login
PermitRootLogin noUse protocol version 2 only
Protocol 2Set maximum authentication attempts
MaxAuthTries 3Configure idle timeout
ClientAliveInterval 300 ClientAliveCountMax 2Disable password authentication (if using key-based auth)
PasswordAuthentication noDisable empty passwords
PermitEmptyPasswords noEnable public key authentication
PubkeyAuthentication yesSpecify allowed users
AllowUsers username1 username2Disable X11 forwarding if not needed
X11Forwarding no`Step 5: Validate Configuration Syntax
Before restarting the SSH service, validate the configuration syntax:
`bash
Test configuration syntax
sudo sshd -tCheck for specific configuration file
sudo sshd -t -f /etc/ssh/sshd_config`If the configuration is valid, you should see no output. Any errors will be displayed for correction.
Configuration Files and Parameters
Main Configuration File Structure
The /etc/ssh/sshd_config file contains various configuration parameters:
| Parameter | Description | Default Value | Example | |-----------|-------------|---------------|---------| | Port | SSH listening port | 22 | Port 2222 | | Protocol | SSH protocol version | 2 | Protocol 2 | | PermitRootLogin | Allow root login | yes | PermitRootLogin no | | MaxAuthTries | Max authentication attempts | 6 | MaxAuthTries 3 | | ClientAliveInterval | Keep-alive interval | 0 | ClientAliveInterval 300 | | PasswordAuthentication | Allow password auth | yes | PasswordAuthentication no |
Configuration Parameter Examples
`bash
Network and Port Configuration
Port 2222 AddressFamily any ListenAddress 0.0.0.0 ListenAddress ::Authentication Configuration
LoginGraceTime 2m PermitRootLogin no StrictModes yes MaxAuthTries 3 MaxSessions 10Public Key Authentication
PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2Password Authentication
PasswordAuthentication no PermitEmptyPasswords noChallenge Response Authentication
ChallengeResponseAuthentication noKerberos Authentication
KerberosAuthentication noGSSAPI Authentication
GSSAPIAuthentication noSession Configuration
X11Forwarding no PrintMotd no PrintLastLog yes TCPKeepAlive yes`Firewall Configuration
UFW (Uncomplicated Firewall) Configuration
If using UFW, update the firewall rules:
`bash
Check current UFW status
sudo ufw statusAllow new SSH port
sudo ufw allow 2222/tcpAdd rule with specific protocol and description
sudo ufw allow 2222/tcp comment 'SSH custom port'Remove old SSH rule (only after confirming new port works)
sudo ufw delete allow 22/tcpReload UFW rules
sudo ufw reloadVerify new rules
sudo ufw status numbered`iptables Configuration
For systems using iptables directly:
`bash
Allow incoming connections on new SSH port
sudo iptables -A INPUT -p tcp --dport 2222 -j ACCEPTAllow established connections
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPTSave iptables rules (Debian/Ubuntu)
sudo iptables-save > /etc/iptables/rules.v4Save iptables rules (RHEL/CentOS)
sudo service iptables save`firewalld Configuration
For RHEL/CentOS systems using firewalld:
`bash
Check firewalld status
sudo firewall-cmd --stateAdd new SSH port permanently
sudo firewall-cmd --permanent --add-port=2222/tcpRemove default SSH service (optional)
sudo firewall-cmd --permanent --remove-service=sshReload firewall configuration
sudo firewall-cmd --reloadVerify configuration
sudo firewall-cmd --list-ports sudo firewall-cmd --list-services`Testing and Verification
Pre-Restart Testing
Before restarting the SSH service, ensure you have alternative access:
`bash
Verify configuration syntax
sudo sshd -tCheck current SSH connections
who wVerify backup access methods are available
- Console access
- KVM/IPMI access
- Physical access
`Service Restart Methods
#### Method 1: Graceful Restart
`bash
Systemd systems
sudo systemctl restart ssh # Debian/Ubuntu sudo systemctl restart sshd # RHEL/CentOSSysV systems
sudo service ssh restart # Debian/Ubuntu sudo service sshd restart # RHEL/CentOS`#### Method 2: Reload Configuration
`bash
Reload without dropping existing connections
sudo systemctl reload ssh # Debian/Ubuntu sudo systemctl reload sshd # RHEL/CentOSSend HUP signal to SSH daemon
sudo kill -HUP $(pgrep sshd)`Connection Testing
Test the new SSH port configuration:
`bash
Test from the same server (localhost)
ssh -p 2222 username@localhostTest from remote location
ssh -p 2222 username@server_ip_addressTest with verbose output for troubleshooting
ssh -v -p 2222 username@server_ip_addressTest connection without executing commands
ssh -p 2222 -o BatchMode=yes username@server_ip_address echo "Connection successful"`Verification Commands
Confirm the SSH daemon is listening on the new port:
`bash
Check listening ports
sudo netstat -tlnp | grep ssh sudo ss -tlnp | grep sshVerify specific port
sudo lsof -i :2222 sudo netstat -tlnp | grep 2222Check SSH daemon status
sudo systemctl status ssh sudo systemctl status sshd`Troubleshooting
Common Issues and Solutions
| Issue | Symptoms | Solution |
|-------|----------|----------|
| Connection Refused | Cannot connect to new port | Check firewall rules and service status |
| Permission Denied | Authentication failures | Verify user permissions and key authentication |
| Port Already in Use | Service fails to start | Choose different port or stop conflicting service |
| Configuration Syntax Error | Service fails to restart | Run sshd -t and fix syntax errors |
| Firewall Blocking | Timeout on connection | Update firewall rules for new port |
Diagnostic Commands
`bash
Check SSH daemon logs
sudo journalctl -u ssh -f # Debian/Ubuntu sudo journalctl -u sshd -f # RHEL/CentOSView system logs
sudo tail -f /var/log/auth.log # Debian/Ubuntu sudo tail -f /var/log/secure # RHEL/CentOSCheck network connectivity
telnet server_ip 2222 nc -zv server_ip 2222Verify SSH daemon configuration
sudo sshd -T | grep port sudo sshd -T | head -20`Recovery Procedures
If you lose SSH access:
1. Console Access Recovery:
`bash
Access via console/KVM
Edit SSH configuration
sudo nano /etc/ssh/sshd_configRestore from backup
sudo cp /etc/ssh/backup/sshd_config.* /etc/ssh/sshd_configRestart SSH service
sudo systemctl restart ssh`2. Emergency Access:
`bash
Start SSH on default port temporarily
sudo /usr/sbin/sshd -p 22 -f /etc/ssh/sshd_config.backupCreate temporary SSH daemon
sudo /usr/sbin/sshd -D -p 22 &`Best Practices
Security Hardening Checklist
| Practice | Implementation | Priority | |----------|----------------|----------| | Use Non-Standard Port | Change from 22 to custom port | High | | Disable Root Login | PermitRootLogin no | High | | Use Key-Based Authentication | Disable password authentication | High | | Implement Fail2Ban | Install and configure fail2ban | High | | Regular Updates | Keep SSH packages updated | High | | Monitor Logs | Regular log review | Medium | | Use SSH Banners | Configure warning banners | Low |
Configuration Management
`bash
Create configuration management script
#!/bin/bashSSH Configuration Management Script
BACKUP_DIR="/etc/ssh/backup" CONFIG_FILE="/etc/ssh/sshd_config" DATE=$(date +%Y%m%d_%H%M%S)
Function to backup configuration
backup_config() { mkdir -p $BACKUP_DIR cp $CONFIG_FILE $BACKUP_DIR/sshd_config.$DATE echo "Configuration backed up to $BACKUP_DIR/sshd_config.$DATE" }Function to validate configuration
validate_config() { if sshd -t; then echo "Configuration is valid" return 0 else echo "Configuration has errors" return 1 fi }Function to restart SSH service
restart_ssh() { if systemctl restart ssh; then echo "SSH service restarted successfully" systemctl status ssh --no-pager else echo "Failed to restart SSH service" return 1 fi }Main execution
backup_config validate_config && restart_ssh`Monitoring and Alerting
`bash
Create log monitoring script
#!/bin/bashSSH Log Monitor
LOG_FILE="/var/log/auth.log" ALERT_EMAIL="admin@example.com"
Monitor for failed SSH attempts
tail -f $LOG_FILE | while read line; do if echo $line | grep -q "Failed password"; then echo "Failed SSH attempt detected: $line" | mail -s "SSH Alert" $ALERT_EMAIL fi done`Advanced Configurations
Multiple SSH Ports
Configure SSH to listen on multiple ports:
`bash
In /etc/ssh/sshd_config
Port 22 Port 2222 Port 2223Verify multiple ports
sudo netstat -tlnp | grep sshd`Port Knocking Implementation
Implement port knocking for additional security:
`bash
Install knockd
sudo apt-get install knockd # Debian/Ubuntu sudo yum install knock-server # RHEL/CentOSConfigure knockd
sudo nano /etc/knockd.confExample configuration
[options] UseSyslog[openSSH] sequence = 7000,8000,9000 seq_timeout = 5 command = /sbin/iptables -A INPUT -s %IP% -p tcp --dport 2222 -j ACCEPT tcpflags = syn
[closeSSH]
sequence = 9000,8000,7000
seq_timeout = 5
command = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 2222 -j ACCEPT
tcpflags = syn
`
SSH Tunneling Configuration
Configure SSH for secure tunneling:
`bash
Allow tunneling in sshd_config
AllowTcpForwarding yes GatewayPorts no PermitTunnel yesExample tunnel usage
ssh -p 2222 -L 8080:localhost:80 username@server_ip ssh -p 2222 -D 1080 username@server_ip`Automated Security Updates
`bash
Create update script for SSH
#!/bin/bashSSH Security Update Script
Update package lists
apt-get updateCheck for SSH updates
if apt list --upgradable 2>/dev/null | grep -q openssh; then echo "SSH updates available" # Backup configuration cp /etc/ssh/sshd_config /etc/ssh/backup/sshd_config.pre_update_$(date +%Y%m%d) # Update SSH packages apt-get upgrade openssh-server openssh-client -y # Restart SSH service systemctl restart ssh echo "SSH updated and restarted" else echo "No SSH updates available" fi`This comprehensive guide provides all necessary information for securely changing the SSH port on Linux systems. Remember that changing the SSH port is just one component of a comprehensive security strategy that should include strong authentication, regular updates, monitoring, and other security best practices.