SSH VPN tutorial

How To Change Default Ssh Port In Ubuntu

16 min read
How To Change Default Ssh Port In Ubuntu

Elevating Your Ubuntu Server Security: A Definitive Guide to Changing the Default SSH Port

In the intricate world of server management and cybersecurity, securing your infrastructure is paramount. For Ubuntu server administrators, the Secure Shell (SSH) protocol stands as the undisputed champion for remote access, offering a robust, encrypted channel for command-line operations, file transfers, and tunnel creation. However, its ubiquity also makes it a prime target for malicious actors. By default, SSH operates on port 22, a fact that is widely known and relentlessly exploited by automated bots and script kiddies scanning for vulnerabilities.

While changing the default SSH port is often debated as “security by obscurity,” it remains a fundamental and highly effective first line of defense in a layered security strategy. It significantly reduces the noise in your server logs, deters opportunistic automated attacks, and allows you to focus your more advanced security measures on genuine threats. This comprehensive guide will walk you through the process of changing the default SSH port on your Ubuntu server, providing not just the technical steps, but also the crucial context, best practices, and advanced considerations necessary for a robust and secure server environment.

Why Change the Default SSH Port? Understanding the Security Imperative

Before diving into the technicalities, it’s essential to grasp the underlying reasons for this seemingly simple configuration change. Understanding the “why” solidifies its importance within your overall server hardening strategy.

The Allure of Port 22: A Constant Target

Imagine a digital landscape where every server has a front door labeled “22.” Automated bots, armed with dictionaries of common usernames and passwords, relentlessly knock on this door, attempting to brute-force their way in. This ceaseless barrage of login attempts, often originating from compromised machines worldwide, consumes server resources, clutters log files, and, most critically, increases the chances of a successful breach if weak credentials are in use.

By moving SSH to a non-standard port, you effectively make your server invisible to the vast majority of these automated scans. While a determined attacker can still find your new port through more sophisticated scanning techniques, the immediate benefit is a dramatic reduction in unsolicited login attempts, freeing up your server’s resources and cleaning up your /var/log/auth.log file, making it easier to spot legitimate anomalies.

Beyond Obscurity: A Layered Security Approach

It’s crucial to understand that changing the SSH port is not a standalone solution; it’s a foundational component of a comprehensive SSH security best practices framework. Think of it as moving your front door to a less obvious location. While this makes it harder for casual intruders to find, you still need strong locks (key-based authentication), an alarm system (Fail2ban), and perhaps even a security guard (firewall configuration) to truly secure your property.

When combined with other measures like disabling password authentication, using strong SSH keys, implementing two-factor authentication, and employing intrusion detection systems, changing the port significantly bolsters your server’s resilience against various forms of cyber threats. It’s about creating multiple layers of defense, each contributing to the overall security posture.

Reducing Exposure and Log Noise

One of the immediate, tangible benefits of changing the SSH port is the drastic reduction in “noise” within your server’s authentication logs. When SSH is on port 22, your auth.log is often filled with thousands of failed login attempts from various IP addresses, making it challenging to identify genuine, targeted attacks or even legitimate user errors. By moving to a different port, these logs become significantly cleaner, allowing you to quickly and accurately monitor for suspicious activity, troubleshoot login issues, and gain a clearer picture of your server’s security events.

Prerequisites and Best Practices Before You Begin

Before you embark on modifying your SSH configuration, a few critical prerequisites and best practices must be observed. These steps are designed to prevent accidental lockouts and ensure a smooth transition.

Root Access or Sudo Privileges

To modify system-wide configuration files and restart services, you will need administrative privileges. Ensure you are logged in as a user with sudo access, or as the root user directly. For most Ubuntu setups, using sudo is the preferred and more secure method.

Reliable Network Connectivity

Confirm that you have stable and reliable network access to your Ubuntu server. An interrupted connection during the configuration change could lead to an incomplete setup and potential lockout.

Crucial Backup of SSH Configuration

This is arguably the most critical step. Before making any changes to sshd_config, always create a backup. This allows you to easily revert to the original configuration if something goes wrong and you find yourself unable to connect. You can do this with a simple copy command:

sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

Keep this original SSH session open until you have successfully verified access on the new port. This provides a lifeline in case of misconfiguration.

Understanding Potential Pitfalls

Be aware of the risks. Incorrectly modifying the SSH configuration or misconfiguring your firewall can lead to you being locked out of your server. Always proceed with caution, verify each step, and keep your existing SSH session open until you’ve successfully connected via the new port.

