Course contentsShow
← Linux
Lesson 587 of 1,8196. Systemd Internals and Unit OrchestrationFree lesson

Service Sandboxing Mechanics

Apply security features like PrivateTmp and ProtectSystem to isolate service execution environments.

In this lesson, you will learn how to use systemd directives to create virtualized, isolated environments for your services, drastically reducing their attack surface.

The Concept of Service Sandboxing

When a daemon runs on a Linux system, it typically sees the entire file system and shares the /tmp directory with every other process. If a service is compromised, an attacker could potentially read sensitive configuration files or inject malicious scripts into global temporary folders. Sandboxing allows us to define "walls" around a process, restricting what it can see and modify, even if the service itself is running as root.

Implementing Isolation with Systemd

We use unit file directives to enforce these constraints. Two of the most effective tools are PrivateTmp and ProtectSystem.

  • PrivateTmp=true: This creates an isolated /tmp and /var/tmp directory for the service. The service sees its own empty /tmp folder, while the rest of the system's /tmp remains completely invisible to it.
  • ProtectSystem=full: This mounts the /usr, /boot, and /etc directories as read-only for the service. If the service is hijacked, the attacker cannot modify system binaries or configuration files, effectively neutralizing many common persistence techniques.

Consider this example snippet for a custom service unit file:

[Service]
ExecStart=/usr/bin/my-app
# Isolate temporary files
PrivateTmp=true
# Protect core system directories
ProtectSystem=full
# Hide home directories
ProtectHome=true

By adding ProtectHome=true, we make the /home, /root, and /run/user directories inaccessible to the service. If your application does not explicitly need to access these areas, restricting them is a best practice that limits the impact of a breach. These directives don't require external security software; they leverage the kernel's namespace features directly through the systemd manager.

By combining these simple flags, you transform a vulnerable service into a "jailed" process that operates only within the exact boundaries you define.

Key Takeaway: Sandboxing directives like PrivateTmp and ProtectSystem act as protective barriers that restrict a service's view of the file system, preventing unauthorized access to critical directories even if the process is compromised.