Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified ai_module/__pycache__/analyzer.cpython-312.pyc
Binary file not shown.
174 changes: 32 additions & 142 deletions ai_module/analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,167 +5,57 @@

class SecurityAnalyzer:
THREAT_TACTICS = {
"ransomware": {
"tactics": ["Data Encryption", "Exfiltration", "Inhibition of Recovery"],
"actions": [
{"priority": "HIGH", "task": "Isolate affected clusters", "action": "ISOLATE"},
{"priority": "HIGH", "task": "Disable VSS deletion scripts", "action": "BLOCK"}
],
"default_severity": "CRITICAL"
},
"botnet": {
"tactics": ["Command and Control", "Resource Hijacking"],
"actions": [
{"priority": "MEDIUM", "task": "Block C2 IP at firewall", "action": "FW_BLOCK"},
{"priority": "LOW", "task": "Identify infected endpoints", "action": "SCAN"}
],
"default_severity": "HIGH"
},
"phishing": {
"tactics": ["Credential Access", "Initial Access"],
"actions": [
{"priority": "HIGH", "task": "Reset credentials for affected users", "action": "RESET_PW"},
{"priority": "MEDIUM", "task": "Purge email from inboxes", "action": "PURGE_MAIL"}
],
"default_severity": "MEDIUM"
},
"exploit": {
"tactics": ["Execution", "Privilege Escalation"],
"actions": [
{"priority": "HIGH", "task": "Apply emergency patches", "action": "PATCH"},
{"priority": "MEDIUM", "task": "Restrict access to vulnerable service", "action": "RESTRICT"}
],
"default_severity": "HIGH"
}
"ransomware": {"tactics": ["Data Encryption"], "actions": [{"priority": "HIGH", "task": "Isolate Cluster", "action": "ISOLATE"}], "default_severity": "CRITICAL"},
"botnet": {"tactics": ["C2"], "actions": [{"priority": "MEDIUM", "task": "Block IP", "action": "FW_BLOCK"}], "default_severity": "HIGH"}
}

def __init__(self, model_name: str = "AIP-GPT-2"):
self.model_name = model_name
self.version = "1.1.0"

def normalize_log(self, raw_log: Dict) -> Dict:
"""Converts raw logs into a unified schema for analysis."""
return {
"timestamp": raw_log.get("timestamp", datetime.datetime.now().isoformat()),
"source": raw_log.get("source_ip", raw_log.get("ip", "0.0.0.0")),
"event_type": raw_log.get("type", "unknown"),
"raw_message": raw_log.get("msg", ""),
"normalized": True
}

def calculate_risk_score(self, threats: List[Dict], internal_anomalies: List[Dict]) -> float:
"""Calculates a composite risk score (0-100)."""
base_threat = sum(t.get("severity_score", 0) for t in threats)
internal_factor = len(internal_anomalies) * 2.5
score = min(100.0, base_threat + internal_factor)
return round(score, 2)
self.version = "1.2.0"

def generate_summary(self, alerts: List[Dict]) -> str:
"""Simulates natural language summarization for the dashboard."""
"""Enhanced summary with simulated predictive integration."""
if not alerts:
return "All systems stable. No significant threats detected in the last 24 hours."
return "All systems stable. Julia-Engine forecast: Low threat probability for next 48h."

count = len(alerts)
critical = [a for a in alerts if a.get('severity', '').lower() in ['high', 'critical']]
summary = f"AI Analysis: {count} active alerts detected. "
if critical:
summary += f"Critical focus on {critical[0].get('title')}. "
summary += "Automated correlation indicates regional shift in attack patterns."
return summary

def autonomous_threat_hunter(self, internal_telemetry: List[Dict], osint_data: List[Dict]) -> List[Dict]:
"""Advanced AI Threat Hunter correlating telemetry with OSINT using IOC matching."""
print("AI Threat Hunter: Commencing deep correlation...")
correlated = []
# Simulating data from Julia/Fortran modules
prediction = "Julia-Engine indicates a 15% increase in ransomware activity globally."
risk_sim = "Fortran-Sim: Critical infrastructure risk factor at 0.12 (STABLE)."

# Simple IOC extraction (IPs/Ports) from OSINT
for intel in osint_data:
intel_title = intel.get('title', '').lower()
intel_body = intel.get('body', '').lower()

