Secure a new
Ubuntu server in 8 steps
Sudo user, SSH keys, ufw, fail2ban and automatic updates, with commands
The XVer team 2 min read 25 min to do Beginner
Also in ภาษาไทย
On this page
A server with port 22 open to the internet gets password guesses as a matter of routine, so do these eight things before you install anything. The commands work on Ubuntu 22.04 and 24.04 LTS.
Type your own values and the commands on this page follow
1. Update the system#
sudo apt update && sudo apt full-upgrade -y
[ -f /var/run/reboot-required ] && sudo reboot2. Create a sudo user#
Skip this if your image already gives you one.
sudo adduser NEW_USER
sudo usermod -aG sudo NEW_USER3. Sign in with a key#
Run these on your own computer.
ssh-keygen -t ed25519
ssh-copy-id NEW_USER@SERVER_IP
ssh NEW_USER@SERVER_IP4. Turn off passwords and root login#
Only after the key works. The 00 prefix matters: sshd keeps the first value it reads, and some images ship 50-cloud-init.conf with passwords on.
sudo tee /etc/ssh/sshd_config.d/00-hardening.conf <<'EOF'
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
EOF
sudo sshd -t && sudo systemctl reload ssh
sudo sshd -T | grep -E 'permitrootlogin|passwordauthentication'Both lines must say no.
5. Turn on ufw#
Allow SSH first.
sudo ufw allow OpenSSH
sudo ufw allow 80,443/tcp
sudo ufw enable
sudo ufw status verboseWith a fixed IP, narrow SSH further:
sudo ufw allow from MY_IP to any port 22 proto tcp
sudo ufw delete allow OpenSSH6. Install fail2ban#
sudo apt install -y fail2ban
sudo tee /etc/fail2ban/jail.local <<'EOF'
[sshd]
enabled = true
backend = systemd
maxretry = 5
findtime = 10m
bantime = 1h
EOF
sudo systemctl enable --now fail2ban
sudo systemctl restart fail2ban
sudo fail2ban-client status sshd7. Patch automatically#
sudo apt install -y unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades8. Back up, then try a restore#
A firewall does not help when someone drops the database. XVer can back up the whole server daily and keeps the last three; keep another copy off the server too.
See what is listening#
sudo ss -tulpnAnything on 0.0.0.0 or [::] listens on every interface. Close databases and Redis first.
Questions#
Should I move SSH off port 22?
It cuts log noise, but it does not replace keys. Turn passwords off first.
I enabled ufw and lost SSH. What now?
Open the web console and run sudo ufw allow OpenSSH, or sudo ufw disable while you fix the rules.
Do I need ufw if I use a security group?
One is enough when it is right. Two layers cover for a mistake in either.