Step-by-Step Guide: Changing the SSH Port in Ubuntu

Now, let’s proceed with the actual modification process. Follow these steps meticulously to ensure a secure and successful SSH port change.

Step 1: Access Your Ubuntu Server

Begin by establishing an SSH connection to your Ubuntu server using its current default port (22). Open your terminal or SSH client and execute:

ssh your_username@your_server_ip_address

Replace your_username with your actual username and your_server_ip_address with your server’s IP address or hostname.

Step 2: Edit the SSH Daemon Configuration File

The SSH daemon’s configuration is managed by the sshd_config file. You’ll need to edit this file to specify the new port.

Open the file using your preferred text editor. nano is user-friendly for beginners, while vim is popular among experienced users:

sudo nano /etc/ssh/sshd_config

Within this file, locate the line that specifies the port. By default, it looks like this:

#Port 22

The # indicates that the line is commented out, meaning SSH uses the default port 22 implicitly. To change the port, you need to:

  1. Uncomment the line by removing the #.
  2. Change 22 to your desired new port number.

For example, to change the port to 2222, the line should look like this:

Port 2222

Choosing a New Port: When selecting a new port, consider the following:

  • Avoid common ports: Do not choose ports used by other well-known services (e.g., 80 for HTTP, 443 for HTTPS, 21 for FTP, 25 for SMTP). This can lead to conflicts and potential security issues.
  • Port Ranges:
    • Well-known ports (0-1023): Reserved for common services. Avoid these.
    • Registered ports (1024-49151): Can be used, but check for potential conflicts with other registered services.
    • Dynamic/Private/Ephemeral ports (49152-65535): These are generally safe choices as they are not reserved for specific services and are often used for temporary client connections. Choosing a port in this range can offer a slight additional layer of obscurity.
  • Memorability vs. Randomness: A slightly less common but memorable port (e.g., 2222, 2022) might be easier for you to remember, while a completely random high-numbered port offers more obscurity.

After making the change, save the file (Ctrl+O, Enter for nano) and exit the editor (Ctrl+X for nano).

Step 3: Configure the Firewall (UFW)

This is a critical step to prevent locking yourself out. Ubuntu typically uses UFW (Uncomplicated Firewall) as its default firewall management tool. If UFW is active, it will block connections to your new SSH port unless explicitly allowed.

First, check the status of UFW:

sudo ufw status

If UFW is inactive, you can skip this step, but it’s highly recommended to enable and configure it for overall server security. If it’s active and configured, you’ll see a list of allowed ports.

Now, allow traffic on your new SSH port. Replace NEW_PORT with the port number you chose (e.g., 2222):

sudo ufw allow NEW_PORT/tcp

For example:

sudo ufw allow 2222/tcp

You can also specify a specific IP address or range if you want to restrict SSH access even further:

sudo ufw allow from your_ip_address to any port NEW_PORT

After adding the new rule, it’s good practice to reload UFW to ensure the changes take effect immediately:

sudo ufw reload

Important: Do NOT delete the rule for port 22 yet. You will do this only after successfully verifying the new connection.

Step 4: Restart the SSH Service

For the changes in sshd_config to take effect, you must restart the SSH daemon service.

sudo systemctl restart sshd

If you’re using an older Ubuntu version or prefer the legacy command, you might use:

sudo service ssh restart

The systemctl command is the modern standard for managing services on systemd-based Linux distributions like current Ubuntu versions.

Step 5: Verify the New SSH Port

This is the moment of truth. Crucially, do NOT close your existing SSH session. If something goes wrong, this session is your lifeline to revert changes.

Local Verification (Optional, but Recommended)

You can verify that the SSH daemon is listening on the new port from within your existing SSH session:

sudo ss -tulpn | grep sshd

Or, if ss is not available:

sudo netstat -tulpn | grep sshd

You should see an entry indicating that sshd is listening on your chosen NEW_PORT (e.g., 0.0.0.0:2222 or :::2222).

Client-Side Verification

Open a new terminal window or SSH client on your local machine. Attempt to connect to your server using the new port:

ssh -p NEW_PORT your_username@your_server_ip_address

For example:

ssh -p 2222 your_username@your_server_ip_address

If the connection is successful, congratulations! You have successfully changed the SSH port. You can now safely close your original SSH session that was connected on port 22.

