Using Least Privilege in Automation Scripts

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 159 of 205

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:

  1. Which user runs it? Ideally a dedicated account created for this one job.
  2. What can that user access? Exactly the files, folders and commands the job needs, granted through ownership and groups.
  3. What can the script inherit from its caller? Environment variables, the PATH, the umask and open files all come from whoever started it.
  4. 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
ToolNotes
setprivFrom util-linux. Sets user, group, supplementary groups and capabilities precisely. --reset-env clears the environment. Must be run by root.
runuserFrom util-linux. A simpler "switch user and run a command" for root, without passwords or logging.
sudo -u USERWorks 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:

  • PATH decides which program runs for a command name. A caller could put a folder containing a fake tar first. Set PATH explicitly at the top of the script.
  • Other environment variables can change how programs behave (LD_PRELOAD, BASH_ENV, IFS in 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 readonly constants, not options, so a caller cannot redirect the backup to another folder or make it read other data.
  • Safe inherited state. PATH is set to system folders only, and umask 077 makes every archive readable only by appbackup.
  • Self-check. readlink -f finds 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 & 022 must 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 setpriv to replace itself with a new copy running as appbackup, with that user's groups, a clean environment and no inheritable capabilities. exec means no root process waits in the background. The new copy runs the same checks again, this time as appbackup, and continues.
  • Refusing other users. Any user other than root or appbackup is 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 .part and 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 KEEP is removed. The rm works 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

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Using Least Privilege in Automation Scripts and get answers drawn from it.

Signed-in readers only.