How to Change SSH Port for Enhanced Linux Server Security

Learn to secure your Linux server by changing the default SSH port 22. Complete guide with configuration steps, firewall setup, and security best practices.

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 ssh

or

systemctl status sshd

Verify 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/backup

Backup 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_config

Using vim editor

sudo vim /etc/ssh/sshd_config

Using 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 22

Change 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 no

Use protocol version 2 only

Protocol 2

Set maximum authentication attempts

MaxAuthTries 3

Configure idle timeout

ClientAliveInterval 300 ClientAliveCountMax 2

Disable password authentication (if using key-based auth)

PasswordAuthentication no

Disable empty passwords

PermitEmptyPasswords no

Enable public key authentication

PubkeyAuthentication yes

Specify allowed users

AllowUsers username1 username2

Disable 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 -t

Check 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 10

Public Key Authentication

PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2

Password Authentication

PasswordAuthentication no PermitEmptyPasswords no

Challenge Response Authentication

ChallengeResponseAuthentication no

Kerberos Authentication

KerberosAuthentication no

GSSAPI Authentication

GSSAPIAuthentication no

Session 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 status

Allow new SSH port

sudo ufw allow 2222/tcp

Add 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/tcp

Reload UFW rules

sudo ufw reload

Verify 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 ACCEPT

Allow established connections

sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Save iptables rules (Debian/Ubuntu)

sudo iptables-save > /etc/iptables/rules.v4

Save iptables rules (RHEL/CentOS)

sudo service iptables save `

firewalld Configuration

For RHEL/CentOS systems using firewalld:

`bash

Check firewalld status

sudo firewall-cmd --state

Add new SSH port permanently

sudo firewall-cmd --permanent --add-port=2222/tcp

Remove default SSH service (optional)

sudo firewall-cmd --permanent --remove-service=ssh

Reload firewall configuration

sudo firewall-cmd --reload

Verify 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 -t

Check current SSH connections

who w

Verify 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/CentOS

SysV 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/CentOS

Send 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@localhost

Test from remote location

ssh -p 2222 username@server_ip_address

Test with verbose output for troubleshooting

ssh -v -p 2222 username@server_ip_address

Test 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 ssh

Verify specific port

sudo lsof -i :2222 sudo netstat -tlnp | grep 2222

Check 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/CentOS

View system logs

sudo tail -f /var/log/auth.log # Debian/Ubuntu sudo tail -f /var/log/secure # RHEL/CentOS

Check network connectivity

telnet server_ip 2222 nc -zv server_ip 2222

Verify 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_config

Restore from backup

sudo cp /etc/ssh/backup/sshd_config.* /etc/ssh/sshd_config

Restart 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.backup

Create 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/bash

SSH 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/bash

SSH 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 2223

Verify 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/CentOS

Configure knockd

sudo nano /etc/knockd.conf

Example 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 yes

Example 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/bash

SSH Security Update Script

Update package lists

apt-get update

Check 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.

Tags

  • Network Hardening
  • SSH
  • linux security
  • server-configuration
  • system-administration

Related Articles

Popular Technical Articles & Tutorials

Explore our comprehensive collection of technical articles, programming tutorials, and IT guides written by industry experts:

Browse all 8+ technical articles | Read our IT blog

How to Change SSH Port for Enhanced Linux Server Security