Skip to content

VPS: Linux Security Tips

Learn how to improve the security of your Linux server with essential tips to prevent unauthorized access and protect your services → Find out more

26 November 202615 min read37 Views0 helpful

Introduction

This guide contains a few tips and recommendations to help you make your Linux server more secure. Since (virtual) servers need to be accessible from the outside, basic protection against unauthorized access is always recommended and should not be neglected.

Info

Please note that these instructions are not exhaustive, and more detailed information can be found in other areas of the ZAP documentation (e.g. 2FA (SSH)).

Tip

The easiest way to protect your server is always the same, regardless of the server: use secure passwords, update your services regularly, and generally pay attention to which services you install and which guides you follow.

Keep your system up to date: updates and security patches

Many attacks exploit security vulnerabilities for which an update has long been available. So keep your operating system and all installed packages up to date. It is best to install security updates automatically and install all other updates yourself on a regular basis.

The commands below apply to Debian and Ubuntu, which you can select when ordering or reinstalling your VPS, as well as AlmaLinux, Rocky Linux, and CentOS Stream, which you install using a custom ISO.

Info

You will only receive security updates for as long as your system version is still supported by its manufacturer. Automatic updates will not upgrade your system to a new major version (for example, from Debian 12 to Debian 13).

Create a snapshot first

Before updating many packages at once or installing a new kernel, create a restore point. If something goes wrong, you can roll back to this state.

  1. Open the Backups section in your VPS dashboard.
  2. Click New Backup.
  3. Select Snapshot as the Type and click Create snapshot.

You can create your own backups and snapshots with an active ZapX Pass. Learn more in Daily backup, restore, and locked actions.

Automatic security updates on Debian and Ubuntu

On Debian and Ubuntu, the unattended-upgrades package handles automatic updates. It is usually already installed on Ubuntu. Install and enable it with:

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

Confirm that you want updates to be downloaded and installed automatically. After that, the file /etc/apt/apt.conf.d/20auto-upgrades will contain these two lines:

Code
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";

The updates installed automatically are listed in /etc/apt/apt.conf.d/50unattended-upgrades. By default, Ubuntu installs only security updates, while Debian also installs regular updates for your Debian version.

Run a test to check that everything works. Nothing will be installed:

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

You can find information about what happened during automatic runs in the /var/log/unattended-upgrades/ directory.

