The fixed code implements a whitelist of allowed hosts and checks if the provided URL's host is in this list. It also prevents access to loopback and local addresses, mitigating the risk of SSRF attacks.
The fixed code implements URL validation using a regex pattern and restricts requests to a specific allowed domain. This prevents attackers from accessing internal resources or making requests to unintended destinations.
This Flask application creates a proxy endpoint that makes requests to any URL provided as a query parameter, allowing potential SSRF attacks.
Fixed Code:
pythonCopyimport requestsfrom flask import Flask, request, jsonifyfrom urllib.parse import urlparseimport ipaddressapp =Flask(__name__)ALLOWED_DOMAINS = ['api.example.com','data.example.com']defis_valid_public_ip(ip_str):try: ip = ipaddress.ip_address(ip_str)returnnot (ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast)exceptValueError:returnFalsedefis_allowed_url(url): parsed_url =urlparse(url)ifnot parsed_url.scheme in ['http','https']:returnFalseif parsed_url.hostname in ALLOWED_DOMAINS:returnTruetry: ip = ipaddress.ip_address(parsed_url.hostname)returnis_valid_public_ip(ip)exceptValueError:returnFalse@app.route('/proxy')defproxy(): url = request.args.get('url')ifnot url ornotis_allowed_url(url):returnjsonify({'error': 'Invalid or disallowed URL'}),403try: response = requests.get(url, allow_redirects=False)returnjsonify({'status': response.status_code,'content': response.text })except requests.RequestException as e:returnjsonify({'error': str(e)}),400if__name__=='__main__': app.run(debug=True)
Reason for Fix:
The fixed code implements several security measures:
It checks if the URL's domain is in the allowed list.
It validates that the URL uses either HTTP or HTTPS protocols.
If the hostname is an IP address, it ensures it's a valid public IP address.
It disables redirects to prevent potential bypass techniques. These measures significantly reduce the risk of SSRF attacks while still allowing the proxy functionality for legitimate use cases.