File size: 34,198 Bytes
a1a9b32
 
a727c9c
 
 
 
 
 
 
 
a1a9b32
a727c9c
 
a1a9b32
 
a727c9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1a9b32
 
a727c9c
 
 
 
 
 
 
 
36d97f7
a727c9c
 
 
36d97f7
 
 
0dc4267
36d97f7
 
 
 
0dc4267
 
36d97f7
 
0dc4267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36d97f7
 
 
 
 
a727c9c
 
36d97f7
 
 
a727c9c
 
 
36d97f7
 
 
a727c9c
 
 
 
36d97f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a727c9c
 
 
 
 
adc8fc0
a727c9c
 
 
adc8fc0
 
a727c9c
 
 
 
adc8fc0
 
 
0dc4267
 
 
 
 
 
 
 
 
adc8fc0
 
0dc4267
 
 
 
 
 
 
 
 
 
a727c9c
 
 
 
 
 
 
 
adc8fc0
 
 
 
 
 
 
 
 
 
 
a727c9c
 
 
 
 
adc8fc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d40d11
adc8fc0
6d40d11
adc8fc0
6d40d11
 
 
 
 
 
 
 
adc8fc0
 
6d40d11
 
 
 
 
 
 
 
 
 
 
adc8fc0
 
 
 
6d40d11
adc8fc0
6d40d11
 
 
adc8fc0
 
 
6d40d11
 
 
adc8fc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a727c9c
 
 
a1a9b32
a727c9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1a9b32
a727c9c
a1a9b32
a727c9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1a9b32
 
a727c9c
a1a9b32
a727c9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1a9b32
 
a727c9c
 
 
 
 
a1a9b32
 
78a8a45
36d97f7
a727c9c
36d97f7
 
 
 
 
 
 
 
 
a727c9c
 
36d97f7
 
 
a727c9c
36d97f7
a727c9c
 
78a8a45
36d97f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a727c9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78a8a45
 
a727c9c
 
 
78a8a45
a727c9c
 
 
 
 
 
78a8a45
 
a727c9c
 
 
 
 
 
 
 
 
 
 
 
 
 
78a8a45
a727c9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f1e791
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a727c9c
 
78a8a45
a727c9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adc8fc0
 
 
 
 
 
 
 
6d40d11
adc8fc0
6d40d11
adc8fc0
a727c9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78a8a45
a1a9b32
0dc4267
4f1e791
 
 
 
 
 
 
0dc4267
 
 
 
 
 
4f1e791
 
 
 
 
 
 
 
 
 
 
 
 
 
0dc4267
 
4f1e791
 
0dc4267
4f1e791
 
 
0dc4267
4f1e791
0dc4267
 
 
 
 
 
 
 
 
4f1e791
0dc4267
4f1e791
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dc4267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f1e791
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dc4267
4f1e791
 
 
 
 
 
 
 
0dc4267
 
4f1e791
 
 
 
 
0dc4267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a727c9c
4f1e791
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dc4267
 
 
 
a727c9c
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
const express = require('express');
const cors = require('cors');
const si = require('systeminformation');
const { exec } = require('child_process');
const fs = require('fs').promises;
const path = require('path');
const WebSocket = require('ws');
const http = require('http');
const rateLimit = require('express-rate-limit');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const port = 3000;

// Middleware sécurité
app.use(cors());
app.use(express.json());

// Rate limiting pour protéger l'API
const limiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100 // limite chaque IP à 100 requêtes par fenêtre
});
app.use(limiter);

// État temps réel du système
let systemState = {
    threatsBlocked: 0,
    serverHealth: 100,
    networkTraffic: 0,
    criticalAlerts: 0,
    activeConnections: [],
    blockedIPs: new Set(),
    systemLogs: []
};

// Configuration des fichiers de log à surveiller (adapter selon OS)
const LOG_FILES = {
    auth: process.platform === 'win32' ? null : '/var/log/auth.log',
    syslog: process.platform === 'win32' ? null : '/var/log/syslog',
    nginx: '/var/log/nginx/access.log',
    apache: '/var/log/apache2/access.log'
};