If you want the server to restart automatically after an update that requires a restart, add these lines to /etc/apt/apt.conf.d/50unattended-upgrades (or remove the // from the existing lines) and adjust the time:

Code
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "04:00";
Warning

The automatic restart happens without prompting you. Running game servers and other services will be briefly unavailable, and connected players will be disconnected from the server. Choose a time when as few people as possible are online.

Automatic security updates on AlmaLinux, Rocky Linux, and CentOS Stream

Here, dnf-automatic handles automatic updates. Install the package:

bash
sudo dnf install dnf-automatic

Then open the /etc/dnf/automatic.conf file (for example, with sudo nano /etc/dnf/automatic.conf) and set these values in the [commands] section:

Code
upgrade_type = security
apply_updates = yes

Then enable the timer:

bash
sudo systemctl enable --now dnf-automatic.timer

The timer starts updates daily at 6:00 AM, with a random delay of up to one hour. Check whether it is active with systemctl list-timers dnf-automatic.timer.

Warning

CentOS Stream does not mark updates as security updates. If you set upgrade_type = security, nothing will be installed. On CentOS Stream, set upgrade_type = default instead to install all available updates.

Starting with version 9, dnf-automatic can also restart the server automatically if an update requires it (for example, a new kernel). To do this, set reboot = when-needed in the same section. The restart will then take place five minutes after the update. This setting is not available in version 8.

Check whether a restart is required

A new kernel and some system libraries only become active after a restart. Here's how to check whether your server needs to be restarted:

Debian and Ubuntu:

bash
ls /var/run/reboot-required
cat /var/run/reboot-required.pkgs

If the /var/run/reboot-required file exists, a restart is required. The /var/run/reboot-required.pkgs file shows which packages triggered it.

AlmaLinux, Rocky Linux, and CentOS Stream:

bash
sudo dnf needs-restarting -r

If the message Reboot is required to fully utilize these updates. appears, you should restart the server. If the command is missing, install it with sudo dnf install dnf-plugins-core.

Then restart the server with sudo reboot. If you cannot connect to it via SSH afterward, open the Console section in the dashboard and check the boot process. If that doesn't help, you can start the server in a rescue environment from the Rescue section or restore your snapshot from the Backups section.

  • Security updates: automatically every day, as described above.
  • All other updates: install them yourself about once a week, using sudo apt update && sudo apt upgrade on Debian and Ubuntu, or sudo dnf upgrade on AlmaLinux, Rocky Linux, and CentOS Stream. Create a snapshot beforehand.
  • Restart after kernel updates: as soon as possible, but at a quiet time, for example at night or when no players are online.
  • After each update: check that your services are running again. Use systemctl --failed to see which services did not start.

Secure SSH

SSH (Secure Shell) is a service that lets you access your server's console remotely to run commands. Here's how to set up SSH on your server: Initial access (SSH)

By default, SSH uses password-based login. However, this has the major disadvantage that authentication can be bypassed relatively easily through brute-force attacks, especially if you use a password that is too simple for your SSH login. So if you choose the password option, please use a secure password.

To better protect your server against unauthorized SSH access, you should enable authentication exclusively via SSH keys and disable password login. See the SSH key guide, which explains how to generate and add SSH keys.

Configuring service ports

ServicePort
SSH22
FTP21
Mail25
DNS53
HTTP80
HTTPS443

Services such as SSH and FTP always use the same ports by default (some of them are listed in the table above). If an external attacker tries to attack your SSH service through brute force, they first need to know which port SSH uses. If you don't configure these ports differently, ports 22 and 21 are usually the first ones they'll try to run commands directly on the server or access files via FTP.

To prevent this, we recommend setting custom ports for standard services. The next section explains how to do this:

Warning

Your desired port must be between 1024 and 65535 and must not already be in use!

Use cat /etc/services to view some standard ports so you don't choose one that is already in use.

SSH port

To change the SSH port, you need to edit the configuration file. It is usually located at /etc/ssh/sshd_config. If it isn't, you can search for it with the following command:

Code
find / -name "sshd_config" 2>/dev/null

Now open the file with nano (as root or with sudo).

Code
sudo nano /etc/ssh/sshd_config

Enter your desired port after Port. If Port is commented out (that is, #Port 22), remove the "#" and replace 22 with your desired port. Save the file (in Nano, press Ctrl + o) and close it (Nano: Ctrl + x).

The SSH service now needs to be restarted for the changes to take effect.

Code
# Unter Ubuntu/Debian/CentOS z.B.
sudo systemctl restart sshd

FTP port

If you have installed an FTP service such as proFTPd, you can also easily change the port by editing the configuration file. The process is similar to the SSH service.

Find the proftpd.conf configuration file:

Code
find / -name "proftpd.conf" 2>/dev/null

The file is usually located at /etc/proftpd.conf (CentOS) or /etc/proftpd/proftpd.conf (Ubuntu, Debian). Open the file with nano, remove the "#" before port, and enter your desired port after it. Follow the notes above to avoid entering an invalid port.

Tip

Use Ctrl + W to search in nano.

Code
nano /etc/proftpd/proftpd.conf

Using a firewall

The principle of making a server accessible from the outside is always the same: a port must be open for the server to be reachable from outside. For SSH, this is by default port 22/TCP. (See above for how to change the default port.)

The problem is that this port is now accessible to anyone, regardless of who they are, where they're connecting from, or what their intentions are. This creates a major security vulnerability, as attackers could flood the server with login attempts to either guess the correct password (through brute force, if password login is still enabled) or cripple the server network through overload (e.g. a DDoS attack).

To reduce these effects, you can use firewall rules to restrict access to open ports.

There are two methods you can use for this:

  • IPTables: The classic Linux firewall, with many options, but somewhat more complex to use.
  • UFW: A simpler interface for IPTables that avoids complicated commands, but is somewhat more limited.

Ultimately, it's up to you which method you want to use. Depending on your use case, you may need the flexibility of IPTables, but sometimes UFW is enough (e.g. if you simply want to open or close ports – it's better than nothing!).

IPTables

In this section, you'll use IPTables to create rules that limit the number of connection attempts. Explanations of the individual commands are below the code block.

Note that this rule is enabled only for port 22 (the value after --dport). The commands would need to be adjusted for other services.

Info

The following commands do not work on every Linux distribution, but they do work on most of the popular distros.

First, log in to your Linux server. If you need help, follow our guide Initial access (SSH). Then run the following commands in the order shown.

Code
iptables -A INPUT -p tcp --syn --dport 22 -m connlimit --connlimit-above 2 --connlimit-mask 32 -j DROP
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 1 --hitcount 2 -j DROP
  1. The first rule drops packets if there are more than 2 connections in the TIME_WAIT state to port 22 from a single IP address.
  2. The second rule adds the IP address of a new connection to the recent list.
  3. The third rule drops new connections from IP addresses that have made more than 2 connection attempts in the last second.

UFW

As described above, UFW is a "simpler" interface for IPTables. The first step is to install UFW, since it is not included by default in all Linux distributions. Run the commands as root or with sudo.

First, log in to your Linux server. If you need help, follow our guide Initial access (SSH). The following instructions have been tested on Debian and Ubuntu, but should also work on other Linux distributions.

First, update the apt repository and installed services.

Code
sudo apt update && sudo apt upgrade -y

Then install UFW via apt.

Code
sudo apt install ufw -y

Make sure the installation was successful by running the following command.

Code
sudo ufw status
> Firewall not loaded

To avoid locking yourself out of your server, you must allow the SSH service before enabling the firewall.

Warning

If you have already changed the SSH port, enter the new port here instead of 22.

Use the following commands to allow the SSH service.

Code
sudo ufw allow 22/tcp
sudo ufw enable
sudo ufw status

A successful output should look like this:

Code
Status: active
  
To Action From
-- ------ ----
22/tcp ALLOW Anywhere
22/tcp (v6) ALLOW Anywhere (v6)

Now run the following command, which limits connections to 6 per minute.

Code
ufw limit 22/tcp
Info

UFW only allows limiting to 6 connections per minute. The UFW limiter is quite simple and is not suitable for every situation. For a more detailed and flexible configuration, we recommend using IPTables directly.

Tip

The firewall (whether IPTables or UFW) counts connection attempts "blindly" and blocks accordingly. With Fail2Ban, you can check log files for unusual activity. The next section explains how to install and enable Fail2Ban.

Additional protection with Fail2Ban

Fail2Ban is a service that blocks IP addresses that try to log in to the server with likely malicious intent. Fail2Ban monitors log files for unusual activity and makes it relatively easy to secure your system effectively.

Tip

An alternative to Fail2Ban with a community blocklist is CrowdSec.

After installation, Fail2Ban already includes preconfigured settings for some commonly used services, including:

  • apache
  • lighttpd
  • sshd
  • qmail
  • postfix
  • Courier Mail Server Additional services can easily be added by specifying a regular expression (RegEx) and the desired log file.
As an example, let's look at an entry in /var/log/auth.log. This file contains all SSH login attempts, whether successful or failed.

Here's the entry:

Code
Dec 2 12:59:19 vps-zap515723-2 sshd[364126]: Failed password for root from 92.117.xxx.xxx port 52504 ssh2

Fail2Ban uses this log file and monitors it for failed authentications. Since the log file contains the attacker's IP address, Fail2Ban can block that IP address after a few failed attempts.

Installing Fail2Ban

First, log in to your Linux server. If you need help, follow our guide Initial access (SSH). Run the commands as root or with sudo.

Code
sudo apt update && sudo apt upgrade -y
sudo apt install fail2ban

After installation, you can check the status directly with systemctl: (Press Ctrl+C to exit systemctl.)

Code
systemctl status fail2ban.service
* fail2ban.service - Fail2Ban Service
     Loaded: loaded (/lib/systemd/system/fail2ban.service; enabled; vendor pres>
     Active: active (running) since Sat 2023-12-02 13:10:33 UTC; 24s ago
       Docs: man:fail2ban(1)
    Process: 23988 ExecStartPre=/bin/mkdir -p /run/fail2ban (code=exited, statu>
   Main PID: 23989 (fail2ban-server)
        CPU: 409ms
     CGroup: /system.slice/fail2ban.service
             `-23989 /usr/bin/python3 /usr/bin/fail2ban-server -xf start

Dec 02 13:10:33 vps-zap515723-1 systemd[1]: Starting Fail2Ban Service...
Dec 02 13:10:33 vps-zap515723-1 systemd[1]: Started Fail2Ban Service.
Dec 02 13:10:34 vps-zap515723-1 fail2ban-server[23989]: Server ready

Configuring Fail2Ban

Fail2Ban is now installed, but it is not yet active or configured. Look in /etc/fail2ban; the following files should currently be there:

Code
action.d fail2ban.d jail.conf paths-arch.conf paths-debian.conf
fail2ban.conf filter.d jail.d paths-common.conf paths-opensuse.conf

To create an active "jail", you need to create a file named jail.local. Simply copy the contents of jail.conf into the new file and open it:

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

You can now make all settings in the jail.local file, including which services to monitor. You should focus only on the section after [Default]. The default section contains general basic settings.

Scroll down a little until you find this section, then adjust it, for example, as follows:

AttributeDescriptionValue
ignoreipIP addresses that should not be blocked127.0.0.1/8
ignorecommandNot relevant.
bantimeHow long an IP address remains blocked1h
findtimePeriod during which failed logins are counted10m
maxretryNumber of failed attempts that result in a ban5
Code
# kann mit Leerzeichen (und/oder Komma) getrennt definiert werden.
#ignoreip = 127.0.0.1/8 ::1

# ignorecommand = /path/to/command <ip>
ignorecommand =

# "bantime" ist die Anzahl der Sekunden, die ein Host gesperrt ist.
bantime  = 1h

# Ein Host wird gesperrt, wenn er "maxretry" Fehler innerhalb von "findtime"
# Sekunden erzeugt hat.
findtime  = 10m

# "maxretry" ist die Anzahl der Fehler, bevor ein Host gesperrt wird.
maxretry = 5

You've now finished configuring the basic settings. To monitor the SSH service, for example, scroll down to the [sshd] tag. If you changed your port, enter it under port.

The [sshd] section should then look like this:

Code
[sshd]

enabled = true
port = 22
filter = sshd
logpath = /var/log/auth.log
maxretry = 4
Tip

As you can see, you can also configure individual settings for specific services (for example, maxretry, which is lower than the default setting). Although you have already set general options, you can configure most settings separately for each service. If you don't, the general setting will be used.

Now you just need to restart Fail2Ban to start monitoring.

Code
sudo systemctl restart fail2ban.service

Check that Fail2Ban is working

If you have access to a VPN or a second server, you can try to get Fail2Ban to block you to test whether the service is working. Using a VPN or a hotspot on your phone should give you a different IP address that you can use to test Fail2Ban.

Warning

Do not test this on your regular network, as your own IP address could be blocked and you could lock yourself out.

Try connecting to your server via SSH (using a different IP address!) and enter the wrong password each time. The result should look something like this:

Code
root@185.223.29.xxx's password:
Permission denied, please try again.
root@185.223.29.xxx's password:
Permission denied, please try again.
root@185.223.29.xxx's password:
root@185.223.29.xxx: Permission denied (publickey,password).
root@vps-zap515723-2:/var/log# ssh root@185.223.29.179
root@185.223.29.xxx's password:
Permission denied, please try again.
root@185.223.29.xxx's password:
Permission denied, please try again.
root@185.223.29.xxx's password:
^C
root@vps-zap515723-2:/var/log# ssh root@185.223.29.xxx
ssh: connect to host 185.223.29.xxx port 22: Connection refused

As you can see, the connection from your Fail2Ban-protected server is now rejected (Connection refused instead of Permission denied).

Now display the Fail2Ban status. You'll see that an IP address has been blocked.

Code
fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed: 4
|  |- Total failed:     8
|  `- File list:        /var/log/auth.log
`- Actions
   |- Currently banned: 1
   |- Total banned:     1
   `- Banned IP list:   xxx

If you want to unblock the IP again, you can do so with the following command: fail2ban-client set sshd unbanip {your IP}.

Info

If you have an unusually high number of IP bans, it's a good idea to increase the ban duration with each failed attempt to reduce the number of possible login attempts.

Code
[sshd]

enabled = true
port    = 22
filter  = sshd
logpath = /var/log/auth.log
maxretry = 4

bantime = 1h
# Bantime sollte mit jeder Sperre dieser IP steigen
bantime.increment = true
# Skalierungsfaktor von 24 Stunden (1h,24h,48h,3d,4d....)
bantime.factor = 24
# Maximale Sperrzeit = 5 Wochen
bantime.maxtime = 5w

Protect your web server with Cloudflare

Many people use Cloudflare as a DNS manager for their domain. Cloudflare not only has one of the largest networks in the world, resulting in faster load times, lower latency, and a better user experience, but also protects your websites against DoS/DDoS attacks, including flooding and new types of attacks discovered every day. In this guide, you'll learn how to protect your web server from attacks.

We'll assume your domain is already managed by Cloudflare. If not, you can follow their guide to transfer your domain. In the Cloudflare dashboard, go to the DNS Records tab and make sure the record for your web server has the orange cloud and shows "Proxied".

Then all traffic going through your domain will pass through Cloudflare and from there to your server – legitimate traffic. However, your server will still be accessible from outside Cloudflare. To prevent this, you need to restrict access to ports 80 and 443 using the TCP protocol on your Linux server, allowing access only when traffic comes from legitimate Cloudflare IPs.

To do this, you can manually create firewall rules using Cloudflare's public IPv4 list and Cloudflare's public IPv6 list.

Alternatively, save time and use tools such as Cloudflare-ufw to quickly import these firewall rules in bulk. Make sure you don't have separate rules that allow unrestricted access to your web server other than the ones you just added; otherwise, the rules won't work.

Conclusion – your server is now much more secure than before!

This guide has shown you some basic and advanced features for securing your Linux server. If you've implemented all the recommendations relevant to your system, your server is already much more secure than before – congratulations!

Of course, there are more steps you can take:

  • 2FA (SSH)
  • Add more configurations for Fail2Ban
  • Set up email notifications in Fail2Ban
  • And much more...

Free tools

Related tools for servers and developers

View all

FAQ

Frequently asked questions

Use secure passwords, update services regularly, and be careful about which services you install and which instructions you follow.
Enable authentication exclusively via SSH keys and disable password login. See the SSH key guide for details.
Port 22. Attackers trying to brute-force SSH first need to know which port it uses.

Feedback

Was this article helpful?

Your feedback helps us prioritize and improve content.

0 of 0 people found this article helpful.

Personal support

Need more help than the guide provides?

Our ZAP-Hosting support team knows your product — briefly describe your issue and we'll help you personally.

Zappy knows this guide and answers you right in the chat.