DebianDebian Based

How To Change SSH Listening Port on Debian 12

Change SSH Listening Port on Debian 12

Securing your Debian 12 server is essential in today’s cyber landscape, and one of the simplest yet effective security measures is changing the default SSH port. By default, SSH runs on port 22, making it a prime target for automated attacks and malicious bots constantly scanning the internet. This comprehensive guide will walk you through the process of changing your SSH listening port on Debian 12 (Bookworm), enhancing your server’s security through a simple configuration change.

Understanding SSH and Port Security

SSH (Secure Shell) is a cryptographic network protocol that enables secure system administration and file transfers over unsecured networks. It provides a secure channel over an unsecured network by using strong encryption to protect the communication between client and server.

The default SSH port is 22, which is widely known and frequently targeted by automated scanning tools and bots. These automated systems constantly probe servers across the internet, attempting to find open SSH ports and exploit weak credentials through brute force attacks.

Changing your SSH port offers several security benefits:

  • Reduced exposure to automated attacks targeting port 22
  • Fewer log entries from random scanning attempts
  • An additional layer in your defense-in-depth strategy

However, it’s important to understand that changing the SSH port falls under “security through obscurity” – a technique that relies on secrecy rather than inherent security measures. While it can significantly reduce automated attacks, it should be considered just one component of a comprehensive security strategy.

Prerequisites Before Making Changes

Before proceeding with changing your SSH port, ensure you have:

  • Root or sudo privileges on your Debian 12 system
  • Current SSH access to your server
  • Basic understanding of command-line text editors (like nano or vim)
  • Knowledge of your system’s firewall configuration
  • A backup plan in case something goes wrong

It’s also recommended to update your system before making configuration changes:

sudo apt update && sudo apt upgrade -y

This ensures you’re working with the latest packages and security patches on your Debian 12 system.

Step 1: Checking Current SSH Configuration

First, you need to verify your current SSH configuration to understand the existing setup before making changes.

To check if SSH is installed and running:

sudo systemctl status ssh

To verify the current SSH port:

sudo grep -i port /etc/ssh/sshd_config

This command will display the current port configuration in the SSH daemon configuration file. By default, you should see Port 22 or the line might be commented out with a # symbol, indicating that the default port 22 is being used.

You can also check which ports SSH is actively listening on using:

sudo netstat -pnltu | grep ssh

Or if netstat isn’t available:

sudo ss -tulpn | grep ssh

The output will show the SSH daemon (sshd) listening on port 22 (or another port if previously configured).

Step 2: Backing Up the SSH Configuration

Before modifying any system configuration files, it’s crucial to create backups. This allows you to revert to a working state if anything goes wrong during the process.

Create a backup of the SSH configuration file:

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

This command creates a copy of your SSH configuration file with the .backup extension. If you encounter issues after making changes, you can restore this backup with:

sudo cp /etc/ssh/sshd_config.backup /etc/ssh/sshd_config
sudo systemctl restart ssh

Creating proper backups is an essential practice for system administrators and can save significant time and stress when troubleshooting.

Step 3: Editing the SSH Configuration File

Now that you have a backup, you can proceed to modify the SSH configuration:

1. Open the SSH configuration file using your preferred text editor. In this example, we’ll use nano:

sudo nano /etc/ssh/sshd_config