// Surveillance temps réel des connexions réseau suspectes avec détection exfiltration
async function monitorNetworkConnections() {
    try {
        const connections = await si.networkConnections();
        const now = new Date().toISOString();
        
        // Détection heuristique avancée
        const suspiciousPorts = [4444, 5555, 6666, 31337, 12345, 9001, 9050, 1080, 9051]; // Tor, SOCKS, C2
        const largeTransfers = connections.filter(conn => {
            // Détection basée sur la durée et la taille (si disponible)
            return conn.state === 'ESTABLISHED' && 
                   (suspiciousPorts.includes(conn.peerPort) || 
                    conn.peerPort > 50000 || // Ports éphémères suspects
                    conn.localPort === 445 || conn.localPort === 139); // SMB exfiltration
        });
        
        // NOUVEAU: Détection scans de ports et reconnaissance
        const scanAttempts = connections.filter(conn => {
            return conn.state === 'SYN_SENT' && 
                   connections.filter(c => c.peerAddress === conn.peerAddress).length > 10;
        });
        
        if (scanAttempts.length > 0) {
            broadcastAlert({
                type: 'PORT_SCAN_DETECTED',
                data: scanAttempts,
                timestamp: now,
                severity: 'HIGH',
                description: `Scan de ports détecté depuis ${scanAttempts[0].peerAddress}`
            });
        }
        
        // Détection exfiltration massive (connexions longues + gros volumes)
        const exfiltrationCandidates = connections.filter(conn => {
            return conn.state === 'ESTABLISHED' && 
                   (conn.peerPort === 443 || conn.peerPort === 80) &&
                   Math.random() > 0.95; // Simulation detection comportementale
        });
        
        if (largeTransfers.length > 0) {
            systemState.criticalAlerts += largeTransfers.length;
            largeTransfers.forEach(conn => {
                broadcastAlert({
                    type: 'SUSPICIOUS_CONNECTION',
                    data: conn,
                    timestamp: now,
                    severity: 'HIGH',
                    details: `Port suspect ${conn.peerPort} détecté - Possible canal C2`
                });
            });
        }
        
        // Alerte spéciale exfiltration
        if (exfiltrationCandidates.length > 0 && Math.random() > 0.7) {
            broadcastAlert({
                type: 'EXFILTRATION_DETECTED',
                data: {
                    connections: exfiltrationCandidates,
                    estimatedVolume: Math.floor(Math.random() * 500) + ' MB',
                    destination: conn.peerAddress
                },
                timestamp: now,
                severity: 'CRITICAL',
                description: 'Volume anormal de données sortantes détecté - Possible exfiltration FICoba/TAJ'
            });
        }
        
        systemState.activeConnections = connections.slice(0, 50);
    } catch (error) {
        console.error('Erreur surveillance réseau:', error);
    }
}

// Surveillance des processus + Détection Exfiltration de données (TAJ/FPR)
async function monitorProcesses() {
    try {
        const processes = await si.processes();
        
        // Détection classique: crypto-mining ou surcharge
        const suspiciousProcs = processes.list.filter(proc => {
            return proc.cpu > 80 || (proc.name.includes('crypt') && proc.cpu > 20);
        });
        
        // NOUVEAU: Détection exfiltration massive de fichiers (type attaque Ministère Intérieur)
        const fileAccessProcs = processes.list.filter(proc => {
            // Détection processus accédant à de gros volumes de fichiers simultanément
            const suspiciousPatterns = ['tar', 'zip', '7z', 'rar', 'scp', 'rsync', 'ftp', 'sftp', 'curl', 'wget', 'nc', 'netcat'];
            return suspiciousPatterns.some(p => proc.name.toLowerCase().includes(p)) && proc.cpu > 5;
        });
        
        // NOUVEAU: Détection injection mémoire (process hollowing)
        const injectedProcs = processes.list.filter(proc => {
            // Processus système avec utilisation CPU anormale ou chemins suspects
            const systemProcs = ['lsass.exe', 'svchost.exe', 'csrss.exe', 'services.exe'];
            return systemProcs.includes(proc.name.toLowerCase()) && proc.cpu > 30;
        });
        
        if (injectedProcs.length > 0) {
            broadcastAlert({
                type: 'PROCESS_INJECTION_DETECTED',
                data: injectedProcs,
                timestamp: new Date().toISOString(),
                severity: 'CRITICAL',
                description: 'Injection de processus système détectée - Technique Mimikatz/LSASS probable'
            });
        }
        
        if (suspiciousProcs.length > 0) {
            broadcastAlert({
                type: 'PROCESS_ALERT',
                data: suspiciousProcs,
                timestamp: new Date().toISOString(),
                severity: 'CRITICAL'
            });
        }
        
        // Alerte spéciale pour exfiltration potentielle
        if (fileAccessProcs.length > 0) {
            broadcastAlert({
                type: 'DATA_EXFILTRATION_DETECTED',
                data: fileAccessProcs,
                timestamp: new Date().toISOString(),
                severity: 'CRITICAL',
                description: 'Processus de compression/transfert massif détecté - Risque extraction TAJ/FPR'
            });
        }
    } catch (error) {
        console.error('Erreur surveillance processus:', error);
    }
}

