Skip to content

Dedicated Server: Linux Security Tips

Discover how to improve your Linux server's security with essential tips to prevent unauthorized access and protect your services

26 November 202615 min read38 Views0 helpful

Introduction

This guide contains some tips and advice on how to make your Linux server more secure. Since servers need to be accessible from the outside, basic protection against unwanted access is definitely recommended and should not be neglected.

Info

Please note that these instructions are not exhaustive. More detailed information can be found in other sections 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 strong passwords, update your services regularly, and generally be careful about 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 been available for a long time. Therefore, keep your operating system and all installed packages up to date. It’s best to install security updates automatically and install all other updates yourself on a regular basis.

The commands below apply to Debian, Ubuntu, AlmaLinux, and CentOS Stream, which you can install in the Installation section of your Dedicated Server.

Info

You’ll only receive security updates for as long as your system version is still supported by its vendor. Automatic updates won’t switch to a new major version (for example, from Debian 12 to Debian 13) on their own.

Back up your data first

Before updating many packages at once or installing a new kernel, back up important data and configurations. The dashboard doesn’t have a section for backups or snapshots for Dedicated Servers. Therefore, copy your data to another system yourself, for example, using rsync or SFTP.

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. Afterward, 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 that are installed automatically are specified in /etc/apt/apt.conf.d/50unattended-upgrades. On Ubuntu, only security updates are included by default. On Debian, regular updates for your Debian version are included as well.

You can check that everything is working with a dry run. Nothing will be installed:

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