If the connection fails: Do not panic. Revisit steps 2, 3, and 4. Check your sshd_config for typos, verify your UFW rules, and ensure the SSH service restarted without errors. Since your original session is still open, you can correct any mistakes and retry.

Removing the Old Firewall Rule (Post-Verification)

Once you have successfully connected via the new port and confirmed everything is working, you can remove the UFW rule for the old port 22 to further secure your server:

sudo ufw delete allow 22/tcp

Then reload UFW:

sudo ufw reload

Verify UFW status again to confirm port 22 is no longer allowed:

sudo ufw status

If you frequently connect to your server, you can simplify future connections by updating your local SSH client configuration file (~/.ssh/config). This allows you to connect without explicitly specifying the port each time.

Open or create the ~/.ssh/config file on your local machine:

nano ~/.ssh/config

Add an entry for your server:

Host my_ubuntu_server
    Hostname your_server_ip_address
    User your_username
    Port NEW_PORT
    IdentityFile ~/.ssh/id_rsa # If you use key-based authentication

Replace my_ubuntu_server with a memorable alias, your_server_ip_address, your_username, and NEW_PORT with your specific details. Now you can simply connect using:

ssh my_ubuntu_server

Advanced Considerations and Best Practices

Changing the SSH port is a great start, but true network security involves a multi-faceted approach. Let’s delve into some advanced considerations.

Choosing an Appropriate Port

As discussed, the choice of port matters. While any non-standard port offers more obscurity than 22, opting for a port in the dynamic/private range (49152-65535) provides an additional layer of protection against port scanners that might specifically target registered ports. Avoid ports used by other critical services to prevent conflicts and ensure system stability.

Integrating with Other Security Measures

A changed SSH port is most effective when integrated into a broader Ubuntu server security strategy.

Key-Based Authentication

This is arguably the most significant security enhancement for SSH. Instead of passwords, which can be brute-forced or guessed, key-based authentication uses cryptographic key pairs. Your private key remains on your local machine, and the public key is stored on the server. This method is far more secure. After setting up key-based authentication, you can disable password authentication entirely.

Disabling Password Authentication

Once you have reliably configured and tested key-based authentication, you should disable password authentication in /etc/ssh/sshd_config. Locate the line:

#PasswordAuthentication yes

Change it to:

PasswordAuthentication no

Remember to restart the SSH service (sudo systemctl restart sshd) after this change and verify you can still connect using your SSH key.

Fail2ban

Fail2ban is an intrusion prevention framework that scans log files (like /var/log/auth.log) for suspicious patterns, such as multiple failed login attempts. When it detects such activity, it automatically updates firewall rules to temporarily or permanently ban the offending IP address. Even with a changed SSH port, Fail2ban remains invaluable for defending against targeted attacks or internal threats. Ensure Fail2ban is configured to monitor your new SSH port.

Limiting SSH Access by IP

If your server is accessed from a limited set of known IP addresses (e.g., your office, home, or specific VPN endpoints), you can configure SSH to only allow connections from those IPs. This can be done directly in sshd_config using AllowUsers, AllowGroups, or by configuring UFW rules to allow connections only from specific source IPs to your new SSH port.

Two-Factor Authentication (2FA)

For the highest level of security, consider implementing 2FA for SSH. Modules like libpam-google-authenticator can integrate with SSH to require a time-based one-time password (TOTP) in addition to your password or SSH key.

SELinux or AppArmor Implications

Ubuntu primarily uses AppArmor for mandatory access control, not SELinux. Generally, changing the SSH port does not require specific AppArmor profile adjustments, as AppArmor’s default SSH profile is typically flexible enough to accommodate port changes. However, in highly customized or hardened environments, it’s always wise to check AppArmor logs (/var/log/syslog or dmesg) for any denials related to the SSH service after a port change, though this is rare for this specific modification.

Monitoring and Logging

Even after implementing robust security measures, continuous monitoring is key. Regularly review your /var/log/auth.log for any unusual activity. Tools like logwatch or more advanced SIEM (Security Information and Event Management) solutions can automate log analysis and alert you to potential security incidents. With a non-standard SSH port, your logs will be much cleaner, making it easier to spot genuine threats.

Troubleshooting Common Issues

Despite careful planning, issues can arise. Here’s how to troubleshoot common problems:

