Server-Side Request Forgery in Python
Vulnerable example
The snippet below demonstrates a common security issue where user input is not correctly validated, allowing an attacker to make arbitrary requests to any URL. This can lead to server-side request forgery (SSRF) attacks.
@tools.route("/fetch", methods=['POST'])
def tools_fetch():
url = request.form.get("url")
if not url or not 'vulnerableapp.com' in url:
return jsonify({'status': 'fail'})
res = requests.get(url)
Prevention
To prevent SSRF attacks, you should restrict the sources’ hosts to trusted hostnames. In this case, we’re allowing only URLs that end with .example.com
.
@tools.route("/fetch", methods=['POST'])
def tools_fetch():
parsed_url = urlparse(url)
hostname = parsed_url.hostname
if not hostname or not hostname.endswith('.example.com'):
return jsonify({'status': 'fail'})
References
OWASP: Server-Side Request Forgery Prevention Cheat Sheet Python Documentation