| |
| import requests |
| from flask import Flask, request, Response |
| from urllib.parse import urlparse |
|
|
| app = Flask(__name__) |
|
|
| |
| IP_BLACKLIST = [ |
| "127.0.0.1", "localhost", |
| "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", |
| "0.0.0.0", "169.254.0.0/16" |
| ] |
|
|
| def is_ip_blacklisted(hostname): |
| """检查域名或IP是否在黑名单中""" |
| import ipaddress |
| try: |
| import socket |
| ip_addr = socket.gethostbyname(hostname) |
| ip = ipaddress.ip_address(ip_addr) |
| for cidr in IP_BLACKLIST: |
| if ip in ipaddress.ip_network(cidr): |
| return True |
| return False |
| except (socket.gaierror, ValueError): |
| return False |
|
|
| |
| @app.route('/<path:full_target>', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS']) |
| def proxy(full_target): |
| final_target_url = full_target |
| |
| if not (final_target_url.startswith('http://') or final_target_url.startswith('https://')): |
| final_target_url = 'https://' + final_target_url |
| |
| try: |
| parsed_url = urlparse(final_target_url) |
| domain = parsed_url.netloc |
| if not domain or is_ip_blacklisted(domain): |
| return f"Error: Invalid or forbidden target URL.", 400 |
| except Exception: |
| return f"Error: Could not parse target URL.", 400 |
|
|
| params = request.args |
| headers = {key: value for key, value in request.headers if key.lower() != 'host'} |
| headers['Host'] = domain |
| data = request.get_data() |
|
|
| print(f"[*] Forwarding request: {request.method} {final_target_url}") |
|
|
| try: |
| resp = requests.request( |
| method=request.method, |
| url=final_target_url, |
| headers=headers, |
| data=data, |
| params=params, |
| stream=True, |
| timeout=30 |
| ) |
|
|
| excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection'] |
| response_headers = { |
| key: value for key, value in resp.raw.headers.items() |
| if key.lower() not in excluded_headers |
| } |
|
|
| return Response(resp.iter_content(chunk_size=1024), resp.status_code, response_headers) |
|
|
| except requests.exceptions.RequestException as e: |
| print(f"[!] Error forwarding request: {e}") |
| return Response(f"Proxying failed: {e}", status=502) |
|
|
| |
| @app.route('/') |
| def index(): |
| return """ |
| <h1>Full URL Reverse Proxy</h1> |
| <p>This proxy allows you to access any website by placing the full URL in the path.</p> |
| <p>Usage: <code>https://{your_space_name}.hf.space/<full_target_url_with_protocol></code></p> |
| <p>Example: To access <code>https://api.github.com/zen</code>, you would request:</br> |
| <code>https://{your_space_name}.hf.space/https://api.github.com/zen</code></p> |
| """.format(your_space_name=request.host.split('.')[0]), 200 |