“Connection Refused”

  • Firewall: The most common cause. Check your UFW rules (sudo ufw status) to ensure the new port is explicitly allowed.
  • SSH Service Not Running: Verify the SSH daemon is active (sudo systemctl status sshd). If not, restart it.
  • Incorrect Port: Double-check that you’re using the correct new port number in your client command and that it matches the Port directive in sshd_config.

“Connection Timed Out”

  • Firewall (External): If your server is in a cloud environment (e.g., AWS EC2, DigitalOcean), ensure that the cloud provider’s firewall (security groups, network ACLs) also allows traffic on your new SSH port. This is distinct from UFW.
  • Network Issue: A general network connectivity problem between your client and the server.

“Permission Denied”

  • Incorrect Username/Password: Verify your credentials.
  • SSH Key Issues: If using key-based authentication, ensure your private key has the correct permissions (chmod 400 ~/.ssh/id_rsa) and that the public key is correctly installed in ~/.ssh/authorized_keys on the server.
  • Disabling Password Authentication: If you disabled password authentication, ensure you are using SSH keys.

Getting Locked Out

If you accidentally close your original session and cannot reconnect:

  • Console Access: Most cloud providers offer a web-based console or KVM access. Use this to log in directly to your server and revert changes to sshd_config or UFW.
  • Cloud Provider Recovery: Some cloud platforms offer recovery modes or snapshot restoration options that might allow you to access or revert your server to a previous state.
  • Backup: This is why the backup of sshd_config is so vital. If you can access the console, copy sshd_config.bak back to sshd_config and restart SSH.

Reverting Changes

Should you need to revert the SSH port back to 22 (or any other port), the process mirrors the steps for changing it:

  1. Access your server via the currently configured new SSH port.
  2. Edit /etc/ssh/sshd_config and change the Port directive back to 22 (or comment it out by adding a #).
  3. Modify your UFW rules:
    • Allow port 22: sudo ufw allow 22/tcp
    • Delete the rule for your old custom port: sudo ufw delete allow NEW_PORT/tcp
    • Reload UFW: sudo ufw reload
  4. Restart the SSH service: sudo systemctl restart sshd.
  5. Verify the connection on port 22 from a new terminal.

Conclusion

Changing the default SSH port on your Ubuntu server is a straightforward yet impactful step in enhancing your server’s security posture. While it’s not a silver bullet against all forms of attack, it significantly reduces the attack surface from automated bots and opportunistic scanners, cleans up your server logs, and allows you to focus on more sophisticated threats. When combined with other SSH security best practices such as key-based authentication, disabling password logins, and implementing Fail2ban, you create a robust and resilient environment for your critical infrastructure. Proactive vulnerability management and continuous monitoring are the hallmarks of a secure system, and changing the SSH port is an excellent starting point on that journey.

Question and Answer (Q&A)

Q: Is changing the SSH port security by obscurity?

A: While it does rely on obscurity to some extent, it’s more accurately described as a practical first layer of defense. It won’t stop a highly determined, targeted attacker who can perform comprehensive port scans, but it will deter the vast majority of automated, untargeted brute-force attacks and significantly reduce log noise. It’s an effective part of a multi-layered security strategy, not a standalone solution.

Q: What port range should I choose for my new SSH port?

A: It’s best to choose a port from the dynamic/private range, which is 49152-65535. These ports are not officially registered for specific services and are less likely to conflict with other applications or be targeted by common port scans. Avoid well-known ports (0-1023) and registered ports (1024-49151) to minimize conflicts and potential security risks.

Q: Can I run SSH on multiple ports simultaneously?

A: Yes, you can. In the /etc/ssh/sshd_config file, you can add multiple Port directives, each on its own line. For example:

Port 22
Port 2222

This allows you to transition gradually, keeping port 22 open temporarily while you test the new port. However, for maximum security, it’s recommended to eventually disable port 22 once you’ve confirmed the new port is fully functional and secure.

Q: What if I forget the new SSH port I configured?

A: If you forget the new port and get locked out, your primary recovery method will be through out-of-band access. This typically means using your cloud provider’s web-based console (e.g., EC2 Instance Connect, DigitalOcean console) or KVM access if it’s a physical server. Once you have console access, you can log in directly, edit /etc/ssh/sshd_config to find or change the port, and restart the SSH service.

Q: Does changing the port affect existing SSH keys?

A: No, changing the SSH port does not affect your existing SSH keys. Key-based authentication relies on the cryptographic pair (public and private keys), not the port number. You will still use the same private key to authenticate, but you’ll need to specify the