You can find out 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 reboot, add these lines to /etc/apt/apt.conf.d/50unattended-upgrades (or remove the // before 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 and CentOS Stream

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

bash
sudo dnf install dnf-automatic

Then open the file /etc/dnf/automatic.conf (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. You can check whether it’s 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 happen five minutes after the update. This setting is not available on AlmaLinux 8.

Check whether a restart is required

A new kernel and some system libraries only take effect 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 file /var/run/reboot-required exists, a restart is required. The file /var/run/reboot-required.pkgs shows which packages triggered it.

AlmaLinux and CentOS Stream:

bash
sudo dnf needs-restarting -r

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

Then restart the server with sudo reboot. If it is no longer accessible over SSH afterward, open the Remote Management section in the dashboard, click Start session, and then click Open Remote Management. There you can see your server’s screen and check the boot process.

  • Security updates: automatically and daily, 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 and CentOS Stream. Back up your data first.
  • Restart after kernel updates: do so promptly, 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 haven’t started.

Secure SSH

SSH (Secure Shell) is a service that lets you remotely access your server’s console to run commands. Learn how to set up SSH on your server here: First 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 for SSH access that is too simple. So if you choose to use a password, please use a strong one.

To better protect your server against unwanted SSH access, you should enable authentication exclusively with SSH keys and disable password login. See the SSH key guide for VPS, which explains how to generate and add SSH keys (the content applies equally to Dedicated Servers).

Configuring service ports

ServicePort
SSH22
FTP21
Mail25
DNS53
HTTP80
HTTPS443

Services such as SSH or FTP always use the same ports by default (some of them are listed in the table above). If an external attacker tries to crack your SSH service using brute force, they first need to know which port SSH uses. If you don’t change these ports, 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 configuring custom ports for standard services. The next section explains how to do this:

Warning

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

Use cat /etc/services to see some standard ports so that you don’t choose one that’s already in use.

Change the 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 there, you can search for it with this 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 chosen port after Port. If Port is commented out (e.g. #Port 22), remove the "#" and replace 22 with your chosen port. Save the file (in Nano, press Ctrl + o) and close it (Nano: Ctrl + x).

You now need to restart the SSH service for the changes to take effect.

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

Change the FTP port

If you’ve installed an FTP service such as proFTPd, you can also easily change the port through the configuration file. The procedure is similar to the one for SSH.

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 chosen port. Follow the instructions above to avoid choosing 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 outside is always the same: a port must be open for the server to be accessible from the 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 everyone, 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 overload the server network (e.g. with a DDoS attack).

To reduce these risks, you can apply firewall rules that restrict access to open ports.

There are two methods you can use:

  • 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, the choice is yours. 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 provided below the code block.

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

Info

The following commands don’t work on every Linux distribution, but they work on most of the popular distros.

First, log in to your Linux server. If you need help, follow our First access (SSH) guide. 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 mentioned above, UFW is a “simpler” interface for IPTables. The first step is to install UFW, as it isn’t included by default in all Linux distributions. You should run the commands as root or with sudo.

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

First, update the apt package index 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 need to allow the SSH service before enabling the firewall.

Warning

If you’ve 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 to limit connections to 6 per minute.

Code
ufw limit 22/tcp
Info

UFW only allows a limit of 6 connections per minute. The UFW limiter is quite simple and isn’t suitable for every situation. For a more detailed and flexible configuration, we recommend using IPTables directly.

Tip

The firewall (whether IPTables or UFW) only “blindly” counts connection attempts and blocks them accordingly. With Fail2Ban, you can check log files for suspicious 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 potentially malicious intent. Fail2Ban monitors log files for suspicious activity, making it a relatively simple and effective way to secure your system.

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

  • apache
  • lighttpd
  • sshd
  • qmail
  • postfix
  • Courier Mail Server You can easily add other services using a regular expression (RegEx) and specifying 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 and monitors this log file for failed authentications. Since the log file contains the attacker’s IP address, Fail2Ban can block this IP after a few failed attempts.

Install Fail2Ban

First, log in to your Linux server. If you need help, follow our First access (SSH) guide. You should 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

Configure Fail2Ban

Fail2Ban is now installed, but it isn’t active or configured yet. 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 called 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 your settings in the jail.local file, including which services to monitor. Only look at the section after [Default]. The Default section is for general basic settings.

Scroll down a little until you find this section and 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 will 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 der letzten "findtime"
# Sekunden erzeugt hat.
findtime  = 10m

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

That completes the basic settings. To monitor the SSH service, for example, scroll down to the [sshd] tag. If you’ve changed your port, enter it under port.

The [sshd] tag 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 set individual options for specific services (for example, maxretry, which is lower than the default value). Even though you’ve already set the general options, you can override most settings 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 test whether Fail2Ban is working by getting yourself blocked. Using a VPN or a hotspot on your phone should give you a different IP address that you can use to test Fail2Ban.

Warning

Don’t test this on your usual network, as your own IP address could be blocked and you could lock yourself out.

Try connecting to your server over SSH (using a different IP!) and enter the wrong password each time. The result should look 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 is now rejected by your Fail2Ban-protected server (Connection refused instead of Permission denied).

Now show the status of Fail2Ban. You’ll see that an IP address has been banned.

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 this command: fail2ban-client set sshd unbanip {deine IP}.

Info

If you have an unusually high number of banned IPs, we recommend increasing 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

Secure 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, which leads to faster load times, lower latency, and a better user experience, but also protects your websites from 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 that your domain is already managed by Cloudflare. If it isn’t, 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 an orange cloud and displays “Proxied.”

Then all traffic to your domain passes through Cloudflare and from there to your server—legitimate traffic. However, your server is still accessible from outside Cloudflare. To address this, you need to restrict access to ports 80 and 443 over TCP on your Linux server and only allow legitimate Cloudflare traffic.

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

Alternatively, save time by using tools such as Cloudflare-ufw to quickly import these firewall rules in bulk. Make sure you don’t have any 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 introduced you to 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 other steps you can take:

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

Free tools

Related tools for servers and developers

View all

FAQ

Frequently asked questions

Use strong passwords, regularly update your services, and be careful about which services you install and which instructions you follow.
Password-based SSH login can be easily bypassed by brute-force attacks, especially with weak passwords. It is recommended to enable authentication only via SSH keys and disable password login.
SSH uses port 22 by default. Since services like SSH or FTP always use the same default ports, these are common targets for automated attacks – appropriate protection measures are recommended.

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.