Sub topic 13
Running Jobs with Least Privilege
This chapter assumes you can write a basic cron entry and a systemd service and timer pair, and that you understand Unix users, groups and file modes. It covers how to give a scheduled job only the access it needs, so a bug or a compromise in the job does less damage.
Why scheduled jobs deserve least privilege
Scheduled jobs run unattended, often at night, often for years. Nobody watches them run. A job that runs as root can delete the wrong directory, fill the disk, or be turned into a foothold if an attacker controls any input it reads. The principle of least privilege says the job should have the smallest set of permissions that lets it do its work.
Three questions guide the design:
- Which user should run the job?
- Which files, sockets and networks does it need to reach?
- Where do its credentials live, and who can read them?
Run as a dedicated user
The first step is to stop using root by default. Create a system account for each job or group of related jobs. A system account has no password and no login shell, so nobody can log in as it.
sudo useradd --system --no-create-home --shell /usr/sbin/nologin backup
sudo install -d -o backup -g backup -m 0750 /var/backups/dbThe install -d command creates the output directory owned by the new user, with mode 0750 so other users cannot read the backups.
The job's script should be owned by root and not writable by the job user. If the job user can edit its own script, any compromise of that account becomes a persistent root-level problem whenever something later runs the script with more privilege.
sudo install -o root -g root -m 0755 backup.sh /usr/local/bin/backup.shChoosing the user in cron
Cron supports this in two ways. Each user has a personal crontab, edited with crontab -e. Root can edit another user's crontab with -u:
sudo crontab -u backup -eThe system-wide files /etc/crontab and files in /etc/cron.d/ have an extra sixth field naming the user. Personal crontabs do not have this field.
# /etc/cron.d/backup (note the user field after the schedule)
[email protected]
PATH=/usr/local/bin:/usr/bin:/bin
30 2 * * * backup /usr/local/bin/backup.sh >> /var/log/backup/backup.log 2>&1A common error is to put a user name in a personal crontab. Cron then tries to run the user name as a command. The reverse also fails: omitting the user field in /etc/cron.d/ makes cron read the first word of the command as the user name. Files in /etc/cron.d/ must also be owned by root, must not be writable by group or others, and their names may contain only letters, digits, underscores and hyphens on Debian-based systems. A file that breaks these rules is silently ignored.
Choosing the user in systemd
In a service unit, User= and Group= set the account. The unit from the earlier chapter already does this with User=backup. Systemd drops privileges before running ExecStart, so the script never has root's rights.
You can also let systemd create a temporary account for the run:
[Service]
DynamicUser=yes
StateDirectory=reportWith DynamicUser=yes, systemd allocates a user ID when the service starts and releases it afterwards. StateDirectory=report creates /var/lib/report owned by that user and keeps it between runs. This works well for jobs that only need their own state directory. It is a poor fit if the job must read files owned by a specific existing account.
Narrow what the job can touch
A dedicated user limits who the job acts as. Systemd can also limit what the job process can see and do. These options go in the [Service] section.
| Option | Effect |
|---|---|
| `NoNewPrivileges=yes` | The process and its children cannot gain privileges through setuid binaries or file capabilities. |
| `PrivateTmp=yes` | The job gets its own empty `/tmp` and `/var/tmp`, invisible to other processes. |
| `ProtectSystem=strict` | The whole file system is read-only for the job, except `/dev`, `/proc` and `/sys` handled separately. |
| `ProtectHome=yes` | `/home`, `/root` and `/run/user` appear empty. |
| `ReadWritePaths=/var/backups/db` | Re-enables writing for the listed paths when `ProtectSystem=` is on. |
| `PrivateNetwork=yes` | The job has no network access except a loopback interface. |
| `CapabilityBoundingSet=` | An empty value removes all Linux capabilities from the job. |
Here is a hardened version of the backup service:
# /etc/systemd/system/backup.service
[Unit]
Description=Nightly backup
[Service]
Type=oneshot
User=backup
Group=backup
ExecStart=/usr/local/bin/backup.sh
TimeoutStartSec=1h
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/var/backups/db
CapabilityBoundingSet=Do not set PrivateNetwork=yes on this particular job. It runs pg_dump and then pings a heartbeat URL, so it needs the network or a local database socket. Each restriction you add is a hypothesis that the job does not need that access, and the test is to run the job and see.
Measuring the result
Systemd can score a unit's exposure. Lower is better:
systemd-analyze security backup.serviceThe output lists each setting with an exposure rating and ends with an overall score. Use it as a guide to find unrestricted options, not as a goal to reach zero. A job that must write to several places will reasonably score higher than one that only reads.
Debugging a restricted service
When a hardened job fails with "Read-only file system" or "Permission denied", the cause is usually a path missing from ReadWritePaths=. Read the journal, find the path the script tried to write, and add it only if the job should write there:
sudo systemctl daemon-reload
sudo systemctl start backup.service
journalctl -u backup.service --since "5 minutes ago"Remember daemon-reload after every unit edit. Without it, systemd keeps running the old definition.
Give the job only the access it needs
Privilege is more than the Unix user. Think about each kind of access.
Files and groups
Prefer group membership over broad permissions. If the job must read a log directory owned by group adm, add the job user to that group rather than making the files world-readable:
sudo usermod -aG adm backupGroup changes apply to new processes only. A systemd service started after the change sees them. Check the effective groups with id backup.
Database accounts
The operating system user and the database user are separate. A backup job needs read access to the data, not the ability to drop tables. Create a database role with only the required privileges. For PostgreSQL, the built-in pg_read_all_data role (version 14 and later) grants read access to all tables without write rights:
sudo -u postgres psql -c "CREATE ROLE backup LOGIN;"
sudo -u postgres psql -c "GRANT pg_read_all_data TO backup;"With peer authentication, the OS user backup can then connect as the database role backup without a password.
Sudo is a last resort
If a job needs one privileged command, avoid running the whole job as root. Allow that single command through a sudoers file, edited with visudo -f:
# /etc/sudoers.d/backup (edit with: sudo visudo -f /etc/sudoers.d/backup)
backup ALL=(root) NOPASSWD: /usr/bin/systemctl reload nginxName the exact command and arguments. A rule like NOPASSWD: ALL removes the benefit of having a dedicated user.
Keep secrets out of the job's reach and out of logs
Credentials are part of privilege. Three rules apply.
- Do not put passwords in a crontab or in a command line. Command lines are visible to every user in
psoutput, and crontabs often end up in backups and mail. - Store secrets in a file readable only by the job user, for example mode 0600, and load it in the script.
- In systemd,
LoadCredential=passes a file to the service through a private directory whose path is in$CREDENTIALS_DIRECTORY. This needs systemd version 247 or later.
[Service]
User=backup
LoadCredential=dbpass:/etc/backup/dbpass#!/usr/bin/env bash
set -euo pipefail
# Read the secret from the private credentials directory set by systemd
PGPASSFILE="${CREDENTIALS_DIRECTORY}/dbpass"
export PGPASSFILEHere the secret file stays owned by root with mode 0600. Systemd reads it and exposes a copy to the service only. The job user never needs access to /etc/backup.
Also check that the script does not print secrets. With set -x enabled, the shell writes every expanded command, including passwords, to the log.
Review checklist and verification
Verify the setup instead of assuming it works. Check the account first, then the file permissions, then test as the job user.
id backup
ls -ld /var/backups/db /usr/local/bin/backup.sh
sudo -u backup /usr/local/bin/backup.sh
systemd-analyze security backup.serviceRunning the script by hand as the job user exposes permission errors before the schedule does. Be aware that sudo -u does not reproduce systemd's restrictions or cron's minimal environment, so finish the test by starting the real unit with systemctl start backup.service.
Exercise
A systemd service has User=backup, ProtectSystem=strict and ReadWritePaths=/var/backups/db. The script writes its temporary file to /var/backups/tmp and the job fails with "Read-only file system". Give two valid fixes and say which is the more restrictive.
Show answer
Fix one: change the script to create its temporary file inside /var/backups/db, which is already writable. Fix two: add /var/backups/tmp to ReadWritePaths=. The first fix is more restrictive because it grants no extra write access. It also keeps the temporary file on the same file system as the final file, so the rename stays atomic.
Exercise
You add a line to /etc/cron.d/report that reads 0 3 * * * /usr/local/bin/report.sh, and it never runs. Name two likely causes.
Show answer
Files in /etc/cron.d/ need a user field after the schedule, so cron treats /usr/local/bin/report.sh as a user name. The line should be 0 3 * * * report /usr/local/bin/report.sh. A second cause is the file's ownership or mode: it must be owned by root and not writable by group or others, and its name must use only allowed characters, or cron ignores it.