インフラ・運用 2026.02.16

SSH Port 22 Attack Prevention: Complete Security Guide

約15分で読めます

Learn how to secure your SSH server by changing the default port 22. Step-by-step implementation guide with dual-port strategy and security hardening tips.

Are You Concerned About SSH Security Attacks?

Do you manage servers and worry about these security issues?

  • Constant brute force attacks on SSH port 22
  • Security logs filled with unauthorized access attempts
  • Concerns about server compromise through SSH vulnerabilities
  • Uncertainty about proper SSH hardening procedures

If any of these sound familiar, you're not alone. SSH security is a critical concern for system administrators and web developers managing their own servers. The default SSH port 22 is under constant attack, but there's a systematic approach to significantly improve your server's security posture.

Why Port 22 is a Primary Target for Attackers

The Mathematics of Attack Frequency

Port 22 faces an overwhelming volume of attacks due to its predictable nature. In our experience managing client servers over the past 20 years, we've observed attack patterns that reveal the scope of this challenge.

Real-World Attack Scenarios

Automated scanning tools continuously probe port 22 across the internet. These attacks typically follow predictable patterns:

  • Dictionary attacks using common username/password combinations
  • Brute force attempts targeting root and admin accounts
  • Credential stuffing using leaked password databases
  • Exploitation attempts targeting known SSH vulnerabilities

One client's e-commerce server experienced over 20,000 failed SSH login attempts in a single day before implementing port changes. The constant attack volume not only posed security risks but also consumed server resources and filled log files.

The Security Through Obscurity Debate

While changing SSH ports isn't a complete security solution, it dramatically reduces noise and automated attacks. This approach provides several benefits:

  • Reduced attack surface from automated scanning
  • Cleaner security logs for easier monitoring
  • Lower resource consumption from failed connection attempts
  • Additional time to detect and respond to targeted attacks

サーバー・インフラでお困りですか?

障害対応・移行・パフォーマンスチューニングなど、ご相談ください

無料で相談する

Step-by-Step SSH Port Migration Procedure

Phase 1: Preparation and Dual-Port Strategy

The safest approach involves temporarily running SSH on both the old and new ports. This prevents lockouts if configuration issues arise.

1. Choose Your New Port

Select a port between 1024-65535 that doesn't conflict with existing services:

# Check which ports are currently in use
sudo netstat -tlnp | grep :22
sudo netstat -tlnp | grep :2222  # Example new port

2. Backup Current Configuration

# Create backup of SSH configuration
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup.$(date +%Y%m%d)

# Verify backup
ls -la /etc/ssh/sshd_config.backup*

3. Configure Dual Port Setup

Edit the SSH configuration to listen on both ports initially:

sudo nano /etc/ssh/sshd_config

Add or modify these lines:

# Listen on both ports temporarily
Port 22
Port 2222  # Your chosen new port

# Enable these security settings while we're here
PermitRootLogin no
PasswordAuthentication no
PermitEmptyPasswords no
X11Forwarding no
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2

Phase 2: Service Configuration and Testing

4. Update Service Configuration

Restart SSH service and verify both ports are active:

# Test configuration syntax
sudo sshd -t

# Restart SSH service
sudo systemctl restart sshd

# Verify both ports are listening
sudo netstat -tlnp | grep sshd

Expected output should show:

tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1234/sshd
tcp 0 0 0.0.0.0:2222 0.0.0.0:* LISTEN 1234/sshd

5. Firewall Configuration

Update firewall rules to allow the new port:

# Allow new SSH port
sudo ufw allow 2222/tcp

# Verify rules
sudo ufw status numbered

6. Test New Port Connection

From another machine or session, test the new port:

# Test connection to new port
ssh -p 2222 username@your-server-ip

# If using key authentication
ssh -i /path/to/key -p 2222 username@your-server-ip

Phase 3: Client Configuration and Port Transition

7. Update SSH Client Configurations

Update your local SSH config for seamless connections:

# Edit local SSH config
nano ~/.ssh/config

# Add or update server entry
Host myserver
    HostName your-server-ip
    Port 2222
    User username
    IdentityFile ~/.ssh/your-key

8. Final Port Migration

Once you've confirmed the new port works correctly, remove port 22:

# Edit SSH config to remove port 22
sudo nano /etc/ssh/sshd_config

# Change from:
# Port 22
# Port 2222
# To:
Port 2222

# Restart SSH
sudo systemctl restart sshd

9. Remove Old Port from Firewall

# UFW example
sudo ufw delete allow 22/tcp

# Verify final firewall state
sudo ufw status

Common Pitfalls and How to Avoid Them

Cloud Provider Firewall Forgotten

This is the most frequent mistake we encounter. Cloud providers often have multiple firewall layers:

AWS Security Groups:

# Check current security group rules
aws ec2 describe-security-groups --group-ids sg-xxxxxxxxx