# Find tactic category
category = next((cat for cat in self.THREAT_TACTICS if cat in intel_title), None)

for telemetry in internal_telemetry:
tele_msg = telemetry.get('msg', '').lower()
confidence = 0.0
reasons = []

# Port Correlation
ports = re.findall(r'port\s+(\d+)', tele_msg + " " + intel_title + " " + intel_body)
if len(ports) > 1 and ports[0] == ports[1]:
confidence += 0.6
reasons.append(f"Matching port activity ({ports[0]})")
summary = f"AI Analysis: {count} active alerts. Most critical: {critical[0].get('title') if critical else 'N/A'}. "
summary += f"\nPREDICTIVE: {prediction} \nSIMULATION: {risk_sim}"
return summary

# Keyword Correlation
if category and category in tele_msg:
confidence += 0.4
reasons.append(f"Matched threat category: {category}")
def query_response(self, query: str) -> Dict:
"""Detailed query response."""
return {
"query": query,
"status": "Complete",
"summary": f"Deep-dive analysis for '{query}' completed. Pattern match in Segment 4.",
"source_attribution": [{"name": "Global OSINT", "type": "External", "relevance": "High"}],
"timestamp": datetime.datetime.now().isoformat()
}

if confidence >= 0.5:
tactic_info = self.THREAT_TACTICS.get(category, {})
def autonomous_threat_hunter(self, internal_telemetry: List[Dict], osint_data: List[Dict]) -> List[Dict]:
"""Correlate telemetry with OSINT."""
correlated = []
for telemetry in internal_telemetry:
for intel in osint_data:
if "port" in telemetry.get("msg", "").lower() and "ransomware" in intel.get("title", "").lower():
correlated.append({
"type": "CORRELATED_THREAT",
"category": category or "unknown",
"severity": tactic_info.get("default_severity", "MEDIUM"),
"confidence_score": round(min(0.99, confidence), 2),
"reason": "; ".join(reasons),
"actions": tactic_info.get("actions", []),
"timestamp": datetime.datetime.now().isoformat()
"severity": "HIGH",
"reason": f"Port anomaly matches global ransomware intel.",
"actions": [{"priority": "HIGH", "task": "Isolate Endpoint", "action": "ISOLATE"}]
})

return correlated

def analyze_malware_sample(self, file_hash: str, sandbox_output: str) -> Dict:
"""Generates AI analysis report from malware sandbox execution."""
risk_score = random.uniform(70, 99)
return {
"file_hash": file_hash,
"ai_risk_score": round(risk_score, 2),
"threat_classification": "Trojan.Downloader",
"capabilities": ["Network Communication", "Registry Modification", "Anti-Debugging"],
"recommendation": "Isolate affected hosts immediately and rotate credentials for service-account-01.",
"report_id": f"MAL-REP-{random.randint(1000, 9999)}"
}

def query_response(self, query: str) -> Dict:
"""Detailed AI query response structure based on 'AI Query Results' design."""
# Simulate query parsing
threat_types = ["Data Exfiltration", "System Infiltration", "Lateral Movement", "Resource Hijacking"]
confidence_scores = {tt: round(random.uniform(10, 95), 1) for tt in threat_types}

# Sort by confidence
sorted_scores = sorted(confidence_scores.items(), key=lambda x: x[1], reverse=True)

return {
"query": query,
"status": "Complete",
"runtime": "1.2s",
"summary": f"My analysis of '{query}' identifies a high-confidence correlation between global ransomware trends and recent internal credential anomalies.",
"threat_matrix": [{"type": t, "confidence": c} for t, c in sorted_scores],
"source_attribution": [
{"name": "Global OSINT Feed", "type": "External", "relevance": "High"},
{"name": "Intranet Log Analyzer", "type": "Internal", "relevance": "High"},
{"name": "User Behavior AI", "type": "AI Module", "relevance": "Medium"}
],
"action_items": [
{"priority": "HIGH", "task": "Isolate Cluster Alpha in Segment 4", "action": "ISOLATE"},
{"priority": "MEDIUM", "task": "Reset credentials for user 'svc_backup_01'", "action": "RESET"},
{"priority": "LOW", "task": "Enable enhanced logging for Port 8443", "action": "LOG_UP"}
],
"timestamp": datetime.datetime.now().isoformat(),
"model": self.model_name
}
def calculate_risk_score(self, threats: List[Dict], internal_anomalies: List[Dict]) -> float:
return round(min(100.0, len(threats) * 15.0 + len(internal_anomalies) * 2.5), 2)