// NOUVEAU: Surveillance Email/Messagerie (Vector attaque Ministère Intérieur)
async function monitorEmailSecurity() {
    // Surveillance logs email suspects (si disponible)
    try {
        // Simulation de détection d'accès anormaux à des boîtes mail professionnelles
        const suspiciousLogins = [
            { user: 'agent.interieur@gouv.fr', ip: '185.220.101.42', time: new Date().toISOString(), country: 'RU' },
            { user: 'admin.taj@interieur.fr', ip: '198.51.100.15', time: new Date().toISOString(), country: 'CN' }
        ];
        
        suspiciousLogins.forEach(login => {
            if (Math.random() > 0.7) { // Simulation aléatoire pour démo
                broadcastAlert({
                    type: 'EMAIL_COMPROMISE',
                    data: login,
                    timestamp: new Date().toISOString(),
                    severity: 'CRITICAL',
                    description: `Connexion suspecte via messagerie: ${login.user} depuis ${login.country}`
                });
            }
        });
    } catch (error) {
        console.error('Erreur surveillance email:', error);
    }
}

// NOUVEAU: Surveillance Fichiers Sensibles (TAJ/FPR + FICOBA/DGFiP)
async function monitorSensitiveFiles() {
    // Simulation de monitoring d'accès aux fichiers sensibles administration française
    const sensitiveFiles = [
        { name: 'TAJ_2024.db', path: '/secure/taj/', type: 'POLICE' },
        { name: 'FPR_National.dat', path: '/secure/fpr/', type: 'POLICE' },
        { name: 'Fichiers_Police.enc', path: '/secure/police/', type: 'POLICE' },
        // NOUVEAU: Fichiers DGFiP/Bercy suite piratage Ficoba janvier 2024
        { name: 'FICOBA_National.db', path: '/secure/dgfip/ficoba/', type: 'FINANCES', records: '46M' },
        { name: 'Comptes_Bancaires.csv', path: '/secure/dgfip/exports/', type: 'FINANCES', records: '1.2M' },
        { name: 'Coffres_Forts.dat', path: '/secure/dgfip/', type: 'FINANCES' },
        { name: 'RIB_Entreprises_2024.sql', path: '/secure/bercy/', type: 'FINANCES' }
    ];
    
    // Détection accès massif ou exfiltration fichiers financiers (type Ficoba)
    const financeFiles = sensitiveFiles.filter(f => f.type === 'FINANCES');
    const policeFiles = sensitiveFiles.filter(f => f.type === 'POLICE');
    
    // Aléatoire: soit attaque police, soit finances
    const targetSet = Math.random() > 0.6 ? financeFiles : policeFiles;
    
    if (Math.random() > 0.80) {
        const targetFile = targetSet[Math.floor(Math.random() * targetSet.length)];
        const isFinance = targetFile.type === 'FINANCES';
        
        broadcastAlert({
            type: 'SENSITIVE_FILE_ACCESS',
            data: {
                file: targetFile.name,
                path: targetFile.path,
                user: 'inconnu',
                volume: Math.floor(Math.random() * 5000) + ' requêtes/min',
                records: targetFile.records || 'N/A',
                type: targetFile.type
            },
            timestamp: new Date().toISOString(),
            severity: 'CRITICAL',
            description: isFinance 
                ? `🚨 ALERTE FICoba/DGFiP: Accès massif détecté sur ${targetFile.name} - Risque exfiltration données bancaires (${targetFile.records} comptes potentiels)`
                : `ALERTE ROUGE: Accès anormal au fichier ${targetFile.name} - Possible extraction TAJ/FPR`
        });
    }
}

// NOUVEAU: Détection Codes d'accès volés (Credentials)
async function monitorCredentialTheft() {
    // Détection d'utilisation de codes d'accès compromis
    const compromisedAttempts = [
        { type: 'VPN', user: 'admin_taj', source: 'IP_anonymizer' },
        { type: 'RDP', user: 'agent_police', source: 'Tor_exit_node' }
    ];
    
    compromisedAttempts.forEach(attempt => {
        if (Math.random() > 0.9) {
            broadcastAlert({
                type: 'CREDENTIAL_STOLEN',
                data: attempt,
                timestamp: new Date().toISOString(),
                severity: 'HIGH',
                description: `Tentative avec identifiants potentiellement volés: ${attempt.user}`
            });
        }
    });
}

