49 lines
1.1 KiB
Plaintext
49 lines
1.1 KiB
Plaintext
== How to fix it in Python Standard Library
|
|
|
|
=== Code examples
|
|
|
|
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()
|
|
----
|
|
|
|
=== How does this work?
|
|
|
|
include::../../common/fix/pre-approved-list.adoc[]
|
|
|
|
include::../../common/fix/blacklist.adoc[]
|
|
|
|
=== Pitfalls
|
|
|
|
include::../../common/pitfalls/starts-with.adoc[]
|
|
|
|
include::../../common/pitfalls/blacklist-toctou.adoc[]
|