File size: 12,446 Bytes
063d154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/**
 * ThreatLens OSINT - Ethical Intelligence Platform
 * A legitimate OSINT analysis tool using transformers.js
 * 
 * IMPORTANT: This platform only processes publicly available data
 * and operates within legal and ethical boundaries.
 */

import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.0';

// Configure transformers.js
env.allowLocalModels = false;
env.useBrowserCache = true;

// Application State
const AppState = {
    models: {
        sentiment: null,
        ner: null,
        summarization: null,
        zeroShot: null
    },
    isReady: false,
    complianceAccepted: false
};

// Threat categories for classification
const THREAT_CATEGORIES = [
    'malware',
    'phishing',
    'ransomware',
    'data breach',
    'denial of service',
    'social engineering',
    'insider threat',
    'zero-day vulnerability',
    'supply chain attack',
    'credential theft'
];

// Sample threat intelligence data
const SAMPLE_DATA = {
    threat: `CVE-2024-1234: Critical Remote Code Execution Vulnerability in Enterprise Software
    
A critical security vulnerability has been discovered in the authentication module of Enterprise Software X, allowing remote attackers to execute arbitrary code. The vulnerability affects versions 2.0 through 3.5. Organizations running affected versions should immediately apply the security patch released by the vendor.

Impact: Remote code execution with system privileges
CVSS Score: 9.8 (Critical)
Affected Components: Authentication module, session management
Attack Vector: Network-based, requires no authentication
Mitigation: Update to version 3.6 or apply vendor patch

This vulnerability has been observed being actively exploited in the wild by threat actor group APT-29, targeting financial institutions in North America and Europe.`,

    entities: `Security researchers at Mandiant have identified a new threat actor group operating from Eastern Europe. 
    The group, tracked as APT-45, has been targeting healthcare organizations in the United States, Germany, and France. 
    The attacks originate from IP addresses in Russia and Ukraine. The group uses custom malware developed by a team 
    based in Moscow. Victims include major hospitals in New York, Berlin, and Paris. The campaign has been active 
    since January 2024.`,

    sentiment: `URGENT SECURITY ADVISORY: We have detected active exploitation of a critical vulnerability in our systems. 
    Immediate action is required. All customers are advised to change their passwords immediately and enable multi-factor 
    authentication. We take this incident extremely seriously and are working around the clock to address the situation.`,

    summary: `A sophisticated cyber espionage campaign has been discovered targeting government agencies and defense 
    contractors across multiple countries. The campaign, attributed to a nation-state actor, employs advanced persistent 
    threat tactics including custom malware, living-off-the-land techniques, and encrypted communication channels. 
    The attackers gained initial access through spear-phishing emails containing malicious documents that exploited a 
    previously unknown vulnerability in a popular document viewer. Once inside the network, the threat actors conducted 
    reconnaissance, moved laterally using stolen credentials, and exfiltrated sensitive documents over a period of 
    several months. The campaign was discovered when an organization's security team noticed unusual network traffic 
    patterns to an unknown external server. Forensic analysis revealed the presence of a previously unknown backdoor 
    that had been installed on multiple systems. The malware employed several anti-analysis techniques including 
    code obfuscation, anti-debugging checks, and encrypted payloads. Communication with command and control servers 
    was conducted using a custom protocol that mimicked legitimate HTTPS traffic. The threat actors demonstrated 
    sophisticated operational security, rotating infrastructure frequently and using proxy servers to mask their 
    true location. Attribution analysis suggests the campaign may be linked to a known threat group associated with 
    a foreign intelligence service. Organizations are advised to review their security posture, implement network 
    segmentation, and enhance monitoring for suspicious activity.`,

    classify: `An attacker is attempting to trick employees into revealing their login credentials by sending 
    fraudulent emails that appear to come from the IT department, directing them to a fake login page.`
};

// Initialize Application
async function initApp() {
    // Check compliance
    const complianceAccepted = localStorage.getItem('complianceAccepted');
    if (!complianceAccepted) {
        showComplianceModal();
    } else {
        AppState.complianceAccepted = true;
    }
    
    // Setup navigation
    setupNavigation();
    
    // Load models
    await loadModels();
}

// Load AI Models
async function loadModels() {
    updateModelStatus('loading', 'Loading AI models...');
    
    try {
        // Load sentiment analysis model
        updateModelStatus('loading', 'Loading sentiment analysis model...');
        AppState.models.sentiment = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english', {
            progress_callback: (progress) => updateProgress(progress)
        });
        
        // Load NER model
        updateModelStatus('loading', 'Loading entity recognition model...');
        AppState.models.ner = await pipeline('ner', 'Xenova/bert-base-NER', {
            progress_callback: (progress) => updateProgress(progress)
        });
        
        // Load summarization model
        updateModelStatus('loading', 'Loading summarization model...');
        AppState.models.summarization = await pipeline('summarization', 'Xenova/distilbart-cnn-6-6', {
            progress_callback: (progress) => updateProgress(progress)
        });
        
        // Load zero-shot classification
        updateModelStatus('loading', 'Loading classification model...');
        AppState.models.zeroShot = await pipeline('zero-shot-classification', 'Xenova/nli-deberta-v3-xsmall', {
            progress_callback: (progress) => updateProgress(progress)
        });
        
        AppState.isReady = true;
        updateModelStatus('ready', 'AI models ready');
        
    } catch (error) {
        console.error('Error loading models:', error);
        updateModelStatus('error', 'Error loading models');
        showNotification('Failed to load AI models. Please refresh the page.', 'error');
    }
}

// Update model status indicator
function updateModelStatus(status, text) {
    const indicator = document.getElementById('modelStatus');
    const statusText = document.getElementById('modelStatusText');
    
    indicator.className = 'status-indicator ' + status;
    statusText.textContent = text;
}

// Update loading progress
function updateProgress(progress) {
    if (progress.status === 'progress') {
        const fill = document.getElementById('progressFill');
        if (fill) {
            fill.style.width = `${Math.round(progress.progress || 0)}%`;
        }
    }
}

// Setup Navigation
function setupNavigation() {
    const navItems = document.querySelectorAll('.nav-item');
    
    navItems.forEach(item => {
        item.addEventListener('click', () => {
            const tabId = item.dataset.tab;
            switchTab(tabId);
        });
    });
}

// Switch Tab
function switchTab(tabId) {
    // Update nav items
    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.toggle('active', item.dataset.tab === tabId);
    });
    
    // Update tab content
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.toggle('active', tab.id === `${tabId}-tab`);
    });
}

// Load Sample Data
window.loadSampleData = function() {
    document.getElementById('threatInput').value = SAMPLE_DATA.threat;
    document.getElementById('entityInput').value = SAMPLE_DATA.entities;
    document.getElementById('sentimentInput').value = SAMPLE_DATA.sentiment;
    document.getElementById('summaryInput').value = SAMPLE_DATA.summary;
    document.getElementById('classifyInput').value = SAMPLE_DATA.classify;
    showNotification('Sample data loaded', 'success');
};

// Analyze Threat
window.analyzeThreat = async function() {
    if (!AppState.isReady) {
        showNotification('Models are still loading. Please wait.', 'warning');
        return;
    }
    
    const input = document.getElementById('threatInput').value.trim();
    if (!input) {
        showNotification('Please enter text to analyze', 'warning');
        return;
    }
    
    const btn = document.getElementById('analyzeBtn');
    btn.disabled = true;
    showProgress('Analyzing threat intelligence...');
    
    try {
        // Perform sentiment analysis
        const sentiment = await AppState.models.sentiment(input);
        
        // Perform classification
        const classification = await AppState.models.zeroShot(input, THREAT_CATEGORIES);
        
        // Generate analysis results
        const results = generateThreatAnalysis(input, sentiment, classification);
        displayAnalysisResults(results);
        
    } catch (error) {
        console.error('Analysis error:', error);
        showNotification('Error during analysis. Please try again.', 'error');
    } finally {
        btn.disabled = false;
        hideProgress();
    }
};

// Generate Threat Analysis
function generateThreatAnalysis(input, sentiment, classification) {
    // Determine threat level based on classification confidence
    const topCategory = classification.labels[0];
    const topScore = classification.scores[0];
    
    let threatLevel = 'low';
    let threatColor = 'success';
    let threatIcon = '✓';
    
    if (topScore > 0.7 && ['ransomware', 'data breach', 'zero-day vulnerability'].includes(topCategory)) {
        threatLevel = 'critical';
        threatColor = 'danger';
        threatIcon = '⚠️';
    } else if (topScore > 0.6 && ['malware', 'phishing', 'credential theft'].includes(topCategory)) {
        threatLevel = 'high';
        threatColor = 'warning';
        threatIcon = '⚡';
    } else if (topScore > 0.4) {
        threatLevel = 'medium';
        threatColor = 'info';
        threatIcon = 'ℹ️';
    }
    
    // Determine sentiment urgency
    const isUrgent = sentiment[0].label === 'NEGATIVE';
    
    return {
        threatLevel,
        threatColor,
        threatIcon,
        category: topCategory,
        confidence: (topScore * 100).toFixed(1),
        sentiment: sentiment[0].label,
        sentimentScore: (sentiment[0].score * 100).toFixed(1),
        isUrgent,
        recommendations: generateRecommendations(topCategory, threatLevel)
    };
}

// Generate Recommendations
function generateRecommendations(category, level) {
    const recommendations = {
        'malware': [
            'Isolate affected systems immediately',
            'Run comprehensive malware scan',
            'Check for lateral movement indicators'
        ],
        'phishing': [
            'Alert users about the phishing campaign',
            'Block malicious domains/URLs',
            'Review email gateway logs'
        ],
        'ransomware': [
            'Disconnect affected systems from network',
            'Do not pay ransom - contact law enforcement',
            'Restore from clean backups'
        ],
        'data breach': [
            'Activate incident response plan',
            'Notify affected parties per regulations',
            'Preserve evidence for investigation'
        ],
        'credential theft': [
            'Force password reset for affected accounts',
            'Enable multi-factor authentication',
            'Review access logs for unauthorized activity'
        ]
    };
    
    return recommendations[category] || [
        'Review and assess the threat intelligence',
        'Update security controls as needed',
        'Monitor for indicators of compromise'
    ];
}

// Display Analysis Results
function displayAnalysisResults(results) {
    const output = document.getElementById('analysisOutput');
    
    output.innerHTML = `
        <div class="threat-level threat-${results.threatLevel}">