Explore WaseerHost

Appearance

GuideSecurity 11 min read

How to secure a VPS: first-hour Linux hardening checklist

Secure a VPS in its first hour with a sudo user, SSH keys, no password login, a ufw firewall, automatic updates, fail2ban and backups. Commands for Ubuntu and Debian.

How to secure a VPS: first-hour Linux hardening checklist

Summarize with:

Share:

To secure a VPS, do eight things in the first hour: update it, create a non-root sudo user, switch to SSH keys, turn off password and root login, enable a firewall, confirm automatic security updates, add fail2ban and set up backups. This guide gives the commands for Ubuntu and Debian in an order that keeps a working login open at every step. The SSH, firewall and update commands follow the Ubuntu Server documentation, the OpenSSH manual pages and the ufw manual.

Key takeaways

  • Keep your first root session open until you have logged in as the new user from a second terminal. That open session is how you undo a mistake.
  • SSH keys with PasswordAuthentication no stop password guessing. A firewall and fail2ban add to that, but they do not replace it.
  • OpenSSH uses the first value it finds for each setting, so a config file that sorts earlier can override your change. Check the result with sudo sshd -T.
  • Ubuntu installs security updates automatically by default. Reboots are off by default, so decide how the server will restart after kernel updates.
  • A backup stored only on the same VPS does not protect you if you lose the server. Keep a copy somewhere else and test a restore.

Before you start

You need three things:

  • The server's IP address and the root password or SSH key your provider gave you.
  • A terminal with an SSH client on your own computer. If you have never connected before, read how to SSH into a VPS first.
  • About an hour without interruptions.

The examples use deploy as the new user name and 203.0.113.10 as the server address. Replace both with your own values. The steps suit a new server from any provider, including a WaseerHost VPS.

Log in as root and keep that terminal open for the whole guide.

bash
ssh [email protected]

How to secure a VPS in eight steps

1. Update the system

A new image can be weeks behind on patches. Refresh the package lists and install the pending upgrades.

bash
apt update
apt upgrade

If the file /var/run/reboot-required exists afterwards, an update has asked for a restart. Reboot with reboot, then log in again.

2. Create a non-root sudo user

Daily work as root means every typing mistake runs with full privileges. Create a normal user and add it to the sudo group. On Ubuntu and Debian, members of that group can run commands as root with sudo.

bash
adduser deploy
adduser deploy sudo

adduser asks for a password. Choose a long one and store it in a password manager, because sudo will ask for it. If the sudo command is missing, which can happen on a minimal Debian image, install it as root with apt install sudo.

3. Set up SSH key login

An SSH key pair replaces the password for remote login. The private key stays on your computer and the public key goes on the server.

  1. On your own computer, not the server, create a key. Ed25519 is the default key type in current OpenSSH.

    bash
    ssh-keygen -t ed25519

    Accept the default file location and set a passphrase when asked.

  2. Copy the public key to the new user.

    bash
    ssh-copy-id [email protected]

    ssh-copy-id logs in with the user's password and appends your key to ~/.ssh/authorized_keys on the server. If your computer has no ssh-copy-id command, paste the contents of id_ed25519.pub as a new line in that file instead.

  3. If your provider created the server with your key already installed for root, you can copy that file to the new user. Run this in the root session.

    bash
    mkdir -p /home/deploy/.ssh
    cp /root/.ssh/authorized_keys /home/deploy/.ssh/authorized_keys
    chown -R deploy:deploy /home/deploy/.ssh
    chmod 700 /home/deploy/.ssh
    chmod 600 /home/deploy/.ssh/authorized_keys

    The permissions matter. sshd refuses to use an authorized_keys file if other users can write to the file, the .ssh directory or the home directory.

  4. Open a second terminal and test the new login. Do not close the root session.

    bash
    ssh [email protected]
    sudo whoami

    The login should ask for your key passphrase, not the account password, and sudo whoami should print root. Do not continue until both work.

4. Disable password login and root login over SSH

Attackers can guess passwords on a server that accepts them over SSH. Turning off password authentication ends that line of attack.

On Ubuntu, /etc/ssh/sshd_config starts with the line Include /etc/ssh/sshd_config.d/*.conf, so you can keep your changes in a separate file. On Debian, check for that line with grep -n Include /etc/ssh/sshd_config. If it is missing, put the settings in /etc/ssh/sshd_config itself.

  1. Create the file from your deploy session.

    bash
    sudo nano /etc/ssh/sshd_config.d/00-hardening.conf
  2. Add these lines and save.

    text
    PasswordAuthentication no
    KbdInteractiveAuthentication no
    PermitRootLogin no
    PubkeyAuthentication yes
  3. Look for conflicting values. sshd uses the first value it finds for each keyword and reads the included files in name order. The 00- prefix makes your file load first, but it helps to see what else is there.

    bash
    sudo grep -ri passwordauthentication /etc/ssh/sshd_config /etc/ssh/sshd_config.d/
  4. Test the configuration, then restart the service.

    bash
    sudo sshd -t
    sudo systemctl restart ssh.service

    sshd -t prints nothing when the file is valid. Fix any error it reports before you restart.

  5. Print the settings sshd is using.

    bash
    sudo sshd -T | grep -Ei 'passwordauthentication|permitrootlogin|kbdinteractiveauthentication'

    All three lines should end in no. Open a third terminal and confirm that ssh [email protected] still works before you close anything.

The table shows what each setting does.

SettingOpenSSH defaultValue to useEffect
PasswordAuthenticationyesnoNobody can log in with a password
KbdInteractiveAuthenticationyesnoCloses the other route to password prompts
PermitRootLoginprohibit-passwordnoRoot cannot log in over SSH at all
PubkeyAuthenticationyesyesKey login stays on

5. Turn on the firewall with ufw

ufw is the default firewall tool on Ubuntu, and it starts disabled. On Debian, install it with sudo apt install ufw. Add the SSH rule before you enable it, because enabling ufw can drop existing connections.

bash
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp
sudo ufw enable
sudo ufw status verbose

ufw asks for confirmation when you enable it over SSH. Answer yes once the port 22 rule is in place.

Open other ports only when a service needs them. A web server needs these two.

bash
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

To slow down repeated SSH connections, use a limit rule instead of the plain allow rule. ufw then denies an IP address that starts 6 or more connections within 30 seconds.

bash
sudo ufw limit ssh/tcp

If you run Docker, note one exception. The Docker documentation states that published container ports are routed before ufw's rules apply, so a published port is reachable even if ufw does not allow it. Bind such ports to 127.0.0.1 or read Docker's firewall page before you rely on ufw.

6. Confirm automatic security updates

Ubuntu installs the unattended-upgrades package by default, and it applies security updates once per day. Check that both options are set to "1".

bash
cat /etc/apt/apt.conf.d/20auto-upgrades
text
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";

On Debian, or if the file is missing, install and enable the package.

bash
sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

A dry run shows what the next run would install without changing anything.

bash
sudo unattended-upgrade -v --dry-run

Some updates only take effect after a reboot, and automatic reboots are off by default. To let the server restart itself at a quiet hour, set these two options in /etc/apt/apt.conf.d/50unattended-upgrades.

text
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "02:00";

If an unplanned restart would hurt your site, leave the option off and reboot by hand when /var/run/reboot-required appears. The logs are in /var/log/unattended-upgrades.

7. Install fail2ban

fail2ban reads the login logs and bans an IP address after repeated failures. With password login off it protects less than it used to, but it keeps the logs readable and it can guard other services later.

bash
sudo apt install fail2ban

The fail2ban manual recommends leaving the .conf files unchanged to ease upgrades. Put your changes in /etc/fail2ban/jail.local.

ini
[sshd]
enabled = true

Restart the service and check the jail.

bash
sudo systemctl restart fail2ban
sudo fail2ban-client status sshd

The upstream defaults ban an address for 10 minutes after 5 failures within 10 minutes. To change them, add bantime, findtime or maxretry lines under [sshd]. If you ban yourself, connect from another network or the provider console and run sudo fail2ban-client set sshd unbanip followed by your IP address.

8. Set up backups

Hardening lowers the chance of a break-in. Backups are what you use after a break-in, a bad deploy or a deleted database. Plan for two kinds.

  • Take a provider snapshot before risky changes such as a release upgrade. A snapshot is quick to restore but it lives with the same provider.
  • Schedule file and database backups to another location. The Ubuntu Server documentation recommends keeping backups off-site and covers tools such as rsnapshot and Bacula, as well as plain shell scripts.

Restore one backup to a test location before you trust the schedule. Until you have restored a backup once, you do not know that it works.

What to check before you finish

Run these from the deploy account and compare the output.

CheckCommandWhat you should see
SSH settingssudo sshd -T | grep -Ei 'passwordauthentication|permitrootlogin'Both values are no
Firewallsudo ufw status verboseStatus: active, incoming denied by default, only the ports you opened
Listening servicessudo ss -tulpnNo service you do not recognise
Updatessudo unattended-upgrade -v --dry-runThe run finishes without errors
fail2bansudo fail2ban-client status sshdThe jail is listed with its ban counts
Sudo membersgetent group sudoOnly the accounts you expect

ss -tulpn lists every TCP and UDP port with a listening process. If a database such as MySQL or Redis listens on a public address, bind it to 127.0.0.1 unless another server needs to reach it.

If you get locked out

Lockouts usually come from one of three mistakes.

  1. You disabled passwords before the key worked. Use the open root session to delete 00-hardening.conf, then run systemctl restart ssh.service and repeat step 3.
  2. You enabled ufw without the port 22 rule. From a session that is still open, run sudo ufw allow 22/tcp.
  3. fail2ban banned your own address. Wait for the ban to expire or unban the address as shown in step 7.

If no session is open, use the web console or rescue mode in your provider's control panel. It gives you a login that does not depend on SSH or the firewall.

Choose the server location before you build on it

The steps above work the same in any data center, so choose the location for your visitors. A server close to them answers faster. WaseerHost has data centers in the USA, Germany and Finland, and you can see the current VPS plans on the product page. If you run a website on the server, the website security page covers the layers above the operating system.

Frequently asked questions

Yes, if you maintain it. A VPS is a server on the public internet, so anyone can try to connect to it. With key-only SSH login, a default-deny firewall, automatic security updates and off-server backups, the common automated attacks fail.

Waqas Ahmed Waseer

Written by

Waqas Ahmed Waseer

Founder & CEO

Founder and CEO of Wasevo LLC, the company that runs WaseerHost. He works on cPanel/WHM servers, WHMCS billing and the Next.js storefront.

Related Guides

Get new guides by email

One short email when we publish something useful. No spam; unsubscribe at any time.

Free SSL · Free migration · 24/7 support

Secure hosting

See security features
30-day money-back guarantee

Renews at the same price for the term you choose