// Lecture des logs d'authentification (détection brute force)
async function monitorAuthLogs() {
    if (process.platform === 'win32') return; // Skip sur Windows pour l'instant
    
    try {
        const authLog = await fs.readFile(LOG_FILES.auth, 'utf8').catch(() => '');
        const lines = authLog.split('\n').slice(-100); // 100 dernières lignes
        
        const failedAttempts = lines.filter(line => 
            line.includes('Failed password') || 
            line.includes('authentication failure')
        );
        
        if (failedAttempts.length > 5) {
            broadcastAlert({
                type: 'BRUTE_FORCE_DETECTED',
                count: failedAttempts.length,
                timestamp: new Date().toISOString(),
                severity: 'CRITICAL',
                ips: extractIPs(failedAttempts)
            });
        }
    } catch (error) {
        // Silencieux si fichier inaccessible
    }
}

function extractIPs(lines) {
    const ipRegex = /\b(?:\d{1,3}\.){3}\d{1,3}\b/g;
    const ips = [];
    lines.forEach(line => {
        const matches = line.match(ipRegex);
        if (matches) ips.push(...matches);
    });
    return [...new Set(ips)];
}

// API Temps réel - Statistiques système réelles
app.get('/api/stats', async (req, res) => {
    try {
        const [networkStats, cpu, mem] = await Promise.all([
            si.networkStats(),
            si.currentLoad(),
            si.mem()
        ]);
        
        const traffic = networkStats[0] ? 
            ((networkStats[0].tx_sec + networkStats[0].rx_sec) / 1024 / 1024).toFixed(2) : 0;
        
        const health = Math.max(0, 100 - (cpu.currentload * 0.8) - ((mem.used / mem.total) * 20));
        
        res.json({
            threatsBlocked: systemState.threatsBlocked,
            serverHealth: parseFloat(health.toFixed(1)),
            networkTraffic: parseFloat(traffic),
            criticalAlerts: systemState.criticalAlerts,
            cpuLoad: cpu.currentload,
            memoryUsed: ((mem.used / mem.total) * 100).toFixed(1)
        });
    } catch (error) {
        res.status(500).json({ error: 'Erreur récupération stats' });
    }
});

// API Logs en temps réel (depuis la mémoire pour la rapidité)
app.get('/api/log', (req, res) => {
    const recentLogs = systemState.systemLogs.slice(-20);
    if (recentLogs.length > 0) {
        const log = recentLogs[Math.floor(Math.random() * recentLogs.length)];
        res.json(log);
    } else {
        // Fallback si pas encore de logs réels
        res.json({
            msg: 'Surveillance active - Aucune menace détectée',
            type: 'info',
            ip: '127.0.0.1',
            time: new Date().toLocaleTimeString('fr-FR', { hour12: false })
        });
    }
});

// API Géolocalisation des menaces (simulation avec données réelles possibles via GeoIP)
app.get('/api/geo', async (req, res) => {
    // Ici vous intégreriez une vraie base GeoIP ou API AbuseIPDB
    const countries = ['RU', 'CN', 'KP', 'IR', 'BR', 'US', 'FR'];
    const types = ['Port Scan', 'SSH Brute', 'SQL Injection', 'DDoS', 'Malware C2'];
    
    res.json({
        country: countries[Math.floor(Math.random() * countries.length)],
        type: types[Math.floor(Math.random() * types.length)],
        ip: `${Math.floor(Math.random()*255)}.${Math.floor(Math.random()*255)}.${Math.floor(Math.random()*255)}.${Math.floor(Math.random()*255)}`,
        timestamp: new Date().toISOString(),
        real: false // Mettre à true quand connecté à AbuseIPDB
    });
});

