-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
808 lines (678 loc) · 24.1 KB
/
Copy pathserver.js
File metadata and controls
808 lines (678 loc) · 24.1 KB
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
const express = require('express');
const session = require('express-session');
const path = require('path');
const fs = require('fs');
const { spawn, exec } = require('child_process');
const http = require('http');
const os = require('os');
const socketIo = require('socket.io');
const nodemailer = require('nodemailer');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
const port = 3000;
const FUZZERS_FILE = path.join(__dirname, 'fuzzers.json');
const LEXBOR_DIR = process.env.LEXBOR_DIR || path.join(__dirname, '..', 'lexbor-site');
const LEXBOR_REPO_URL = process.env.LEXBOR_REPO_URL || 'https://github.com/lexbor/lexbor.git';
const AMALGAMATION_CACHE_DIR = path.join(__dirname, '.amalgamation_cache');
const amalgamationLib = require('./lib/amalgamation');
amalgamationLib.init(LEXBOR_DIR, AMALGAMATION_CACHE_DIR, LEXBOR_REPO_URL);
if (!process.env.LEXBOR_SECRET
|| !process.env.LEXBOR_ADMIN
|| !process.env.LEXBOR_ADMIN_PASS)
{
env_info();
process.exit(1);
}
function env_info() {
console.error('Please, set environment:');
console.error('\tLEXBOR_SECRET');
console.error('\tLEXBOR_ADMIN');
console.error('\tLEXBOR_ADMIN_PASS');
}
// Email Transporter Configuration
// NOTE: Replace with real SMTP credentials in production
const transporter = nodemailer.createTransport({
host: 'smtp.lexbor.com',
port: 587,
auth: {
user: '',
pass: ''
}
});
// Helper to send email
const sendCrashNotification = async (email, fuzzerName, crashFile) => {
if (!email) return;
const mailOptions = {
from: '"Fuzzer Admin" <postmaster@lexbor.com>',
to: email,
subject: `[CRASH ALERT] New crash detected for ${fuzzerName}`,
text: `
Fuzzer: ${fuzzerName}
Time: ${new Date().toLocaleString()}
Crash File: ${crashFile}
Please check the admin panel for details.
`
};
try {
// In a real app, we would await this. For now, we just log it if it fails (likely due to bad creds)
// or just log the attempt to console since we don't have real SMTP.
console.log('---------------------------------------------------');
console.log(`[MOCK EMAIL] To: ${email}`);
console.log(`Subject: ${mailOptions.subject}`);
console.log(mailOptions.text);
console.log('---------------------------------------------------');
// await transporter.sendMail(mailOptions);
} catch (error) {
console.error('Error sending email:', error);
}
};
// Helper to read fuzzers
const getFuzzers = () => {
try {
if (!fs.existsSync(FUZZERS_FILE)) return [];
const data = fs.readFileSync(FUZZERS_FILE, 'utf8');
return JSON.parse(data);
} catch (err) {
console.error('Error reading fuzzers file:', err);
return [];
}
};
// Helper to write fuzzers
const saveFuzzers = (fuzzers) => {
try {
fs.writeFileSync(FUZZERS_FILE, JSON.stringify(fuzzers, null, 2));
} catch (err) {
console.error('Error writing fuzzers file:', err);
}
};
// Helper to check if process is running
const isProcessRunning = (pid) => {
try {
process.kill(pid, 0);
return true;
} catch (e) {
return false;
}
};
// Helper to format duration
const formatDuration = (startTime) => {
if (!startTime) return '-';
const diff = Date.now() - new Date(startTime).getTime();
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
};
// Helper to get process stats (CPU and Memory)
const getProcessStats = (pid) => {
return new Promise((resolve) => {
// pcpu: percentage of CPU usage
// rss: resident set size (memory) in KB
exec(`ps -p ${pid} -o pcpu=,rss=`, (error, stdout, stderr) => {
if (error || stderr) {
resolve({ cpu: '0.0', memory: '0.00 MB' });
return;
}
const parts = stdout.trim().split(/\s+/);
if (parts.length < 2) {
resolve({ cpu: '0.0', memory: '0.00 MB' });
return;
}
const cpu = parseFloat(parts[0]).toFixed(1);
const rss = parseInt(parts[1], 10); // KB
const memory = isNaN(rss) ? '0.00 MB' : (rss / 1024).toFixed(2) + ' MB';
resolve({ cpu, memory });
});
});
};
// Helper to get crash count
const getCrashCount = (crashDir) => {
try {
if (fs.existsSync(crashDir)) {
return fs.readdirSync(crashDir).length;
}
} catch (e) {
console.error('Error counting crashes:', e);
}
return 0;
};
// Set EJS as the view engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Middleware to parse POST request bodies
app.use(express.urlencoded({ extended: true }));
// Session configuration
const sessionMiddleware = session({
secret: process.env.LEXBOR_SECRET, // In production, use a secure random string
resave: false,
saveUninitialized: true,
cookie: { secure: false } // Set to true if using HTTPS
});
app.use(sessionMiddleware);
// Share session with Socket.IO
io.engine.use(sessionMiddleware);
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
// Amalgamation routes
app.use(require('./routes/amalgamation'));
// Authentication middleware
const requireAuth = (req, res, next) => {
if (req.session.isAuthenticated) {
next();
} else {
res.redirect('/login');
}
};
// Login page route
app.get('/login', (req, res) => {
if (req.session.isAuthenticated) {
res.redirect('/');
} else {
res.render('login', {
title: 'Login',
error: req.query.error ? 'Invalid credentials' : null,
cb: req.query.cb ? req.query.cb : ""
});
}
});
// Login action
app.post('/login', (req, res) => {
const { username, password } = req.body;
const redirect = req.query.cb ? req.query.cb : "/"
// Simple hardcoded credentials (in production, use a database)
if (username === process.env.LEXBOR_ADMIN && password === process.env.LEXBOR_ADMIN_PASS) {
req.session.isAuthenticated = true;
req.session.user = username;
res.redirect(redirect);
} else {
res.redirect('/login?cb=' + encodeURIComponent(redirect) + '&error=1');
}
});
// Admin dashboard (protected)
app.get('/admin', requireAuth, (req, res) => {
res.render('admin', {
title: 'Admin Dashboard',
user: req.session.user || 'Administrator'
});
});
// Developers Page
app.get('/developers', (req, res) => {
res.render('developers');
});
// Lexbor Page
app.get('/developers/lexbor', (req, res) => {
res.render('lexbor');
});
// Fuzzers Management Routes
app.get('/fuzzers', (req, res) => {
let fuzzers = getFuzzers();
let updated = false;
// Update status and duration
fuzzers = fuzzers.map(f => {
if (f.pid) {
if (!isProcessRunning(f.pid)) {
f.pid = null;
f.startTime = null;
f.duration = '-';
updated = true;
} else {
f.duration = formatDuration(f.startTime);
}
}
// Add crash count
f.crashCount = getCrashCount(f.crashDir);
return f;
});
if (updated) saveFuzzers(fuzzers);
res.render('fuzzers', {
fuzzers: fuzzers,
is_admin: req.session.isAuthenticated,
originalUrl: req.originalUrl
});
});
app.post('/fuzzers/add', requireAuth, (req, res) => {
const { name, path: fuzzerPath, dict, args: fuzzerARGS, email } = req.body;
const fuzzers = getFuzzers();
// Automatically determine crash directory
// Format: /path/to/fuzzer_dir/fuzzer_name_crashes
const fuzzerDir = path.dirname(fuzzerPath);
const fuzzerName = path.basename(fuzzerPath);
const crashDir = path.join(fuzzerDir, `${fuzzerName}_crashes`);
const corpusDir = path.join(fuzzerDir, `${fuzzerName}_corpus`);
// Ensure crash directory exists
try {
if (!fs.existsSync(crashDir)) {
fs.mkdirSync(crashDir, { recursive: true });
}
} catch (err) {
console.error('Error creating crash directory:', err);
}
// Ensure corpus directory exists
try {
if (!fs.existsSync(corpusDir)) {
fs.mkdirSync(corpusDir, { recursive: true });
}
} catch (err) {
console.error('Error creating corpus directory:', err);
}
fuzzers.push({
id: Date.now().toString(),
name,
path: fuzzerPath,
crashDir: crashDir,
corpusDir: corpusDir,
email: email || null,
knownCrashes: [], // Track known crashes to avoid duplicate alerts
pid: null,
startTime: null,
dict: dict.trim(),
args: fuzzerARGS.trim()
});
saveFuzzers(fuzzers);
res.redirect('/fuzzers');
});
app.post('/fuzzers/start/:id', requireAuth, (req, res) => {
const fuzzers = getFuzzers();
const fuzzer = fuzzers.find(f => f.id === req.params.id);
if (fuzzer && !fuzzer.pid) {
try {
// Determine log directory and file
// Format: /path/to/fuzzer_dir/fuzzer_name_logs/fuzzer.log
const fuzzerDir = path.dirname(fuzzer.path);
const crashDir = fuzzer.crashDir;
let corpusDir = fuzzer.corpusDir;
const fuzzerName = path.basename(fuzzer.path);
const logDir = path.join(fuzzerDir, `${fuzzerName}_logs`);
const logPath = path.join(logDir, 'fuzzer.log');
let args = [`-artifact_prefix=${crashDir}/`];
if (fuzzer.dict?.length > 0) {
args.push(`-dict=${fuzzer.dict}`);
}
if (fuzzer.args?.length > 0) {
const parts = fuzzer.args.trim().split(/\s+/);
args.push(...parts);
}
// Ensure crash directory exists
if (!fs.existsSync(crashDir)) {
fs.mkdirSync(crashDir, { recursive: true });
}
// Ensure log directory exists
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir, { recursive: true });
}
// Ensure corpus directory exists
if (!corpusDir) {
corpusDir = path.join(fuzzerDir, `${fuzzerName}_corpus`);
}
if (!fs.existsSync(corpusDir)) {
fs.mkdirSync(corpusDir, { recursive: true });
}
args.push(corpusDir);
const out = fs.openSync(logPath, 'a');
const err = fs.openSync(logPath, 'a');
// Spawn the process detached so it keeps running
const child = spawn(fuzzer.path, args, {
detached: true,
stdio: ['ignore', out, err]
});
child.unref();
fuzzer.pid = child.pid;
fuzzer.startTime = new Date().toISOString();
fuzzer.logPath = logPath; // Save log path for reference
fuzzer.corpusDir = corpusDir;
saveFuzzers(fuzzers);
} catch (err) {
console.error('Failed to start fuzzer:', err);
}
}
res.redirect('/fuzzers');
});
app.post('/fuzzers/stop/:id', requireAuth, (req, res) => {
const fuzzers = getFuzzers();
const fuzzer = fuzzers.find(f => f.id === req.params.id);
if (fuzzer && fuzzer.pid) {
try {
process.kill(fuzzer.pid);
fuzzer.pid = null;
fuzzer.startTime = null;
saveFuzzers(fuzzers);
} catch (err) {
console.error('Failed to stop fuzzer:', err);
}
}
res.redirect('/fuzzers');
});
app.post('/fuzzers/delete/:id', requireAuth, (req, res) => {
let fuzzers = getFuzzers();
const fuzzer = fuzzers.find(f => f.id === req.params.id);
// Stop if running before deleting
if (fuzzer && fuzzer.pid) {
try {
process.kill(fuzzer.pid);
} catch (e) {}
}
fuzzers = fuzzers.filter(f => f.id !== req.params.id);
saveFuzzers(fuzzers);
res.redirect('/fuzzers');
});
app.post('/fuzzers/start-all', requireAuth, (req, res) => {
const fuzzers = getFuzzers();
for (const fuzzer of fuzzers) {
if (fuzzer.pid) continue;
try {
const fuzzerDir = path.dirname(fuzzer.path);
const crashDir = fuzzer.crashDir;
let corpusDir = fuzzer.corpusDir;
const fuzzerName = path.basename(fuzzer.path);
const logDir = path.join(fuzzerDir, `${fuzzerName}_logs`);
const logPath = path.join(logDir, 'fuzzer.log');
let args = [`-artifact_prefix=${crashDir}/`];
if (fuzzer.dict?.length > 0) {
args.push(`-dict=${fuzzer.dict}`);
}
if (fuzzer.args?.length > 0) {
const parts = fuzzer.args.trim().split(/\s+/);
args.push(...parts);
}
if (!fs.existsSync(crashDir)) fs.mkdirSync(crashDir, { recursive: true });
if (!fs.existsSync(logDir)) fs.mkdirSync(logDir, { recursive: true });
if (!corpusDir) {
corpusDir = path.join(fuzzerDir, `${fuzzerName}_corpus`);
}
if (!fs.existsSync(corpusDir)) fs.mkdirSync(corpusDir, { recursive: true });
args.push(corpusDir);
const out = fs.openSync(logPath, 'a');
const err = fs.openSync(logPath, 'a');
const child = spawn(fuzzer.path, args, {
detached: true,
stdio: ['ignore', out, err]
});
child.unref();
fuzzer.pid = child.pid;
fuzzer.startTime = new Date().toISOString();
fuzzer.logPath = logPath;
fuzzer.corpusDir = corpusDir;
} catch (err) {
console.error(`Failed to start fuzzer ${fuzzer.name}:`, err);
}
}
saveFuzzers(fuzzers);
res.redirect('/fuzzers');
});
app.post('/fuzzers/stop-all', requireAuth, (req, res) => {
const fuzzers = getFuzzers();
for (const fuzzer of fuzzers) {
if (!fuzzer.pid) continue;
try {
process.kill(fuzzer.pid);
} catch (e) {}
fuzzer.pid = null;
fuzzer.startTime = null;
}
saveFuzzers(fuzzers);
res.redirect('/fuzzers');
});
// View Logs Route
app.get('/fuzzers/logs/:id', (req, res) => {
const fuzzers = getFuzzers();
const fuzzer = fuzzers.find(f => f.id === req.params.id);
if (!fuzzer) {
return res.redirect('/fuzzers');
}
res.render('logs', {
title: `Logs: ${fuzzer.name}`,
fuzzer: fuzzer
});
});
// View Crashes Route
app.get('/fuzzers/crashes/:id', (req, res) => {
const fuzzers = getFuzzers();
const fuzzer = fuzzers.find(f => f.id === req.params.id);
if (!fuzzer || !fuzzer.crashDir) {
return res.redirect('/fuzzers');
}
let crashes = [];
try {
if (fs.existsSync(fuzzer.crashDir)) {
const files = fs.readdirSync(fuzzer.crashDir);
crashes = files.map(file => {
const filePath = path.join(fuzzer.crashDir, file);
const stats = fs.statSync(filePath);
return {
name: file,
size: (stats.size / 1024).toFixed(2) + ' KB',
date: stats.mtime.toLocaleString()
};
});
}
} catch (err) {
console.error('Error reading crash directory:', err);
}
res.render('crashes', {
title: `Crashes: ${fuzzer.name}`,
fuzzer: fuzzer,
crashes: crashes
});
});
// Download Crash Route
app.get('/fuzzers/crashes/:id/download/:filename', requireAuth, (req, res) => {
const fuzzers = getFuzzers();
const fuzzer = fuzzers.find(f => f.id === req.params.id);
if (!fuzzer || !fuzzer.crashDir) {
return res.status(404).send('Fuzzer or crash directory not found');
}
const filePath = path.join(fuzzer.crashDir, req.params.filename);
// Security check: prevent directory traversal
if (!filePath.startsWith(path.resolve(fuzzer.crashDir))) {
return res.status(403).send('Access denied');
}
if (fs.existsSync(filePath)) {
res.download(filePath);
} else {
res.status(404).send('File not found');
}
});
// Delete Crash Route
app.post('/fuzzers/crashes/:id/delete/:filename', requireAuth, (req, res) => {
const fuzzers = getFuzzers();
const fuzzer = fuzzers.find(f => f.id === req.params.id);
if (!fuzzer || !fuzzer.crashDir) {
return res.status(404).send('Fuzzer or crash directory not found');
}
const filePath = path.join(fuzzer.crashDir, req.params.filename);
// Security check: prevent directory traversal
if (!filePath.startsWith(path.resolve(fuzzer.crashDir))) {
return res.status(403).send('Access denied');
}
try {
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
} catch (err) {
console.error('Error deleting crash file:', err);
}
res.redirect(`/fuzzers/crashes/${fuzzer.id}`);
});
// Socket.io connection for logs
io.on('connection', (socket) => {
// Check authentication
const session = socket.request.session;
if (session && session.isAuthenticated) {
socket.join('admins');
}
socket.on('join_log', (fuzzerId) => {
// Ensure user is authenticated for logs too
// if (!socket.request.session || !socket.request.session.isAuthenticated) {
// return;
// }
const fuzzers = getFuzzers();
const fuzzer = fuzzers.find(f => f.id === fuzzerId);
if (!fuzzer || !fuzzer.logPath) {
socket.emit('log_data', 'Log path not configured or fuzzer not found.\n');
return;
}
const logPath = fuzzer.logPath;
// Start from the end of the file (tail)
let currentSize = 0;
try {
const stats = fs.statSync(logPath);
currentSize = stats.size;
} catch (e) {}
// Send a message indicating we are starting from now
socket.emit('log_data', `[Connected to log stream. Showing new logs from ${new Date().toLocaleTimeString()}...]\n`);
if (fs.existsSync(logPath)) {
const watcher = fs.watch(logPath, (eventType) => {
if (eventType === 'change') {
fs.stat(logPath, (err, stats) => {
if (err) return;
if (stats.size > currentSize) {
const stream = fs.createReadStream(logPath, {
start: currentSize,
end: stats.size
});
stream.on('data', (chunk) => {
socket.emit('log_data', chunk.toString());
});
currentSize = stats.size;
} else if (stats.size < currentSize) {
// File was truncated
currentSize = stats.size;
socket.emit('log_data', '\n[Logs cleared]\n');
}
});
}
});
socket.on('disconnect', () => {
watcher.close();
});
} else {
socket.emit('log_data', 'No logs found for this fuzzer yet.\n');
}
});
});
// Log cleanup task (every 10 minutes)
setInterval(() => {
console.log('Running log cleanup...');
const fuzzers = getFuzzers();
fuzzers.forEach(fuzzer => {
if (fuzzer.pid && fuzzer.logPath && fs.existsSync(fuzzer.logPath)) {
try {
fs.truncateSync(fuzzer.logPath, 0);
console.log(`Cleared logs for fuzzer: ${fuzzer.name}`);
} catch (err) {
console.error(`Failed to clear logs for ${fuzzer.name}:`, err);
}
}
});
}, 10 * 60 * 1000); // 10 minutes
// Fetch lexbor updates (every 5 minutes)
setInterval(() => {
amalgamationLib.fetchUpdates();
}, 5 * 60 * 1000);
// Cleanup stale master cache (every hour)
setInterval(() => {
amalgamationLib.cleanupMasterCache();
}, 60 * 60 * 1000);
// Broadcast fuzzer stats (every 2 seconds)
setInterval(async () => {
const fuzzers = getFuzzers();
const fuzzerStats = {};
let updated = false;
// System Stats
const systemStats = {
cores: os.cpus().length,
load: os.loadavg()[0].toFixed(2), // 1 minute load average
memory: os.totalmem(),
memory_free: os.freemem()
};
for (const fuzzer of fuzzers) {
// Check for new crashes
let currentCrashes = [];
try {
if (fs.existsSync(fuzzer.crashDir)) {
currentCrashes = fs.readdirSync(fuzzer.crashDir);
}
} catch (e) {}
const crashCount = currentCrashes.length;
// Initialize knownCrashes if missing (migration)
if (!fuzzer.knownCrashes) {
fuzzer.knownCrashes = currentCrashes;
updated = true;
}
// Detect new crashes
const newCrashes = currentCrashes.filter(c => !fuzzer.knownCrashes.includes(c));
if (newCrashes.length > 0) {
// Send notifications
for (const crash of newCrashes) {
console.log(`New crash detected for ${fuzzer.name}: ${crash}`);
if (fuzzer.email) {
sendCrashNotification(fuzzer.email, fuzzer.name, crash);
}
}
// Update known crashes
fuzzer.knownCrashes = [...fuzzer.knownCrashes, ...newCrashes];
updated = true;
}
if (fuzzer.pid) {
if (isProcessRunning(fuzzer.pid)) {
const procStats = await getProcessStats(fuzzer.pid);
fuzzerStats[fuzzer.id] = {
isRunning: true,
pid: fuzzer.pid,
duration: formatDuration(fuzzer.startTime),
cpu: procStats.cpu + '%',
memory: procStats.memory,
crashCount: crashCount
};
} else {
// Process died unexpectedly
fuzzer.pid = null;
fuzzer.startTime = null;
updated = true;
fuzzerStats[fuzzer.id] = {
isRunning: false,
duration: '-',
cpu: '-',
memory: '-',
crashCount: crashCount
};
}
} else {
fuzzerStats[fuzzer.id] = {
isRunning: false,
duration: '-',
cpu: '-',
memory: '-',
crashCount: crashCount
};
}
}
if (updated) saveFuzzers(fuzzers);
// Prepare stats for public (without crashCount)
const publicFuzzerStats = {};
const sensitiveFuzzerStats = {};
for (const [id, stat] of Object.entries(fuzzerStats)) {
const { crashCount, pid, isRunning, ...rest } = stat;
publicFuzzerStats[id] = rest;
sensitiveFuzzerStats[id] = { crashCount, pid, isRunning };
}
const publicStats = { system: systemStats, fuzzers: publicFuzzerStats };
const sensitiveStats = { fuzzers: sensitiveFuzzerStats };
// Emit public stats to everyone
io.emit('fuzzer_stats', publicStats);
// Emit sensitive stats (crashCount) only to admins
io.to('admins').emit('fuzzer_sensitive_stats', sensitiveStats);
}, 2000);
// Logout action
app.get('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
console.error('Error destroying session:', err);
}
res.redirect(req.query.cb ? req.query.cb : "/");
});
});
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});