In this lesson, you will learn how to apply Mandatory Access Control (MAC) to restrict the scope and privileges of automated background tasks managed by systemd timers.
When you schedule a task with systemd timers, the associated service often runs with broad permissions inherited from the system context. Without MAC, a vulnerability in a script—such as a backup utility or a cleanup job—could allow an attacker to escape the task's intended scope and access sensitive system files. By confining these services within an AppArmor profile or SELinux context, you ensure that even if the task is compromised, its actions remain strictly bound by policy.
Applying MAC to Timer-Driven Services
To secure a timer, you must apply the MAC policy to the target Service unit, not the Timer unit itself. The Timer unit merely acts as a trigger, while the Service unit executes the actual code.
For example, if you have a service backup-data.service triggered by backup-data.timer, you should define an AppArmor profile for the binary or script invoked by that service:
# /etc/apparmor.d/usr.local.bin.backup-script
profile backup-script /usr/local/bin/backup-script {
# Deny all by default, explicitly permit only required paths
owner /home/user/data/ r,
/usr/bin/tar ix,
/dev/null rw,
}
Once the profile is loaded, ensure your systemd service unit explicitly declares the security context. If you are using SELinux, you would use the SELinuxContext directive in the [Service] section of your unit file:
[Service]
ExecStart=/usr/local/bin/backup-script
SELinuxContext=system_u:system_r:backup_t:s0
By explicitly labeling the process, you prevent it from interacting with files or sockets outside of its defined backup_t domain. Even if an attacker finds an injection flaw in your backup script, the kernel will block any attempt to modify /etc/shadow or other critical system areas, as those paths fall outside the allowed policy. Always test your policies in complain mode first to ensure the timer task performs its duties before enforcing strict enforce mode.
Key Takeaway: Securing systemd timers requires applying MAC labels to the underlying service units to ensure that automated background tasks operate under the principle of least privilege.