Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,367 +1,134 @@
|
|
| 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
|
| 10 |
-
import socket
|
| 11 |
-
import sys
|
| 12 |
-
import time
|
| 13 |
-
import requests
|
| 14 |
-
import zipfile
|
| 15 |
-
import io
|
| 16 |
-
from datetime import datetime
|
| 17 |
-
from fastapi import FastAPI, BackgroundTasks
|
| 18 |
-
from fastapi.responses import HTMLResponse, JSONResponse
|
| 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)
|
| 27 |
-
logger = logging.getLogger("WadeEngine")
|
| 28 |
-
|
| 29 |
-
app = FastAPI(title="WADE Engine Ultimate", version="5.0")
|
| 30 |
-
|
| 31 |
-
# API KEYS (Fetched from Hugging Face Cloud 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 |
|
| 36 |
-
#
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
"stackoverflow.com": 7000, "amazon.com": 10500, "apple.com": 13000,
|
| 41 |
-
"netflix.com": 9000, "linkedin.com": 7500, "whatsapp.com": 5000,
|
| 42 |
-
"openai.com": 3000, "facebook.com": 7600, "instagram.com": 4500,
|
| 43 |
-
"twitter.com": 6500, "x.com": 10000, "twitch.tv": 4000,
|
| 44 |
-
"gmail.com": 9500, "outlook.com": 8000, "yahoo.com": 10000,
|
| 45 |
-
"paruluniversity.ac.in": 5000
|
| 46 |
-
}
|
| 47 |
|
|
|
|
| 48 |
app.add_middleware(
|
| 49 |
CORSMiddleware,
|
| 50 |
-
allow_origins=["*"],
|
| 51 |
allow_methods=["*"],
|
| 52 |
allow_headers=["*"],
|
| 53 |
)
|
| 54 |
|
| 55 |
-
#
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
conn.execute('''CREATE TABLE IF NOT EXISTS logs
|
| 60 |
-
(id INTEGER PRIMARY KEY, url TEXT, score INTEGER, verdict TEXT, sources TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''')
|
| 61 |
-
init_db()
|
| 62 |
-
|
| 63 |
-
# --- INDUSTRY-READY THREAT INTELLIGENCE ---
|
| 64 |
-
class ThreatIntel:
|
| 65 |
-
def __init__(self):
|
| 66 |
-
self.malicious_urls = set()
|
| 67 |
-
self.loaded = False
|
| 68 |
-
|
| 69 |
-
async def update_feeds(self):
|
| 70 |
-
logger.info("🔄 WADE: Updating Threat Intelligence from GitHub & URLHaus...")
|
| 71 |
-
sources = [
|
| 72 |
-
"https://urlhaus.abuse.ch/downloads/text_online/",
|
| 73 |
-
"https://raw.githubusercontent.com/mitchellkrogza/Phishing.Database/master/phishing-links-ACTIVE.txt"
|
| 74 |
-
]
|
| 75 |
-
|
| 76 |
-
count = 0
|
| 77 |
-
async with httpx.AsyncClient() as client:
|
| 78 |
-
for source in sources:
|
| 79 |
-
try:
|
| 80 |
-
r = await client.get(source, timeout=10)
|
| 81 |
-
if r.status_code == 200:
|
| 82 |
-
for line in r.text.splitlines():
|
| 83 |
-
if not line.startswith("#") and line.strip():
|
| 84 |
-
self.malicious_urls.add(line.strip())
|
| 85 |
-
count += 1
|
| 86 |
-
except Exception as e:
|
| 87 |
-
logger.error(f"⚠️ Feed Error ({source}): {e}")
|
| 88 |
-
self.loaded = True
|
| 89 |
-
logger.info(f"✅ WADE Intel Updated: {len(self.malicious_urls)} Active Threats.")
|
| 90 |
-
|
| 91 |
-
intel_db = ThreatIntel()
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
|
| 97 |
-
# ---
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
| 99 |
try:
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
| 108 |
try:
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
except: pass
|
| 120 |
-
if isinstance(creation_date, datetime):
|
| 121 |
-
return (datetime.now() - creation_date).days
|
| 122 |
except Exception as e:
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
# 2. Fallback to SSL Certificate Issue Date
|
| 127 |
-
try:
|
| 128 |
-
ctx = ssl.create_default_context()
|
| 129 |
-
with socket.create_connection((domain, 443), timeout=2.0) as sock:
|
| 130 |
-
with ctx.wrap_socket(sock, server_hostname=domain) as ssock:
|
| 131 |
-
cert = ssock.getpeercert()
|
| 132 |
-
start_date_str = cert['notBefore']
|
| 133 |
-
start_date = datetime.strptime(start_date_str, "%b %d %H:%M:%S %Y %Z")
|
| 134 |
-
return (datetime.now() - start_date).days
|
| 135 |
-
except:
|
| 136 |
-
pass
|
| 137 |
-
|
| 138 |
-
except Exception:
|
| 139 |
-
pass
|
| 140 |
-
return -1
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
async with httpx.AsyncClient() as client:
|
| 147 |
-
res = await client.get(
|
| 148 |
-
f"https://www.virustotal.com/api/v3/urls/{url_id}",
|
| 149 |
-
headers={"x-apikey": VIRUSTOTAL_API_KEY},
|
| 150 |
-
timeout=5.0
|
| 151 |
-
)
|
| 152 |
-
if res.status_code == 200:
|
| 153 |
-
stats = res.json()['data']['attributes']['last_analysis_stats']
|
| 154 |
-
return {"malicious": stats.get('malicious', 0), "total": sum(stats.values())}
|
| 155 |
-
except: pass
|
| 156 |
-
return {"malicious": 0, "total": "Database Error"}
|
| 157 |
-
|
| 158 |
-
def log_scan(url: str, result: dict):
|
| 159 |
-
try:
|
| 160 |
-
with sqlite3.connect(DB_PATH) as conn:
|
| 161 |
-
conn.execute(
|
| 162 |
-
"INSERT INTO logs (url, score, verdict, sources) VALUES (?, ?, ?, ?)",
|
| 163 |
-
(url, result.get("risk_score", 0), result.get("verdict", "UNKNOWN"), "AI+OSINT")
|
| 164 |
-
)
|
| 165 |
-
except: pass
|
| 166 |
-
|
| 167 |
-
# --- RECALIBRATED AI SCANNER ---
|
| 168 |
-
class HybridScanner:
|
| 169 |
-
def __init__(self):
|
| 170 |
-
self.groq = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None
|
| 171 |
-
if GEMINI_API_KEY: genai.configure(api_key=GEMINI_API_KEY)
|
| 172 |
-
|
| 173 |
-
async def scan(self, url, vt_data, domain_age):
|
| 174 |
-
vt_score = vt_data.get('malicious', 0) if isinstance(vt_data.get('malicious'), int) else 0
|
| 175 |
-
|
| 176 |
-
# FIX: Explicit JSON instructions in System Prompt
|
| 177 |
-
system_prompt = (
|
| 178 |
-
"You are WADE Security AI. You analyze URLs for phishing and malware threats.\n"
|
| 179 |
-
"BE OBJECTIVE, NOT PARANOID. If VirusTotal is 0 and the site is > 30 days old, default to SAFE.\n"
|
| 180 |
-
"Only flag as MALICIOUS if the URL shows clear phishing patterns (brand typos, deceptive paths).\n"
|
| 181 |
-
"You MUST return ONLY valid JSON with exactly these keys: "
|
| 182 |
-
"{'risk_score': int (0-100), 'verdict': 'SAFE' or 'MALICIOUS', 'threat_type': str, 'harm': str, 'effect': str}"
|
| 183 |
-
)
|
| 184 |
-
|
| 185 |
-
# FIX: Isolate the URL and Context into the User Prompt
|
| 186 |
-
user_prompt = f"Analyze URL: '{url}'.\nContext: Domain Age: {domain_age} days. VirusTotal Flags: {vt_score}."
|
| 187 |
-
|
| 188 |
-
if self.groq:
|
| 189 |
-
try:
|
| 190 |
-
res = self.groq.chat.completions.create(
|
| 191 |
-
model="llama-3.3-70b-versatile",
|
| 192 |
-
messages=[
|
| 193 |
-
{"role": "system", "content": system_prompt},
|
| 194 |
-
{"role": "user", "content": user_prompt}
|
| 195 |
-
],
|
| 196 |
-
response_format={"type": "json_object"}
|
| 197 |
-
)
|
| 198 |
-
return json.loads(res.choices[0].message.content)
|
| 199 |
-
except Exception as e:
|
| 200 |
-
logger.error(f"Groq API Error: {e}")
|
| 201 |
-
pass
|
| 202 |
-
|
| 203 |
-
if GEMINI_API_KEY:
|
| 204 |
-
try:
|
| 205 |
-
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 206 |
-
res = model.generate_content(f"{system_prompt}\n\n{user_prompt}")
|
| 207 |
-
clean_json = res.text.replace("```json", "").replace("```", "").strip()
|
| 208 |
-
return json.loads(clean_json)
|
| 209 |
-
except Exception as e:
|
| 210 |
-
logger.error(f"Gemini API Error: {e}")
|
| 211 |
-
pass
|
| 212 |
-
|
| 213 |
-
return {"risk_score": 0, "verdict": "SAFE", "threat_type": "None", "harm": "None", "effect": "None"}
|
| 214 |
-
|
| 215 |
-
scanner = HybridScanner()
|
| 216 |
-
|
| 217 |
-
class ScanRequest(BaseModel):
|
| 218 |
-
url: str
|
| 219 |
|
|
|
|
|
|
|
|
|
|
| 220 |
@app.post("/analyze")
|
| 221 |
-
async def analyze_url(
|
| 222 |
-
|
| 223 |
-
|
| 224 |
|
| 225 |
-
#
|
| 226 |
-
|
| 227 |
-
return {
|
| 228 |
-
"risk_score": 85,
|
| 229 |
-
"verdict": "MALICIOUS",
|
| 230 |
-
"threat_type": "Malware Testing Payload Detected",
|
| 231 |
-
"harm": "High risk of drive-by download or remote code execution.",
|
| 232 |
-
"effect": "Connection severed by WADE IPS",
|
| 233 |
-
"domain_age": -1,
|
| 234 |
-
"vt_data": {"malicious": 12, "total": 89}
|
| 235 |
-
}
|
| 236 |
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
"vt_data": {"malicious": 0, "total": 95}
|
| 242 |
-
}
|
| 243 |
-
|
| 244 |
-
if url in intel_db.malicious_urls:
|
| 245 |
-
return {
|
| 246 |
-
"risk_score": 100, "verdict": "MALICIOUS", "threat_type": "Confirmed Phishing (GitHub Feed)",
|
| 247 |
-
"harm": "In Global Blacklist", "effect": "Credential Theft", "domain_age": -1,
|
| 248 |
-
"vt_data": {"malicious": "High", "total": "OSINT"}
|
| 249 |
-
}
|
| 250 |
-
|
| 251 |
-
age = get_domain_age(url)
|
| 252 |
-
vt_data = await check_virustotal(url)
|
| 253 |
|
| 254 |
-
|
|
|
|
|
|
|
| 255 |
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
result['risk_score'] = max(result.get('risk_score', 0), 90)
|
| 259 |
-
result['verdict'] = "MALICIOUS"
|
| 260 |
-
result['threat_type'] = "Security Vendor Flagged"
|
| 261 |
-
|
| 262 |
-
if age != -1 and age < 3 and result.get('risk_score', 0) < 40:
|
| 263 |
-
result['risk_score'] = 50
|
| 264 |
-
result['threat_type'] = "Very Newly Registered Domain"
|
| 265 |
-
|
| 266 |
-
final_result = {**result, "domain_age": age, "vt_data": vt_data}
|
| 267 |
-
background_tasks.add_task(log_scan, url, final_result)
|
| 268 |
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
return """
|
| 274 |
-
<html>
|
| 275 |
-
<body style="background-color: #050505; color: #00f3ff; font-family: monospace; text-align: center; margin-top: 20%;">
|
| 276 |
-
<h1>🛡️ WADE ENGINE ACTIVE</h1>
|
| 277 |
-
<p>Web AI Defense Engine API is currently running and monitoring traffic.</p>
|
| 278 |
-
</body>
|
| 279 |
-
</html>
|
| 280 |
"""
|
| 281 |
|
| 282 |
-
#
|
| 283 |
-
trusted_cache = {
|
| 284 |
-
"timestamp": 0,
|
| 285 |
-
"domains": []
|
| 286 |
-
}
|
| 287 |
-
|
| 288 |
-
# ==========================================
|
| 289 |
-
# REACT DASHBOARD ENDPOINTS
|
| 290 |
-
# ==========================================
|
| 291 |
-
@app.get("/dashboard/stats")
|
| 292 |
-
async def get_stats():
|
| 293 |
-
try:
|
| 294 |
-
with sqlite3.connect(DB_PATH) as conn:
|
| 295 |
-
cursor = conn.cursor()
|
| 296 |
-
cursor.execute("SELECT verdict, COUNT(*) FROM logs GROUP BY verdict")
|
| 297 |
-
results = dict(cursor.fetchall())
|
| 298 |
-
|
| 299 |
-
safe = results.get("SAFE", 0)
|
| 300 |
-
phishing = results.get("MALICIOUS", 0)
|
| 301 |
-
suspicious = results.get("SUSPICIOUS", 0)
|
| 302 |
-
|
| 303 |
-
return {
|
| 304 |
-
"total_scans": safe + phishing + suspicious,
|
| 305 |
-
"safe": safe,
|
| 306 |
-
"phishing": phishing,
|
| 307 |
-
"suspicious": suspicious
|
| 308 |
-
}
|
| 309 |
-
except Exception as e:
|
| 310 |
-
return {"total_scans": 0, "safe": 0, "phishing": 0, "suspicious": 0}
|
| 311 |
-
|
| 312 |
-
@app.get("/dashboard/recent")
|
| 313 |
-
async def get_recent_scans():
|
| 314 |
try:
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
return scans
|
| 330 |
-
except Exception:
|
| 331 |
-
return []
|
| 332 |
-
|
| 333 |
-
@app.get("/trusted-domains")
|
| 334 |
-
def get_trusted_domains():
|
| 335 |
-
global trusted_cache
|
| 336 |
-
current_time = time.time()
|
| 337 |
-
|
| 338 |
-
if current_time - trusted_cache["timestamp"] > 86400 or not trusted_cache["domains"]:
|
| 339 |
-
try:
|
| 340 |
-
print("WADE: Downloading latest Tranco Top 10k list...")
|
| 341 |
-
url = "https://tranco-list.eu/top-1m.csv.zip"
|
| 342 |
-
resp = requests.get(url, timeout=10)
|
| 343 |
-
|
| 344 |
-
with zipfile.ZipFile(io.BytesIO(resp.content)) as z:
|
| 345 |
-
csv_name = z.namelist()[0]
|
| 346 |
-
with z.open(csv_name) as f:
|
| 347 |
-
domains = []
|
| 348 |
-
for i, line in enumerate(f):
|
| 349 |
-
if i >= 10000: break
|
| 350 |
-
domain = line.decode('utf-8').strip().split(',')[1]
|
| 351 |
-
domains.append(domain)
|
| 352 |
-
|
| 353 |
-
custom_safe = ["paruluniversity.ac.in"]
|
| 354 |
-
trusted_cache["domains"] = list(set(domains + custom_safe))
|
| 355 |
-
trusted_cache["timestamp"] = current_time
|
| 356 |
-
print(f"WADE: Successfully cached {len(trusted_cache['domains'])} trusted domains.")
|
| 357 |
-
|
| 358 |
-
except Exception as e:
|
| 359 |
-
print(f"Error fetching Tranco list: {e}")
|
| 360 |
-
if not trusted_cache["domains"]:
|
| 361 |
-
# Ensure the fallback array is also completely clean
|
| 362 |
-
trusted_cache["domains"] = ["google.com", "youtube.com", "github.com", "paruluniversity.ac.in"]
|
| 363 |
|
| 364 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
|
|
|
|
|
|
|
|
|
|
| 366 |
if __name__ == "__main__":
|
| 367 |
-
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import json
|
|
|
|
|
|
|
|
|
|
| 3 |
import asyncio
|
| 4 |
+
import concurrent.futures
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
from urllib.parse import urlparse
|
| 7 |
+
|
| 8 |
import whois
|
| 9 |
+
from fastapi import FastAPI
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
from pydantic import BaseModel
|
|
|
|
| 12 |
from groq import Groq
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# ---------------------------------------------------------
|
| 15 |
+
# 1. API Configuration & Setup
|
| 16 |
+
# ---------------------------------------------------------
|
| 17 |
+
app = FastAPI(title="WADE Intelligence Core")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
# Enable CORS for the Chrome Extension
|
| 20 |
app.add_middleware(
|
| 21 |
CORSMiddleware,
|
| 22 |
+
allow_origins=["*"],
|
| 23 |
allow_methods=["*"],
|
| 24 |
allow_headers=["*"],
|
| 25 |
)
|
| 26 |
|
| 27 |
+
# Initialize Groq Client (Ensure your API key is set in your environment variables)
|
| 28 |
+
# Example: export GROQ_API_KEY="gsk_your_api_key_here"
|
| 29 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "your_groq_api_key_here")
|
| 30 |
+
groq_client = Groq(api_key=GROQ_API_KEY)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
# Request Data Model
|
| 33 |
+
class ScanRequest(BaseModel):
|
| 34 |
+
url: str
|
| 35 |
|
| 36 |
+
# ---------------------------------------------------------
|
| 37 |
+
# 2. Helper Functions (Domain Extraction & OSINT)
|
| 38 |
+
# ---------------------------------------------------------
|
| 39 |
+
def extract_domain(url: str) -> str:
|
| 40 |
+
"""Safely extracts the domain name from a full URL."""
|
| 41 |
try:
|
| 42 |
+
if not url.startswith(('http://', 'https://')):
|
| 43 |
+
url = 'http://' + url
|
| 44 |
+
parsed_uri = urlparse(url)
|
| 45 |
+
return parsed_uri.netloc.split(':')[0] # Removes port if present
|
| 46 |
+
except Exception:
|
| 47 |
+
return url
|
| 48 |
|
| 49 |
+
def get_whois_data(domain: str, timeout_seconds: int = 2) -> str:
|
| 50 |
+
"""Executes WHOIS lookup with a strict timeout to prevent API hanging."""
|
| 51 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
|
| 52 |
+
future = executor.submit(whois.whois, domain)
|
| 53 |
try:
|
| 54 |
+
result = future.result(timeout=timeout_seconds)
|
| 55 |
+
if result.creation_date:
|
| 56 |
+
# Some registries return a list of dates, some return a single date
|
| 57 |
+
if isinstance(result.creation_date, list):
|
| 58 |
+
return str(result.creation_date[0])
|
| 59 |
+
return str(result.creation_date)
|
| 60 |
+
return "Unknown"
|
| 61 |
+
except concurrent.futures.TimeoutError:
|
| 62 |
+
print(f"[WADE] WHOIS timeout for {domain}. Bypassing.")
|
| 63 |
+
return "Unknown (Timeout)"
|
|
|
|
|
|
|
|
|
|
| 64 |
except Exception as e:
|
| 65 |
+
print(f"[WADE] WHOIS error for {domain}: {e}")
|
| 66 |
+
return "Unknown (Error)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
@lru_cache(maxsize=1000)
|
| 69 |
+
def cached_whois_lookup(domain: str) -> str:
|
| 70 |
+
"""Caches the result to prevent redundant WHOIS lookups for the same domain."""
|
| 71 |
+
return get_whois_data(domain)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
+
# ---------------------------------------------------------
|
| 74 |
+
# 3. Main AI Analysis Endpoint
|
| 75 |
+
# ---------------------------------------------------------
|
| 76 |
@app.post("/analyze")
|
| 77 |
+
async def analyze_url(payload: ScanRequest):
|
| 78 |
+
target_url = payload.url
|
| 79 |
+
target_domain = extract_domain(target_url)
|
| 80 |
|
| 81 |
+
# A. Execute Non-Blocking, Cached OSINT Lookup
|
| 82 |
+
domain_age = await asyncio.to_thread(cached_whois_lookup, target_domain)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
+
# B. Construct the System Prompt for the LLM
|
| 85 |
+
system_prompt = f"""
|
| 86 |
+
You are WADE, a highly strict cybersecurity Intrusion Prevention System (IPS).
|
| 87 |
+
Your job is to analyze the following web target and determine if it is malicious.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
Target URL: {target_url}
|
| 90 |
+
Domain: {target_domain}
|
| 91 |
+
Domain Registration Age: {domain_age}
|
| 92 |
|
| 93 |
+
If the domain age is "Unknown" or very recent, increase the risk score slightly.
|
| 94 |
+
If the domain is a known safe platform (like google.com, wikipedia.org), risk should be 0.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
Return ONLY a valid JSON object with exactly these three keys:
|
| 97 |
+
1. "risk_score": An integer from 0 to 100. (Above 75 means malicious/block).
|
| 98 |
+
2. "threat_type": A short 2-3 word classification (e.g., "Phishing Attempt", "Safe Site", "Suspicious Tracker").
|
| 99 |
+
3. "harm_analysis": A 1-2 sentence explanation of what this site does and why you gave it that score.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
"""
|
| 101 |
|
| 102 |
+
# C. Execute AI Analysis
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
try:
|
| 104 |
+
chat_completion = groq_client.chat.completions.create(
|
| 105 |
+
messages=[
|
| 106 |
+
{"role": "system", "content": system_prompt}
|
| 107 |
+
],
|
| 108 |
+
model="llama3-70b-8192", # You can change this to llama3-8b-8192 for faster/cheaper tests
|
| 109 |
+
temperature=0.1, # Low temperature for highly analytical/deterministic outputs
|
| 110 |
+
response_format={"type": "json_object"} # Forces the LLM to return strict JSON
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# Parse the JSON response from Groq
|
| 114 |
+
ai_response = chat_completion.choices[0].message.content
|
| 115 |
+
result = json.loads(ai_response)
|
| 116 |
+
|
| 117 |
+
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
except Exception as e:
|
| 120 |
+
print(f"[WADE] AI Analysis Failed: {e}")
|
| 121 |
+
# Graceful Failover: If the API limits out or crashes, do not break the browser.
|
| 122 |
+
return {
|
| 123 |
+
"risk_score": 10,
|
| 124 |
+
"threat_type": "Analysis Failed",
|
| 125 |
+
"harm_analysis": f"Backend AI was unreachable or timed out. Defaulting to safe passage. Error: {str(e)}"
|
| 126 |
+
}
|
| 127 |
|
| 128 |
+
# ---------------------------------------------------------
|
| 129 |
+
# 4. Server Execution
|
| 130 |
+
# ---------------------------------------------------------
|
| 131 |
if __name__ == "__main__":
|
| 132 |
+
import uvicorn
|
| 133 |
+
# Run the server on port 8000
|
| 134 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|