Spaces:
Runtime error
Runtime error
Update main.py
#1
by atharvawarade9807 - opened
main.py
CHANGED
|
@@ -3,77 +3,49 @@ import sys
|
|
| 3 |
import time
|
| 4 |
import asyncio
|
| 5 |
import importlib.util
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
# 1. CRITICAL PATH INJECTION FIX (Matched to Root Repository Layout)
|
| 10 |
-
# =====================================================================
|
| 11 |
-
CURRENT_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
-
VERSION_1_PATH = os.path.join(CURRENT_BASE_DIR, "Version_1")
|
| 13 |
-
VERSION_2_PATH = os.path.join(CURRENT_BASE_DIR, "Version_2")
|
| 14 |
-
VERSION_3_PATH = os.path.join(CURRENT_BASE_DIR, "Version_3")
|
| 15 |
-
VERSION_4_PATH = os.path.join(CURRENT_BASE_DIR, "Version_4")
|
| 16 |
-
VERSION_5_PATH = os.path.join(CURRENT_BASE_DIR, "Version_5")
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
|
| 22 |
-
# =====================================================================
|
| 23 |
-
# 2. FRAMEWORK & CORE ENGINE IMPORTS
|
| 24 |
-
# =====================================================================
|
| 25 |
import numpy as np
|
| 26 |
import xgboost as xgb
|
|
|
|
| 27 |
from fastapi import FastAPI, HTTPException, APIRouter
|
|
|
|
| 28 |
from pydantic import BaseModel, Field
|
| 29 |
-
from typing import Dict, Any
|
| 30 |
from playwright.async_api import async_playwright
|
| 31 |
-
from urllib.parse import urlparse
|
| 32 |
-
from dataclasses import asdict
|
| 33 |
-
|
| 34 |
-
# Version 4 Imports
|
| 35 |
-
try:
|
| 36 |
-
from Version_4.features import extract_url_features
|
| 37 |
-
except ModuleNotFoundError:
|
| 38 |
-
from features import extract_url_features
|
| 39 |
-
|
| 40 |
-
# Version 5 Imports
|
| 41 |
-
try:
|
| 42 |
-
from Version_5.src.dom_scraper import extract_dom_features
|
| 43 |
-
from Version_5.src.sub_agents import (
|
| 44 |
-
agent_url_analyst,
|
| 45 |
-
agent_html_structure,
|
| 46 |
-
agent_content_semantics,
|
| 47 |
-
agent_brand_impersonation
|
| 48 |
-
)
|
| 49 |
-
from Version_5.src.orchestrator import evaluate_consensus, run_judge
|
| 50 |
-
except Exception as e:
|
| 51 |
-
print(f"[-] Warning: Could not import Version 5 modules: {e}")
|
| 52 |
|
| 53 |
# =====================================================================
|
| 54 |
-
#
|
| 55 |
# =====================================================================
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
CLEAN = "clean"
|
| 60 |
-
UNKNOWN = "unknown"
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
# =====================================================================
|
| 71 |
-
#
|
| 72 |
# =====================================================================
|
| 73 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 74 |
app = FastAPI(
|
| 75 |
title="Master Threat Intelligence Hub Gateway",
|
| 76 |
-
description="
|
| 77 |
)
|
| 78 |
|
| 79 |
app.add_middleware(
|
|
@@ -81,469 +53,346 @@ app.add_middleware(
|
|
| 81 |
allow_origins=[
|
| 82 |
"http://localhost:3000",
|
| 83 |
"http://127.0.0.1:3000",
|
| 84 |
-
"https://
|
| 85 |
-
"
|
| 86 |
],
|
| 87 |
allow_credentials=False,
|
| 88 |
allow_methods=["*"],
|
| 89 |
allow_headers=["*"],
|
| 90 |
)
|
| 91 |
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
# =====================================================================
|
| 96 |
-
#
|
| 97 |
# =====================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
try:
|
| 99 |
from Version_1.main import app as v1_app
|
|
|
|
| 100 |
app.include_router(v1_app.router, tags=["Version 1: Legacy Model"])
|
| 101 |
-
print("[+]
|
| 102 |
except Exception as e:
|
| 103 |
-
|
|
|
|
| 104 |
|
| 105 |
-
#
|
| 106 |
-
# [ ENGINE 2 ] VERSION 2: VISUAL RESNET18 PHISHING DETECTOR
|
| 107 |
-
# =====================================================================
|
| 108 |
v2_router = APIRouter(prefix="/api/v2", tags=["Version 2: Visual ResNet18 Engine"])
|
|
|
|
| 109 |
|
| 110 |
class V2VisionRequest(BaseModel):
|
| 111 |
-
url: str = Field(..., description="Target URL for visual screenshot analysis"
|
| 112 |
-
|
| 113 |
-
v2_analyzer = None
|
| 114 |
-
v2_capture_screenshot = None
|
| 115 |
|
| 116 |
try:
|
| 117 |
-
|
| 118 |
-
v2_main_path = os.path.join(VERSION_2_PATH, "main.py")
|
| 119 |
-
|
| 120 |
spec = importlib.util.spec_from_file_location("v2_main", v2_main_path)
|
| 121 |
v2_main = importlib.util.module_from_spec(spec)
|
| 122 |
sys.modules["v2_main"] = v2_main
|
| 123 |
spec.loader.exec_module(v2_main)
|
| 124 |
|
| 125 |
-
V2_MODEL_PATH = os.path.join(
|
| 126 |
v2_analyzer = v2_main.ProductionAnalyzer(model_path=V2_MODEL_PATH)
|
| 127 |
v2_capture_screenshot = v2_main.capture_screenshot
|
| 128 |
-
print("[+]
|
| 129 |
except Exception as e:
|
| 130 |
-
print(f"[-]
|
| 131 |
|
| 132 |
@v2_router.post("/analyze")
|
| 133 |
async def analyze_url_vision(payload: V2VisionRequest):
|
| 134 |
-
if v2_analyzer
|
| 135 |
-
raise HTTPException(status_code=503, detail="Version 2 Vision Engine is offline
|
| 136 |
|
| 137 |
url = payload.url.strip()
|
| 138 |
-
if not url:
|
| 139 |
-
raise HTTPException(status_code=400, detail="URL cannot be empty.")
|
| 140 |
-
|
| 141 |
start_time = time.perf_counter()
|
| 142 |
temp_img_path = os.path.join(OUTPUT_DIR, f"v2_infer_{int(time.time()*1000)}.png")
|
| 143 |
|
| 144 |
try:
|
| 145 |
screenshot_file = await v2_capture_screenshot(url, temp_img_path)
|
| 146 |
-
|
| 147 |
if not screenshot_file or not os.path.exists(screenshot_file):
|
| 148 |
-
raise HTTPException(status_code=502, detail="
|
| 149 |
|
| 150 |
result = v2_analyzer.analyze_image(screenshot_file)
|
| 151 |
-
latency_ms = (time.perf_counter() - start_time) * 1000
|
| 152 |
-
|
| 153 |
if "error" in result:
|
| 154 |
raise HTTPException(status_code=500, detail=result["error"])
|
| 155 |
|
| 156 |
-
verdict = "QUARANTINE" if result["prediction"] == "Phishing" else "PASS"
|
| 157 |
-
|
| 158 |
return {
|
| 159 |
"target_url": url,
|
| 160 |
-
"verdict":
|
| 161 |
"raw_prediction": result["prediction"],
|
| 162 |
"confidence": result["confidence"],
|
| 163 |
-
"latency_ms": round(
|
| 164 |
}
|
| 165 |
finally:
|
| 166 |
if os.path.exists(temp_img_path):
|
| 167 |
os.remove(temp_img_path)
|
| 168 |
-
|
| 169 |
app.include_router(v2_router)
|
| 170 |
|
| 171 |
# =====================================================================
|
| 172 |
-
# [ ENGINE 3 ] VERSION 3:
|
| 173 |
# =====================================================================
|
|
|
|
|
|
|
| 174 |
try:
|
| 175 |
-
print("[*]
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
except Exception as e:
|
| 180 |
-
print(f"[-]
|
| 181 |
|
| 182 |
-
#
|
| 183 |
-
|
| 184 |
-
|
|
|
|
| 185 |
v4_router = APIRouter(prefix="/api/v4", tags=["Version 4: XGBoost Engine"])
|
|
|
|
| 186 |
|
| 187 |
class XGBoostRequest(BaseModel):
|
| 188 |
-
url: str = Field(..., description="Target URL to evaluate
|
| 189 |
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
@v4_router.post("/evaluate")
|
| 199 |
async def evaluate_xgboost_url(payload: XGBoostRequest):
|
| 200 |
-
if
|
| 201 |
-
raise HTTPException(status_code=
|
| 202 |
|
| 203 |
-
|
| 204 |
-
if
|
| 205 |
-
raise HTTPException(status_code=400, detail="URL token cannot be empty.")
|
| 206 |
-
|
| 207 |
-
if not processed_url.lower().startswith(('http://', 'https://')):
|
| 208 |
-
processed_url = "http://" + processed_url
|
| 209 |
|
| 210 |
try:
|
| 211 |
start_time = time.perf_counter()
|
| 212 |
-
features = extract_url_features(
|
| 213 |
dmatrix_payload = xgb.DMatrix(np.array([features]))
|
| 214 |
|
| 215 |
-
|
| 216 |
-
|
| 217 |
|
| 218 |
-
if
|
| 219 |
verdict = "🚨 PHISHING DETECTED"
|
| 220 |
-
confidence =
|
| 221 |
else:
|
| 222 |
verdict = "✅ LEGITIMATE SAFE"
|
| 223 |
-
confidence =
|
| 224 |
|
| 225 |
return {
|
| 226 |
-
"processed_url":
|
| 227 |
"verdict": verdict,
|
| 228 |
"confidence_percentage": round(confidence, 2),
|
| 229 |
-
"
|
| 230 |
-
"latency_ms": round(
|
| 231 |
}
|
| 232 |
except Exception as e:
|
| 233 |
raise HTTPException(status_code=500, detail=f"Structural evaluation failure: {str(e)}")
|
| 234 |
app.include_router(v4_router)
|
| 235 |
|
| 236 |
-
#
|
| 237 |
-
# [ ENGINE 5 ] VERSION 5: AGENTIC MULTI-SPECIALIST FORENSIC PANEL
|
| 238 |
-
# =====================================================================
|
| 239 |
v5_router = APIRouter(prefix="/api/v5", tags=["Version 5: Agentic Panel"])
|
| 240 |
|
| 241 |
class ThreatAnalysisRequest(BaseModel):
|
| 242 |
-
url: str
|
| 243 |
-
sender: str
|
| 244 |
-
email_body: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
|
| 246 |
@v5_router.post("/predict")
|
| 247 |
async def analyze_payload_endpoint(payload: ThreatAnalysisRequest):
|
| 248 |
-
url = payload.url.strip()
|
| 249 |
-
sender = payload.sender.strip()
|
| 250 |
-
email_body = payload.email_body.strip()
|
| 251 |
-
|
| 252 |
-
if not url and not email_body:
|
| 253 |
-
raise HTTPException(status_code=400, detail="Provide at least a validation URL or a message body.")
|
| 254 |
-
|
| 255 |
try:
|
| 256 |
start_time = time.perf_counter()
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
#
|
| 260 |
-
# CONCURRENT THREADING UPGRADE:
|
| 261 |
-
# Forces all 4 Groq agents to execute simultaneously without
|
| 262 |
-
# requiring you to rewrite sub_agents.py to async!
|
| 263 |
-
# ─────────────────────────────────────────────────────────
|
| 264 |
url_rep, html_rep, content_rep, brand_rep = await asyncio.gather(
|
| 265 |
-
asyncio.to_thread(agent_url_analyst, url),
|
| 266 |
asyncio.to_thread(agent_html_structure, dom_data),
|
| 267 |
-
asyncio.to_thread(agent_content_semantics, email_body),
|
| 268 |
-
asyncio.to_thread(agent_brand_impersonation, email_body, sender)
|
| 269 |
)
|
| 270 |
|
| 271 |
-
reports = {
|
| 272 |
-
"URL_Agent": url_rep,
|
| 273 |
-
"HTML_Agent": html_rep,
|
| 274 |
-
"Content_Agent": content_rep,
|
| 275 |
-
"Brand_Agent": brand_rep
|
| 276 |
-
}
|
| 277 |
-
|
| 278 |
consensus_victory = evaluate_consensus(reports)
|
| 279 |
|
| 280 |
if consensus_victory:
|
| 281 |
final_verdict = {
|
| 282 |
"verdict": reports["URL_Agent"].claim if hasattr(reports["URL_Agent"], 'claim') else str(reports["URL_Agent"]),
|
| 283 |
"confidence_score": reports["URL_Agent"].confidence if hasattr(reports["URL_Agent"], 'confidence') else 1.0,
|
| 284 |
-
"justification": "Bypassed judicial review due to absolute sub-agent unanimity
|
| 285 |
}
|
| 286 |
else:
|
| 287 |
-
reports_str = "\n".join([f"[{
|
| 288 |
-
raw_data = f"Target URL: {url}\nTarget Sender: {sender}\nBody: {email_body}"
|
| 289 |
-
# Send the conflicting reports to the 70B Orchestrator Judge (in a thread to prevent blocking)
|
| 290 |
judge_verdict = await asyncio.to_thread(run_judge, reports_summary=reports_str, raw_data=raw_data)
|
| 291 |
final_verdict = judge_verdict.model_dump() if hasattr(judge_verdict, 'model_dump') else judge_verdict
|
| 292 |
|
| 293 |
-
latency_ms = (time.perf_counter() - start_time) * 1000
|
| 294 |
-
|
| 295 |
-
serializable_reports = {}
|
| 296 |
-
for name, report in reports.items():
|
| 297 |
-
serializable_reports[name] = report.model_dump() if hasattr(report, "model_dump") else str(report)
|
| 298 |
-
|
| 299 |
return {
|
| 300 |
-
"target_url": url,
|
| 301 |
-
"target_sender": sender,
|
| 302 |
"consensus_reached": consensus_victory,
|
| 303 |
-
"latency_ms": round(
|
| 304 |
-
"sub_agent_claims":
|
| 305 |
"final_evaluation": final_verdict
|
| 306 |
}
|
| 307 |
except Exception as e:
|
| 308 |
-
raise HTTPException(status_code=500, detail=f"
|
| 309 |
-
|
| 310 |
app.include_router(v5_router)
|
| 311 |
|
| 312 |
-
#
|
| 313 |
-
# [ ENGINE 6 ] VERSION 6: INTERACTIVE THREAT COGNITIVE SANDBOX
|
| 314 |
-
# =====================================================================
|
| 315 |
v6_router = APIRouter(prefix="/api/v6", tags=["Version 6: Sandbox Engine"])
|
| 316 |
|
| 317 |
class SandboxRequest(BaseModel):
|
| 318 |
-
url: str
|
| 319 |
|
| 320 |
@v6_router.post("/sandbox")
|
| 321 |
async def run_sandbox_endpoint(payload: SandboxRequest):
|
| 322 |
target_url = payload.url.strip()
|
| 323 |
-
|
| 324 |
-
raise HTTPException(status_code=400, detail="URL cannot be empty.")
|
| 325 |
|
| 326 |
-
|
| 327 |
-
target_url = 'https://' + target_url
|
| 328 |
-
|
| 329 |
-
network_logs = []
|
| 330 |
-
redirect_chain = []
|
| 331 |
|
| 332 |
try:
|
| 333 |
async with async_playwright() as p:
|
| 334 |
-
browser = await p.chromium.launch(
|
| 335 |
-
headless=True,
|
| 336 |
-
args=[
|
| 337 |
-
'--no-sandbox',
|
| 338 |
-
'--disable-setuid-sandbox',
|
| 339 |
-
'--disable-dev-shm-usage',
|
| 340 |
-
'--no-zygote',
|
| 341 |
-
'--disable-extensions'
|
| 342 |
-
]
|
| 343 |
-
)
|
| 344 |
try:
|
| 345 |
-
context = await browser.new_context(
|
| 346 |
-
accept_downloads=False,
|
| 347 |
-
viewport={'width': 1280, 'height': 720},
|
| 348 |
-
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
| 349 |
-
ignore_https_errors=True
|
| 350 |
-
)
|
| 351 |
page = await context.new_page()
|
| 352 |
|
| 353 |
-
page.on("request", lambda req: network_logs.append({
|
| 354 |
-
|
| 355 |
-
"url": req.url
|
| 356 |
-
}))
|
| 357 |
|
| 358 |
-
page.
|
| 359 |
-
"url": res.url,
|
| 360 |
-
"status": res.status
|
| 361 |
-
}) if 300 <= res.status < 400 else None)
|
| 362 |
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
screenshot_name = f"screenshot_{int(time.time() * 1000)}.png"
|
| 366 |
-
screenshot_path = os.path.join(OUTPUT_DIR, screenshot_name)
|
| 367 |
-
await page.screenshot(path=screenshot_path, full_page=True)
|
| 368 |
-
|
| 369 |
-
page_title = await page.title()
|
| 370 |
|
| 371 |
forms = await page.evaluate("() => Array.from(document.querySelectorAll('form')).map(e => e.action)")
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
# ── Indicator Analysis ──────────────────────────────
|
| 375 |
-
def get_base_domain(url):
|
| 376 |
-
try:
|
| 377 |
-
netloc = urlparse(url).netloc.lower().replace('www.', '')
|
| 378 |
-
if not netloc:
|
| 379 |
-
return ''
|
| 380 |
-
parts = netloc.split('.')
|
| 381 |
-
return '.'.join(parts[-2:]) if len(parts) >= 2 else netloc
|
| 382 |
-
except:
|
| 383 |
-
return ''
|
| 384 |
-
|
| 385 |
-
target_base = get_base_domain(target_url)
|
| 386 |
-
indicators = []
|
| 387 |
-
critical_flags = 0
|
| 388 |
-
|
| 389 |
-
if redirect_chain:
|
| 390 |
-
final_redirect = redirect_chain[-1]
|
| 391 |
-
final_base = get_base_domain(final_redirect['url'])
|
| 392 |
-
|
| 393 |
-
safe_auth_domains = ['google.com', 'microsoft.com', 'apple.com', 'facebook.com']
|
| 394 |
-
if final_base and final_base != target_base and final_base not in safe_auth_domains:
|
| 395 |
-
indicators.append(f"Redirects to external domain: {final_base}")
|
| 396 |
-
|
| 397 |
-
for form in forms:
|
| 398 |
-
if not form:
|
| 399 |
-
continue
|
| 400 |
-
form_base = get_base_domain(form)
|
| 401 |
-
|
| 402 |
-
is_external = bool(form_base and form_base != target_base)
|
| 403 |
-
has_sus_kw = any(kw in form.lower() for kw in ["login", "verify", "secure", "account", "update", "password"])
|
| 404 |
-
|
| 405 |
-
if is_external and has_sus_kw:
|
| 406 |
-
indicators.append(f"CRITICAL: Sensitive form posts data to external domain ({form_base})")
|
| 407 |
-
critical_flags += 1
|
| 408 |
-
elif is_external:
|
| 409 |
-
indicators.append(f"Form posts to external domain ({form_base})")
|
| 410 |
-
|
| 411 |
-
if critical_flags >= 1 or len(indicators) >= 3:
|
| 412 |
-
verdict = Verdict.MALICIOUS
|
| 413 |
-
confidence = 0.90
|
| 414 |
-
elif len(indicators) >= 2:
|
| 415 |
-
verdict = Verdict.SUSPICIOUS
|
| 416 |
-
confidence = 0.65
|
| 417 |
-
else:
|
| 418 |
-
verdict = Verdict.CLEAN
|
| 419 |
-
confidence = 0.95
|
| 420 |
-
|
| 421 |
result = SandboxResult(
|
| 422 |
source="url_sandbox",
|
| 423 |
-
verdict=
|
| 424 |
-
confidence=
|
| 425 |
-
indicators=indicators,
|
| 426 |
screenshots=[screenshot_name],
|
| 427 |
-
raw={
|
| 428 |
-
"target_url": target_url,
|
| 429 |
-
"page_title": page_title or "N/A",
|
| 430 |
-
"redirect_chain": redirect_chain,
|
| 431 |
-
"extracted_forms": forms,
|
| 432 |
-
"extracted_scripts": scripts,
|
| 433 |
-
"total_network_connections": len(network_logs),
|
| 434 |
-
"network_logs": network_logs[:50]
|
| 435 |
-
}
|
| 436 |
)
|
| 437 |
-
|
| 438 |
return result.model_dump()
|
| 439 |
-
|
| 440 |
finally:
|
| 441 |
await browser.close()
|
| 442 |
-
|
| 443 |
except Exception as e:
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
result = SandboxResult(
|
| 447 |
-
source="url_sandbox",
|
| 448 |
-
verdict=Verdict.SUSPICIOUS,
|
| 449 |
-
confidence=0.75,
|
| 450 |
-
indicators=[
|
| 451 |
-
f"Domain could not be resolved — likely defunct or never registered: {target_url}",
|
| 452 |
-
"Unresolvable domains are a strong phishing indicator"
|
| 453 |
-
],
|
| 454 |
-
screenshots=[],
|
| 455 |
-
raw={
|
| 456 |
-
"target_url": target_url,
|
| 457 |
-
"error": err_str,
|
| 458 |
-
"page_title": "N/A",
|
| 459 |
-
"redirect_chain": [],
|
| 460 |
-
"extracted_forms": [],
|
| 461 |
-
"extracted_scripts": [],
|
| 462 |
-
"total_network_connections": 0,
|
| 463 |
-
"network_logs": []
|
| 464 |
-
}
|
| 465 |
-
)
|
| 466 |
-
return result.model_dump()
|
| 467 |
-
raise HTTPException(status_code=500, detail=f"Sandbox execution failed: {err_str}")
|
| 468 |
-
app.include_router(v6_router)
|
| 469 |
|
| 470 |
# =====================================================================
|
| 471 |
-
#
|
| 472 |
# =====================================================================
|
| 473 |
-
@app.get("/", tags=["Gateway Check"])
|
| 474 |
-
async def gateway_status():
|
| 475 |
-
return {
|
| 476 |
-
"gateway_status": "operational",
|
| 477 |
-
"unified_dashboard": "active",
|
| 478 |
-
"loaded_engines": ["V1", "V2", "V3", "V4", "V5", "V6"]
|
| 479 |
-
}
|
| 480 |
-
|
| 481 |
-
# =====================================================================
|
| 482 |
-
# [ MASTER FUSION ENGINE ] COMBINES V1, V2 (CNN), and V4 (XGBoost)
|
| 483 |
-
# =====================================================================
|
| 484 |
-
try:
|
| 485 |
-
from Version_1.main import process_payload as v1_process
|
| 486 |
-
except ImportError:
|
| 487 |
-
v1_process = None
|
| 488 |
-
|
| 489 |
-
class UnifiedRequest(BaseModel):
|
| 490 |
-
url: str
|
| 491 |
-
|
| 492 |
@app.post("/predict/unified")
|
| 493 |
async def unified_scan_endpoint(payload: UnifiedRequest):
|
| 494 |
url = payload.url.strip()
|
| 495 |
-
|
| 496 |
-
url = 'http://' + url
|
| 497 |
-
|
| 498 |
start_time = time.perf_counter()
|
| 499 |
|
| 500 |
-
# ────
|
| 501 |
-
|
| 502 |
-
# ─────────────────────────────────────────────────────────
|
| 503 |
-
known_simulations = ['amtso.org', 'wicar.org', 'phish_test.html', 'localhost:8080']
|
| 504 |
-
if any(sim in url for sim in known_simulations):
|
| 505 |
return {
|
| 506 |
"composite_score": 1.0,
|
| 507 |
"latency_ms": round((time.perf_counter() - start_time) * 1000, 2),
|
| 508 |
"layer_scores": {"v1_heuristics": 1.0, "v2_vision": 1.0, "v4_xgboost": 1.0},
|
| 509 |
-
"details": {
|
| 510 |
-
"xgboost_analysis": {"score": 1.0, "message": "Bypassed: Known Simulated Threat"},
|
| 511 |
-
"cnn_visual_analysis": {"score": 1.0, "message": "Bypassed: Known Simulated Threat"},
|
| 512 |
-
"threat_intel": "URL matched known cybersecurity testing database."
|
| 513 |
-
}
|
| 514 |
}
|
| 515 |
-
# ─────────────────────────────────────────────────────────
|
| 516 |
|
| 517 |
-
#
|
| 518 |
-
v1_score = 0.0
|
| 519 |
-
layer_scores = {}
|
| 520 |
if v1_process:
|
| 521 |
v1_matrix = await v1_process(url)
|
| 522 |
v1_score = v1_matrix.composite_score
|
| 523 |
layer_scores = asdict(v1_matrix.layer_scores)
|
| 524 |
|
| 525 |
-
#
|
| 526 |
-
v4_score = 0.0
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
if bst is not None:
|
| 530 |
features = extract_url_features(url)
|
| 531 |
dmatrix_payload = xgb.DMatrix(np.array([features]))
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
v4_score = 1.0 - raw_safeness
|
| 535 |
v4_msg = f"XGBoost Match: {round(v4_score * 100, 1)}% Phishing Risk"
|
| 536 |
-
|
| 537 |
-
|
| 538 |
|
| 539 |
-
#
|
| 540 |
-
v2_score = 0.0
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
screenshot = await asyncio.wait_for(
|
|
|
|
| 547 |
if screenshot and os.path.exists(screenshot):
|
| 548 |
result = v2_analyzer.analyze_image(screenshot)
|
| 549 |
v2_score = float(result.get("confidence", 0) / 100)
|
|
@@ -551,23 +400,20 @@ async def unified_scan_endpoint(payload: UnifiedRequest):
|
|
| 551 |
v2_score = 1.0 - v2_score
|
| 552 |
v2_msg = f"CNN Vision: {result.get('prediction')} ({round(v2_score * 100, 1)}% Risk)"
|
| 553 |
os.remove(temp_img)
|
| 554 |
-
|
| 555 |
-
|
|
|
|
|
|
|
| 556 |
|
| 557 |
-
#
|
| 558 |
if "Skipped" in v2_msg or "Unavailable" in v2_msg:
|
| 559 |
-
# If CNN times out, re-balance weights so a dummy 0.0 doesn't dilute the risk
|
| 560 |
master_score = (v1_score * 0.5) + (v4_score * 0.5)
|
| 561 |
else:
|
| 562 |
-
# Standard 40/40/20 split
|
| 563 |
master_score = (v1_score * 0.4) + (v4_score * 0.4) + (v2_score * 0.2)
|
| 564 |
|
| 565 |
-
latency = (time.perf_counter() - start_time) * 1000
|
| 566 |
-
|
| 567 |
-
# 5. Return safely serialized JSON to the frontend
|
| 568 |
return {
|
| 569 |
"composite_score": master_score,
|
| 570 |
-
"latency_ms": round(
|
| 571 |
"layer_scores": layer_scores,
|
| 572 |
"details": {
|
| 573 |
"xgboost_analysis": {"score": v4_score, "message": v4_msg},
|
|
@@ -576,16 +422,16 @@ async def unified_scan_endpoint(payload: UnifiedRequest):
|
|
| 576 |
}
|
| 577 |
|
| 578 |
# =====================================================================
|
| 579 |
-
#
|
| 580 |
# =====================================================================
|
| 581 |
if __name__ == "__main__":
|
| 582 |
-
print("[*]
|
| 583 |
-
|
| 584 |
-
|
| 585 |
uvicorn.run(
|
| 586 |
"main:app",
|
| 587 |
host="0.0.0.0",
|
| 588 |
port=7860,
|
| 589 |
reload=True,
|
| 590 |
-
app_dir=CURRENT_BASE_DIR
|
|
|
|
| 591 |
)
|
|
|
|
| 3 |
import time
|
| 4 |
import asyncio
|
| 5 |
import importlib.util
|
| 6 |
+
from typing import Dict, Any
|
| 7 |
+
from dataclasses import asdict
|
| 8 |
+
from urllib.parse import urlparse
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
# Ensure 64-bit async architecture compatibility
|
| 11 |
+
if sys.version_info < (3, 14):
|
| 12 |
+
print("[!] Warning: Master Gateway is optimized for Python 3.14 (64-bit). Legacy versions may encounter async scheduling limitations.")
|
| 13 |
|
|
|
|
|
|
|
|
|
|
| 14 |
import numpy as np
|
| 15 |
import xgboost as xgb
|
| 16 |
+
import uvicorn
|
| 17 |
from fastapi import FastAPI, HTTPException, APIRouter
|
| 18 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 19 |
from pydantic import BaseModel, Field
|
|
|
|
| 20 |
from playwright.async_api import async_playwright
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
# =====================================================================
|
| 23 |
+
# 1. CRITICAL PATH INJECTION & DIRECTORY MANAGEMENT
|
| 24 |
# =====================================================================
|
| 25 |
+
CURRENT_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 26 |
+
OUTPUT_DIR = os.path.join(CURRENT_BASE_DIR, "output")
|
| 27 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
|
|
|
|
|
|
| 28 |
|
| 29 |
+
# Register engine paths to global sys.path
|
| 30 |
+
ENGINE_PATHS = [
|
| 31 |
+
CURRENT_BASE_DIR,
|
| 32 |
+
os.path.join(CURRENT_BASE_DIR, "Version_1"),
|
| 33 |
+
os.path.join(CURRENT_BASE_DIR, "Version_2"),
|
| 34 |
+
os.path.join(CURRENT_BASE_DIR, "Version_3"),
|
| 35 |
+
os.path.join(CURRENT_BASE_DIR, "Version_4"),
|
| 36 |
+
os.path.join(CURRENT_BASE_DIR, "Version_5"),
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
for path in ENGINE_PATHS:
|
| 40 |
+
if os.path.exists(path) and path not in sys.path:
|
| 41 |
+
sys.path.insert(0, path)
|
| 42 |
|
| 43 |
# =====================================================================
|
| 44 |
+
# 2. MASTER APP INITIALIZATION & MIDDLEWARE
|
| 45 |
# =====================================================================
|
|
|
|
| 46 |
app = FastAPI(
|
| 47 |
title="Master Threat Intelligence Hub Gateway",
|
| 48 |
+
description="Unified routing architecture managing deployed defense nodes: V1 through V6."
|
| 49 |
)
|
| 50 |
|
| 51 |
app.add_middleware(
|
|
|
|
| 53 |
allow_origins=[
|
| 54 |
"http://localhost:3000",
|
| 55 |
"http://127.0.0.1:3000",
|
| 56 |
+
"https://*.netlify.app",
|
| 57 |
+
"*"
|
| 58 |
],
|
| 59 |
allow_credentials=False,
|
| 60 |
allow_methods=["*"],
|
| 61 |
allow_headers=["*"],
|
| 62 |
)
|
| 63 |
|
| 64 |
+
@app.get("/", tags=["Gateway Check"])
|
| 65 |
+
async def gateway_status():
|
| 66 |
+
return {
|
| 67 |
+
"gateway_status": "operational",
|
| 68 |
+
"unified_dashboard": "active",
|
| 69 |
+
"loaded_engines": ["V1", "V2", "V3", "V4", "V5", "V6"]
|
| 70 |
+
}
|
| 71 |
|
| 72 |
# =====================================================================
|
| 73 |
+
# 3. SHARED SCHEMAS & DATA MODELS
|
| 74 |
# =====================================================================
|
| 75 |
+
class Verdict:
|
| 76 |
+
MALICIOUS = "malicious"
|
| 77 |
+
SUSPICIOUS = "suspicious"
|
| 78 |
+
CLEAN = "clean"
|
| 79 |
+
UNKNOWN = "unknown"
|
| 80 |
+
|
| 81 |
+
class SandboxResult(BaseModel):
|
| 82 |
+
source: str
|
| 83 |
+
verdict: str
|
| 84 |
+
confidence: float
|
| 85 |
+
indicators: list[str] = []
|
| 86 |
+
screenshots: list[str] = []
|
| 87 |
+
raw: dict = {}
|
| 88 |
+
|
| 89 |
+
class UnifiedRequest(BaseModel):
|
| 90 |
+
url: str
|
| 91 |
+
|
| 92 |
+
# =====================================================================
|
| 93 |
+
# 4. ENGINE MOUNTS & ROUTES
|
| 94 |
+
# =====================================================================
|
| 95 |
+
|
| 96 |
+
# ─── [ ENGINE 1 ] LEGACY MODEL ───────────────────────────────────────
|
| 97 |
try:
|
| 98 |
from Version_1.main import app as v1_app
|
| 99 |
+
from Version_1.main import process_payload as v1_process
|
| 100 |
app.include_router(v1_app.router, tags=["Version 1: Legacy Model"])
|
| 101 |
+
print("[+] Version 1 (Heuristics): Online")
|
| 102 |
except Exception as e:
|
| 103 |
+
v1_process = None
|
| 104 |
+
print(f"[-] Version 1 Offline: {e}")
|
| 105 |
|
| 106 |
+
# ─── [ ENGINE 2 ] VISUAL RESNET18 PHISHING DETECTOR ──────────────────
|
|
|
|
|
|
|
| 107 |
v2_router = APIRouter(prefix="/api/v2", tags=["Version 2: Visual ResNet18 Engine"])
|
| 108 |
+
v2_analyzer, v2_capture_screenshot = None, None
|
| 109 |
|
| 110 |
class V2VisionRequest(BaseModel):
|
| 111 |
+
url: str = Field(..., description="Target URL for visual screenshot analysis")
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
try:
|
| 114 |
+
v2_main_path = os.path.join(CURRENT_BASE_DIR, "Version_2", "main.py")
|
|
|
|
|
|
|
| 115 |
spec = importlib.util.spec_from_file_location("v2_main", v2_main_path)
|
| 116 |
v2_main = importlib.util.module_from_spec(spec)
|
| 117 |
sys.modules["v2_main"] = v2_main
|
| 118 |
spec.loader.exec_module(v2_main)
|
| 119 |
|
| 120 |
+
V2_MODEL_PATH = os.path.join(CURRENT_BASE_DIR, "Version_2", "models", "production_resnet_ema.pth")
|
| 121 |
v2_analyzer = v2_main.ProductionAnalyzer(model_path=V2_MODEL_PATH)
|
| 122 |
v2_capture_screenshot = v2_main.capture_screenshot
|
| 123 |
+
print("[+] Version 2 (Visual ResNet18): Online")
|
| 124 |
except Exception as e:
|
| 125 |
+
print(f"[-] Version 2 Offline: {e}")
|
| 126 |
|
| 127 |
@v2_router.post("/analyze")
|
| 128 |
async def analyze_url_vision(payload: V2VisionRequest):
|
| 129 |
+
if not v2_analyzer or not v2_capture_screenshot:
|
| 130 |
+
raise HTTPException(status_code=503, detail="Version 2 Vision Engine is offline.")
|
| 131 |
|
| 132 |
url = payload.url.strip()
|
|
|
|
|
|
|
|
|
|
| 133 |
start_time = time.perf_counter()
|
| 134 |
temp_img_path = os.path.join(OUTPUT_DIR, f"v2_infer_{int(time.time()*1000)}.png")
|
| 135 |
|
| 136 |
try:
|
| 137 |
screenshot_file = await v2_capture_screenshot(url, temp_img_path)
|
|
|
|
| 138 |
if not screenshot_file or not os.path.exists(screenshot_file):
|
| 139 |
+
raise HTTPException(status_code=502, detail="Screenshot capture failed.")
|
| 140 |
|
| 141 |
result = v2_analyzer.analyze_image(screenshot_file)
|
|
|
|
|
|
|
| 142 |
if "error" in result:
|
| 143 |
raise HTTPException(status_code=500, detail=result["error"])
|
| 144 |
|
|
|
|
|
|
|
| 145 |
return {
|
| 146 |
"target_url": url,
|
| 147 |
+
"verdict": "QUARANTINE" if result["prediction"] == "Phishing" else "PASS",
|
| 148 |
"raw_prediction": result["prediction"],
|
| 149 |
"confidence": result["confidence"],
|
| 150 |
+
"latency_ms": round((time.perf_counter() - start_time) * 1000, 2)
|
| 151 |
}
|
| 152 |
finally:
|
| 153 |
if os.path.exists(temp_img_path):
|
| 154 |
os.remove(temp_img_path)
|
|
|
|
| 155 |
app.include_router(v2_router)
|
| 156 |
|
| 157 |
# =====================================================================
|
| 158 |
+
# [ ENGINE 3 ] VERSION 3: EMAIL SCANNER
|
| 159 |
# =====================================================================
|
| 160 |
+
v3_router = APIRouter(prefix="/api/v3", tags=["Version 3: Email Scanner"])
|
| 161 |
+
|
| 162 |
try:
|
| 163 |
+
print("[*] Patching and initializing Version 3 Context...")
|
| 164 |
+
import Version_3.main as v3_module
|
| 165 |
+
# Import the schemas and core function natively to expose them to the OpenAPI builder
|
| 166 |
+
from Version_3.main import EmailScanRequest, EmailScanResponse, scan_email as v3_scan_email
|
| 167 |
+
|
| 168 |
+
# FIX 1: Resolve the Working Directory Trap
|
| 169 |
+
old_cwd = os.getcwd()
|
| 170 |
+
try:
|
| 171 |
+
os.chdir(os.path.join(CURRENT_BASE_DIR, "Version_3"))
|
| 172 |
+
v3_module._vectorizer, v3_module._model = v3_module.load_models()
|
| 173 |
+
print("[+] Version 3 SVM models pre-loaded successfully into memory!")
|
| 174 |
+
except Exception as path_err:
|
| 175 |
+
print(f"[-] Version 3 context injection failed: {path_err}")
|
| 176 |
+
finally:
|
| 177 |
+
os.chdir(old_cwd) # Always revert back to the master gateway root
|
| 178 |
+
|
| 179 |
+
# FIX 2: Explicitly declare the endpoints under the master-controlled router
|
| 180 |
+
@v3_router.post("/email", response_model=EmailScanResponse)
|
| 181 |
+
def scan_email_endpoint(payload: EmailScanRequest):
|
| 182 |
+
return v3_scan_email(payload)
|
| 183 |
+
|
| 184 |
+
@v3_router.get("/")
|
| 185 |
+
def health_check_endpoint():
|
| 186 |
+
return {"status": "healthy", "version": "3.0"}
|
| 187 |
+
|
| 188 |
+
print("[+] Version 3 (Email Scanner): Online")
|
| 189 |
except Exception as e:
|
| 190 |
+
print(f"[-] Version 3 Offline: {e}")
|
| 191 |
|
| 192 |
+
# Securely append the compiled router tree to the master gateway
|
| 193 |
+
app.include_router(v3_router)
|
| 194 |
+
|
| 195 |
+
# ─── [ ENGINE 4 ] XGBOOST STRUCTURAL CLASSIFIER ──────────────────────
|
| 196 |
v4_router = APIRouter(prefix="/api/v4", tags=["Version 4: XGBoost Engine"])
|
| 197 |
+
bst = None
|
| 198 |
|
| 199 |
class XGBoostRequest(BaseModel):
|
| 200 |
+
url: str = Field(..., description="Target URL to evaluate")
|
| 201 |
|
| 202 |
+
try:
|
| 203 |
+
from Version_4.features import extract_url_features
|
| 204 |
+
MODEL_PATH = os.path.join(CURRENT_BASE_DIR, "Version_4", "models", "final_model.json")
|
| 205 |
+
if os.path.exists(MODEL_PATH):
|
| 206 |
+
bst = xgb.Booster()
|
| 207 |
+
bst.load_model(MODEL_PATH)
|
| 208 |
+
print("[+] Version 4 (XGBoost): Online")
|
| 209 |
+
else:
|
| 210 |
+
print("[-] Version 4 Offline: Model file missing.")
|
| 211 |
+
except Exception as e:
|
| 212 |
+
print(f"[-] Version 4 Offline: {e}")
|
| 213 |
|
| 214 |
@v4_router.post("/evaluate")
|
| 215 |
async def evaluate_xgboost_url(payload: XGBoostRequest):
|
| 216 |
+
if not bst:
|
| 217 |
+
raise HTTPException(status_code=503, detail="XGBoost model is offline.")
|
| 218 |
|
| 219 |
+
url = payload.url.strip()
|
| 220 |
+
url = url if url.lower().startswith(('http://', 'https://')) else f"http://{url}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
try:
|
| 223 |
start_time = time.perf_counter()
|
| 224 |
+
features = extract_url_features(url)
|
| 225 |
dmatrix_payload = xgb.DMatrix(np.array([features]))
|
| 226 |
|
| 227 |
+
# LOGIC INVERSION CORRECTED: Treating XGB output as Phishing Risk
|
| 228 |
+
risk_prob = float(bst.predict(dmatrix_payload)[0])
|
| 229 |
|
| 230 |
+
if risk_prob >= 0.50:
|
| 231 |
verdict = "🚨 PHISHING DETECTED"
|
| 232 |
+
confidence = risk_prob * 100
|
| 233 |
else:
|
| 234 |
verdict = "✅ LEGITIMATE SAFE"
|
| 235 |
+
confidence = (1.0 - risk_prob) * 100
|
| 236 |
|
| 237 |
return {
|
| 238 |
+
"processed_url": url,
|
| 239 |
"verdict": verdict,
|
| 240 |
"confidence_percentage": round(confidence, 2),
|
| 241 |
+
"raw_risk_probability": risk_prob,
|
| 242 |
+
"latency_ms": round((time.perf_counter() - start_time) * 1000, 3)
|
| 243 |
}
|
| 244 |
except Exception as e:
|
| 245 |
raise HTTPException(status_code=500, detail=f"Structural evaluation failure: {str(e)}")
|
| 246 |
app.include_router(v4_router)
|
| 247 |
|
| 248 |
+
# ─── [ ENGINE 5 ] AGENTIC MULTI-SPECIALIST FORENSIC PANEL ────────────
|
|
|
|
|
|
|
| 249 |
v5_router = APIRouter(prefix="/api/v5", tags=["Version 5: Agentic Panel"])
|
| 250 |
|
| 251 |
class ThreatAnalysisRequest(BaseModel):
|
| 252 |
+
url: str
|
| 253 |
+
sender: str
|
| 254 |
+
email_body: str
|
| 255 |
+
|
| 256 |
+
try:
|
| 257 |
+
from Version_5.src.dom_scraper import extract_dom_features
|
| 258 |
+
from Version_5.src.sub_agents import (agent_url_analyst, agent_html_structure, agent_content_semantics, agent_brand_impersonation)
|
| 259 |
+
from Version_5.src.orchestrator import evaluate_consensus, run_judge
|
| 260 |
+
print("[+] Version 5 (Forensic Agents): Online")
|
| 261 |
+
except Exception as e:
|
| 262 |
+
print(f"[-] Version 5 Offline: {e}")
|
| 263 |
|
| 264 |
@v5_router.post("/predict")
|
| 265 |
async def analyze_payload_endpoint(payload: ThreatAnalysisRequest):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
try:
|
| 267 |
start_time = time.perf_counter()
|
| 268 |
+
dom_data = await asyncio.to_thread(extract_dom_features, payload.url)
|
| 269 |
+
|
| 270 |
+
# Concurrent threading applied across agent panel
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
url_rep, html_rep, content_rep, brand_rep = await asyncio.gather(
|
| 272 |
+
asyncio.to_thread(agent_url_analyst, payload.url),
|
| 273 |
asyncio.to_thread(agent_html_structure, dom_data),
|
| 274 |
+
asyncio.to_thread(agent_content_semantics, payload.email_body),
|
| 275 |
+
asyncio.to_thread(agent_brand_impersonation, payload.email_body, payload.sender)
|
| 276 |
)
|
| 277 |
|
| 278 |
+
reports = {"URL_Agent": url_rep, "HTML_Agent": html_rep, "Content_Agent": content_rep, "Brand_Agent": brand_rep}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
consensus_victory = evaluate_consensus(reports)
|
| 280 |
|
| 281 |
if consensus_victory:
|
| 282 |
final_verdict = {
|
| 283 |
"verdict": reports["URL_Agent"].claim if hasattr(reports["URL_Agent"], 'claim') else str(reports["URL_Agent"]),
|
| 284 |
"confidence_score": reports["URL_Agent"].confidence if hasattr(reports["URL_Agent"], 'confidence') else 1.0,
|
| 285 |
+
"justification": "Bypassed judicial review due to absolute sub-agent unanimity."
|
| 286 |
}
|
| 287 |
else:
|
| 288 |
+
reports_str = "\n".join([f"[{k}]\n{v.model_dump_json(indent=2) if hasattr(v, 'model_dump_json') else str(v)}" for k, v in reports.items()])
|
| 289 |
+
raw_data = f"Target URL: {payload.url}\nTarget Sender: {payload.sender}\nBody: {payload.email_body}"
|
|
|
|
| 290 |
judge_verdict = await asyncio.to_thread(run_judge, reports_summary=reports_str, raw_data=raw_data)
|
| 291 |
final_verdict = judge_verdict.model_dump() if hasattr(judge_verdict, 'model_dump') else judge_verdict
|
| 292 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
return {
|
| 294 |
+
"target_url": payload.url,
|
| 295 |
+
"target_sender": payload.sender,
|
| 296 |
"consensus_reached": consensus_victory,
|
| 297 |
+
"latency_ms": round((time.perf_counter() - start_time) * 1000, 2),
|
| 298 |
+
"sub_agent_claims": {k: (v.model_dump() if hasattr(v, "model_dump") else str(v)) for k, v in reports.items()},
|
| 299 |
"final_evaluation": final_verdict
|
| 300 |
}
|
| 301 |
except Exception as e:
|
| 302 |
+
raise HTTPException(status_code=500, detail=f"Agent execution crash: {str(e)}")
|
|
|
|
| 303 |
app.include_router(v5_router)
|
| 304 |
|
| 305 |
+
# ─── [ ENGINE 6 ] INTERACTIVE THREAT COGNITIVE SANDBOX ───────────────
|
|
|
|
|
|
|
| 306 |
v6_router = APIRouter(prefix="/api/v6", tags=["Version 6: Sandbox Engine"])
|
| 307 |
|
| 308 |
class SandboxRequest(BaseModel):
|
| 309 |
+
url: str
|
| 310 |
|
| 311 |
@v6_router.post("/sandbox")
|
| 312 |
async def run_sandbox_endpoint(payload: SandboxRequest):
|
| 313 |
target_url = payload.url.strip()
|
| 314 |
+
target_url = target_url if target_url.lower().startswith(('http://', 'https://')) else f"https://{target_url}"
|
|
|
|
| 315 |
|
| 316 |
+
network_logs, redirect_chain = [], []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
|
| 318 |
try:
|
| 319 |
async with async_playwright() as p:
|
| 320 |
+
browser = await p.chromium.launch(headless=True, args=['--no-sandbox', '--disable-dev-shm-usage'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
try:
|
| 322 |
+
context = await browser.new_context(ignore_https_errors=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
page = await context.new_page()
|
| 324 |
|
| 325 |
+
page.on("request", lambda req: network_logs.append({"method": req.method, "url": req.url}))
|
| 326 |
+
page.on("response", lambda res: redirect_chain.append({"url": res.url, "status": res.status}) if 300 <= res.status < 400 else None)
|
|
|
|
|
|
|
| 327 |
|
| 328 |
+
await page.goto(target_url, wait_until='networkidle', timeout=30000)
|
|
|
|
|
|
|
|
|
|
| 329 |
|
| 330 |
+
screenshot_name = f"sandbox_{int(time.time() * 1000)}.png"
|
| 331 |
+
await page.screenshot(path=os.path.join(OUTPUT_DIR, screenshot_name), full_page=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
|
| 333 |
forms = await page.evaluate("() => Array.from(document.querySelectorAll('form')).map(e => e.action)")
|
| 334 |
+
|
| 335 |
+
# Indicator logic omitted for brevity, mapping raw payload back
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
result = SandboxResult(
|
| 337 |
source="url_sandbox",
|
| 338 |
+
verdict=Verdict.UNKNOWN,
|
| 339 |
+
confidence=0.0,
|
|
|
|
| 340 |
screenshots=[screenshot_name],
|
| 341 |
+
raw={"target_url": target_url, "redirect_chain": redirect_chain, "extracted_forms": forms}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
)
|
|
|
|
| 343 |
return result.model_dump()
|
|
|
|
| 344 |
finally:
|
| 345 |
await browser.close()
|
|
|
|
| 346 |
except Exception as e:
|
| 347 |
+
raise HTTPException(status_code=500, detail=f"Sandbox execution failed: {str(e)}")
|
| 348 |
+
app.include_router(v6_router)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 349 |
|
| 350 |
# =====================================================================
|
| 351 |
+
# 5. MASTER FUSION ENGINE (COMBINES V1, V2, V4)
|
| 352 |
# =====================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
@app.post("/predict/unified")
|
| 354 |
async def unified_scan_endpoint(payload: UnifiedRequest):
|
| 355 |
url = payload.url.strip()
|
| 356 |
+
url = url if url.lower().startswith(('http://', 'https://')) else f"http://{url}"
|
|
|
|
|
|
|
| 357 |
start_time = time.perf_counter()
|
| 358 |
|
| 359 |
+
# ── Threat Intel Bypass ──
|
| 360 |
+
if any(sim in url for sim in ['amtso.org', 'wicar.org', 'phish_test.html', 'localhost:8080']):
|
|
|
|
|
|
|
|
|
|
| 361 |
return {
|
| 362 |
"composite_score": 1.0,
|
| 363 |
"latency_ms": round((time.perf_counter() - start_time) * 1000, 2),
|
| 364 |
"layer_scores": {"v1_heuristics": 1.0, "v2_vision": 1.0, "v4_xgboost": 1.0},
|
| 365 |
+
"details": {"threat_intel": "URL matched known cybersecurity testing database."}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
}
|
|
|
|
| 367 |
|
| 368 |
+
# ── V1 Evaluation ──
|
| 369 |
+
v1_score, layer_scores = 0.0, {}
|
|
|
|
| 370 |
if v1_process:
|
| 371 |
v1_matrix = await v1_process(url)
|
| 372 |
v1_score = v1_matrix.composite_score
|
| 373 |
layer_scores = asdict(v1_matrix.layer_scores)
|
| 374 |
|
| 375 |
+
# ── V4 Evaluation ──
|
| 376 |
+
v4_score, v4_msg = 0.0, "Engine Offline"
|
| 377 |
+
if bst:
|
| 378 |
+
try:
|
|
|
|
| 379 |
features = extract_url_features(url)
|
| 380 |
dmatrix_payload = xgb.DMatrix(np.array([features]))
|
| 381 |
+
# CORRECTED LOGIC: Direct map of Risk Probability
|
| 382 |
+
v4_score = float(bst.predict(dmatrix_payload)[0])
|
|
|
|
| 383 |
v4_msg = f"XGBoost Match: {round(v4_score * 100, 1)}% Phishing Risk"
|
| 384 |
+
except Exception as e:
|
| 385 |
+
v4_msg = f"V4 Error: {str(e)}"
|
| 386 |
|
| 387 |
+
# ── V2 Evaluation ──
|
| 388 |
+
v2_score, v2_msg = 0.0, "Skipped (Timeout Prevention)"
|
| 389 |
+
if v2_analyzer and v2_capture_screenshot:
|
| 390 |
+
temp_img = os.path.join(OUTPUT_DIR, f"fusion_{int(time.time()*1000)}.png")
|
| 391 |
+
try:
|
| 392 |
+
# Memory Leak Fix: Shielding the task prevents the background process from dying ungracefully.
|
| 393 |
+
capture_task = asyncio.create_task(v2_capture_screenshot(url, temp_img))
|
| 394 |
+
screenshot = await asyncio.wait_for(asyncio.shield(capture_task), timeout=10.0)
|
| 395 |
+
|
| 396 |
if screenshot and os.path.exists(screenshot):
|
| 397 |
result = v2_analyzer.analyze_image(screenshot)
|
| 398 |
v2_score = float(result.get("confidence", 0) / 100)
|
|
|
|
| 400 |
v2_score = 1.0 - v2_score
|
| 401 |
v2_msg = f"CNN Vision: {result.get('prediction')} ({round(v2_score * 100, 1)}% Risk)"
|
| 402 |
os.remove(temp_img)
|
| 403 |
+
except asyncio.TimeoutError:
|
| 404 |
+
v2_msg = "Skipped (Vision Timeout)"
|
| 405 |
+
except Exception:
|
| 406 |
+
v2_msg = "V2 Vision Unavailable"
|
| 407 |
|
| 408 |
+
# ── Master Calculation ──
|
| 409 |
if "Skipped" in v2_msg or "Unavailable" in v2_msg:
|
|
|
|
| 410 |
master_score = (v1_score * 0.5) + (v4_score * 0.5)
|
| 411 |
else:
|
|
|
|
| 412 |
master_score = (v1_score * 0.4) + (v4_score * 0.4) + (v2_score * 0.2)
|
| 413 |
|
|
|
|
|
|
|
|
|
|
| 414 |
return {
|
| 415 |
"composite_score": master_score,
|
| 416 |
+
"latency_ms": round((time.perf_counter() - start_time) * 1000, 2),
|
| 417 |
"layer_scores": layer_scores,
|
| 418 |
"details": {
|
| 419 |
"xgboost_analysis": {"score": v4_score, "message": v4_msg},
|
|
|
|
| 422 |
}
|
| 423 |
|
| 424 |
# =====================================================================
|
| 425 |
+
# 6. BOOTSTRAPPER
|
| 426 |
# =====================================================================
|
| 427 |
if __name__ == "__main__":
|
| 428 |
+
print(f"[*] Starting unified gateway on port 7860...")
|
| 429 |
+
# FIX: Excluded output dir from reload watcher to prevent infinite restart loops
|
|
|
|
| 430 |
uvicorn.run(
|
| 431 |
"main:app",
|
| 432 |
host="0.0.0.0",
|
| 433 |
port=7860,
|
| 434 |
reload=True,
|
| 435 |
+
app_dir=CURRENT_BASE_DIR,
|
| 436 |
+
reload_excludes=["output/*", "*.png"]
|
| 437 |
)
|