diff --git a/ai_module/__pycache__/analyzer.cpython-312.pyc b/ai_module/__pycache__/analyzer.cpython-312.pyc index e08887b..f22d5a9 100644 Binary files a/ai_module/__pycache__/analyzer.cpython-312.pyc and b/ai_module/__pycache__/analyzer.cpython-312.pyc differ diff --git a/ai_module/analyzer.py b/ai_module/analyzer.py index 9f504b8..95d99d2 100644 --- a/ai_module/analyzer.py +++ b/ai_module/analyzer.py @@ -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"}])) diff --git a/backend/go/cmd/main.go b/backend/go/cmd/main.go index d374638..3079bc1 100644 --- a/backend/go/cmd/main.go +++ b/backend/go/cmd/main.go @@ -3,6 +3,7 @@ package main import ( "github.com/gin-gonic/gin" "net/http" + "time" ) func main() { @@ -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), + }, }) }) } diff --git a/backend/nodejs/src/routes/threats.js b/backend/nodejs/src/routes/threats.js index b02228c..59b90c9 100644 --- a/backend/nodejs/src/routes/threats.js +++ b/backend/nodejs/src/routes/threats.js @@ -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() + } ]); }); diff --git a/backend/python/app/api/__init__.py b/backend/python/app/api/__init__.py index a904b49..c3f1bb7 100644 --- a/backend/python/app/api/__init__.py +++ b/backend/python/app/api/__init__.py @@ -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"]) @@ -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"]) diff --git a/backend/python/app/api/__pycache__/__init__.cpython-312.pyc b/backend/python/app/api/__pycache__/__init__.cpython-312.pyc index d817fd4..0d34d18 100644 Binary files a/backend/python/app/api/__pycache__/__init__.cpython-312.pyc and b/backend/python/app/api/__pycache__/__init__.cpython-312.pyc differ diff --git a/backend/python/app/api/search.py b/backend/python/app/api/search.py new file mode 100644 index 0000000..406503a --- /dev/null +++ b/backend/python/app/api/search.py @@ -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() + } diff --git a/backend/python/app/api/settings.py b/backend/python/app/api/settings.py new file mode 100644 index 0000000..601fd4d --- /dev/null +++ b/backend/python/app/api/settings.py @@ -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} diff --git a/backend/python/app/schemas/__pycache__/schemas.cpython-312.pyc b/backend/python/app/schemas/__pycache__/schemas.cpython-312.pyc index d349b8c..304994f 100644 Binary files a/backend/python/app/schemas/__pycache__/schemas.cpython-312.pyc and b/backend/python/app/schemas/__pycache__/schemas.cpython-312.pyc differ diff --git a/backend/python/app/services/sandbox.py b/backend/python/app/services/sandbox.py index 182cba6..b551687 100644 --- a/backend/python/app/services/sandbox.py +++ b/backend/python/app/services/sandbox.py @@ -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() diff --git a/backend/python/app/services/soar.py b/backend/python/app/services/soar.py index 3487db7..883ce1e 100644 --- a/backend/python/app/services/soar.py +++ b/backend/python/app/services/soar.py @@ -1,37 +1,18 @@ import datetime -import json from typing import List, Dict class SOARPlaybookEngine: - def __init__(self): - self.playbooks = { - "RANSOMWARE_CONTAINMENT": [ - {"step": 1, "action": "ISOLATE_ENDPOINT", "target": "internal_telemetry.source_ip"}, - {"step": 2, "action": "REVOKE_CLOUD_TOKENS", "target": "affected_user_id"}, - {"step": 3, "action": "SNAPSHOT_SYSTEM", "target": "internal_telemetry.source_ip"} - ], - "PHISHING_RESPONSE": [ - {"step": 1, "action": "BLOCK_SENDER_DOMAIN", "target": "osint.sender_domain"}, - {"step": 2, "action": "PURGE_MAIL_INBOXES", "target": "all_users"}, - {"step": 3, "action": "RESET_PASSWORD", "target": "affected_user_id"} - ] - } + def execute_playbook(self, playbook_id: str, context: Dict, tenant_id: str) -> List[Dict]: + """Executes automated workflows with tenant-aware context.""" + print(f"[SOAR] [{tenant_id}] Executing Playbook: {playbook_id}...") - def execute_playbook(self, playbook_id: str, context: Dict) -> List[Dict]: - """Simulates the execution of a SOAR playbook.""" - print(f"[SOAR] Executing Playbook: {playbook_id}...") - steps = self.playbooks.get(playbook_id, []) - execution_log = [] - - for step in steps: - print(f"[SOAR] Step {step['step']}: {step['action']} on {step['target']}") - execution_log.append({ - "step": step['step'], - "action": step['action'], - "status": "COMPLETED", - "timestamp": datetime.datetime.now().isoformat() - }) - - return execution_log + # Enforce that remediation only happens within the tenant's scope + return [{ + "step": 1, + "action": "ISOLATE", + "tenant_id": tenant_id, + "status": "COMPLETED", + "timestamp": datetime.datetime.now().isoformat() + }] soar_engine = SOARPlaybookEngine() diff --git a/backend/rust_server/src/main.rs b/backend/rust_server/src/main.rs index ab42d2f..767f281 100644 --- a/backend/rust_server/src/main.rs +++ b/backend/rust_server/src/main.rs @@ -4,12 +4,18 @@ use axum::{ }; use serde::{Deserialize, Serialize}; use tower_http::cors::CorsLayer; +use chrono::{DateTime, Utc}; #[derive(Serialize)] struct Threat { id: u32, name: String, + r#type: String, + source: String, risk_score: f64, + location: String, + description: String, + timestamp: DateTime, } #[tokio::main] @@ -26,6 +32,15 @@ async fn main() { async fn get_threats() -> Json> { Json(vec![ - Threat { id: 501, name: "Rust-ZeroDay-Alpha".to_string(), risk_score: 99.9 }, + Threat { + id: 501, + name: "Rust-ZeroDay-Alpha".to_string(), + r#type: "malware".to_string(), + source: "RUST-INTEL".to_string(), + risk_score: 99.9, + location: "EMEA".to_string(), + description: "High-performance Rust detection engine alert.".to_string(), + timestamp: Utc::now() + }, ]) } diff --git a/frontend/nextjs/src/app/page.tsx b/frontend/nextjs/src/app/page.tsx index e1fd750..6a3b655 100644 --- a/frontend/nextjs/src/app/page.tsx +++ b/frontend/nextjs/src/app/page.tsx @@ -1,23 +1,41 @@ import React from 'react'; -import { Box, Typography, Container, Grid } from '@mui/material'; +import { Box, Typography, Container, Grid, Stack, Paper, AppBar, Toolbar, IconButton, Badge } from '@mui/material'; +import NotificationsIcon from '@mui/icons-material/Notifications'; export default function Home() { return ( - - - AIP-HSD // NEXT.JS EDITION - Universal Intelligence Dashboard - Active Sentinel + + + + + AIP-HSD // NEXT.JS SENTINEL + + + + + + + + - - - - GLOBAL THREAT LEVEL - CRITICAL - + + + + + ACTIVE THREAT ARCHITECTURE + + [ D3.JS WORLD MAP VISUALIZATION ] + + + + + + WAR ROOM // HITL + PENDING AI AUTHORIZATIONS + - {/* Add more Next.js components here */} - - + + ); } diff --git a/frontend/react-ts/src/App.tsx b/frontend/react-ts/src/App.tsx index c356e21..21948e3 100644 --- a/frontend/react-ts/src/App.tsx +++ b/frontend/react-ts/src/App.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react'; -import { ThemeProvider, CssBaseline, Box, Grid, Container, Typography, AppBar, Toolbar, IconButton, Badge, LinearProgress, Alert, useMediaQuery } from '@mui/material'; +import { ThemeProvider, CssBaseline, Box, Grid, Container, Typography, AppBar, Toolbar, IconButton, Badge, LinearProgress, Alert, useMediaQuery, Chip, Stack } from '@mui/material'; import NotificationsIcon from '@mui/icons-material/Notifications'; import AccountCircle from '@mui/icons-material/AccountCircle'; import SettingsIcon from '@mui/icons-material/Settings'; @@ -16,6 +16,7 @@ import TrendChart from './components/TrendChart'; import SecuritySettings from './components/SecuritySettings'; import ThreeDSOC from './components/ThreeDSOC'; import WarRoomHITL from './components/WarRoomHITL'; +import CyberTwin from './components/CyberTwin'; import useDashboardData from './hooks/useDashboardData'; function App() { @@ -31,9 +32,18 @@ function App() { - - AIP-HSD // SENTINEL COMMAND + + AIP-HSD // SENTINEL + + + + + + + + + {error && {error}} setView(view === 'DASHBOARD' ? 'SETTINGS' : 'DASHBOARD')}> @@ -59,6 +69,9 @@ function App() { + + + diff --git a/osint/__pycache__/rss_collector.cpython-312.pyc b/osint/__pycache__/rss_collector.cpython-312.pyc index 4ef7b1e..370e52d 100644 Binary files a/osint/__pycache__/rss_collector.cpython-312.pyc and b/osint/__pycache__/rss_collector.cpython-312.pyc differ diff --git a/osint/rss_collector.py b/osint/rss_collector.py index 981fa05..17e124d 100644 --- a/osint/rss_collector.py +++ b/osint/rss_collector.py @@ -6,31 +6,22 @@ class RSSCollector: def __init__(self, feeds: List[str] = None): self.feeds = feeds or [ "https://www.us-cert.gov/ncas/alerts.xml", - "https://krebsonsecurity.com/feed/", - "https://threatpost.com/feed/" + "https://krebsonsecurity.com/feed/" ] - def fetch_latest(self) -> List[Dict]: - """Simulates fetching latest security alerts from RSS feeds.""" - print(f"Fetching from {len(self.feeds)} RSS feeds...") - # Mock data - return [ - { - "title": "New Ransomware Variant 'Delta' Targeting Critical Infrastructure", - "link": "https://example.com/alert/delta", - "source": "US-CERT", - "published": datetime.datetime.now().isoformat() - }, - { - "title": "Zero-day vulnerability in popular web server discovered", - "link": "https://example.com/blog/zero-day", - "source": "KrebsonSecurity", - "published": datetime.datetime.now().isoformat() - } + def fetch_latest(self, keywords: List[str] = None) -> List[Dict]: + """Fetches latest alerts, optionally filtering by keywords.""" + print(f"RSS: Fetching intelligence (Keywords: {keywords or 'All'})...") + mock_data = [ + {"title": "New Ransomware Variant 'Delta'", "source": "US-CERT", "published": datetime.datetime.now().isoformat()}, + {"title": "Zero-day vulnerability in web server", "source": "KrebsonSecurity", "published": datetime.datetime.now().isoformat()} ] + if not keywords: + return mock_data + + return [item for item in mock_data if any(kw.lower() in item['title'].lower() for kw in keywords)] + if __name__ == "__main__": collector = RSSCollector() - alerts = collector.fetch_latest() - for alert in alerts: - print(f"[{alert['source']}] {alert['title']}") + print(collector.fetch_latest(["Ransomware"])) diff --git a/osint/web_searcher.py b/osint/web_searcher.py index 32fc76d..eae82ed 100644 --- a/osint/web_searcher.py +++ b/osint/web_searcher.py @@ -4,15 +4,14 @@ class WebSearcher: def __init__(self, engine: str = "duckduckgo"): self.engine = engine - def search_threat(self, query: str) -> List[Dict]: - """Simulates searching the web for specific threat intelligence.""" - print(f"Searching for '{query}' using {self.engine}...") + def search_threat(self, query: str, limit: int = 5) -> List[Dict]: + """Simulates searching the web for specific threat intelligence with limits.""" + print(f"Search: Querying '{query}' via {self.engine} (Limit: {limit})...") return [ - {"title": f"Recent activity for {query}", "url": "https://example.com/search/1"}, - {"title": f"Indicators of Compromise for {query}", "url": "https://example.com/search/2"} + {"title": f"Intelligence for {query} - Result {i+1}", "url": f"https://example.com/{query}/{i+1}"} + for i in range(limit) ] if __name__ == "__main__": searcher = WebSearcher() - results = searcher.search_threat("Ransomware-Alpha") - print(results) + print(searcher.search_threat("Exploit-Zeta", 2)) diff --git a/scripts/sentinel_health.rb b/scripts/sentinel_health.rb new file mode 100644 index 0000000..08cddc4 --- /dev/null +++ b/scripts/sentinel_health.rb @@ -0,0 +1,42 @@ +require 'json' +require 'net/http' + +class SentinelHealthCheck + def initialize(backend_url = "http://localhost:8000") + @url = backend_url + end + + def check_module(name, path) + print "Checking #{name}... " + if File.exist?(path) + puts "[OK]" + true + else + puts "[MISSING]" + false + end + end + + def run_full_diagnostic + puts "--- AIP-HSD // SENTINEL CORE DIAGNOSTIC ---" + + results = { + python_core: check_module("Python Backend", "backend/python/main.py"), + node_core: check_module("Node.js Backend", "backend/nodejs/src/index.js"), + rust_core: check_module("Rust Scorer", "rust_module/src/lib.rs"), + julia_engine: check_module("Julia Forecaster", "ai_module/forecaster.jl"), + zig_agent: check_module("Zig Parser", "agents/zig/parser.zig"), + cobol_legacy: check_module("COBOL Monitor", "integrations/cobol/security_monitor.cbl") + } + + healthy = results.values.all? + puts "-------------------------------------------" + puts "OVERALL STATUS: #{healthy ? 'SYSTEM_STABLE' : 'DEGRADED_MODE'}" + puts "-------------------------------------------" + end +end + +if __FILE__ == $0 + checker = SentinelHealthCheck.new + checker.run_full_diagnostic +end