43 lines
1.0 KiB
Plaintext
Raw Normal View History

=== How to fix it in Python Standard Library
The following code is vulnerable to SSRF as it opens a URL defined by untrusted data.
==== Noncompliant code example
[source,python,diff-id=1,diff-type=noncompliant]
----
from flask import request
from urllib.request import urlopen
@app.route('/example')
def example():
url = request.args["url"]
urlopen(url).read() # Noncompliant
----
==== Compliant solution
[source,python,diff-id=1,diff-type=compliant]
----
from flask import request
from urllib.parse import urlparse
from urllib.request import urlopen
SCHEMES_ALLOWLIST = ['https']
DOMAINS_ALLOWLIST = ['trusted1.example.com', 'trusted2.example.com']
@app.route('/example')
def example():
url = request.args["url"]
if urlparse(url).hostname in DOMAINS_ALLOWLIST and urlparse(url).scheme in SCHEMES_ALLOWLIST:
urlopen(url).read()
----
include::../../common/fix/how-does-this-work.adoc[]
The compliant code example uses such an approach.
=== Pitfalls
include::../../common/pitfalls/starts-with.adoc[]