File size: 9,602 Bytes
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
315
316
317
318
import { useState, useEffect, useCallback } from 'react';

// Helper function for random values
const rand = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min;
const randFloat = (min: number, max: number) => (Math.random() * (max - min) + min).toFixed(1);

// Types for security data
export interface SecurityEvent {
  id: string;
  time: string;
  event: string;
  severity: 'info' | 'warning' | 'critical';
  source?: string;
}

export interface ThreatData {
  level: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  score: number;
  activeThreats: number;
  blockedAttacks: number;
  lastIncident: string;
}

export interface SOCMetrics {
  activeIncidents: number;
  criticalAlerts: number;
  warningAlerts: number;
  infoAlerts: number;
  resolvedToday: number;
  mttd: number;
  mttr: number;
}

export interface NetworkMetrics {
  inboundGbps: number;
  outboundGbps: number;
  packetsPerSec: number;
  activeConnections: number;
  blockedIPs: number;
  ddosStatus: 'normal' | 'elevated' | 'attack';
}

export interface MalwareMetrics {
  detected24h: number;
  ransomware: number;
  trojans: number;
  quarantined: number;
  cleaned: number;
}

export interface FirewallMetrics {
  status: 'active' | 'degraded' | 'offline';
  blocked24h: number;
  allowed24h: number;
  rulesActive: number;
  lastUpdate: string;
}

// Event generators
const eventTemplates = {
  critical: [
    'Ransomware detected on endpoint WKS-{id}',
    'Brute force attack from {ip}',
    'Zero-day exploit attempt detected',
    'Data exfiltration detected to {ip}',
    'Privilege escalation on SRV-{id}',
    'C2 communication blocked',
    'Credential theft attempt detected',
    'SQL injection attack on /api/users',
  ],
  warning: [
    'Multiple failed logins from {ip}',
    'Unusual outbound traffic pattern',
    'New device connected: {device}',
    'Anomalous user behavior: {user}',
    'Port scan detected from {ip}',
    'Suspicious DNS query to {domain}',
    'Certificate expiring in {days} days',
    'High CPU usage on firewall node',
  ],
  info: [
    'Security scan completed successfully',
    'Signature database updated',
    'User {user} logged in from new location',
    'Backup verification complete',
    'Policy update applied',
    'Scheduled vulnerability scan started',
    'System health check passed',
    'New IOC feed synchronized',
  ],
};

const generateIP = () => `${rand(1, 223)}.${rand(0, 255)}.${rand(0, 255)}.${rand(1, 254)}`;
const generateEvent = (severity: 'info' | 'warning' | 'critical'): SecurityEvent => {
  const templates = eventTemplates[severity];
  let event = templates[rand(0, templates.length - 1)];
  
  event = event
    .replace('{id}', String(rand(1, 99)).padStart(2, '0'))
    .replace('{ip}', generateIP())
    .replace('{device}', `Device-${rand(100, 999)}`)
    .replace('{user}', ['admin', 'john.doe', 'api-service', 'backup-svc'][rand(0, 3)])
    .replace('{domain}', ['suspicious.xyz', 'malware.io', 'c2server.net'][rand(0, 2)])
    .replace('{days}', String(rand(5, 30)));

  const now = new Date();
  return {
    id: `evt-${Date.now()}-${rand(1000, 9999)}`,
    time: `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`,
    event,
    severity,
    source: generateIP(),
  };
};