// API Vulnérabilités avec MITRE ATT&CK mapping
app.get('/api/vulns', async (req, res) => {
    // Données réalistes de vulnérabilités récentes
    const cves = [
        { id: 'CVE-2024-21626', component: 'Docker/runc', score: 9.8, status: 'Non corrigé', mitre: 'TA0004', desc: 'Container escape via /proc' },
        { id: 'CVE-2023-36874', component: 'Windows Error Reporting', score: 7.8, status: 'Analyse', mitre: 'TA0005', desc: 'LPE via WER' },
        { id: 'CVE-2024-21413', component: 'Microsoft Outlook', score: 9.8, status: 'Non corrigé', mitre: 'TA0001', desc: 'RCE via lien malveillant' },
        { id: 'CVE-2020-1472', component: 'Netlogon/Zerologon', score: 10.0, status: 'Critique', mitre: 'TA0006', desc: 'Élévation privilèges AD' },
        { id: 'CVE-2024-FICOBa', component: 'DGFiP FICoba API', score: 9.1, status: 'Actif', mitre: 'TA0010', desc: 'Exfiltration données bancaires' }
    ];
    
    res.json({
        stats: {
            critical: cves.filter(c => c.score >= 9.0).length,
            high: cves.filter(c => c.score >= 7.0 && c.score < 9.0).length,
            medium: cves.filter(c => c.score >= 5.0 && c.score < 7.0).length
        },
        list: cves
    });
});

// API Dark Web Monitor (simulation de feeds)
app.get('/api/darkweb', async (req, res) => {
    const leaks = [
        {
            source: 'XXS_RU_Club',
            type: 'FICoba Database',
            volume: '1.2M records',
            target: 'DGFiP',
            confidence: 'High',
            price: '0.5 BTC',
            date: '2025-01-29',
            iocs: ['185.220.101.42', 'ms-office-update.org']
        },
        {
            source: 'Telegram_Bot',
            type: 'VPN Credentials',
            volume: '120 records',
            target: 'Ministère Intérieur',
            confidence: 'Medium',
            price: 'Free',
            date: '2025-01-28',
            iocs: ['t.me/steal_data_bot']
        }
    ];
    
    res.json({ leaks, timestamp: new Date().toISOString() });
});

// API Infrastructure - Données réelles des serveurs
app.get('/api/infra', async (req, res) => {
    try {
        const [cpu, mem, temp, processes] = await Promise.all([
            si.currentLoad(),
            si.mem(),
            si.cpuTemperature(),
            si.processes()
        ]);
        
        const servers = [
            {
                id: 1,
                name: 'Firewall-Principal',
                status: 'Online',
                load: Math.floor(cpu.currentload),
                ram: Math.floor((mem.used / 1024 / 1024 / 1024)),
                temp: Math.floor(temp.main || 45),
                processes: processes.all
            },
            {
                id: 2,
                name: 'Serveur-Base-Données',
                status: mem.used > mem.total * 0.9 ? 'Warning' : 'Online',
                load: Math.floor(cpu.currentload * 1.2) % 100,
                ram: Math.floor((mem.used / 1024 / 1024 / 1024)) + 2,
                temp: Math.floor((temp.main || 45) + 5),
                processes: processes.running
            },
            {
                id: 3,
                name: 'Node-Securite-IA',
                status: 'Online',
                load: Math.floor(cpu.currentload * 0.8),
                ram: Math.floor((mem.used / 1024 / 1024 / 1024) * 0.5),
                temp: Math.floor((temp.main || 45) - 2),
                processes: processes.blocked
            }
        ];
        
        res.json({ servers });
    } catch (error) {
        res.status(500).json({ error: 'Erreur monitoring infrastructure' });
    }
});

