Salta al contenuto principale
Lympha technologies

Guide pratiche

How to secure a VPS running Ubuntu Linux

Basic security hardening for an Ubuntu Linux VPS, command by command: package updates, changing the SSH port, the ufw firewall, users with limited privileges, root access disabled, Fail2ban against brute force and a password policy.

As soon as you take the reins of command, you need to make sure your VPS has at least a minimum of defence against external attacks. No system is perfect, just as no system is truly impenetrable; that, however, is no excuse for skipping a set of technical measures aimed, at the very least, at stopping even the simplest attacks from succeeding.

As a matter of policy at VPS GREEN, VPSs are delivered with the chosen operating system exactly as the vendor releases it. This clearly calls for a few security-focused steps before you can install your own software. As the famous line from the Spider-Man comics goes: the system administrator has great power, but also great responsibility.

VPS GREEN's technical staff are not authorised to access your VPSs; on the other hand, they are always available to support you with the operating system.

Prerequisites

  1. A VPS running a Linux operating system
  2. A user with adequate privileges, i.e. sudo or root itself
  3. A text editor; in our example we will use nano
  4. The apt package manager, normally included in the operating system
  5. [Recommended] A firewall; in our example we will use ufw

Update your operating system

Your first responsibility as a sysadmin is to keep the operating system and its applications secure and functional, day after day. Distribution and operating system developers release frequent package updates, very often for security reasons: keeping your distribution or operating system up to date is an essential part of protecting your VPS.

Application vendors sometimes publish a list of compatible or incompatible system packages or libraries: before updating specific components, make sure there are no incompatibilities with the applications you have installed or will need to install on the VPS.

First of all, let's make sure the package library is up to date. Simply connect to the VPS via SSH or via the console and run the command:

$ sudo apt update && sudo apt upgrade

Apt will respond with a series of details, including the number of packages to be updated. It's worth remembering (unless your requirements dictate otherwise) to always keep your VPS up to date, confirming the proposed packages, as in the example:

6 upgraded, 8 newly installed, 0 to remove and 0 not upgraded.
6 standard LTS security updates
Need to get 54.5 MB of archives.
After this operation, 242 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y

Change the default Secure Shell port

Although not mandatory, it can be a good idea to change the standard SSH port, normally set to 22. This fairly trivial step avoids attacks from bots that would normally target the standard port. The procedure is quite simple: just edit the service's configuration file with your text editor of choice.

$ sudo nano /etc/ssh/sshd_config

Look for the string "Port 22" and change the number to whichever port you prefer, taking care not to use a port already used by another system protocol. By convention, ports between 49152 and 65535 are considered free, not assigned to any specific protocol or application.

# This is the sshd server system-wide configuration file.
# Port 22
Port 4422

Save your changes and restart the SSH service:

$ sudo systemctl restart sshd

Once the service restarts you shouldn't notice any difference, but clearly the next time you connect you will need to use the string:

ssh Nome_Utente@IPv4_del_VPS -p Numero_della_porta

If you are using a firewall, remember to add the new port and allow inbound traffic. For example, if you decide to use ufw, run the command:

$ sudo ufw allow 4422
$ sudo ufw show added
Added user rules (see 'ufw status' for running firewall):
ufw allow 25565
ufw allow 22
ufw allow 4422

This adds the new port chosen for SSH and lets you check which ports are configured on the firewall. If, as well as no longer using port 22, you also want to block traffic on it, you can set a deny rule:

$ sudo ufw deny 22
$ sudo ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip
To                         Action      From
--                         ------      ----
25565                      ALLOW IN    Anywhere
22                         DENY IN     Anywhere
4422                       ALLOW IN    Anywhere
25565 (v6)                 ALLOW IN    Anywhere (v6)
22 (v6)                    DENY IN     Anywhere (v6)
4422 (v6)                  ALLOW IN    Anywhere (v6)

The status verbose parameter gives you an overview of the firewall configuration. If everything matches what you want to achieve, make sure the firewall service is active:

$ sudo ufw enable

Don't use root for everything: create an account with limited rights

As a general rule, it's best not to use the root user all the time, especially for operations that don't require such elevated privileges. To create a new user, use this command:

$ sudo adduser Nome_del_Nuovo_Utente

The system will ask you to set a password (as ever, avoid weak passwords) and other details (name, etc.). Once created, the user can be used straight away to access the VPS. If the new user needs to perform operations that require privileges, you can proceed in two different ways:

  1. use the $ su root command to switch temporarily to the root user;
  2. add the user to the list of "sudoers", a special list of users who can elevate their privileges through the sudo command.

While the first method needs no further explanation, the second involves adding the new user to the list. To authorise them, run as root:

$ echo "Nome_del_Nuovo_Utente  ALL=(ALL) NOPASSWD:ALL" | sudo tee /etc/sudoers.d/Nome_del_Nuovo_Utente

