TExcelTAD

Privilege Escalation

Getting a foothold is rarely the end goal. A phished password or a bug in a web application usually gives an attacker the rights of one ordinary account: the www-data user of a web server, a sales employee's Windows login. To read the database, install software, dump other users' credentials or switch off the logs, they need more: root on Linux, SYSTEM or a local administrator on Windows, Domain Admin in Active Directory. Moving from fewer to more rights is privilege escalation, and on well-patched systems it almost always works the same way: the attacker finds something a more privileged account trusts that the low-privileged account can change.

That framing is also the defence. Privilege escalation is, in most real cases, a configuration bug, and configuration can be audited.

Definitions

Term Meaning
Vertical escalation Gaining a higher privilege level (user to root or SYSTEM)
Horizontal escalation Gaining the rights of another account at the same level (one customer reading another's orders)
Trust boundary The line between code running with different rights; escalation is crossing it without permission
SUID / SGID Linux file bits that run a program with its owner's (or group's) rights instead of the caller's; details in Linux permissions
Least privilege Every account and process gets only the rights its task needs

The mechanics of users, processes and rights are in processes and privileges, and the kernel's side in the OS course's Linux security and Windows security lessons.

The classes, as misconfigurations

Each row is a pattern: what a privileged component trusts, how a low-privileged user could change it, and what fixes it. The details of using these belong to authorised testing in Penetration Testing; here the point is to recognise them in an audit.

Class The trusted thing the user can change Fix
Unexpected SUID program A root-owned SUID binary that can run commands or write files (an editor, an interpreter, a copy of find) Remove the bit; keep a baseline of SUID files and alert on changes
Over-broad sudo rule NOPASSWD for a program that can spawn a shell (vim, less, python3), or a wildcard argument Grant exact commands with fixed arguments; never interpreters or editors; see sudoers
Writable script run by root A cron job or service that executes a file in a directory users can write Root-owned files in root-owned directories, mode 755 or stricter
PATH hijacking A privileged script calls tar instead of /usr/bin/tar, and the PATH it inherits starts with a writable directory Absolute paths in privileged scripts; secure_path in sudoers
Writable service definition A user can edit a systemd unit or a Windows service's binary path Correct ownership and ACLs on unit files and service executables
Windows unquoted service path C:\Program Files\Acme Agent\agent.exe without quotes is tried as C:\Program.exe, then C:\Program Files\Acme.exe Quote the path; users must not be able to write into C:\ or Program Files
Windows AlwaysInstallElevated A policy that installs every .msi package as SYSTEM, whoever starts it Leave the policy off (both its user and machine keys)
Unpatched kernel or service A known bug in code that runs with full rights Patch management; reduce kernel attack surface (seccomp, disabling unused modules)
Credentials lying around Passwords in scripts, shell history, backup files, environment variables Secrets managers, file permissions, scanning for secrets

Detection 1: audit SUID files against a baseline

A server built from a known image has a known, short list of SUID programs. Any new entry is worth a look. The session runs in your sandbox; the "baseline" is the list recorded when the image was approved, and a new SUID file has appeared in a user's directory since then (in this sandbox it is a harmless copy of true owned by learner; on a real server the dangerous case is a new root-owned one):

bash · try it yourself
cat > baseline.txt <<'EOF'
/usr/bin/chfn
/usr/bin/chsh
/usr/bin/gpasswd
/usr/bin/mount
/usr/bin/newgrp
/usr/bin/passwd
/usr/bin/su
/usr/bin/umount
EOF
mkdir tools && cp /bin/true tools/helper && chmod u+s tools/helper
find / -xdev -perm -4000 -type f 2>/dev/null | sort > now.txt
echo "SUID files now: $(wc -l < now.txt)"
comm -13 baseline.txt now.txt | while read -r f; do
  echo "NEW SUID: $(stat -c '%A %U' "$f") $f"
done
SUID files now: 9
NEW SUID: -rwsr-xr-x learner /home/learner/tools/helper

comm -13 prints the lines only in the second file. Run as a daily job, or as a file-integrity rule (AIDE, auditd, EDR), it turns "an attacker left a SUID shell behind" into an alert. The same session can check the PATH problem, which needs no root at all to find:

bash · try it yourself
mkdir -p "$HOME/bin"
export PATH="$HOME/bin:$PATH"
IFS=: read -ra dirs <<< "$PATH"
for d in "${dirs[@]}"; do
  if [ -w "$d" ]; then echo "writable: $d"; else echo "ok:       $d"; fi
done
writable: /home/learner/bin
ok:       /usr/local/bin
ok:       /usr/bin
ok:       /bin
ok:       /usr/sbin
ok:       /sbin

A writable directory in your own PATH is normal for your own account. It becomes a finding when the PATH belongs to a root cron job or service that calls programs by bare name.

Detection 2: review sudo rules and Windows services

Configuration files are text, so a short program can flag the risky patterns. The rules and services below are synthetic:

python · try it yourself
SHELL_CAPABLE = {"vim", "vi", "less", "more", "find", "python3", "perl", "bash", "awk", "tar", "env"}

sudoers = [
    "alice  ALL=(root) /usr/bin/systemctl restart nginx",
    "deploy ALL=(root) NOPASSWD: /usr/bin/vim /etc/nginx/nginx.conf",
    "backup ALL=(root) NOPASSWD: /usr/bin/tar *",
    "ops    ALL=(ALL) ALL",
]
for line in sudoers:
    user, rule = line.split(None, 1)
    command = rule.split(")", 1)[1].replace("NOPASSWD:", "").split()
    program = command[0].rsplit("/", 1)[-1]
    issues = []
    if program in SHELL_CAPABLE:
        issues.append(f"{program} can start a shell")
    if "*" in command[1:]:
        issues.append("wildcard argument")
    if command == ["ALL"]:
        issues.append("any command (needs a password and a good reason)")
    print(f"{user:7} {'; '.join(issues) or 'ok'}")

services = [  # name, binary path as registered, can ordinary users write to the folder?
    ("AcmeAgent", r"C:\Program Files\Acme Agent\agent.exe", False),
    ("Spooler", r'"C:\Windows\System32\spoolsv.exe"', False),
    ("LabUpdater", r"C:\Tools\Lab Updater\update.exe", True),
]
print()
for name, path, writable in services:
    unquoted = not path.startswith('"') and " " in path.split(".exe")[0]
    flags = (["unquoted path with spaces"] if unquoted else []) + (["user-writable folder"] if writable else [])
    print(f"{name:10} {', '.join(flags) or 'ok'}")
alice   ok
deploy  vim can start a shell
backup  tar can start a shell; wildcard argument
ops     any command (needs a password and a good reason)

AcmeAgent  unquoted path with spaces
Spooler    ok
LabUpdater unquoted path with spaces, user-writable folder

AcmeAgent is unquoted but every folder on its path is protected, so the finding is low risk and still worth fixing; LabUpdater combines both conditions and is the real problem. On real systems, tools such as Lynis (Linux) or the Windows benchmarks of CIS automate checks like these.

Detecting escalation as it happens

Audits find the doors; logs show someone walking through them:

  • Linux: sudo writes every use (and every refused attempt, user NOT in sudoers) to the auth log or the journal; auditd rules can log every execve with an effective UID of 0 started by a real UID that is not 0. An interactive root shell whose parent is a web server process is a classic alert.
  • Windows: event 4672 (special privileges assigned to a new logon), 4688 (process creation, with the command line if enabled), 7045 (a new service installed) and 4732 (a member added to a security-enabled local group such as Administrators). These are introduced in the Windows event log.

Pitfalls

  • Treating escalation as an exotic exploit. Kernel exploits make headlines; misconfigured sudo rules, writable scripts and leftover passwords cause most real cases.
  • "It's only a test server." Test servers share credentials and networks with production more often than anyone admits. Escalation there is a step towards production.
  • Fixing the instance, not the cause. Removing one SUID bit by hand is undone at the next deployment. Fix the image or the configuration management that built it, then add the baseline check.
  • Giving sudo to a script. NOPASSWD: /opt/app/deploy.sh is safe only if no user can write deploy.sh or anything it calls.

Practice

  1. A cron job runs /opt/reports/build.sh as root every hour. The file is -rwxr-xr-x root root, but /opt/reports is drwxrwxrwx. Is this a problem?
  2. Which sudo rule is safer: ALL=(root) NOPASSWD: /usr/bin/systemctl restart nginx or ALL=(root) NOPASSWD: /usr/bin/systemctl *?
Answers
  1. Yes. Anyone who can write the directory can delete or rename build.sh and put their own file in its place (the file's own permissions don't protect it from removal by someone with write access to the directory, unless the sticky bit is set). Make the directory root-owned and 755.
  2. The first. The wildcard version allows any systemctl command, including starting arbitrary units, editing them (systemctl edit) or paging output through a pager that can spawn a shell.

Test yourself

What do most real-world privilege escalations on patched systems have in common?

  1. They need a kernel zero-day
  2. A privileged component trusts something that a low-privileged user can change
  3. They only work on Windows
  4. They require physical access

In the SUID audit session, how was the new file found?

  1. By its hash
  2. By comparing today's sorted list of SUID files with the approved baseline (comm -13)
  3. By reading the auth log
  4. By running it

Why is deploy ALL=(root) NOPASSWD: /usr/bin/vim /etc/nginx/nginx.conf dangerous?

  1. vim is slow
  2. vim can run shell commands, which would then run as root
  3. The file path is wrong
  4. NOPASSWD rules are ignored

Which Windows event records a new service being installed?

  1. 4624
  2. 4625
  3. 7045
  4. 1102