// Contrôle réseau avec exécution réelle (nécessite sudo/root)
app.post('/api/network/control', async (req, res) => {
    const { interface, action } = req.body;
    const isOn = action === 'on';
    
    // Vérification des entrées pour sécurité
    const allowedInterfaces = ['wifi', 'bluetooth', 'ethernet'];
    if (!allowedInterfaces.includes(interface)) {
        return res.status(400).json({ error: 'Interface non autorisée' });
    }
    
    let command = '';
    const osType = process.platform;
    
    if (osType === 'linux') {
        if (interface === 'wifi') {
            command = isOn ? 'nmcli radio wifi on' : 'nmcli radio wifi off';
        } else if (interface === 'bluetooth') {
            command = isOn ? 'rfkill unblock bluetooth' : 'rfkill block bluetooth';
        } else if (interface === 'ethernet') {
            command = isOn ? 'ip link set eth0 up' : 'ip link set eth0 down';
        }
    } else if (osType === 'win32') {
        const iface = interface === 'wifi' ? 'Wi-Fi' : (interface === 'ethernet' ? 'Ethernet' : 'Bluetooth');
        command = isOn ? `netsh interface set interface "${iface}" enable` : 
                        `netsh interface set interface "${iface}" disable`;
    }
    
    // Exécution réelle avec privilèges (décommenter quand prêt pour production)
    /*
    exec(command, { sudo: true }, (error, stdout, stderr) => {
        if (error) {
            console.error(`Erreur ${interface}:`, error);
            return res.json({ 
                success: false, 
                error: 'Permissions insuffisantes - Exécuter avec sudo',
                simulated: true 
            });
        }
        broadcastAlert({
            type: 'NETWORK_CHANGE',
            interface: interface,
            action: action,
            timestamp: new Date().toISOString()
        });
        res.json({ success: true, interface: interface, state: action });
    });
    */
    
    // Exécution réelle de la commande système
    exec(command, (error, stdout, stderr) => {
        if (error) {
            console.error(`Erreur ${interface}:`, error);
            // Fallback en mode simulation si pas de droits
            res.json({ 
                success: true, 
                simulated: true, 
                warning: 'Permissions insuffisantes - Mode simulation activé',
                message: `${interface} ${action}`,
                command: command
            });
            return;
        }
        
        broadcastAlert({
            type: 'NETWORK_CHANGE',
            interface: interface,
            action: action,
            timestamp: new Date().toISOString()
        });
        
        res.json({ 
            success: true, 
            simulated: false, 
            message: `${interface} ${action} - Exécuté avec succès`,
            command: command
        });
    });
});

// WebSocket pour alertes instantanées
function broadcastAlert(data) {
    wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(JSON.stringify(data));
        }
    });
}

// Gestion des connexions WebSocket
wss.on('connection', (ws) => {
    console.log('Client SOC connecté');
    
    ws.send(JSON.stringify({
        type: 'CONNECTED',
        message: 'Connexion temps réel établie',
        timestamp: new Date().toISOString()
    }));
    
    ws.on('close', () => {
        console.log('Client déconnecté');
    });
});

// Boucle de surveillance continue
setInterval(monitorNetworkConnections, 2000); // Toutes les 2 secondes
setInterval(monitorProcesses, 5000); // Toutes les 5 secondes
setInterval(monitorAuthLogs, 10000); // Toutes les 10 secondes

// NOUVEAUX: Surveillance spécifique attaques administrations
setInterval(monitorEmailSecurity, 8000); // Email compromise detection
setInterval(monitorSensitiveFiles, 6000); // Fichiers TAJ/FPR
setInterval(monitorCredentialTheft, 12000); // Codes d'accès volés

console.log('🔴 MODULES SPÉCIAUX ACTIVÉS:');
console.log('   📧 Surveillance Messageries Professionnelles');
console.log('   🗄️  Protection Fichiers TAJ/FPR');
console.log('   💳 Protection FICoba/DGFiP (Données Bancaires)');
console.log('   🔑 Détection Codes d\'Accès Compromis');
console.log('   🏦 Détection Exfiltration Données Financières');

// Endpoint pour blocage IP (intégration avec iptables/Windows Firewall)
app.post('/api/block-ip', (req, res) => {
    const { ip, reason } = req.body;
    if (!ip || !/^(\d{1,3}\.){3}\d{1,3}$/.test(ip)) {
        return res.status(400).json({ error: 'IP invalide' });
    }
    
    systemState.blockedIPs.add(ip);
    systemState.threatsBlocked++;
    
    // Ici: commande réelle pour bloquer l'IP au niveau firewall
    // Linux: iptables -A INPUT -s ${ip} -j DROP
    // Windows: netsh advfirewall firewall add rule name="Block ${ip}" dir=in action=block remoteip=${ip}
    
    broadcastAlert({
        type: 'IP_BLOCKED',
        ip: ip,
        reason: reason || 'Suspicious activity',
        timestamp: new Date().toISOString()
    });
    
    res.json({ success: true, ip: ip, totalBlocked: systemState.blockedIPs.size });
});

// NOUVEAU: Surveillance USB et Périphériques (Data Loss Prevention matériel)
let usb;
try {
    usb = require('usb');
    console.log('✅ Module USB chargé avec succès');
} catch (e) {
    console.log('⚠️  Module USB non disponible - Mode simulation');
}

let authorizedUSBDevices = new Set();
let blockedUSBDevices = new Set();

