Secure a new Linux server

The first things to do on a new Ubuntu server: your own user, key-only SSH, a firewall and automatic security updates.

· Updated

A new cloud server is reachable from the whole internet within minutes of starting. These steps, done first, close the most common ways in. They're written for Ubuntu 24.04 and work on any recent Ubuntu or Debian.

Before you start

  • A new Ubuntu server and its IP address, from your cloud provider.
  • An SSH key on your computer. If you don't have one, create it with ssh-keygen -t ed25519.
  • The ability to log in as root, or as the provider's default user with sudo.

Warning

Keep your first SSH session open until step 6 is done. If something is wrong, you can still fix it from there.

Steps

  1. Log in, then update the system:

    bash
    sudo apt update && sudo apt upgrade -y
  2. Create your own user and give it sudo, replacing deploy with the name you want:

    bash
    sudo adduser deploy
    sudo usermod -aG sudo deploy
  3. From your own computer, copy your SSH key to the new user:

    bash
    ssh-copy-id [email protected]
  4. On the server, open /etc/ssh/sshd_config and set these two lines, removing any # in front of them:

    /etc/ssh/sshd_config
    PermitRootLogin no
    PasswordAuthentication no
  5. Check the file, then restart SSH:

    bash
    sudo sshd -t && sudo systemctl restart ssh
  6. In a new terminal, check you can log in as your user with your key: ssh [email protected]. Only then close the first session.

  7. Turn on the firewall, allowing SSH first:

    bash
    sudo ufw allow OpenSSH
    sudo ufw enable
  8. Install security updates automatically:

    bash
    sudo apt install -y unattended-upgrades
    sudo dpkg-reconfigure --priority=low unattended-upgrades

What happens next

The server now only accepts your key, root can't log in over SSH, and only port 22 is open. Open more ports only when something needs them, for example sudo ufw allow 'Nginx Full' for a web server.

Next steps