Spaces:
Sleeping
Sleeping
File size: 5,807 Bytes
674e485 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | from flask import Flask, request, Response, stream_with_context
import requests
from urllib.parse import urljoin, urlparse, urlencode
import logging
from datetime import datetime
from functools import lru_cache
import re
from bs4 import BeautifulSoup
app = Flask(__name__)
# Configuration
TARGET_SITE = "https://osint10x.com" # Replace with your target site
CACHE_TIMEOUT = 300
LOGGING_ENABLED = True
# Set up logging
if LOGGING_ENABLED:
logging.basicConfig(
filename='proxy_logs.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def get_proxy_url(original_url, proxy_host):
"""Convert original URL to proxy URL"""
if not original_url:
return original_url
if original_url.startswith('//'):
original_url = 'https:' + original_url
if not original_url.startswith(('http://', 'https://')):
original_url = urljoin(TARGET_SITE, original_url)
parsed = urlparse(original_url)
if parsed.netloc:
# Create the proxy URL path
return f"{proxy_host}/{parsed.path}{'?' + parsed.query if parsed.query else ''}"
return original_url
def modify_html_content(content, proxy_host):
"""Modify HTML content to rewrite URLs and fix resources"""
try:
soup = BeautifulSoup(content, 'html.parser')
# Update various HTML elements that contain URLs
url_attributes = {
'a': 'href',
'img': 'src',
'script': 'src',
'link': 'href',
'form': 'action',
'iframe': 'src',
'source': 'src',
'video': 'src',
'audio': 'src'
}
for tag, attr in url_attributes.items():
for element in soup.find_all(tag, **{attr: True}):
original_url = element[attr]
proxied_url = get_proxy_url(original_url, proxy_host)
if proxied_url:
element[attr] = proxied_url
# Handle inline CSS with url() references
style_tags = soup.find_all('style')
for style in style_tags:
if style.string:
style.string = re.sub(
r'url\([\'"]?([^\'"())]+)[\'"]?\)',
lambda m: f'url({get_proxy_url(m.group(1), proxy_host)})',
style.string
)
# Handle style attributes
for tag in soup.find_all(style=True):
tag['style'] = re.sub(
r'url\([\'"]?([^\'"())]+)[\'"]?\)',
lambda m: f'url({get_proxy_url(m.group(1), proxy_host)})',
tag['style']
)
return str(soup).encode('utf-8')
except Exception as e:
logging.error(f"Error modifying HTML: {str(e)}")
return content
def modify_css_content(content, proxy_host):
"""Modify CSS content to rewrite URLs"""
try:
content_str = content.decode('utf-8')
modified_content = re.sub(
r'url\([\'"]?([^\'"())]+)[\'"]?\)',
lambda m: f'url({get_proxy_url(m.group(1), proxy_host)})',
content_str
)
return modified_content.encode('utf-8')
except Exception as e:
logging.error(f"Error modifying CSS: {str(e)}")
return content
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def proxy(path):
try:
# Get the proxy's host
proxy_host = request.host_url.rstrip('/')
# Build target URL
target_url = urljoin(TARGET_SITE, path)
# Forward the request
request_headers = dict(request.headers)
request_headers['Host'] = urlparse(TARGET_SITE).netloc
# Handle query parameters
query_string = request.query_string.decode('utf-8')
if query_string:
target_url = f"{target_url}?{query_string}"
response = requests.request(
method=request.method,
url=target_url,
headers=request_headers,
data=request.get_data(),
cookies=request.cookies,
allow_redirects=False,
stream=True
)
# Handle redirects
if response.is_redirect:
location = response.headers.get('Location')
if location:
modified_location = get_proxy_url(location, proxy_host)
response.headers['Location'] = modified_location
# Modify response headers
response_headers = dict(response.headers)
# Remove problematic headers
headers_to_remove = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
for header in headers_to_remove:
response_headers.pop(header, None)
# Handle different content types
content_type = response.headers.get('content-type', '').lower()
if 'text/html' in content_type:
content = modify_html_content(response.content, proxy_host)
return Response(content, response.status_code, response_headers)
elif 'text/css' in content_type:
content = modify_css_content(response.content, proxy_host)
return Response(content, response.status_code, response_headers)
else:
# Stream other content types directly
return Response(
stream_with_context(response.iter_content(chunk_size=8192)),
response.status_code,
response_headers
)
except Exception as e:
logging.error(f"Proxy Error: {str(e)}")
return Response(f"Proxy Error: {str(e)}", status=500)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000) |