async function monitorUSBDevices() {
    try {
        // Surveillance native USB si module disponible
        if (usb) {
            const devices = usb.getDeviceList();
            devices.forEach(device => {
                const deviceId = `${device.deviceDescriptor.idVendor}:${device.deviceDescriptor.idProduct}`;
                const deviceInfo = {
                    vendor: device.deviceDescriptor.idVendor.toString(16),
                    model: device.deviceDescriptor.idProduct.toString(16),
                    type: 'usb-native'
                };
                checkUSBDevice(deviceId, deviceInfo);
            });
        }
        
        // Surveillance des montages de périphériques (Linux)
        if (process.platform === 'linux') {
            exec('lsblk -J 2>/dev/null || echo "[]"', (error, stdout) => {
                if (error || !stdout) return;
                try {
                    const result = JSON.parse(stdout);
                    const devices = result.blockdevices || [];
                    devices.forEach(dev => {
                        if (dev.type === 'disk' && dev.rm === true) { // removable
                            const deviceId = `${dev.vendor || 'Unknown'}:${dev.model || 'Unknown'}`;
                            checkUSBDevice(deviceId, dev);
                        }
                    });
                } catch (e) {}
            });
        }
        
        // Surveillance Windows via PowerShell
        if (process.platform === 'win32') {
            exec('Get-PnpDevice -Class USB | Where-Object {$_.Status -eq "OK"} | Select-Object InstanceId, FriendlyName | ConvertTo-Json -Compress 2>$null', 
                { shell: 'powershell.exe' }, (error, stdout) => {
                if (error || !stdout) return;
                try {
                    const devices = JSON.parse(stdout);
                    // Traitement des périphériques USB Windows
                    if (Array.isArray(devices)) {
                        devices.forEach(dev => {
                            if (dev.FriendlyName) {
                                const deviceId = dev.InstanceId || 'unknown';
                                checkUSBDevice(deviceId, {
                                    model: dev.FriendlyName,
                                    vendor: 'Windows',
                                    type: 'usb-windows'
                                });
                            }
                        });
                    }
                } catch (e) {}
            });
        }
        
        // Surveillance macOS
        if (process.platform === 'darwin') {
            exec('system_profiler SPUSBDataType -json 2>/dev/null || echo "{}"', (error, stdout) => {
                if (error || !stdout) return;
                try {
                    const data = JSON.parse(stdout);
                    // Traitement des périphériques USB macOS
                } catch (e) {}
            });
        }
    } catch (error) {
        console.error('Erreur surveillance USB:', error);
    }
}

function checkUSBDevice(deviceId, deviceInfo) {
    if (blockedUSBDevices.has(deviceId)) {
        // Bloquer le périphérique
        broadcastAlert({
            type: 'USB_BLOCKED',
            device: deviceInfo,
            timestamp: new Date().toISOString(),
            severity: 'WARNING',
            description: `Périphérique USB bloqué: ${deviceInfo.model}`
        });
        return;
    }
    
    if (!authorizedUSBDevices.has(deviceId)) {
        broadcastAlert({
            type: 'USB_DETECTED',
            device: deviceInfo,
            timestamp: new Date().toISOString(),
            severity: 'INFO',
            description: `Nouveau périphérique USB détecté: ${deviceInfo.model} - En attente d'autorisation`
        });
    }
}

// NOUVEAU: Surveillance File System (accès fichiers sensibles)
const chokidar = require('chokidar'); // Nécessite: npm install chokidar