2. Look for the line that specifies the port. It typically appears near the beginning of the file and might be commented out (prefixed with a #):

#Port 22

3. Uncomment the line by removing the # character and change the port number to your preferred value:

Port 2222

When selecting a new port number, keep these considerations in mind:

  • Choose a port number above 1024 to avoid requiring root privileges
  • Avoid well-known ports used by common services (like 80, 443, 3306)
  • The valid range for port numbers is 1-65535
  • Consider using ports in the range 49152-65535 (the dynamic/private ports range)

4. Save the changes and exit the text editor. In nano, press Ctrl + O to write the changes, Enter to confirm, and Ctrl + X to exit.

It’s important to choose a port number that isn’t already in use by another service on your system to avoid conflicts. Common ports to avoid include 20, 21, 23, 25, 53, 80, 110, 443, and other standard service ports.

Step 4: Configuring the Firewall

After changing the SSH port in the configuration file, you need to update your firewall rules to allow connections to the new port. Otherwise, you might lock yourself out of the server.

For UFW (Uncomplicated Firewall)

If you’re using UFW, which is common on Debian systems:

1. Allow connections to the new SSH port:

sudo ufw allow 2222/tcp

2. Verify the new rule has been added:

sudo ufw status

3. After confirming the new port works, you can optionally remove the rule for port 22:

sudo ufw delete allow 22/tcp

4. Apply the changes by reloading the firewall:

sudo ufw reload

For iptables

If you’re directly using iptables:

1. Add a rule to allow the new SSH port:

sudo iptables -A INPUT -p tcp --dport 2222 -j ACCEPT

2. Save the iptables rules to persist across reboots:

sudo apt install iptables-persistent
sudo netfilter-persistent save

Configuring your firewall correctly is crucial – if you forget this step, you might lose access to your server after the SSH service restarts on the new port.

Step 5: Restarting the SSH Service

After modifying the configuration and updating the firewall, you need to restart the SSH service for the changes to take effect:

sudo systemctl restart ssh

Or alternatively:

sudo systemctl restart sshd

To verify that the service restarted successfully and is running properly:

sudo systemctl status ssh

The output should show that the service is “active (running)”. This confirms that the SSH daemon has successfully restarted with the new configuration.

Important safety tip: Don’t close your current SSH session until you’ve verified that you can connect on the new port. This way, if there’s an issue with the new configuration, you’ll still have access to fix it.

Step 6: Verifying and Testing the New Configuration

Before logging out of your current session, it’s essential to verify that SSH is listening on the new port and that you can establish a connection:

1. Check that SSH is listening on the new port:

sudo ss -tulpn | grep ssh

You should see output showing the sshd process listening on your new port (e.g., 2222).

2. Open a new terminal window and try connecting to your server using the new port:

ssh username@your_server_ip -p 2222

Replace username with your username, your_server_ip with your server’s IP address, and 2222 with your chosen port number.

3. If the connection is successful, you’ll be prompted for your password or SSH key passphrase, and you should get a shell session on the server.

4. Only after confirming that the new port works correctly, you can close your original SSH session and continue working through the new connection.

Advanced SSH Security Measures

Changing the SSH port is just one aspect of securing your SSH server. To further enhance security, consider implementing these additional measures:

Key-based Authentication

Using SSH key pairs instead of passwords provides stronger security:

1. Generate an SSH key pair on your local machine:

ssh-keygen -t ed25519 -C "your_email@example.com"

2. Copy the public key to your server:

ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 2222 username@your_server_ip

3. Disable password authentication by editing /etc/ssh/sshd_config:

PasswordAuthentication no

4. Restart SSH to apply the changes:

sudo systemctl restart ssh

Configure Fail2ban

Fail2ban is a service that monitors login attempts and blocks IP addresses that show malicious signs:

1. Install Fail2ban:

sudo apt install fail2ban

2. Create a custom configuration:

sudo nano /etc/fail2ban/jail.local

3. Add configuration for SSH on your custom port:

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

4. Restart Fail2ban:

sudo systemctl restart fail2ban

These advanced security measures, when combined with changing the default SSH port, significantly enhance your server’s security posture.

Common Issues and Troubleshooting

Even with careful planning, you might encounter issues when changing your SSH port. Here are some common problems and their solutions:

Connection Refused Error

If you receive a “Connection refused” error when trying to connect to the new port:

1. Verify the SSH service is running:

sudo systemctl status ssh

2. Check if the SSH daemon is listening on the correct port:

sudo ss -tulpn | grep ssh

3. Ensure the firewall is allowing connections to the new port:

sudo ufw status

4. Check for syntax errors in the SSH configuration:

sudo sshd -t

This command tests the configuration file for errors without restarting the service.

SELinux Issues

If your system uses SELinux, you might need to update the security contexts:

sudo semanage port -a -t ssh_port_t -p tcp 2222

Cannot Connect After Reboot

If you can’t connect after a system reboot:

1. Access your server through an alternative method (console access, VNC, etc.)

2. Check if the SSH service started properly:

sudo systemctl status ssh

3. Verify that your firewall rules were saved and loaded correctly:

sudo ufw status

4. If necessary, restore your backup configuration:

sudo cp /etc/ssh/sshd_config.backup /etc/ssh/sshd_config
sudo systemctl restart ssh

Proper troubleshooting requires understanding SSH logs, which can be viewed with:

sudo journalctl -u ssh

This command displays logs specific to the SSH service, which can help identify the cause of any issues.

Best Practices for SSH Port Management

To maintain a secure and well-managed SSH environment:

1. Document your changes: Keep records of port changes in your system documentation.

2. Use consistent ports across environments: When managing multiple systems, use the same non-standard port when possible to simplify administration.

3. Regularly audit your SSH configuration: Periodically review your SSH settings to ensure they remain secure.

4. Consider port knocking or SSH jump servers: For highly sensitive environments, implement advanced techniques like port knocking or gateway servers.

5. Monitor SSH connection attempts: Set up logging and alerts for failed SSH connection attempts to detect potential brute force attacks.

6. Keep SSH software updated: Regularly update OpenSSH to protect against newly discovered vulnerabilities.

Remember that changing the SSH port is not a substitute for other security measures but works best as part of a comprehensive security strategy.

Additional Security Considerations

Beyond changing your SSH port, consider these additional security measures:

1. Limit user access: Configure SSH to allow only specific users to connect.

AllowUsers username1 username2

2. Implement connection timeouts: Add these lines to your SSH configuration:

ClientAliveInterval 300
ClientAliveCountMax 2

This disconnects inactive sessions after approximately 10 minutes.

3. Disable root login: Prevent direct root login via SSH:

PermitRootLogin no

4. Use SSH protocol version 2: Ensure you’re using the more secure SSH protocol version:

Protocol 2

5. Regular security audits: Periodically scan your system for vulnerabilities and unnecessary open ports.

Implementing these additional measures creates a robust security posture that goes beyond simply changing the default SSH port.

Congratulations! You have successfully changed port SSH. Thanks for using this tutorial to change the SSH listening port on the Debian 12 “Bookworm” system. For additional help or useful information, we recommend you check the official Debian website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button