This way we use the root user to create a file dedicated to the new user in sudoers.d/, which will be read by sudo and will authorise our new user. At this point we can connect to the VPS via SSH using the new user even for operations that require special privileges, such as:

$ sudo apt update

Disable root access to the server

The root user is created by default on GNU/Linux systems and is usually the account with the highest level of access on the system. It is strongly discouraged — and dangerous — to leave your VPS accessible exclusively as the root user, because this account can perform operations without any restraint, including harmful and irreversible ones. It is therefore strongly recommended to disable direct root access via remote-access protocols (RDP, VNC, etc.) in general, and not just for the SSH protocol.

The procedure is quite simple: just edit the service's configuration file with your text editor of choice.

$ sudo nano /etc/ssh/sshd_config

Look for the string "PermitRootLogin yes" and set it to "no":

# Authentication:
# PermitRootLogin yes
PermitRootLogin no

Save your changes and restart the SSH service:

$ sudo systemctl restart sshd

From now on, any attempt to connect via SSH as root@IPv4_del_VPS will fail. Remember to create a user to use for remote access. In any case, root can still be used to log in via the VPS GREEN web console.

A little extra protection… Fail2ban

Fail2ban is extremely useful for preventing intrusion attempts and can therefore add one more small safeguard to your VPS's security. The purpose of Fail2ban is to block the IP addresses from which bots or attackers try to access your system, particularly when the attacker is a bot attempting a brute force (i.e. trying to connect to a service using random passwords or passwords taken from a dictionary).

Installation couldn't be simpler:

$ sudo apt install fail2ban

The application works perfectly well exactly as installed. If you prefer to customise a few parameters, you can edit the configuration in the /etc/fail2ban/jail.conf file; for more detail we recommend the official documentation on the Fail2ban project website.

As suggested in the documentation, let's create our own configuration file:

$ sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
$ sudo nano /etc/fail2ban/jail.local

Remember that parameters marked as [DEFAULT] apply globally, to all services; these values are, however, "overridden" if you set them in the sections dedicated to individual services. Example:

# [DEFAULT]
bantime = 1h
...
[sshd]
# To use more aggressive sshd modes set filter parameter "mode" in jail.local:
# normal (default), ddos, extra or aggressive (combines all).
# See "tests/files/logs/sshd" or "filter.d/sshd.conf" for usage example and details.
#mode   = normal
port    = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s
bantime = 3h

In our example we set the ban time globally to 1 hour (bantime = 1h), while for the SSH service we set a bantime of 3 hours. To apply your customisations straight away, you need to restart the service:

$ sudo systemctl restart fail2ban.service

Take care not to write duplicate parameters within the same [DEFAULT] section or within any [service_name]: otherwise Fail2ban will not start and will return an error.

Change your passwords often

It is good practice to define a password rotation policy, especially for users with elevated privileges. There is no set rule but, generally speaking, the more often you change your password (making it as complex as you can), the better. To change your own user's password:

$ passwd

If the password to change belongs to another user, you will need to specify their name:

$ sudo passwd root

Conclusion

Although Linux (in general) is famous for being among the most secure operating systems, it does have some vulnerabilities. Many security threats can end in data loss or corruption — in other words, cost and time to recover. For example:

  1. Malware — intrusive software intentionally designed to damage operating systems.
  2. Sniffing — a practice aimed at intercepting packets in transit to and from unprotected applications.
  3. Brute force — an attack aimed at guessing passwords through automatic generation or dictionaries.
  4. SQL injection — a practice that exploits weaknesses in a web application's code to gain access to the server's database.
  5. Cross-site scripting (XSS) — a client-side attack in which malicious code is injected into a website.
  6. No function-level control — software can cause this by failing to verify access rights correctly, granting root privileges to ordinary users.
  7. Broken authentication — identity theft that usually occurs as a result of unencrypted data, weak passwords or incorrectly configured session timeouts.

Before implementing any security measure, make yourself aware of the elements you should be monitoring. Here are a few:

  1. VPS hosting security
  2. Software installed on the server
  3. Connections via SSH and other protocols enabled on the server
  4. Root access and logins
  5. Passwords, user rights and privileges
  6. Firewall
  7. Connections via FTP and other file-exchange protocols enabled on the server
  8. Log files

Protecting a server is not impossible: if you have followed this guide, you have already taken the first step. Next up: logging in with SSH keys and disabling password login. And if you want your security verified, not just declared: that's our job.

Guide originally published on the blog of VPS GREEN, the VPS service running on our green private cloud.

Share this article

LinkedIn X Email

Lympha Editorial Team

The articles on this blog come from the field experience of our Business Units and Competence Centres: the people writing are the people who design, run and support the systems we write about, every day. Content is provided for information purposes and reflects the state of the art at the date of publication.

You may also like