Starting a new Linux Ubuntu Server and secure it with UFW Firewall


First, log in to the server using SSH as the root. 

1.- Create a user with sudo capabilities

sudo useradd <name>

sudo usermod -aG sudo <name>

2.- Add ~/.ssh public keys

mkdir ~/.ssh
touch ~/.ssh/authorized_keys

# set permissions
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

3.- Generate SSH key pair

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

Follow the steps, set a passphrase, and copy both generated files, private and public keys, into a safe location. Write the public key into the authorized_keys file.

cat <ir_rsa>.pub >> ~/.ssh/authorized_keys

4.- Test keys from the outside world!

ssh -i <ir_rsa:privatekey> <name>@<server IP> # MUST be successful 

Convert private key to .ppk if necessary using PuttyGen

5.- Only allow SSH connections using a private key (public key authentication)

sudo nano /etc/ssh/sshd_config

# Disable Password Authentication:
PasswordAuthentication no

# Enable Public Key Authentication:
PubkeyAuthentication yes

# Restart sshd service
sudo systemctl restart sshd

6.- Install UFW firewall and rules to allow port 22, deny all in, and allow all out. This can vary based on the application. For PostgreSQL servers, we can open port 5432 for IPs, networks, or subnetworks. An application can also require to allow all port 80 and redirect HTTP to port 443 for secure encrypted connections, so allowing 443 is required

sudo apt-get update
sudo apt-get install ufw

sudo nano /etc/default/ufw

# Ensure the DEFAULT_INPUT_POLICY is set to DROP to deny incoming connections by default
DEFAULT_INPUT_POLICY="DROP"

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp

sudo ufw allow from X.X.X.X to any port <port> proto tcp

# enable UFW
sudo ufw enable

Optional:

Docker + UFW firewall

nano /etc/docker/daemon.json

{
  "iptables": false
}

Did you find this article useful?



  • oAuth2 Authentication

    https://dzone.com/articles/the-right-flow-for-the-job-which-oauth-20-flow-sho OAuth 2.0 is a well-adopted delegated authorization framework that is a...

  • KAFKA Use cases

    Data Streaming: Think of data as a fast-flowing river. We need a way to tap into that stream, harness its power, and direct it where it needs to ...

  • Install docker in Linux ubuntu

    #!/bin/bash # Function to check if a command is available command_exists() {     command -v "$1" >/dev/null 2>&1 } # Fu...

  • PostgreSQL Database Replication

    Primary Server Setup Firewalls to allow connectivity sudo ufw allow from <standbyIP> to any port <port> proto <protocol:-tcp>s...