-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
597 lines (498 loc) · 24.2 KB
/
main.py
File metadata and controls
597 lines (498 loc) · 24.2 KB
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
#!/usr/bin/env python3
import threading
import socket
import select
import requests
import logging
import time
from urllib.parse import urlparse, urljoin
import os
import http.server
import socketserver
from http.server import BaseHTTPRequestHandler
import urllib3
# Disable SSL warnings for proxy usage
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Configuration
LISTEN_HOST = "127.0.0.1"
LISTEN_PORT = 8888
PROXIES_FILE = r"C:\Gofuzzer\proxies.txt"
MAX_RETRIES = 1 # CRITICAL: Only try 1 proxy per request to force rotation
REQUEST_TIMEOUT = 60
PROXY_TIMEOUT = 30
ENABLE_DIRECT_FALLBACK = True
CUSTOM_USER_AGENT = "Dalvik/2.1.0 (Linux; U; Android 7.1.2; SM-G973N Build/LMY48Z)" # Default sqlmap user agent
FORCE_ROTATION = True # Force new proxy for every single request
DEBUG_ROTATION = True # Enable rotation debugging
# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class ProxyRotator:
def __init__(self, proxies_file):
self.proxies_file = proxies_file
self.proxies = []
self.lock = threading.Lock()
self.current_idx = 0
self.failed_proxies = set()
self.load_proxies()
def load_proxies(self):
"""Load proxies from file with validation"""
if not os.path.exists(self.proxies_file):
logger.error(f"Proxies file not found: {self.proxies_file}")
return
try:
with open(self.proxies_file, 'r') as f:
raw_proxies = [line.strip() for line in f if line.strip() and not line.startswith('#')]
# Validate proxy format
validated_proxies = []
for proxy in raw_proxies:
if self._validate_proxy_format(proxy):
validated_proxies.append(proxy)
else:
logger.warning(f"Invalid proxy format: {proxy}")
self.proxies = validated_proxies
logger.info(f"Loaded {len(self.proxies)} valid proxies")
except Exception as e:
logger.error(f"Error loading proxies: {e}")
def _validate_proxy_format(self, proxy):
"""Basic proxy format validation"""
try:
if ':' not in proxy:
return False
parts = proxy.split(':')
if len(parts) < 2:
return False
# Handle auth proxies (user:pass@host:port)
if '@' in proxy:
auth_part, host_part = proxy.split('@')
if ':' not in host_part:
return False
host, port = host_part.split(':')
else:
host, port = parts[0], parts[1]
port = int(port)
return 1 <= port <= 65535
except:
return False
def get_next_proxy(self):
"""Get next proxy in rotation - FORCE rotation for every request"""
with self.lock:
if not self.proxies:
return None
# If forcing rotation, always increment regardless of failures
if FORCE_ROTATION:
proxy = self.proxies[self.current_idx % len(self.proxies)]
old_idx = self.current_idx % len(self.proxies)
self.current_idx += 1
new_idx = self.current_idx % len(self.proxies)
if DEBUG_ROTATION:
logger.info(f"🔄 FORCED ROTATION: {old_idx} -> {new_idx} | Using: {proxy}")
return proxy
# Original logic with failure checking
attempts = 0
while attempts < len(self.proxies):
proxy = self.proxies[self.current_idx % len(self.proxies)]
self.current_idx += 1
if proxy not in self.failed_proxies:
return proxy
attempts += 1
# If all proxies failed, reset failed list and try again
logger.warning("All proxies marked as failed, resetting failed list")
self.failed_proxies.clear()
return self.proxies[0] if self.proxies else None
def mark_proxy_failed(self, proxy):
"""Mark a proxy as failed - but don't if forcing rotation"""
with self.lock:
if not FORCE_ROTATION: # Only mark failed if not forcing rotation
self.failed_proxies.add(proxy)
logger.warning(f"Marked proxy as failed: {proxy}")
else:
logger.warning(f"⚠️ Proxy issue (not marking failed due to FORCE_ROTATION): {proxy}")
def get_proxy_stats(self):
"""Get current proxy rotation statistics"""
with self.lock:
total = len(self.proxies)
failed = len(self.failed_proxies)
current = self.current_idx % total if total > 0 else 0
return {
'total': total,
'failed': failed,
'active': total - failed,
'current_index': current,
'current_proxy': self.proxies[current] if total > 0 else None
}
# Initialize proxy rotator
proxy_rotator = ProxyRotator(PROXIES_FILE)
class RotatingProxyHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
"""Override to use our logger"""
logger.info(f"{self.address_string()} - {format % args}")
def do_CONNECT(self):
"""Handle HTTPS CONNECT requests - Fixed for HTTPS/443"""
try:
# Parse the target host and port
host, port = self.path.split(':')
port = int(port)
logger.info(f"CONNECT {host}:{port}")
# Try with different proxies first
for attempt in range(MAX_RETRIES):
upstream_proxy = proxy_rotator.get_next_proxy()
if not upstream_proxy:
break
# Parse proxy with potential auth
if '@' in upstream_proxy:
auth_part, proxy_host_port = upstream_proxy.split('@')
proxy_user, proxy_pass = auth_part.split(':')
proxy_host, proxy_port = proxy_host_port.split(':')
proxy_auth = f"{proxy_user}:{proxy_pass}"
else:
proxy_host, proxy_port = upstream_proxy.split(':')
proxy_auth = None
proxy_port = int(proxy_port)
logger.debug(f"CONNECT attempt {attempt + 1}: Using proxy {upstream_proxy}")
try:
proxy_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
proxy_socket.settimeout(PROXY_TIMEOUT)
proxy_socket.connect((proxy_host, proxy_port))
# Build CONNECT request with auth if needed
connect_request = f"CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\n"
if proxy_auth:
import base64
auth_header = base64.b64encode(proxy_auth.encode()).decode()
connect_request += f"Proxy-Authorization: Basic {auth_header}\r\n"
connect_request += "\r\n"
proxy_socket.send(connect_request.encode())
# Read response from upstream proxy
response = proxy_socket.recv(4096).decode()
# Check for 407 Proxy Authentication Required
if "407" in response:
logger.error(f"Proxy authentication failed for {upstream_proxy}")
proxy_rotator.mark_proxy_failed(upstream_proxy)
proxy_socket.close()
continue
# Parse status code more reliably
if not self._is_connect_success(response):
raise Exception(f"Upstream proxy rejected CONNECT: {response.strip()}")
# Send success response to client
self.send_response(200, 'Connection established')
self.end_headers()
# Start tunneling
logger.info(f"CONNECT successful via proxy {upstream_proxy}")
self._tunnel_data(self.connection, proxy_socket)
return
except Exception as e:
logger.warning(f"CONNECT failed with proxy {upstream_proxy}: {e}")
proxy_rotator.mark_proxy_failed(upstream_proxy)
try:
proxy_socket.close()
except:
pass
# All proxy attempts failed, try direct connection if enabled
if ENABLE_DIRECT_FALLBACK:
logger.warning(f"All upstream proxies failed for CONNECT {host}:{port}, trying direct connection")
try:
direct_socket = socket.create_connection((host, port), timeout=PROXY_TIMEOUT)
self.send_response(200, 'Connection established')
self.end_headers()
logger.info(f"CONNECT successful via direct connection to {host}:{port}")
self._tunnel_data(self.connection, direct_socket)
return
except Exception as e:
logger.error(f"Direct CONNECT to {host}:{port} failed: {e}")
# Everything failed
self.send_error(502, "All proxy attempts and direct connection failed")
except Exception as e:
logger.error(f"CONNECT error: {e}")
self.send_error(400, "Bad request")
def _is_connect_success(self, response):
"""Check if CONNECT response indicates success"""
try:
if not response:
return False
lines = response.split('\r\n')
if not lines:
return False
status_line = lines[0]
logger.debug(f"CONNECT response status line: {status_line}")
parts = status_line.split(' ', 2)
if len(parts) < 2:
return False
try:
status_code = int(parts[1])
return 200 <= status_code < 300
except ValueError:
return False
except Exception as e:
logger.debug(f"Error parsing CONNECT response: {e}")
return False
def do_GET(self):
"""Handle HTTP GET requests"""
self._handle_http_request()
def do_POST(self):
"""Handle HTTP POST requests"""
self._handle_http_request()
def do_PUT(self):
"""Handle HTTP PUT requests"""
self._handle_http_request()
def do_DELETE(self):
"""Handle HTTP DELETE requests"""
self._handle_http_request()
def do_HEAD(self):
"""Handle HTTP HEAD requests"""
self._handle_http_request()
def do_OPTIONS(self):
"""Handle HTTP OPTIONS requests"""
self._handle_http_request()
def _handle_http_request(self):
"""Handle HTTP requests through rotating proxies - FORCE rotation for each request"""
try:
# Fix URL parsing for sqlmap compatibility
if self.path.startswith('http://') or self.path.startswith('https://'):
# Full URL provided (typical for proxy requests)
target_url = self.path
parsed_url = urlparse(target_url)
target_host = parsed_url.netloc
target_path = parsed_url.path + ('?' + parsed_url.query if parsed_url.query else '')
else:
# Relative path provided
host_header = self.headers.get('Host', '')
if not host_header:
logger.error("No Host header found in request")
self.send_error(400, "Bad Request: No Host header")
return
# Determine protocol based on context or default to HTTPS for security
# Check if this is likely an HTTPS request
if ':443' in host_header or self.path.startswith('/') and not self.path.startswith('http'):
protocol = 'https'
else:
protocol = 'http'
target_host = host_header
target_path = self.path
target_url = f"{protocol}://{target_host}{target_path}"
logger.info(f"{self.command} {target_url}")
# Get request body if present
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length) if content_length > 0 else None
# Prepare headers - Fix header handling
headers = {}
for key, value in self.headers.items():
# Skip proxy-specific headers and problematic ones
if key.lower() not in ['host', 'connection', 'proxy-connection', 'proxy-authorization']:
headers[key] = value
# Override User-Agent if custom one is set
if CUSTOM_USER_AGENT:
headers['User-Agent'] = CUSTOM_USER_AGENT
# Ensure proper Host header for the target
headers['Host'] = target_host.split(':')[0] # Remove port from host header
# CRITICAL FIX: Get a fresh proxy for EVERY request - no retries with same proxy
upstream_proxy = proxy_rotator.get_next_proxy()
if not upstream_proxy:
if ENABLE_DIRECT_FALLBACK:
logger.warning(f"No proxies available for {self.command} {target_url}, trying direct request")
self._try_direct_request(target_url, headers, body)
return
else:
self.send_error(502, "No proxies available")
return
try:
# Handle proxy auth
if '@' in upstream_proxy:
auth_part, proxy_host_port = upstream_proxy.split('@')
proxy_user, proxy_pass = auth_part.split(':')
proxy_url = f"http://{proxy_user}:{proxy_pass}@{proxy_host_port}"
else:
proxy_url = f"http://{upstream_proxy}"
proxy_dict = {
"http": proxy_url,
"https": proxy_url
}
logger.info(f"🔄 USING PROXY: {upstream_proxy} for {self.command} {target_url}")
# Create NEW session for each request to ensure proxy rotation
session = requests.Session()
session.proxies.update(proxy_dict)
response = session.request(
method=self.command,
url=target_url,
headers=headers,
data=body,
timeout=PROXY_TIMEOUT,
allow_redirects=False,
stream=True,
verify=False
)
# Check if client connection is still alive
if not self._is_connection_alive():
logger.warning("Client disconnected during proxy request")
return
# Log the actual response for debugging
logger.info(f"✅ PROXY SUCCESS: {response.status_code} via {upstream_proxy}")
# Check for WAF block indicators
if response.status_code in [302, 403, 406, 429]:
logger.warning(f"⚠️ Potential WAF block: {response.status_code} from {upstream_proxy}")
# Don't mark as failed immediately - might be legitimate response
# Send response back to client
self.send_response(response.status_code)
# Send headers - exclude problematic ones
excluded_headers = {
'connection', 'proxy-connection', 'transfer-encoding',
'content-encoding' # Let client handle compression
}
for name, value in response.headers.items():
if name.lower() not in excluded_headers:
self.send_header(name, value)
self.end_headers()
# Send body
try:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
if not self._is_connection_alive():
logger.warning("Client disconnected while sending body")
return
self.wfile.write(chunk)
except Exception as e:
logger.warning(f"Error sending response body: {e}")
return
except requests.exceptions.ProxyError as e:
if "407" in str(e):
logger.error(f"❌ Proxy authentication required for {upstream_proxy}")
proxy_rotator.mark_proxy_failed(upstream_proxy)
else:
logger.warning(f"❌ Proxy error with {upstream_proxy}: {e}")
proxy_rotator.mark_proxy_failed(upstream_proxy)
except Exception as e:
logger.warning(f"❌ HTTP request failed with proxy {upstream_proxy}: {e}")
proxy_rotator.mark_proxy_failed(upstream_proxy)
# Fallback to direct request if all proxies failed
if ENABLE_DIRECT_FALLBACK:
logger.warning(f"Proxy failed for {self.command} {target_url}, trying direct request")
self._try_direct_request(target_url, headers, body)
else:
if self._is_connection_alive():
self._safe_send_error(502, "Proxy request failed and direct fallback disabled")
except Exception as e:
logger.error(f"HTTP request error: {e}")
if self._is_connection_alive():
self._safe_send_error(500, "Internal server error")
def _try_direct_request(self, target_url, headers, body):
"""Try direct request as fallback"""
try:
response = requests.request(
method=self.command,
url=target_url,
headers=headers,
data=body,
timeout=REQUEST_TIMEOUT,
allow_redirects=False,
stream=True,
verify=False
)
if not self._is_connection_alive():
logger.warning("Client disconnected during direct request")
return
logger.info(f"🔗 DIRECT SUCCESS: {response.status_code}")
self.send_response(response.status_code)
excluded_headers = {
'connection', 'proxy-connection', 'transfer-encoding',
'content-encoding'
}
for name, value in response.headers.items():
if name.lower() not in excluded_headers:
self.send_header(name, value)
self.end_headers()
for chunk in response.iter_content(chunk_size=8192):
if chunk:
if not self._is_connection_alive():
logger.warning("Client disconnected while sending direct response")
return
self.wfile.write(chunk)
return
except Exception as e:
logger.error(f"Direct HTTP request failed: {e}")
if self._is_connection_alive():
self._safe_send_error(502, "All requests failed")
except Exception as e:
logger.error(f"HTTP request error: {e}")
if self._is_connection_alive():
self._safe_send_error(500, "Internal server error")
def _is_connection_alive(self):
"""Check if the client connection is still alive"""
try:
ready = select.select([self.connection], [], [], 0)
if ready[0]:
return False
return True
except:
return False
def _safe_send_error(self, code, message):
"""Safely send error response"""
try:
self.send_error(code, message)
except (ConnectionAbortedError, BrokenPipeError, OSError) as e:
logger.warning(f"Failed to send error {code} - client disconnected: {e}")
except Exception as e:
logger.error(f"Unexpected error sending {code} response: {e}")
def _tunnel_data(self, client_socket, server_socket):
"""Tunnel data between client and server sockets"""
try:
sockets = [client_socket, server_socket]
while True:
ready_sockets, _, error_sockets = select.select(sockets, [], sockets, 60)
if error_sockets:
break
for sock in ready_sockets:
try:
data = sock.recv(4096)
if not data:
return
if sock is client_socket:
server_socket.send(data)
else:
client_socket.send(data)
except:
return
except:
pass
finally:
try:
server_socket.close()
except:
pass
class ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
allow_reuse_address = True
daemon_threads = True
def set_custom_user_agent(user_agent):
"""Set custom user agent for all requests"""
global CUSTOM_USER_AGENT
CUSTOM_USER_AGENT = user_agent
logger.info(f"Custom User-Agent set to: {user_agent}")
if __name__ == "__main__":
# You can set a custom user agent here
# set_custom_user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
logger.info(f"Starting rotating proxy server on http://{LISTEN_HOST}:{LISTEN_PORT}")
logger.info(f"Direct fallback: {'Enabled' if ENABLE_DIRECT_FALLBACK else 'Disabled'}")
logger.info(f"Force rotation: {'Enabled' if FORCE_ROTATION else 'Disabled'}")
logger.info(f"Max retries per request: {MAX_RETRIES}")
logger.info(f"Custom User-Agent: {CUSTOM_USER_AGENT}")
if proxy_rotator.proxies:
logger.info(f"Loaded {len(proxy_rotator.proxies)} proxies")
if DEBUG_ROTATION:
for i, proxy in enumerate(proxy_rotator.proxies[:5]): # Show first 5
logger.info(f" [{i}] {proxy}")
if len(proxy_rotator.proxies) > 5:
logger.info(f" ... and {len(proxy_rotator.proxies) - 5} more")
else:
if ENABLE_DIRECT_FALLBACK:
logger.warning("No valid proxies loaded, but direct fallback is enabled")
else:
logger.error("No valid proxies loaded and direct fallback is disabled. Exiting.")
exit(1)
server = ThreadingHTTPServer((LISTEN_HOST, LISTEN_PORT), RotatingProxyHandler)
try:
logger.info("🚀 Proxy server ready! Send requests to bypass WAF with rotating IPs")
server.serve_forever()
except KeyboardInterrupt:
logger.info("Shutting down...")
stats = proxy_rotator.get_proxy_stats()
logger.info(f"Final stats: {stats['active']}/{stats['total']} proxies active")
server.shutdown()
server.server_close()