Using Least Privilege in Automation Scripts
The principle of least privilege says that a program should run with only the permissions it needs to do its job, and no more. For automation scripts, this means: do not run a backup, cleanup, deployment or monitoring script as root just because that is convenient. Run it as a user that can read what it must read and write what it must write, and nothing else.
The reason is simple. Every script has bugs, and many scripts process data they do not control. When something goes wrong, for example an empty variable in an rm command (lesson 160), a command injection (lesson 155) or a compromised dependency, the damage is limited by the permissions of the user running the script. As root, a mistake can destroy the whole system. As a dedicated user with access to two folders, the same mistake can only affect those two folders.
Understanding the Concept
Linux decides what a process may do mainly by its user ID and group IDs. Every file has an owner, a group and permission bits (lesson 72). A process may read, write or execute a file only if its user or one of its groups is granted that access. The root user (ID 0) bypasses these checks almost completely.
Least privilege in a script comes down to a few questions:
- Which user runs it? Ideally a dedicated account created for this one job.
- What can that user access? Exactly the files, folders and commands the job needs, granted through ownership and groups.
- What can the script inherit from its caller? Environment variables, the
PATH, the umask and open files all come from whoever started it. - Who can change the script? If another user can edit a script that root runs, that user effectively has root.
Bash provides the information to check the first question in two variables:
id -un; echo "EUID=$EUID UID=$UID"
root
EUID=0 UID=0
UID is the real user ID and EUID the effective user ID, the one the kernel uses for permission checks. They usually match. Both are read-only.
Why Running as Root Is Dangerous
Root can write to every file regardless of permissions, so permission errors, which normally stop a buggy command, never happen. An unprivileged user is stopped by the kernel:
setpriv --reuid=nobody --regid=nogroup --clear-groups bash -c 'echo x > /etc/test-file'
echo "status $?"
bash: line 1: /etc/test-file: Permission denied
status 1
The same command run as root would have created the file. For a script with a bug, "Permission denied" is a safety net. Running as root removes it.
Switching to a Less Privileged User
Scripts are often started by root: by cron, by a systemd service, by a package installation or by an administrator using sudo. Such a script should switch to a less privileged user as early as possible. Linux has several tools for this:
setpriv --reuid=nobody --regid=nogroup --init-groups bash -c 'id; echo "EUID=$EUID"'
runuser -u nobody -- id -un
sudo -u nobody -- bash -c 'id -un; echo "HOME=$HOME"'
uid=65534(nobody) gid=65534(nogroup) groups=65534(nogroup)
EUID=65534
nobody
nobody
HOME=/nonexistent
| Tool | Notes |
|---|---|
setpriv | From util-linux. Sets user, group, supplementary groups and capabilities precisely. --reset-env clears the environment. Must be run by root. |
runuser | From util-linux. A simpler "switch user and run a command" for root, without passwords or logging. |
sudo -u USER | Works for non-root callers too, controlled by rules in /etc/sudoers. Logs every use. |
Use --init-groups with setpriv (or the equivalent default in the other tools) so the new process gets the target user's supplementary groups, such as a shared app group. Without it, access granted through groups does not work. --clear-groups removes all supplementary groups instead.
Dedicated Service Users
The cleanest way to give a script exactly the rights it needs is to create a system user for it. A system user has no password, no login shell and usually no home folder:
useradd --system --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin appbackup
groupadd --system app
usermod -aG app appbackup
id appbackup
uid=996(appbackup) gid=995(appbackup) groups=995(appbackup),994(app)
Access is then granted with ordinary ownership and groups. In the example used for the rest of this lesson, the application data is owned by root and readable by the group app, and the backup folder belongs to appbackup alone:
chgrp -R app /srv/app/data
chmod 750 /srv/app/data
chmod 640 /srv/app/data/*
chown appbackup:appbackup /srv/backups/app
chmod 700 /srv/backups/app
ls -ld /srv/app/data /srv/app/data/* /srv/backups/app
drwxr-x--- 2 root app 4096 Nov 24 09:01 /srv/app/data
-rw-r----- 1 root app 8 Nov 24 09:01 /srv/app/data/orders.csv
-rw-r----- 1 root app 4 Nov 24 09:01 /srv/app/data/settings.ini
drwx------ 2 appbackup appbackup 4096 Nov 24 09:01 /srv/backups/app
appbackup can read the data through the group, but cannot change it:
setpriv --reuid=appbackup --regid=appbackup --init-groups bash -c 'echo x >> /srv/app/data/orders.csv'
echo "status $?"
bash: line 1: /srv/app/data/orders.csv: Permission denied
status 1
A backup script running as appbackup therefore cannot damage the data it backs up, even if it has a serious bug.
Narrow sudo Rules
Sometimes a person or another service must start the script as its dedicated user. A sudo rule can allow exactly one command as exactly one user, instead of full root access. Rules go in a file under /etc/sudoers.d/ and should always be checked with visudo:
# Let members of group ops run exactly one script as appbackup, nothing else
%ops ALL=(appbackup) NOPASSWD: /usr/local/sbin/backup-app.sh
visudo -cf /srv/t159/sudoers-test
/srv/t159/sudoers-test: parsed OK
A member of ops can now run sudo -u appbackup /usr/local/sbin/backup-app.sh, and nothing else through sudo. Avoid rules that allow editors, shells, interpreters or commands such as tar, find, less or vi, because each of them can start other programs. Always give the full path of the command.
Protecting the Script Itself
A script that root runs is only as safe as the file it is stored in. If another user can write to the script, or to the folder that contains it, that user can add commands that root will run:
printf '#!/bin/bash\necho "nightly job running as $(id -un)"\n' > job.sh
chmod 777 job.sh
setpriv --reuid=nobody --regid=nogroup --clear-groups bash -c \
'echo "echo \"line added by an unprivileged user, now running as \$(id -un)\"" >> /srv/t159/job.sh'
bash job.sh
nightly job running as root
line added by an unprivileged user, now running as root
The unprivileged user nobody added a line, and root then ran it. With mode 755, the same attempt fails:
chmod 755 job.sh
setpriv --reuid=nobody --regid=nogroup --clear-groups bash -c 'echo "echo again" >> /srv/t159/job.sh'
echo "status $?"
bash: line 1: /srv/t159/job.sh: Permission denied
status 1
The rules for scripts that privileged users run:
- the script and every folder above it must be owned by root (or the service user) and not writable by group or others;
- the same applies to every file the script
sources and every program it runs by a relative name; - install such scripts in system folders such as
/usr/local/sbin, not in home folders or shared project folders.
Controlling What the Script Inherits
A process inherits its environment from its parent. A privileged script started by someone else should not trust that environment:
PATHdecides which program runs for a command name. A caller could put a folder containing a faketarfirst. SetPATHexplicitly at the top of the script.- Other environment variables can change how programs behave (
LD_PRELOAD,BASH_ENV,IFSin old shells, tool-specific variables). Start privileged child processes with a clean environment. - The umask decides the permissions of new files (lesson 113). Set it explicitly.
env -i starts a program with an empty environment plus the variables you list:
env -i PATH=/usr/bin:/bin /usr/bin/env
PATH=/usr/bin:/bin
setpriv --reset-env does the same while switching users, and sets a small standard environment for the new user. --inh-caps=-all also clears inheritable capabilities, so the new process has no special kernel privileges at all:
SECRET_X=1 setpriv --reuid=appbackup --regid=appbackup --init-groups --reset-env --inh-caps=-all -- /srv/t159/showenv.sh
showenv.sh prints its environment and its capability sets:
#!/bin/bash
env | sort
grep -E '^Cap(Inh|Prm|Eff|Amb)' /proc/self/status
HOME=/nonexistent
LOGNAME=appbackup
PATH=/usr/local/bin:/usr/bin
PWD=/srv/t159
SHELL=/usr/sbin/nologin
SHLVL=1
TERM=linux
USER=appbackup
_=/usr/bin/env
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapAmb: 0000000000000000
SECRET_X from the caller did not reach the new process. HOME, USER, LOGNAME and SHELL describe the new user, and all four capability sets are empty.
Least Privilege in systemd Services
When a script runs as a systemd service or timer, the unit file can enforce least privilege before the script starts. Useful settings include User= and Group=, NoNewPrivileges=yes (the process and its children can never gain privileges, for example through sudo or set-user-ID programs), ProtectSystem=strict with ReadWritePaths= (the whole file system is read-only except the listed folders), ProtectHome=yes and PrivateTmp=yes. These settings are enforced by the kernel and do not depend on the script being correct, which makes them a strong second layer.
A Complete Example: A Backup Script That Drops Root
backup-app.sh backs up /srv/app/data into /srv/backups/app. It is designed to be started by root from cron or a systemd timer, or directly by the appbackup user, and it applies every idea from this lesson:
#!/usr/bin/env bash
# backup-app.sh: back up /srv/app/data as the dedicated user appbackup
# Run it as appbackup, or as root (it then switches to appbackup itself).
set -euo pipefail
readonly RUN_AS=appbackup
readonly SRC=/srv/app/data
readonly DEST=/srv/backups/app
readonly KEEP=7
PATH=/usr/local/bin:/usr/bin:/bin # never trust the caller's PATH
export PATH
umask 077 # backups are private to appbackup
die() { printf '%s: %s\n' "${0##*/}" "$1" >&2; exit 1; }
# 1. Refuse to run a copy of this script that others could have changed
self=$(readlink -f -- "$0")
read -r mode owner < <(stat -c '%a %U' -- "$self")
[[ $owner == root ]] || die "$self must be owned by root (owner: $owner)"
(( (8#$mode & 8#022) == 0 )) || die "$self is writable by group or others (mode $mode)"
# 2. Run with exactly the privileges needed: as appbackup, never as root
if (( EUID == 0 )); then
echo "running as root: switching to $RUN_AS" >&2
exec setpriv --reuid="$RUN_AS" --regid="$RUN_AS" --init-groups --reset-env \
--inh-caps=-all -- "$self" "$@"
fi
[[ $(id -un) == "$RUN_AS" ]] || die "must run as $RUN_AS or root, not $(id -un)"
# 3. Do the job with that user's limited rights
[[ -r $SRC && -x $SRC ]] || die "cannot read $SRC (is $RUN_AS in its group?)"
[[ -w $DEST ]] || die "cannot write to $DEST"
stamp=$(date +%Y%m%d-%H%M%S)
archive=$DEST/data-$stamp.tar.gz
[[ ! -e $archive ]] || die "$archive already exists; try again in a second"
tar -czf "$archive.part" -C "$SRC" .
mv -- "$archive.part" "$archive"
printf 'created %s (%s bytes) as %s\n' "$archive" "$(stat -c %s -- "$archive")" "$(id -un)"
# 4. Keep only the newest $KEEP archives
mapfile -t old < <(ls -1t -- "$DEST"/data-*.tar.gz | tail -n +"$((KEEP + 1))")
for f in "${old[@]}"; do
rm -f -- "$f" && printf 'removed old backup %s\n' "$f"
done
How It Works
- Fixed settings. The user, folders and number of backups are
readonlyconstants, not options, so a caller cannot redirect the backup to another folder or make it read other data. - Safe inherited state.
PATHis set to system folders only, andumask 077makes every archive readable only byappbackup. - Self-check.
readlink -ffinds the real file behind any symbolic link. The script refuses to continue unless that file is owned by root and not writable by group or others (mode & 022must be zero). This catches a copy placed in a shared folder, or permissions loosened by mistake. - Dropping root. When started by root, the script uses
exec setprivto replace itself with a new copy running asappbackup, with that user's groups, a clean environment and no inheritable capabilities.execmeans no root process waits in the background. The new copy runs the same checks again, this time asappbackup, and continues. - Refusing other users. Any user other than root or
appbackupis refused, so the script cannot be used by accident from a personal account where it would behave differently. - Checks with clear messages. Before working, the script checks that it can read the source and write the destination, and explains the most likely reason if not.
- Writing safely. The archive is first written as
.partand renamed when complete, so a half-written file never looks like a finished backup. A second run in the same second is refused instead of overwriting the first archive. - Pruning. Archives are listed newest first; everything after the newest
KEEPis removed. Thermworks on full paths inside the fixed destination folder, and--protects against unusual names (lesson 160).
Running the Complete Example
The backup folder already held three archives from earlier tests. Started by root, the script switches users before doing any work, and the new archive belongs to appbackup:
/usr/local/sbin/backup-app.sh; echo "status $?"
ls -lt /srv/backups/app | head -3
running as root: switching to appbackup
created /srv/backups/app/data-20261124-090337.tar.gz (192 bytes) as appbackup
status 0
total 16
-rw------- 1 appbackup appbackup 192 Nov 24 09:03 data-20261124-090337.tar.gz
-rw------- 1 appbackup appbackup 192 Nov 24 09:02 data-20261124-090230.tar.gz
Started by appbackup, it runs directly. Started by any other user, it refuses:
setpriv --reuid=appbackup --regid=appbackup --init-groups /usr/local/sbin/backup-app.sh; echo "status $?"
setpriv --reuid=nobody --regid=nogroup --clear-groups /usr/local/sbin/backup-app.sh; echo "status $?"
created /srv/backups/app/data-20261124-090338.tar.gz (192 bytes) as appbackup
status 0
backup-app.sh: must run as appbackup or root, not nobody
status 1
Two runs within the same second do not overwrite each other:
/usr/local/sbin/backup-app.sh; /usr/local/sbin/backup-app.sh; echo "status $?"
running as root: switching to appbackup
created /srv/backups/app/data-20261124-090339.tar.gz (192 bytes) as appbackup
running as root: switching to appbackup
backup-app.sh: /srv/backups/app/data-20261124-090339.tar.gz already exists; try again in a second
status 1
At this point the folder held six archives from all the tests. To see pruning without waiting for eight backups, a test copy of the script with KEEP=2 (backup-app-keep2.sh, otherwise identical) was run twice, one second apart:
/usr/local/sbin/backup-app-keep2.sh; sleep 1; /usr/local/sbin/backup-app-keep2.sh
ls -1 /srv/backups/app
running as root: switching to appbackup
created /srv/backups/app/data-20261124-090340.tar.gz (192 bytes) as appbackup
removed old backup /srv/backups/app/data-20261124-090338.tar.gz
removed old backup /srv/backups/app/data-20261124-090337.tar.gz
removed old backup /srv/backups/app/data-20261124-090230.tar.gz
removed old backup /srv/backups/app/data-20261124-090227.tar.gz
removed old backup /srv/backups/app/data-20261124-090226.tar.gz
running as root: switching to appbackup
created /srv/backups/app/data-20261124-090341.tar.gz (192 bytes) as appbackup
removed old backup /srv/backups/app/data-20261124-090339.tar.gz
data-20261124-090340.tar.gz
data-20261124-090341.tar.gz
The first run kept its new archive and the newest older one, and removed the other five; the second run removed one more. Only the two newest archives remain.
Finally, copies of the script that others could have modified are refused before they do anything, even when root starts them:
cp /usr/local/sbin/backup-app.sh /srv/t159/copy.sh
chmod 777 /srv/t159/copy.sh
/srv/t159/copy.sh; echo "status $?"
chmod 755 /srv/t159/copy.sh; chown appbackup /srv/t159/copy.sh
/srv/t159/copy.sh; echo "status $?"
copy.sh: /srv/t159/copy.sh is writable by group or others (mode 777)
status 1
copy.sh: /srv/t159/copy.sh must be owned by root (owner: appbackup)
status 1