# Add new SSH port rule
aws ec2 authorize-security-group-ingress \
  --group-id sg-xxxxxxxxx \
  --protocol tcp \
  --port 2222 \
  --cidr 0.0.0.0/0

Google Cloud Firewall:

# Create firewall rule
gcloud compute firewall-rules create allow-ssh-custom \
  --allow tcp:2222 \
  --source-ranges 0.0.0.0/0

SELinux Context Issues

On RHEL/CentOS systems, SELinux may block non-standard SSH ports:

# Check if SELinux is enforcing
sestatus

# Allow SSH on custom port
sudo semanage port -a -t ssh_port_t -p tcp 2222

# Verify the port is added
sudo semanage port -l | grep ssh

If semanage isn't available:

# Install policy tools
sudo yum install policycoreutils-python-utils
# or on newer systems:
sudo dnf install policycoreutils-python-utils

Client Configuration Chaos

Maintaining multiple client configurations can become unwieldy. Create a systematic approach:

# Create a master SSH config template
cat > ~/.ssh/config.template << 'EOF'
# Production servers
Host prod-*
    Port 2222
    User deploy
    IdentityFile ~/.ssh/production-key
    
# Development servers
Host dev-*
    Port 2223
    User developer
    IdentityFile ~/.ssh/development-key
EOF

Service Restart Failures

Configuration syntax errors can prevent SSH from starting:

# Always test configuration before restart
sudo sshd -T | head -20  # Show parsed configuration
sudo sshd -t             # Test configuration syntax

# If SSH fails to start, check logs
sudo journalctl -u sshd -n 50

Advanced SSH Hardening Beyond Port Changes

Key-Based Authentication Setup

Disable password authentication entirely:

# Generate strong SSH key pair (if not already done)
ssh-keygen -t ed25519 -b 4096 -f ~/.ssh/server-key

# Copy public key to server
ssh-copy-id -i ~/.ssh/server-key.pub -p 2222 user@server

# Update sshd_config
PasswordAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey

Fail2Ban Implementation

Automate IP blocking for repeated failed attempts:

# Install fail2ban
sudo apt update && sudo apt install fail2ban  # Ubuntu/Debian
sudo yum install epel-release && sudo yum install fail2ban  # RHEL/CentOS

# Create custom jail for SSH
sudo nano /etc/fail2ban/jail.local

Configuration example:

[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600

Connection Rate Limiting

Implement iptables-based rate limiting:

# Limit SSH connections per IP
sudo iptables -A INPUT -p tcp --dport 2222 -m conntrack --ctstate NEW -m recent --set
sudo iptables -A INPUT -p tcp --dport 2222 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 4 -j DROP

Network Access Restrictions

Limit SSH access to specific IP ranges:

# Allow SSH only from office network
sudo iptables -A INPUT -p tcp --dport 2222 -s 192.168.1.0/24 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 2222 -j DROP

Measuring Security Improvement Results

After implementing these changes, you should observe significant improvements in security metrics:

One client's WordPress hosting server saw a 99.7% reduction in SSH attack attempts within two weeks of implementing these changes. Their server logs became manageable again, and system resources previously consumed by handling attacks were freed for legitimate traffic.

サーバー・インフラでお困りですか?

障害対応・移行・パフォーマンスチューニングなど、ご相談ください

無料で相談する

サーバー管理、丸ごとお任せください

サーバー保守・運用

監視・障害対応・パフォーマンス改善まで、安定稼働をサポートします

200件以上の制作実績 顧客満足度97% 初回相談無料

※ 通常1営業日以内にご返信します

Next Steps: Your SSH Security Action Plan

Implementing SSH security improvements requires careful planning and execution. Start with these immediate actions:

Week 1: Assessment and Planning

  • Audit current SSH configurations across all servers
  • Document existing access patterns and users
  • Choose standardized custom ports for different server types

Week 2: Implementation

  • Implement dual-port strategy on test servers first
  • Update firewall configurations and test thoroughly
  • Begin client configuration updates

Week 3: Monitoring and Refinement

  • Monitor security logs for improvement metrics
  • Fine-tune fail2ban and rate limiting rules
  • Document procedures for team members

Ongoing: Maintenance and Improvement

  • Regular security audits and log reviews
  • Key rotation and access management
  • Stay updated on SSH security best practices

SSH security doesn't end with changing ports—it's an ongoing process of monitoring, updating, and improving your security posture. The steps outlined here provide a solid foundation, but consider working with experienced system administrators to ensure your specific environment receives appropriate security measures.

When implemented correctly, these SSH hardening techniques transform your server from an easy target into a hardened system that deters casual attackers while maintaining convenient access for legitimate users. The investment in proper SSH security pays dividends in reduced security incidents and peace of mind.

この記事をシェア

サーバー・インフラの課題を解決します

構築・移行・監視・障害対応まで、安定した運用環境をご提供します。 初回相談は無料です。

※ 1営業日以内にご返信いたします

この技術でお困りなら

無料でプロに相談できます

相談する
AIに無料相談