First, log in to the server using SSH as the root.
1.- Create a user with sudo capabilitiessudo useradd <name>
sudo usermod -aG sudo <name>
2.- Add ~/.ssh public keysmkdir ~/.ssh
touch ~/.ssh/authorized_keys
# set permissions
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
3.- Generate SSH key pairssh-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 firewallnano /etc/docker/daemon.json
{
"iptables": false
}