Skip to main content
Cron Jobs, PATH Hijacking & Service Misconfigs
Lesson 5 of 12

Cron Jobs, PATH Hijacking & Service Misconfigs

Learn how scheduled cron jobs, unsafe PATH resolution, and misconfigured systemd units create privilege-escalation paths, how to observe hidden tasks with pspy, and how to harden background automation.

Advanced 28 min Linux & Windows
Authorised environments only — The techniques described here are used only in training labs and on systems you own or have written permission to test.

Learning objectives

  • Audit system crontabs, cron directories, and target script permissions for privilege-escalation weaknesses
  • Explain how PATH hijacking and unquoted wildcards compromise privileged scripts
  • Monitor short-lived root processes without elevated privileges using pspy
  • Inspect systemd service and timer units with systemctl to detect writable paths and drop-in misconfigurations
  • Harden scheduled jobs and systemd units using strict ownership, absolute paths, and unit sandboxing

Recommended first: Sudo Rules, SUID/SGID Binaries & Linux CapabilitiesLinux Processes, systemd Sandboxing & auditd Logs

#Why this matters

Even when sudo rules, SUID binaries, and file capabilities are clean, Linux hosts still run automated maintenance every minute: log rotation, backup scripts, health checks, and systemd timers. Because those jobs frequently execute as root, a single weak file permission, relative command name, or writable directory turns routine background automation into a privilege-escalation path.

Unlike interactive sudo flaws, background task weaknesses do not always show up in a quick permission check. Root-owned user crontabs are unreadable to unprivileged accounts, and short-lived timer jobs finish in milliseconds. Defenders and assessors therefore combine configuration auditing with runtime process observation.

#Auditing cron jobs and writable scripts

System-wide scheduled tasks are stored in /etc/crontab, drop-in files under /etc/cron.d/, and periodic directories /etc/cron.hourly/, /etc/cron.daily/, /etc/cron.weekly/, and /etc/cron.monthly/. Per-user crontabs live in /var/spool/cron/crontabs/ (Debian/Ubuntu) or /var/spool/cron/ (RHEL-based distributions) and are normally readable only by root or the owning user.

System crontabs include an explicit username column between the schedule and the command:

Inspecting system crontabs on a lab host
$ cat /etc/crontab
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# m h dom mon dow user  command
*/5 * * * *   root    /opt/maint/cleanup.sh

$ ls -ld /opt/maint /opt/maint/cleanup.sh
drwxr-xr-x 2 root ops 4096 Nov 18 10:12 /opt/maint
-rwxrwxr-x 1 root ops  214 Nov 18 10:12 /opt/maint/cleanup.sh

Here, cleanup.sh runs as root every five minutes, yet it is group-writable by ops. Any member of ops can modify the script so the next cron execution runs arbitrary commands as root. Always check both the script file and every parent directory up to /: if /opt/maint itself is writable by a non-root user or group, that user can rename cleanup.sh and replace it with a new file even if cleanup.sh appears read-only (0644).

A second common cron flaw is wildcard injection. Consider a root job running tar -czf /var/backups/drop.tgz * inside a directory where regular users can create files. The shell expands * before passing arguments to tar. If a directory contains files whose names start with --, tar interprets them as command-line options (such as --checkpoint=1 and --checkpoint-action=exec=...) rather than filenames.

  1. Inspect /etc/crontab & /etc/cron.dCheck script & parent dir permissions | Inspect PATH & wildcards | Observe live executions with pspy

#PATH hijacking in cron and privileged scripts

When a command is invoked without a leading slash (for example backup-sync instead of /usr/local/bin/backup-sync), the shell or execvp searches each directory in the PATH environment variable from left to right and executes the first match.

PATH hijacking occurs in two common situations:

  1. Overly broad PATH in a crontab: An administrator prepends /home/deploy/bin or . to PATH= in /etc/crontab or /etc/cron.d/deploy, and a root cron entry invokes an unqualified binary name. Any user who can write to that earlier directory can place an executable with that name and intercept execution.
  2. Unqualified commands inside privileged scripts or SUID wrappers: A root-owned script or compiled SUID wrapper calls tar or systemctl without an absolute path while failing to reset PATH to trusted system directories.

Compare the unsafe and hardened forms below:

bash
# Unsafe: relies on inherited PATH and unquoted wildcard
tar -czf /var/backups/logs.tgz *

# Hardened: explicit trusted PATH, absolute binary path, end-of-options marker
PATH=/usr/sbin:/usr/bin:/sbin:/bin
/usr/bin/tar -czf /var/backups/logs.tgz -- ./*

Note how -- tells tar to treat all subsequent arguments as filenames rather than flags, neutralising option-based wildcard injection, while ./* prevents leading hyphens at the start of expanded names.

#Observing hidden tasks with pspy

Unprivileged users cannot read /var/spool/cron/crontabs/root, and systemd timers or external triggers may launch scripts that run for only a fraction of a second. Standard ps aux snapshots rarely catch them.

pspy solves this visibility gap without requiring root. It monitors /proc process creation events and inotify filesystem activity across directories such as /usr and /tmp, printing short-lived commands and their effective UID as they start:

Observing a hidden root task with pspy64 on a lab host
$ ./pspy64 -pf -i 1000
CMD: UID=0    PID=4812   | /bin/sh -c /usr/local/sbin/healthcheck.sh
CMD: UID=0    PID=4813   | /usr/bin/curl -s http://127.0.0.1:8080/health

In this lab capture, pspy64 reveals a UID=0 job invoking /usr/local/sbin/healthcheck.sh even though /etc/crontab appeared empty. The auditor can now inspect /usr/local/sbin/healthcheck.sh and check how it is triggered. Note that pspy relies on polling /proc and inotify events; extremely short processes can occasionally be missed, and restricted /proc mount options such as hidepid=2 block unprivileged users from seeing other users' processes.

#Systemd service and timer misconfigurations

Modern Linux distributions schedule many background tasks with systemd .timer and .service units rather than classic cron. Use systemctl to list active units, timers, and full unit definitions including drop-in overrides:

Inspecting systemd timers and unit definitions
$ systemctl list-timers --all
$ systemctl cat lab-report.service
# /etc/systemd/system/lab-report.service
[Service]
Type=oneshot
ExecStart=/opt/reports/generate.sh
EnvironmentFile=/etc/default/lab-report

Inspect every path referenced by a privileged unit (User=root or omitted User=, which defaults to root):

Component Inspection check Risk if writable by non-root
Unit file (/etc/systemd/system/*.service) ls -l on unit and drop-in .d/ directory Attacker edits ExecStart= and awaits restart or reboot
Target binary or script (ExecStart=) ls -ld on binary and parent directories Arbitrary code runs under the service User=
EnvironmentFile= ls -l on referenced environment file Attacker injects PATH or environment variables
WorkingDirectory= and PIDFile= Directory ownership and permissions Symlink or file-clobbering risks during startup

Also review sudo -l for any rule allowing systemctl restart or systemctl daemon-reload alongside editable unit files or scripts.

#Defending and common mistakes

Securing background automation requires locking down files, paths, and execution context together:

  • Tighten file and directory ownership: Ensure root-executed scripts and every parent directory are owned by root:root with mode 0750 or 0700. Remember that write access on a parent directory overrides read-only file permissions inside it.
  • Pin PATH and use absolute paths: Define a minimal PATH=/usr/sbin:/usr/bin:/sbin:/bin in crontabs and scripts, and invoke binaries by full path (/usr/bin/rsync).
  • Defuse wildcard expansion: Never pass bare * into tools like tar, rsync, or chown in shared directories; quote variables ("$file"), iterate safely, and add -- before file arguments.
  • Sandbox systemd units: Run timers and services under dedicated non-root accounts (User=), and enable NoNewPrivileges=yes, ProtectSystem=strict, ProtectHome=yes, and PrivateTmp=yes.
  • Audit with systemd-analyze security: Check unit exposure scores to spot services running needlessly as root with full filesystem access.

Common mistakes include checking script permissions while forgetting parent directory permissions, leaving legacy cron jobs active in /etc/cron.d/ after migrating to systemd timers, and relying on hidepid=2 as a substitute for fixing writable scripts.

#Summary

  • Background privilege escalation commonly stems from writable cron/service scripts, writable parent directories, unsafe PATH search order, or unquoted wildcards in root-owned tasks.
  • Static checks of /etc/crontab, /etc/cron.d/, and systemctl cat should be paired with runtime observation using pspy to catch unreadable crontabs and short-lived timer jobs.
  • Systemd misconfigurations include writable .service files, writable drop-in directories, editable ExecStart targets, and modifiable EnvironmentFile paths.
  • Prevent these flaws with root:root 0750 permissions on scripts and parent directories, explicit PATH and absolute binary paths, -- option terminators, and sandboxed non-root systemd units.

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge