In this lesson, you will learn how to weaponize systemd unit files to create isolated, non-privileged execution environments for your automated background tasks.
When you run a script via a standard cron job or a basic systemd timer, the service often inherits the permissions of the user who started it. If that script is compromised, the attacker gains full access to that user’s environment and files. To prevent this, systemd allows you to define a "sandbox" directly within the service unit file.
Dynamic Users and Namespaces
By using the DynamicUser=yes directive, systemd creates a transient user and group for the lifecycle of the service. This user does not exist in /etc/passwd; it is created on-the-fly and destroyed immediately when the task finishes.
Furthermore, you can restrict the service’s access to the filesystem and network using private namespaces. This ensures that even if your task runs as root, it is trapped inside a virtual "cell."
Example: A Hardened Backup Service
Consider a script that needs to perform a task but shouldn't be able to see your home directory or modify sensitive system files:
[Service]
# Create a temporary identity for this task
DynamicUser=yes
# Create a private /tmp and /var/tmp folder
PrivateTmp=yes
# Hide the rest of the filesystem
ProtectSystem=strict
ProtectHome=yes
# Block access to the network
PrivateNetwork=yes
# Block access to kernel interfaces
ProtectKernelTunables=yes
By adding these flags, you ensure that the process has no visibility into your private files, cannot "see" the host’s network stack, and is limited to only the paths explicitly allowed via ReadWritePaths. If an attacker exploits a vulnerability in your automation script, they are effectively trapped in a box with no way to pivot to the rest of the system or network.
Integrating these security directives into your timers ensures that your automation remains a reliable utility rather than an attack vector.
Key Takeaway: Use DynamicUser=yes and filesystem namespace isolation in your service units to minimize the blast radius of scheduled tasks.