Bookstore CTF Writeup
From LFI to Root: Complete Walkthrough of TryHackMe Bookstore Room
Platform: TryHackMe
Room: Bookstore
Category: Web Security & Privilege Escalation
Difficulty: Medium
Skills: API Testing, LFI Exploitation, Reverse Engineering
📝 My Experience with This Room
This room serves as a brilliant case study in how a misconfigured API can become a critical attack vector, opening the door to Local File Inclusion (LFI) vulnerabilities and ultimately enabling threat actors to gain unauthorized access to sensitive systems.
The initial vulnerability often stems from a lack of proper input validation and sanitization within the API endpoints. By manipulating request parameters, an attacker can traverse the directory structure and force the application to disclose arbitrary files from the server. This LFI flaw is not merely an information disclosure issue; it is frequently the first crucial step in a larger attack chain, allowing hackers to read configuration files, source code, log files, and other critical resources that pave the way for further exploitation.
Furthermore, the room provides fascinating, hands-on practice in reverse engineering for privilege escalation. After establishing an initial foothold, the real challenge begins: analyzing the system's internals, understanding how processes and services interact, and identifying weaknesses in permission models. This involves deconstructing applications, examining running services for misconfigurations, and searching for stored credentials or exploitable binaries. The process beautifully demonstrates how an attacker moves from a low-privileged user to a privileged account by meticulously uncovering and leveraging the subtle flaws hidden within the system's architecture. It's a practical masterclass in the persistence and ingenuity required for advanced penetration testing.
Challenge Description
This room focuses on exploiting vulnerabilities in a misconfigured api with LFI vulnerability in web application and also it provides beginner friendly reverse engineering challenge for privilege escalation...
Network Reconnaissance
Scanning Methodology
The initial footprinting was performed using Nmap with aggressive timing to quickly map the attack surface:
Results & Analysis
Assessment: The web services on ports 80 and 5000 were identified as the most promising vectors for initial exploitation
Web Service Enumeration on Port 80
Initial Assessment
Following the port scan, I began investigating the HTTP service on port 80. The initial reconnaissance revealed a login page that appeared non-functional. Testing with common credentials and basic SQL injection payloads yielded no results, indicating this was not the primary attack vector for this machine.
Directory Brute-Forcing
To discover hidden endpoints and map the application's structure, I initiated a directory brute-forcing attack using ffuf. This approach helps uncover accessible directories and files not linked from the main page.
Next Steps: The ffuf scan successfully identified one interesting directory, shifting the focus from the dead-end login page to this newly discovered endpoint for further investigation.
Source Code Analysis & Vulnerability Discovery
Critical Information Disclosure
During the directory enumeration, I discovered a fascinating file at /assets/js/api.js. This JavaScript file contained detailed developer comments that proved to be a goldmine of information about the application's API structure.
Security Misstep
Buried within the code comments was a crucial piece of information that the developers should never have left in a publicly accessible file:
Vulnerability Identified: The developers inadvertently disclosed:
- Existence of an outdated API endpoint (
/api/v1/) - Specific LFI vulnerability in the
fileparameter - The exact parameter and endpoint structure to exploit
Exploitation Path: This finding immediately provided a clear attack vector. The outdated v1 API endpoint, which was supposed to be deprecated but likely still accessible, became the primary target for Local File Inclusion exploitation.
Exploring Port 5000 & API Discovery
Shifting Focus
Following the critical discovery in the JavaScript file, I shifted my attention to the web service running on port 5000. This non-standard port often hosts development or internal services that might contain the vulnerable API endpoints mentioned in the code comments.
API Endpoint Testing
Using the path structure discovered in api.js, I navigated to the API endpoint on the port 5000 service:
/api/v2/resources/books/random4
Assessment: The endpoint successfully returned a JSON response with four random books from the system. This confirmed that the API structure from the JavaScript file was valid and operational on this service. More importantly, it verified the existence of the v2 API path, suggesting that the vulnerable v1 version might also be accessible on this port.
API Documentation Discovery
Expanding the Attack Surface
While the discovery of the working API endpoint was valuable, it provided limited insight into the full capabilities of the API. To comprehensively map the attack surface, I needed to find the complete API documentation that would reveal all available endpoints and parameters.
Directory Fuzzing for Documentation
I launched a targeted fuzzing attack against the service on port 5000, specifically searching for common documentation paths and files.
Discovery: After systematic enumeration, the fuzzing revealed accessible API documentation that detailed:
- Complete list of available API endpoints
- Required and optional parameters for each endpoint
Next Phase: With the full API documentation in hand, the next logical step was to methodically test each documented endpoint for vulnerabilities, with particular focus on the previously mentioned LFI vulnerability in the v1 API endpoints.
Hitting a Wall & Changing Approach
Exhaustive Testing Leads to Dead End
I methodically tested every single endpoint documented in the API specification. This included attempting various attack vectors:
- LFI payloads on all file-related parameters
- SQL injection attempts on input fields
- Command injection tests
- IDOR and authorization bypass attempts
The Realization
Despite comprehensive testing, all documented endpoints proved to be secure. The v2 API was indeed properly sanitized, and no vulnerabilities were found through conventional means. This created a significant roadblock in the assessment.
Strategic Pivot: Parameter Fuzzing
Recognizing that the vulnerability might lie in an undocumented parameter, I shifted from endpoint fuzzing to parameter fuzzing. The key insight was that while the endpoints were documented, the parameters they accepted might not be fully specified.
Breakthrough Strategy: This approach was based on the hypothesis that while the API interface was updated to v2, there might be backward compatibility or hidden parameters that could reintroduce the v1 vulnerability. The focus moved from what the endpoint is to how it processes unexpected inputs.
The Critical Breakthrough
Parameter Fuzzing Success
After extensive testing, the parameter fuzzing attack against the v1 API endpoint finally yielded a critical finding. Using a focused wordlist, I discovered an undocumented parameter that was not listed in any official documentation.
/api/v1/resources/books (vulnerable version)
show (undocumented)
.bash_history
Key Realization
The discovery revealed a critical oversight in my approach. I had wasted significant time fuzzing the v2 API endpoints, operating under the false assumption that the developers had completely eliminated the v1 vulnerable endpoints. In reality, the vulnerable v1 API was still accessible and contained hidden functionality.
Vulnerability Confirmed:
- V1 API remained fully accessible despite being "deprecated"
- Undocumented
showparameter existed in v1 - The parameter was susceptible to path traversal attacks
- Developers failed to properly secure or remove the old version
Exploitation Ready: With the show parameter identified in the vulnerable v1 API, the path was now clear for systematic Local File Inclusion attacks to read sensitive system files and potentially discover credentials for further access.
LFI Exploitation Success
Initial File Read Achieved
With the undocumented show parameter identified, the next step was to test its susceptibility to Local File Inclusion. The initial test targeted a standard system file to confirm the vulnerability.
show (undocumented)
/etc/passwd
Vulnerability Confirmed
The server responded with the complete contents of the /etc/passwd file, confirming the LFI vulnerability was fully exploitable. This demonstrated that:
- The
showparameter did not implement any path traversal protections - The v1 API endpoint remained completely unsecured
- Arbitrary file read was possible from the application context
- The developers failed to properly deprecate the vulnerable version
Next Objective: With arbitrary file read capabilities confirmed, the focus shifted to enumerating sensitive files to find:
• Application configuration files
• SSH keys
• Database credentials
• User history and logs
The ability to read /etc/passwd provided valuable user enumeration for potential privilege escalation targets.
Critical Credential Discovery
Bash History Analysis
Leveraging the confirmed LFI vulnerability, I proceeded to read the user's .bash_history file, which often contains valuable information about system usage and potentially exposed credentials.
Major Finding
The .bash_history file revealed a critical piece of information - a PIN code that was used to access the Python debugger console on port 5000:
Security Implications:
- Debug interface exposed in production environment
- PIN code stored in cleartext in user history
- Potential for remote code execution via debug console
- Critical misconfiguration in deployment
Next Step: The discovered PIN code provides potential access to the Python debug console. This console, if accessible, would allow for arbitrary command execution on the server with the privileges of the web application, representing a critical escalation point in the attack chain.
Gaining RCE via Debug Console
Console Access Achieved
Using the discovered PIN code from the .bash_history file, I successfully authenticated to the Werkzeug debug console exposed on port 5000. This provided an interactive Python shell with the privileges of the web application process.
Initial Foothold Established
With access to the Python debug console, the next logical step was to achieve remote code execution to establish a more stable and functional foothold on the system.
Exploitation: Through the debug console, I executed Python code to:
- Spawn a reverse shell connection back to my attack machine
- Gain interactive system access
- Establish persistence for further enumeration
- Begin privilege escalation assessment
Impact: This represents a complete breach of the web application, transforming the LFI vulnerability into full remote code execution. The system is now compromised, and the focus shifts to lateral movement and privilege escalation within the environment.
Establishing Reverse Shell
Weaponizing Code Execution
With Python code execution achieved through the debug console, the next step was to establish a proper reverse shell for interactive system access. This provides a more stable and functional connection than the limited debug console interface.
Reverse Shell Implementation
Using a Python reverse shell payload from revshells.com, I executed the following code in the debug console to call back to my attack machine:
Shell Access Obtained:
- Interactive system shell established
- Full command execution capabilities
- Ability to navigate filesystem and execute system commands
- Stable connection for further exploitation
Access Confirmed: The reverse shell successfully connected back to my listener, providing complete command-line access to the target system. This marks the transition from web application vulnerability to full system compromise, opening the path for privilege escalation and lateral movement within the network.
Initial Compromise & User Flag Capture
Reverse Shell Listener
Before executing the reverse shell payload, I established a netcat listener on my attack machine to catch the incoming connection from the target system.
Successful Connection & Flag Retrieval
The reverse shell connected successfully to the listener, providing immediate access to the target system. With shell access established, retrieving the user flag was straightforward:
Compromise Achieved:
- Reverse shell connection established on port 7777
- User-level access obtained
- User flag successfully captured
- Initial foothold consolidated
Current Status: The initial objective of gaining user access and capturing the user flag has been completed successfully. The system is now compromised at the user level, and the focus shifts to privilege escalation to obtain root access and capture the final flag.
Privilege Escalation Vector Identified
Discovery of Suspicious Binary
During post-exploitation enumeration of the user's home directory, I discovered a peculiar executable named try-harder. This binary immediately stood out as a potential privilege escalation vector.
Binary Behavior Analysis
When executed, the program prompts for a "magic number," suggesting it requires specific input to proceed. This behavior indicates the binary likely contains authentication logic that, if bypassed, could lead to elevated privileges.
try-harder (SUID candidate)
Initial Assessment:
- Custom binary with interactive input
- Potential SUID bit set for privilege escalation
- Magic number suggests hidden authentication mechanism
- Requires reverse engineering to understand internal logic
Next Step: The try-harder binary represents a clear privilege escalation opportunity. To exploit it, I need to perform reverse engineering to uncover the correct magic number or identify vulnerabilities in its input handling that could lead to command execution with elevated privileges.
Binary Transfer & Reverse Engineering Setup
Transferring the Binary for Analysis
To perform detailed reverse engineering, I transferred the try-harder binary from the target machine to my attack system. This was accomplished using a Python HTTP server and wget:
# On attacker: wget http://TARGET_IP:8080/try-harder
Reverse Engineering: Finding the Magic Number
When analyzing binary files, we often encounter password or key verification checks. The decompiled code revealed the following logic:
uint user_input;
uint constant_val;
uint result;
setuid(0);
constant_val = 0x5db3;
puts("What's The Magic Number?!");
scanf("%u", &user_input);
result = user_input ^ 0x1116 ^ constant_val;
if (result == 0x5dcd21f4) {
system("/bin/bash -p");
}
else {
puts("Incorrect Try Harder");
}
return;
}
Understanding the Logic
The program performs a simple verification:
/bin/bash -p with root
Finding the Magic Number
Since XOR operations are reversible, we can compute the required input:
input = 0x5dcd6d51 (hex)
input = 1573743953 (decimal)
Ready for Exploitation: The reverse engineering analysis successfully revealed the magic number 1573743953. This number, when provided to the try-harder binary, should grant a root shell through the setuid(0) mechanism, completing the privilege escalation chain.
Privilege Escalation Achieved
Root Access Obtained
Using the magic number discovered through reverse engineering, I successfully executed the try-harder binary and obtained root privileges on the system.
What's The Magic Number?!
1573743953
# whoami
root
Simplified Explanation
The key to solving this was understanding that XOR operations are reversible. The program checked:
To find our_input, we simply reverse the operation using the same XOR values:
Learning Resources
For those interested in learning reverse engineering, here are valuable resources:
- Practical Binary Analysis by Dennis Andriesse
- The Ghidra Book by Kara Nance
- Reverse Engineering for Beginners by Dennis Yurichev (free PDF)
- Crackmes.one - Practice challenges community
- Microcorruption CTF - Embedded security challenges
Compromise Complete: The system is now fully compromised with root-level access. This demonstrates a complete attack chain from initial reconnaissance through web vulnerability exploitation to privilege escalation via binary reverse engineering.
🎯 Mission Accomplished!
This comprehensive walkthrough demonstrates a complete attack chain from initial reconnaissance to full system compromise. The journey through the Bookstore room highlights critical security lessons:
Key Security Takeaways:
- Never leave sensitive information in client-side code
- Properly deprecate and secure old API versions
- Implement robust input validation and sanitization
- Avoid exposing debug interfaces in production
- Conduct regular security assessments and code reviews
Flag
I don't want you to copy paste flags, I want you to practice and learn using my experience!
The END!!!
Thank you for reading! HACK THE WORLD!!!!!(ETHICALLY OF COURSE :X)