function setupFileSystemMonitoring() {
    // Surveillance des répertoires sensibles - détection dynamique du système
    const osType = process.platform;
    let sensitivePaths = [];
    
    if (osType === 'linux') {
        sensitivePaths = [
            '/secure/taj/',
            '/secure/fpr/',
            '/secure/dgfip/',
            '/secure/bercy/',
            '/etc/shadow',
            '/etc/passwd',
            '/var/log/auth.log',
            '/home',
            '/root'
        ];
    } else if (osType === 'win32') {
        sensitivePaths = [
            'C:\\Windows\\System32\\config\\SAM',
            'C:\\Users',
            'C:\\ProgramData',
            'C:\\temp'
        ];
    } else if (osType === 'darwin') {
        sensitivePaths = [
            '/etc/master.passwd',
            '/private/var/log',
            '/Users'
        ];
    }
    
    // Filtrer les chemins qui existent réellement
    const existingPaths = sensitivePaths.filter(p => {
        try {
            require('fs').accessSync(p);
            return true;
        } catch {
            return false;
        }
    });
    
    console.log(`📁 Surveillance File System: ${existingPaths.length} chemins actifs`);
    
    if (existingPaths.length === 0) {
        console.log('⚠️  Aucun chemin sensible accessible - Mode simulation');
        return;
    }
    
    const watcher = chokidar.watch(existingPaths, {
        persistent: true,
        ignoreInitial: true,
        depth: 2,
        awaitWriteFinish: {
            stabilityThreshold: 300,
            pollInterval: 100
        }
    });
    
    watcher.on('access', path => {
        broadcastAlert({
            type: 'FILE_ACCESS',
            file: path,
            timestamp: new Date().toISOString(),
            severity: 'WARNING',
            description: `Accès au fichier sensible: ${path}`
        });
    });
    
    watcher.on('change', path => {
        broadcastAlert({
            type: 'FILE_MODIFIED',
            file: path,
            timestamp: new Date().toISOString(),
            severity: 'CRITICAL',
            description: `Modification fichier sensible: ${path}`
        });
    });
    
    watcher.on('add', path => {
        if (path.includes('TAJ') || path.includes('FPR') || path.includes('FICoba')) {
            broadcastAlert({
                type: 'SENSITIVE_FILE_CREATED',
                file: path,
                timestamp: new Date().toISOString(),
                severity: 'CRITICAL',
                description: `Nouveau fichier sensible créé: ${path}`
            });
        }
    });
}

// API pour contrôle d'accès
app.post('/api/auth/verify', (req, res) => {
    const { username, password, token } = req.body;
    // Vérification 2FA/MFA simulée
    res.json({
        success: true,
        sessionId: 'AUTH-' + Date.now(),
        level: 'ADMIN_T3',
        requires2FA: false,
        permissions: ['read', 'write', 'admin', 'network_control', 'usb_manage']
    });
});

app.post('/api/usb/control', (req, res) => {
    const { deviceId, action } = req.body; // action: 'authorize' ou 'block'
    if (action === 'authorize') {
        authorizedUSBDevices.add(deviceId);
        blockedUSBDevices.delete(deviceId);
    } else {
        blockedUSBDevices.add(deviceId);
        authorizedUSBDevices.delete(deviceId);
    }
    res.json({ success: true, deviceId, action });
});

app.get('/api/access/sessions', (req, res) => {
    res.json({
        sessions: [
            { id: 'sess_001', user: 'ADMIN_SYS', ip: '192.168.1.100', level: 'ADMIN_T3', startTime: new Date().toISOString() },
            { id: 'sess_002', user: 'AGENT_4521', ip: '192.168.1.45', level: 'OPERATOR', startTime: new Date().toISOString() }
        ],
        total: 2,
        failedAttempts: 0
    });
});

// Démarrage
server.listen(port, () => {
    console.log('');
    console.log('╔════════════════════════════════════════════════════════╗');
    console.log('║           🛡️  CYBERSHIELD SOC v3.0 - ACTIF            ║');
    console.log('╠════════════════════════════════════════════════════════╣');
    console.log(`║  Port: ${port}                                          ║`);
    console.log(`║  OS: ${process.platform}                                ║`);
    console.log(`║  Node: ${process.version}                               ║`);
    console.log('╠════════════════════════════════════════════════════════╣');
    console.log('║  MODULES ACTIFS:                                       ║');
    console.log('║    ✅ Surveillance Réseau (Temps réel)                ║');
    console.log('║    ✅ Surveillance Processus                          ║');
    console.log('║    ✅ Surveillance Auth/Brute Force                   ║');
    console.log('║    ✅ Surveillance Email/Messagerie                   ║');
    console.log('║    ✅ Protection Fichiers TAJ/FPR                     ║');
    console.log('║    ✅ Protection FICoba/DGFiP (Données Bancaires)     ║');
    console.log('║    ✅ Détection Codes d\'Accès Compromis               ║');
    console.log('║    ✅ Surveillance USB (DLP Matériel)                 ║');
    console.log('║    ✅ File System Monitoring                          ║');
    console.log('║    ✅ Contrôle Réseau (Kill Switch)                   ║');
    console.log('╠════════════════════════════════════════════════════════╣');
    console.log('║  MODE: PRODUCTION (Commandes système actives)         ║');
    console.log('╚════════════════════════════════════════════════════════╝');
    console.log('');
    
    // Démarrage surveillance USB et File System
    setInterval(monitorUSBDevices, 5000);
    setupFileSystemMonitoring();
});