Reaper1909 commited on
Commit
faaf147
·
verified ·
1 Parent(s): c1be427

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -338
app.py DELETED
@@ -1,338 +0,0 @@
1
- import os
2
- import sqlite3
3
- import json
4
- import logging
5
- import base64
6
- import httpx
7
- import asyncio
8
- import whois
9
- import ssl
10
- import socket
11
- import time
12
- import requests
13
- import zipfile
14
- import io
15
- import re
16
- from datetime import datetime
17
- from fastapi import FastAPI, BackgroundTasks
18
- from fastapi.responses import HTMLResponse
19
- from fastapi.middleware.cors import CORSMiddleware
20
- from pydantic import BaseModel
21
- import google.generativeai as genai
22
- from groq import Groq
23
- import uvicorn
24
-
25
- # --- CONFIG & LOGGING ---
26
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
27
- logger = logging.getLogger("WadeEngine")
28
-
29
- app = FastAPI(title="WADE Engine v7.0", version="7.0")
30
-
31
- # API KEYS (from Hugging Face Secrets)
32
- GROQ_API_KEY = os.getenv("GROQ_API_KEY")
33
- GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
34
- VIRUSTOTAL_API_KEY = os.getenv("VIRUSTOTAL_API_KEY")
35
- GOOGLE_SAFEBROWSING_API_KEY = os.getenv("GOOGLE_SAFEBROWSING_API_KEY")
36
- ABUSEIPDB_API_KEY = os.getenv("ABUSEIPDB_API_KEY")
37
-
38
- # TRUSTED DOMAINS
39
- TRUSTED_AGES = {
40
- "google.com": 9500, "youtube.com": 6900, "wikipedia.org": 8700,
41
- "github.com": 5800, "microsoft.com": 11000, "huggingface.co": 1500,
42
- "stackoverflow.com": 7000, "amazon.com": 10500, "apple.com": 13000,
43
- "netflix.com": 9000, "linkedin.com": 7500, "whatsapp.com": 5000,
44
- "openai.com": 3000, "facebook.com": 7600, "instagram.com": 4500,
45
- "twitter.com": 6500, "x.com": 10000, "twitch.tv": 4000,
46
- "gmail.com": 9500, "outlook.com": 8000, "yahoo.com": 10000,
47
- "paruluniversity.ac.in": 5000
48
- }
49
-
50
- app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
51
-
52
- # --- DATABASE ---
53
- DB_PATH = "wade_logs.db"
54
- def init_db():
55
- with sqlite3.connect(DB_PATH) as conn:
56
- conn.execute('''CREATE TABLE IF NOT EXISTS logs
57
- (id INTEGER PRIMARY KEY, url TEXT, score INTEGER, verdict TEXT, sources TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''')
58
- init_db()
59
-
60
- # --- THREAT INTELLIGENCE ---
61
- class ThreatIntel:
62
- def __init__(self):
63
- self.malicious_urls = set()
64
- async def update_feeds(self):
65
- logger.info("🔄 WADE: Updating Threat Intelligence...")
66
- sources = ["https://urlhaus.abuse.ch/downloads/text_online/", "https://raw.githubusercontent.com/mitchellkrogza/Phishing.Database/master/phishing-links-ACTIVE.txt"]
67
- async with httpx.AsyncClient(follow_redirects=True, timeout=15.0) as client:
68
- for source in sources:
69
- try:
70
- r = await client.get(source)
71
- if r.status_code == 200:
72
- for line in r.text.splitlines():
73
- if not line.startswith("#") and line.strip():
74
- self.malicious_urls.add(line.strip())
75
- except Exception as e:
76
- logger.error(f"⚠️ Feed Error: {e}")
77
- logger.info(f"✅ WADE Intel Updated: {len(self.malicious_urls)} Active Threats.")
78
-
79
- intel_db = ThreatIntel()
80
-
81
- @app.on_event("startup")
82
- async def startup_event():
83
- asyncio.create_task(intel_db.update_feeds())
84
- asyncio.create_task(update_tranco_cache())
85
-
86
- # --- TRANCO CACHE ---
87
- trusted_cache = {"timestamp": 0, "domains": set()}
88
- async def update_tranco_cache():
89
- global trusted_cache
90
- try:
91
- logger.info("WADE: Fetching Tranco Top 10k...")
92
- url = "https://tranco-list.eu/top-1m.csv.zip"
93
- # FIX: Added follow_redirects=True to handle 307 redirects properly
94
- async with httpx.AsyncClient(follow_redirects=True, timeout=15.0) as client:
95
- resp = await client.get(url)
96
- resp.raise_for_status()
97
- with zipfile.ZipFile(io.BytesIO(resp.content)) as z:
98
- with z.open(z.namelist()[0]) as f:
99
- domains = set()
100
- for i, line in enumerate(f):
101
- if i >= 10000: break
102
- domains.add(line.decode('utf-8').strip().split(',')[1])
103
- trusted_cache["domains"] = domains
104
- trusted_cache["timestamp"] = time.time()
105
- logger.info(f"✅ Tranco Cache: {len(domains)} domains")
106
- except Exception as e:
107
- logger.error(f"Tranco fetch failed: {e}")
108
- if not trusted_cache["domains"]:
109
- trusted_cache["domains"] = {"google.com", "microsoft.com", "github.com", "youtube.com"}
110
-
111
- # --- OSINT FUNCTIONS ---
112
- def get_domain_age(domain: str) -> int:
113
- try:
114
- socket.setdefaulttimeout(2.0)
115
- try:
116
- w = whois.whois(domain)
117
- cd = w.creation_date
118
- if isinstance(cd, list): cd = cd[0]
119
- if cd:
120
- if isinstance(cd, str):
121
- for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S"):
122
- try: cd = datetime.strptime(cd, fmt); break
123
- except: pass
124
- if isinstance(cd, datetime): return (datetime.now() - cd).days
125
- except: pass
126
- try:
127
- ctx = ssl.create_default_context()
128
- with socket.create_connection((domain, 443), timeout=2.0) as sock:
129
- with ctx.wrap_socket(sock, server_hostname=domain) as ssock:
130
- cert = ssock.getpeercert()
131
- start_date = datetime.strptime(cert['notBefore'], "%b %d %H:%M:%S %Y %Z")
132
- return (datetime.now() - start_date).days
133
- except: pass
134
- except: pass
135
- return -1
136
-
137
- async def check_virustotal(url: str) -> dict:
138
- if not VIRUSTOTAL_API_KEY: return {"malicious": 0, "total": "No Key"}
139
- try:
140
- url_id = base64.urlsafe_b64encode(url.encode()).decode().strip("=")
141
- async with httpx.AsyncClient(timeout=5.0) as client:
142
- res = await client.get(f"https://www.virustotal.com/api/v3/urls/{url_id}", headers={"x-apikey": VIRUSTOTAL_API_KEY})
143
- if res.status_code == 200:
144
- stats = res.json()['data']['attributes']['last_analysis_stats']
145
- return {"malicious": stats.get('malicious', 0), "total": sum(stats.values())}
146
- except: pass
147
- return {"malicious": 0, "total": "Error"}
148
-
149
- async def check_google_safe_browsing(url: str) -> dict:
150
- if not GOOGLE_SAFEBROWSING_API_KEY: return {"threat": "None", "source": "No Key"}
151
- try:
152
- payload = {
153
- "client": {"clientId": "wade-ips", "clientVersion": "7.0"},
154
- "threatInfo": {
155
- "threatTypes": ["MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE"],
156
- "platformTypes": ["ANY_PLATFORM"],
157
- "threatEntryTypes": ["URL"],
158
- "threatEntries": [{"url": url}]
159
- }
160
- }
161
- async with httpx.AsyncClient(timeout=5.0) as client:
162
- res = await client.post(f"https://safebrowsing.googleapis.com/v4/threatMatches:find?key={GOOGLE_SAFEBROWSING_API_KEY}", json=payload)
163
- if res.status_code == 200:
164
- data = res.json()
165
- if "matches" in data and data["matches"]:
166
- return {"threat": data["matches"][0]["threatType"], "source": "Google Safe Browsing"}
167
- except Exception as e:
168
- logger.error(f"Safe Browsing Error: {e}")
169
- return {"threat": "None", "source": "Google Safe Browsing"}
170
-
171
- async def check_abuseipdb(ip: str) -> dict:
172
- if not ABUSEIPDB_API_KEY: return {"abuse_confidence": 0, "source": "No Key"}
173
- # FIX: Only query AbuseIPDB if the target is actually an IPv4 address
174
- if not re.match(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", ip):
175
- return {"abuse_confidence": 0, "source": "Not an IP"}
176
- try:
177
- async with httpx.AsyncClient(timeout=5.0) as client:
178
- res = await client.get("https://api.abuseipdb.com/api/v2/check", headers={"Key": ABUSEIPDB_API_KEY}, params={"ipAddress": ip, "maxAgeInDays": 30})
179
- if res.status_code == 200:
180
- data = res.json()
181
- return {"abuse_confidence": data['data']['abuseConfidenceScore'], "source": "AbuseIPDB"}
182
- except Exception as e:
183
- logger.error(f"AbuseIPDB Error: {e}")
184
- return {"abuse_confidence": 0, "source": "AbuseIPDB"}
185
-
186
- def log_scan(url: str, result: dict):
187
- try:
188
- with sqlite3.connect(DB_PATH) as conn:
189
- conn.execute("INSERT INTO logs (url, score, verdict, sources) VALUES (?, ?, ?, ?)",
190
- (url, result.get("risk_score", 0), result.get("verdict", "UNKNOWN"), "AI+OSINT+MultiLayer"))
191
- except: pass
192
-
193
- # --- AI SCANNER ---
194
- class HybridScanner:
195
- def __init__(self):
196
- self.groq = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None
197
- if GEMINI_API_KEY: genai.configure(api_key=GEMINI_API_KEY)
198
-
199
- async def scan(self, url: str, vt_data: dict, domain_age: int, safe_browsing: dict, abuse_score: int) -> dict:
200
- vt_score = vt_data.get('malicious', 0) if isinstance(vt_data.get('malicious'), int) else 0
201
- is_sb_flagged = safe_browsing.get("threat") != "None"
202
-
203
- system_prompt = (
204
- "You are WADE, an enterprise-grade Phishing and Malware Detection AI. "
205
- "MINIMIZE FALSE POSITIVES. Legitimate sites use words like 'login' or 'secure'. "
206
- f"Context: VirusTotal Flags: {vt_score}. Google Safe Browsing: {safe_browsing.get('threat', 'Clean')}. AbuseIPDB Score: {abuse_score}. "
207
- "Only flag as MALICIOUS (80-100) for clear Typosquatting, Deceptive URLs, or if Google Safe Browsing flagged it. "
208
- "Return ONLY valid JSON: {'risk_score': int, 'verdict': 'SAFE' or 'MALICIOUS' or 'SUSPICIOUS', 'threat_type': str, 'harm': str, 'effect': str}"
209
- )
210
- user_prompt = f"Analyze URL: '{url}'. Domain Age: {domain_age} days."
211
-
212
- if self.groq:
213
- try:
214
- res = self.groq.chat.completions.create(
215
- model="llama-3.3-70b-versatile",
216
- messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],
217
- response_format={"type": "json_object"}, temperature=0.1
218
- )
219
- return json.loads(res.choices[0].message.content)
220
- except Exception as e:
221
- logger.error(f"Groq API Error (3.3): {e}")
222
- # FIX: Fallback to 3.1 if 3.3 is inaccessible
223
- try:
224
- res = self.groq.chat.completions.create(
225
- model="llama-3.1-70b-versatile",
226
- messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],
227
- response_format={"type": "json_object"}, temperature=0.1
228
- )
229
- return json.loads(res.choices[0].message.content)
230
- except Exception as e2:
231
- logger.error(f"Groq API Error (3.1): {e2}")
232
-
233
- if GEMINI_API_KEY:
234
- try:
235
- # FIX: Updated to 'latest' alias to prevent 404 versioning errors
236
- model = genai.GenerativeModel('gemini-1.5-flash-latest')
237
- res = model.generate_content(f"{system_prompt}\n\n{user_prompt}")
238
- clean_json = res.text.replace("```json", "").replace("```", "").strip()
239
- return json.loads(clean_json)
240
- except Exception as e:
241
- logger.error(f"Gemini API Error: {e}")
242
-
243
- # Fallback
244
- if is_sb_flagged or abuse_score > 50:
245
- return {"risk_score": 90, "verdict": "MALICIOUS", "threat_type": "Multi-Layer Confirmed Threat", "harm": "Known malicious infrastructure", "effect": "Blocked"}
246
- return {"risk_score": 0, "verdict": "SAFE", "threat_type": "No Anomalies", "harm": "None", "effect": "None"}
247
-
248
- scanner = HybridScanner()
249
-
250
- class ScanRequest(BaseModel): url: str
251
-
252
- @app.post("/analyze")
253
- async def analyze_url(request: ScanRequest, background_tasks: BackgroundTasks):
254
- url = request.url
255
- if url in SCAN_CACHE: return SCAN_CACHE[url]
256
-
257
- domain = url.split("//")[-1].split("/")[0].replace("www.", "")
258
-
259
- # 1. Tranco Check
260
- if domain in trusted_cache["domains"] or domain.endswith(tuple(trusted_cache["domains"])):
261
- safe_result = {"risk_score": 0, "verdict": "SAFE", "threat_type": "Global Trusted Domain", "harm": "None", "effect": "None", "domain_age": "Trusted", "vt_data": {"malicious": 0, "total": "Tranco"}, "url": url}
262
- SCAN_CACHE[url] = safe_result
263
- return safe_result
264
-
265
- # 2. OSINT Blacklist
266
- if url in intel_db.malicious_urls:
267
- malicious_result = {"risk_score": 100, "verdict": "MALICIOUS", "threat_type": "Confirmed Phishing (OSINT)", "harm": "Active Threat Feed", "effect": "Blocked", "domain_age": -1, "vt_data": {"malicious": "High", "total": "OSINT"}, "url": url}
268
- SCAN_CACHE[url] = malicious_result
269
- return malicious_result
270
-
271
- # 3. PARALLEL OSINT LOOKUPS
272
- age_task = asyncio.to_thread(get_domain_age, domain)
273
- vt_task = check_virustotal(url)
274
- sb_task = check_google_safe_browsing(url)
275
- abuse_task = check_abuseipdb(domain)
276
-
277
- age, vt_data, safe_browsing, abuse_data = await asyncio.gather(age_task, vt_task, sb_task, abuse_task)
278
-
279
- abuse_score = abuse_data.get("abuse_confidence", 0)
280
- result = await scanner.scan(url, vt_data, age, safe_browsing, abuse_score)
281
-
282
- # 4. Final Calibration
283
- if isinstance(vt_data.get('malicious'), int) and vt_data.get('malicious') > 5:
284
- result['risk_score'] = max(result.get('risk_score', 0), 90)
285
- result['verdict'] = "MALICIOUS"
286
- result['threat_type'] = "Vendor Consensus"
287
-
288
- if safe_browsing.get("threat") != "None":
289
- result['risk_score'] = max(result.get('risk_score', 0), 95)
290
- result['verdict'] = "MALICIOUS"
291
- result['threat_type'] = f"Google Safe Browsing: {safe_browsing['threat']}"
292
-
293
- if abuse_score > 50:
294
- result['risk_score'] = max(result.get('risk_score', 0), 85)
295
- result['verdict'] = "MALICIOUS"
296
- result['threat_type'] = f"AbuseIPDB Score: {abuse_score}%"
297
-
298
- if age != -1 and age < 3 and result.get('risk_score', 0) < 40:
299
- result['risk_score'] = 50
300
- result['threat_type'] = "Very Newly Registered Domain"
301
-
302
- final_result = {**result, "domain_age": age, "vt_data": vt_data, "url": url}
303
- SCAN_CACHE[url] = final_result
304
- if len(SCAN_CACHE) > 500: SCAN_CACHE.pop(next(iter(SCAN_CACHE)))
305
- background_tasks.add_task(log_scan, url, final_result)
306
- return final_result
307
-
308
- SCAN_CACHE = {}
309
-
310
- @app.get("/", response_class=HTMLResponse)
311
- async def read_root():
312
- return "<html><body style='background:#050505; color:#00f3ff; font-family:monospace; text-align:center; margin-top:20%;'><h1>🛡️ WADE v7.0 ACTIVE</h1><p>Multi-Layer AI Threat Detection Running.</p></body></html>"
313
-
314
- @app.get("/dashboard/stats")
315
- async def get_stats():
316
- try:
317
- with sqlite3.connect(DB_PATH) as conn:
318
- cursor = conn.cursor()
319
- cursor.execute("SELECT verdict, COUNT(*) FROM logs GROUP BY verdict")
320
- results = dict(cursor.fetchall())
321
- return {"total_scans": sum(results.values()), "safe": results.get("SAFE", 0), "phishing": results.get("MALICIOUS", 0), "suspicious": results.get("SUSPICIOUS", 0)}
322
- except: return {"total_scans": 0, "safe": 0, "phishing": 0, "suspicious": 0}
323
-
324
- @app.get("/dashboard/recent")
325
- async def get_recent_scans():
326
- try:
327
- with sqlite3.connect(DB_PATH) as conn:
328
- cursor = conn.cursor()
329
- cursor.execute("SELECT id, url, score, verdict, timestamp FROM logs ORDER BY timestamp DESC LIMIT 10")
330
- return [{"_id": r[0], "url": r[1], "risk_score": r[2], "verdict": r[3], "timestamp": r[4]} for r in cursor.fetchall()]
331
- except: return []
332
-
333
- @app.get("/trusted-domains")
334
- def get_trusted_domains():
335
- return {"success": True, "domains": list(trusted_cache["domains"])}
336
-
337
- if __name__ == "__main__":
338
- uvicorn.run(app, host="0.0.0.0", port=7860)