// Main hook
export const useSecuritySimulation = (updateInterval = 3000) => {
  const [threatData, setThreatData] = useState<ThreatData>({
    level: 'LOW',
    score: rand(15, 35),
    activeThreats: rand(0, 3),
    blockedAttacks: rand(800, 1500),
    lastIncident: '2h ago',
  });

  const [socMetrics, setSOCMetrics] = useState<SOCMetrics>({
    activeIncidents: rand(2, 5),
    criticalAlerts: rand(1, 3),
    warningAlerts: rand(8, 15),
    infoAlerts: rand(30, 60),
    resolvedToday: rand(35, 55),
    mttd: parseFloat(randFloat(3, 6)),
    mttr: rand(15, 25),
  });

  const [networkMetrics, setNetworkMetrics] = useState<NetworkMetrics>({
    inboundGbps: parseFloat(randFloat(1.5, 3.5)),
    outboundGbps: parseFloat(randFloat(1.0, 2.5)),
    packetsPerSec: rand(800000, 1400000),
    activeConnections: rand(10000, 50000),
    blockedIPs: rand(10000, 15000),
    ddosStatus: 'normal',
  });

  const [malwareMetrics, setMalwareMetrics] = useState<MalwareMetrics>({
    detected24h: rand(40, 80),
    ransomware: rand(1, 5),
    trojans: rand(8, 20),
    quarantined: rand(30, 60),
    cleaned: rand(20, 40),
  });

  const [firewallMetrics, setFirewallMetrics] = useState<FirewallMetrics>({
    status: 'active',
    blocked24h: rand(1000, 2000),
    allowed24h: rand(40000, 60000),
    rulesActive: rand(2000, 3000),
    lastUpdate: 'Just now',
  });

  const [events, setEvents] = useState<SecurityEvent[]>([
    generateEvent('critical'),
    generateEvent('warning'),
    generateEvent('info'),
  ]);

  const [liveAttacks, setLiveAttacks] = useState(rand(700, 1000));
  const [vpnUsers, setVpnUsers] = useState(rand(200, 300));
  const [complianceScore, setComplianceScore] = useState(rand(82, 95));

  // Update functions
  const updateThreatData = useCallback(() => {
    setThreatData(prev => {
      const newScore = Math.max(0, Math.min(100, prev.score + rand(-5, 5)));
      const newLevel: ThreatData['level'] = 
        newScore > 75 ? 'CRITICAL' : 
        newScore > 50 ? 'HIGH' : 
        newScore > 25 ? 'MEDIUM' : 'LOW';
      
      return {
        ...prev,
        score: newScore,
        level: newLevel,
        activeThreats: Math.max(0, prev.activeThreats + rand(-1, 1)),
        blockedAttacks: prev.blockedAttacks + rand(1, 10),
      };
    });
  }, []);

  const updateSOCMetrics = useCallback(() => {
    setSOCMetrics(prev => ({
      ...prev,
      activeIncidents: Math.max(0, prev.activeIncidents + rand(-1, 2)),
      criticalAlerts: Math.max(0, prev.criticalAlerts + rand(-1, 1)),
      warningAlerts: Math.max(0, prev.warningAlerts + rand(-2, 3)),
      resolvedToday: prev.resolvedToday + rand(0, 2),
      mttd: parseFloat(randFloat(3, 6)),
      mttr: rand(12, 30),
    }));
  }, []);

  const updateNetworkMetrics = useCallback(() => {
    setNetworkMetrics(prev => {
      const ddosChance = Math.random();
      return {
        ...prev,
        inboundGbps: parseFloat(randFloat(1.5, 4.0)),
        outboundGbps: parseFloat(randFloat(1.0, 3.0)),
        packetsPerSec: rand(700000, 1500000),
        activeConnections: rand(8000, 55000),
        blockedIPs: prev.blockedIPs + rand(1, 5),
        ddosStatus: ddosChance > 0.95 ? 'attack' : ddosChance > 0.85 ? 'elevated' : 'normal',
      };
    });
  }, []);

  const updateMalwareMetrics = useCallback(() => {
    setMalwareMetrics(prev => ({
      ...prev,
      detected24h: Math.max(0, prev.detected24h + rand(-2, 5)),
      ransomware: Math.max(0, prev.ransomware + rand(-1, 1)),
      trojans: Math.max(0, prev.trojans + rand(-1, 2)),
      quarantined: prev.quarantined + rand(0, 3),
      cleaned: prev.cleaned + rand(0, 2),
    }));
  }, []);

  const updateFirewallMetrics = useCallback(() => {
    setFirewallMetrics(prev => ({
      ...prev,
      blocked24h: prev.blocked24h + rand(1, 15),
      allowed24h: prev.allowed24h + rand(10, 50),
      lastUpdate: 'Just now',
    }));
  }, []);

  const addNewEvent = useCallback(() => {
    const severityRoll = Math.random();
    const severity: 'info' | 'warning' | 'critical' = 
      severityRoll > 0.95 ? 'critical' : 
      severityRoll > 0.7 ? 'warning' : 'info';
    
    const newEvent = generateEvent(severity);
    setEvents(prev => [newEvent, ...prev].slice(0, 20));
  }, []);

  // Main update effect
  useEffect(() => {
    const interval = setInterval(() => {
      updateThreatData();
      updateSOCMetrics();
      updateNetworkMetrics();
      updateMalwareMetrics();
      updateFirewallMetrics();
      
      // 30% chance to add a new event
      if (Math.random() > 0.7) {
        addNewEvent();
      }

      setLiveAttacks(prev => Math.max(500, Math.min(1500, prev + rand(-50, 50))));
      setVpnUsers(prev => Math.max(100, Math.min(400, prev + rand(-10, 10))));
      setComplianceScore(prev => Math.max(75, Math.min(100, prev + rand(-1, 1))));
    }, updateInterval);

    return () => clearInterval(interval);
  }, [updateInterval, updateThreatData, updateSOCMetrics, updateNetworkMetrics, updateMalwareMetrics, updateFirewallMetrics, addNewEvent]);

  return {
    threatData,
    socMetrics,
    networkMetrics,
    malwareMetrics,
    firewallMetrics,
    events,
    liveAttacks,
    vpnUsers,
    complianceScore,
    addNewEvent,
  };
};

// Context for sharing simulation data across widgets
import { createContext, useContext, ReactNode } from 'react';

interface SecuritySimulationContextType {
  threatData: ThreatData;
  socMetrics: SOCMetrics;
  networkMetrics: NetworkMetrics;
  malwareMetrics: MalwareMetrics;
  firewallMetrics: FirewallMetrics;
  events: SecurityEvent[];
  liveAttacks: number;
  vpnUsers: number;
  complianceScore: number;
}

const SecuritySimulationContext = createContext<SecuritySimulationContextType | null>(null);

export const SecuritySimulationProvider = ({ children }: { children: ReactNode }) => {
  const simulation = useSecuritySimulation(2000);
  
  return (
    <SecuritySimulationContext.Provider value={simulation}>
      {children}
    </SecuritySimulationContext.Provider>
  );
};

export const useSecurityData = () => {
  const context = useContext(SecuritySimulationContext);
  if (!context) {
    throw new Error('useSecurityData must be used within SecuritySimulationProvider');
  }
  return context;
};