Setting Up and Securing SSH on Ubuntu 22.04: A Comprehensive Guide

In this tutorial we will guide you through the process of enabling SSH on your Ubuntu 22.04 system, configuring the appropriate firewall rules to allow inbound connections, and changing the default SSH port for enhanced security.

Prerequisites

  • An Ubuntu 22.04 system with root privileges

Step 1: Update the System

Before you start, make sure your system is up to date. Open a terminal window and run the following commands:

sudo apt update
sudo apt upgrade

Step 2: Install the OpenSSH Server

To enable SSH on your Ubuntu system, you'll need to install the OpenSSH server. Run the following command in the terminal window:

sudo apt install openssh-server

Step 3: Configure Firewall Rules for SSH

By default, Ubuntu comes with the Uncomplicated Firewall (UFW) to manage firewall rules. First, check the status of UFW by running:

sudo ufw status

If UFW is inactive, enable it with the following command:

sudo ufw enable

Next, allow inbound SSH connections by adding a new firewall rule:

sudo ufw allow ssh

Step 4: Change the Default SSH Port

In this example, we'll change the default SSH port from 22 to 33556. You can choose a different port number if you prefer, but make sure it's not already in use by another service.

First, create a backup of the original SSH configuration file:

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

Next, open the SSH configuration file using a text editor like nano:

sudo nano /etc/ssh/sshd_config

Find the line that starts with #Port 22 and change it to the desired port number. Remove the # at the beginning of the line to uncomment it. For example:

Port 33556

Save the file and exit the text editor.

Step 5: Configure Firewall Rules for the Custom SSH Port

Update the firewall rules to allow inbound connections on the custom SSH port. First, delete the previous SSH rule:

sudo ufw delete allow ssh

Then, add a new rule for the custom SSH port:

sudo ufw allow 33556/tcp

Step 6: Restart the SSH Service

Restart the SSH service to apply the changes:

sudo systemctl restart ssh

Step 7: Verify the Configuration

To verify that SSH has been enabled and the new SSH port and firewall rules have been configured correctly, run the following command in the terminal window:

sudo systemctl status ssh

If the configuration was successful, you should see information about the SSH service running with the new port number.

Step 8: Connect to the Custom SSH Port

When connecting to your system via SSH, make sure to specify the new custom port. For example, if your system's IP address is 10.20.30.40 and you've changed the SSH port to 33556, use the following command:

ssh -p 33556 yourusername@10.20.30.40

You've successfully enabled SSH, configured the necessary firewall rules, and changed the default SSH port on your Ubuntu 22.04 system. Remember to use the custom port when connecting to your system via SSH in the future.