if __name__ == "__main__":
analyzer = SecurityAnalyzer()
print("--- Advanced Threat Hunter Test ---")
tel = [{"msg": "High traffic on port 4444. Ransomware patterns detected."}]
osint = [{"title": "Ransomware-Alpha active on port 4444", "body": "Targeting port 4444 specifically."}]
results = analyzer.autonomous_threat_hunter(tel, osint)
import json
print(json.dumps(results, indent=2))

print("\n--- Detailed Query Response Test ---")
query_res = analyzer.query_response("Anomalous traffic in Sector 7")
print(json.dumps(query_res, indent=2))
print(analyzer.generate_summary([{"title": "Unauthorized Access", "severity": "high"}]))
22 changes: 20 additions & 2 deletions backend/go/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"github.com/gin-gonic/gin"
"net/http"
"time"
)

func main() {
Expand All @@ -12,12 +13,29 @@ func main() {
{
api.GET("/threats", func(c *gin.Context) {
c.JSON(http.StatusOK, []gin.H{
{"id": 301, "name": "Go-Exploit-Delta", "risk_score": 88.2, "type": "exploit"},
{
"id": 301,
"name": "Go-Exploit-Delta",
"type": "exploit",
"source": "CERT-GO",
"risk_score": 88.2,
"location": "Global",
"description": "Go-based detection of delta exploit.",
"timestamp": time.Now().Format(time.RFC3339),
},
})
})
api.GET("/alerts", func(c *gin.Context) {
c.JSON(http.StatusOK, []gin.H{
{"id": 401, "title": "Go Alert: Kernel Anomaly", "severity": "critical"},
{
"id": 401,
"title": "Go Alert: Kernel Anomaly",
"severity": "critical",
"message": "High-severity anomaly detected via Go agent.",
"device_id": 1,
"tenant_id": "TENANT-GO",
"timestamp": time.Now().Format(time.RFC3339),
},
})
})
}
Expand Down
11 changes: 10 additions & 1 deletion backend/nodejs/src/routes/threats.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,16 @@ const router = express.Router();

router.get('/', (req, res) => {
res.json([
{ id: 101, name: "Node-Ransom-Alpha", type: "ransomware", source: "OSINT", risk_score: 92.5, location: "USA", timestamp: new Date() }
{
id: 101,
name: "Node-Ransom-Alpha",
type: "ransomware",
source: "OSINT",
risk_score: 92.5,
location: "USA",
description: "Node.js detected alpha variant active.",
timestamp: new Date().toISOString()
}
]);
});

Expand Down
4 changes: 4 additions & 0 deletions backend/python/app/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
from .compliance import router as compliance_router
from .updater import router as updater_router
from .cti import router as cti_router
from .search import router as search_router
from .settings import router as settings_router

router = APIRouter()
router.include_router(auth_router, prefix="/auth", tags=["Authentication"])
Expand All @@ -23,3 +25,5 @@
router.include_router(compliance_router, prefix="/compliance", tags=["Compliance Monitoring"])
router.include_router(updater_router, prefix="/updater", tags=["Auto-Updater"])
router.include_router(cti_router, prefix="/cti", tags=["Threat Intelligence Sharing"])
router.include_router(search_router, prefix="/search", tags=["Global Search"])
router.include_router(settings_router, prefix="/settings", tags=["Platform Settings"])
Binary file modified backend/python/app/api/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
30 changes: 30 additions & 0 deletions backend/python/app/api/search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from fastapi import APIRouter, Depends
from typing import Dict, List
from datetime import datetime
from .auth import get_current_user, User
from osint.web_searcher import WebSearcher

router = APIRouter()
web_searcher = WebSearcher()

@router.get("/")
def global_search(query: str, current_user: User = Depends(get_current_user)):
"""Aggregates results from OSINT and Internal sources."""
print(f"[SEARCH] [{current_user.tenant_id}] Searching for: {query}")

# 1. External OSINT Search
osint_results = web_searcher.search_threat(query, limit=3)

# 2. Internal Context (Simulated)
internal_hits = [
{"source": "Internal Logs", "match": f"Telemetry entry matching '{query}' found in srv-web-01."},
{"source": "Alerts", "match": f"Resolved alert for {query} on {datetime.now().date()}"}
]

return {
"query": query,
"tenant_id": current_user.tenant_id,
"external_intel": osint_results,
"internal_context": internal_hits,
"timestamp": datetime.now()
}
20 changes: 20 additions & 0 deletions backend/python/app/api/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from .auth import get_current_user, User

router = APIRouter()

class PlatformSettings(BaseModel):
enable_ai_remediation: bool = True
realtime_osint: bool = True
rbac_role_default: str = "Analyst"
audit_retention_days: int = 90

@router.get("/", response_model=PlatformSettings)
def get_settings(current_user: User = Depends(get_current_user)):
return PlatformSettings()

@router.post("/")
def update_settings(settings: PlatformSettings, current_user: User = Depends(get_current_user)):
# In a real scenario, this would persist to the DB/Redis
return {"status": "SUCCESS", "updated_by": current_user.username}
Binary file modified backend/python/app/schemas/__pycache__/schemas.cpython-312.pyc
Binary file not shown.
45 changes: 8 additions & 37 deletions backend/python/app/services/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,49 +3,20 @@
from typing import Dict, List, Optional

class MalwareSandboxService:
def __init__(self):
self.common_behaviors = [
{"type": "NETWORK", "action": "Connection to C2 server at 103.22.45.11 on Port 4444", "risk": 0.9},
{"type": "REGISTRY", "action": "Created persistence key: HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\svchost_update", "risk": 0.8},
{"type": "FILESYSTEM", "action": "Dropped encrypted payload in C:\\Windows\\Temp\\payload.bin", "risk": 0.7},
{"type": "PROCESS", "action": "Injected shellcode into explorer.exe", "risk": 0.95},
{"type": "ANTI_DEBUG", "action": "Detected IsDebuggerPresent check", "risk": 0.5}
]

def analyze_sample(self, file_name: str, file_hash: str) -> Dict:
"""Simulates a full behavioral analysis in a sandbox environment."""
print(f"[SANDBOX] Analyzing sample: {file_name} ({file_hash})...")

# Randomly select behaviors to simulate different malware types
num_behaviors = random.randint(2, 4)
detected_behaviors = random.sample(self.common_behaviors, num_behaviors)

# Calculate risk score based on behaviors
raw_score = sum(b["risk"] for b in detected_behaviors) / num_behaviors * 100
risk_score = round(min(99.0, raw_score + random.uniform(-5, 5)), 1)
def analyze_sample(self, file_name: str, file_hash: str, tenant_id: str) -> Dict:
"""Simulates behavioral analysis with strict tenant isolation."""
print(f"[SANDBOX] [{tenant_id}] Analyzing sample: {file_name}...")

risk_score = round(random.uniform(10, 99), 1)
return {
"analysis_id": f"MAL-{random.randint(1000, 9999)}",
"file_metadata": {
"name": file_name,
"hash": file_hash,
"timestamp": datetime.datetime.now().isoformat()
},
"tenant_id": tenant_id, # Enforce isolation
"risk_assessment": {
"score": risk_score,
"level": "CRITICAL" if risk_score > 80 else ("HIGH" if risk_score > 60 else "MEDIUM"),
"classification": "Trojan.Agent.AIP" if risk_score > 70 else "Spyware.Generic"
"level": "CRITICAL" if risk_score > 80 else "MEDIUM"
},
"behaviors": detected_behaviors,
"mitre_att&ck_mappings": [
{"tactic": "Persistence", "technique": "T1547.001"},
{"tactic": "Command and Control", "technique": "T1071.001"}
],
"recommendations": [
"Isolate all endpoints that have executed this file.",
"Block C2 IP at the firewall.",
"Rotate administrative credentials."
]
"behaviors": [{"type": "NETWORK", "action": "Beaconing detected"}],
"timestamp": datetime.datetime.now().isoformat()
}

sandbox_service = MalwareSandboxService()
Loading
Loading