Introduction
In an age where hacker attacks are a daily occurrence, it is of fundamental importance to minimize the attack surface. Containerization is probably the best way to isolate a service provided for the public, but this is not always possible for several reasons. For example, think of a legacy system application developed on systemd. This could make the most of the capabilities provided by a systemd-based operative system and it could be managed via a systemd unit, or it could automatically pull updates using a systemd timer, and so on.
For this reason, we are going to explain how to improve the security of a systemd service. But first, we need to step back for a moment.
With the latest releases systemd has implemented some interesting features relating to security, especially sandboxing.
In this article we are going to show step-by-step how to strengthen services using specific directives, and how to check them with the provided systemd suite.
Debugging
Systemd provided an interesting tool named systemd-analyze. This command analyzes the security and the sandboxing settings of one or more specified services. The command checks for various security-related service settings, assigning each a numeric “exposure level” value, depending on how important the setting is. It then calculates an overall exposure level for the whole unit through an estimation in the range 0.0…10.0, which tells us how exposed a service is security-wise.
This allows us to check the improvements applied to our systemd service step-by-step.
As you can see, several services are now marked as UNSAFE, this is probably due to the fact that not all of the applications are applying the features provided by systemd.
Getting Started
Let’s start from a basic example. We want to create a systemd unit to start the command python3 -m http.server
as a service:
[Unit] Description=Simple Http Server Documentation=https://docs.python.org/3/library/http.server.html [Service] Type=simple ExecStart=/usr/bin/python3 -m http.server ExecStop=/bin/kill -9 $MAINPID [Install] WantedBy=multi-user.target
Save the file and place it under the specific systemd directory of yor distribution.
By checking the security exposure through systemd-analyze security
we get the following result: