-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1717 lines (1573 loc) · 75.4 KB
/
server.js
File metadata and controls
1717 lines (1573 loc) · 75.4 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
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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const VERSION = 'v2026.5.2.15.58';
const express = require('express');
const http = require('http');
const { Server } = require("socket.io");
const { spawn, exec, execFile } = require('child_process');
const path = require('path');
const fs = require('fs');
const cron = require('node-cron');
const axios = require('axios');
const xml2js = require('xml2js');
const crypto = require('crypto');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
const APP_IDENTITY = 'tm-network-scanner';
const PORT = Number(process.env.PORT || 9000);
app.use(express.static(path.join(__dirname)));
app.use('/static', express.static(path.join(__dirname, 'static')));
app.use('/reports', express.static(path.join(__dirname, 'reports_archive')));
app.get('/api/app-identity', (req, res) => {
res.json({ app: APP_IDENTITY, name: 'TM-NMapUI', version: VERSION });
});
app.get('/google-drive/oauth2callback', async (req, res) => {
const result = await runGoogleDriveHelper([
'exchange-code',
'--code', req.query.code || '',
'--state', req.query.state || ''
]);
if (result.success) {
const googleDrive = saveGoogleDriveConfig({ enabled: true });
logEvent(null, 'settings', 'Google Drive connected and sync enabled.');
io.emit('google_drive_status', { ...result, config: googleDrive });
res.send('<html><body><h1>Google Drive connected</h1><p>You can close this window and return to TM-NMapUI.</p></body></html>');
return;
}
io.emit('google_drive_status', { ...result, config: getGoogleDriveConfig() });
res.status(400).send(`<html><body><h1>Google Drive connection failed</h1><p>${String(result.error || 'Unknown error')}</p></body></html>`);
});
// Global state for persistence across tabs
let currentScan = null;
let scanStartTime = null;
let autoScanTask = null;
let discoveredHosts = [];
let currentScanPhase = null;
let currentTarget = null;
let currentScanKind = null;
let lastScanResult = null;
let cachedHops = [];
let isTracerouteRunning = false;
let cachedNetworkInfo = null;
let cachedPublicIP = null;
const CONFIG_PATH = path.join(__dirname, 'config.json');
const HISTORY_PATH = path.join(__dirname, 'history.json');
const REPORTS_DIR = path.join(__dirname, 'reports_archive');
const NMAP_PATH = resolveExecutable(process.env.NMAP_PATH, [
'/opt/homebrew/bin/nmap',
'/usr/local/bin/nmap',
'/usr/bin/nmap',
'/bin/nmap',
'nmap'
]);
const TRACEROUTE_PATH = resolveExecutable(process.env.TRACEROUTE_PATH, [
'/usr/sbin/traceroute',
'/sbin/traceroute',
'/opt/homebrew/bin/traceroute',
'/usr/local/bin/traceroute',
'traceroute'
]);
const BREW_PATH = resolveExecutable(process.env.BREW_PATH, [
'/opt/homebrew/bin/brew',
'/usr/local/bin/brew',
'brew'
]);
const GOWITNESS_PATH = resolveExecutable(process.env.GOWITNESS_PATH, [
'/opt/homebrew/bin/gowitness',
'/usr/local/bin/gowitness',
'gowitness',
...getGoExecutableCandidates('gowitness')
]);
let customerProfileConfig = loadJSON(CONFIG_PATH, {}).customerProfile || {};
let appConfig = loadJSON(CONFIG_PATH, {});
if (!fs.existsSync(REPORTS_DIR)) fs.mkdirSync(REPORTS_DIR);
function loadJSON(filePath, defaultVal = {}) {
if (fs.existsSync(filePath)) {
try { return JSON.parse(fs.readFileSync(filePath)); } catch(e) { return defaultVal; }
}
return defaultVal;
}
function saveJSON(filePath, data) {
fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
}
function saveCustomerProfileConfig(profileConfig) {
const config = loadJSON(CONFIG_PATH, {});
config.customerProfile = profileConfig;
appConfig = config;
customerProfileConfig = profileConfig;
saveJSON(CONFIG_PATH, config);
}
function saveGoogleDriveConfig(googleDriveConfig) {
const config = loadJSON(CONFIG_PATH, {});
config.googleDrive = { ...(config.googleDrive || {}), ...googleDriveConfig };
appConfig = config;
saveJSON(CONFIG_PATH, config);
return config.googleDrive;
}
function saveAutoScanConfig(autoScanConfig) {
const config = loadJSON(CONFIG_PATH, {});
config.autoScan = { ...(config.autoScan || {}), ...autoScanConfig };
appConfig = config;
saveJSON(CONFIG_PATH, config);
setupAutoScan(config);
return config.autoScan;
}
function getGoogleDriveConfig() {
return appConfig.googleDrive || {};
}
function isExecutable(filePath) {
if (!filePath) return false;
try {
fs.accessSync(filePath, fs.constants.X_OK);
return true;
} catch (error) {
return false;
}
}
function resolveExecutable(explicitPath, candidates) {
const searchPaths = (process.env.PATH || '')
.split(path.delimiter)
.filter(Boolean);
const pathCandidates = candidates
.filter(candidate => !candidate.includes(path.sep))
.flatMap(name => searchPaths.map(dir => path.join(dir, name)));
return [explicitPath, ...candidates, ...pathCandidates]
.filter(Boolean)
.map(expandUserPath)
.find(isExecutable) || null;
}
function expandUserPath(filePath) {
if (!filePath || !filePath.startsWith('~')) return filePath;
const homeDir = process.env.HOME || (process.env.SUDO_USER ? `/Users/${process.env.SUDO_USER}` : '');
if (!homeDir) return filePath;
return path.join(homeDir, filePath.slice(1));
}
function getGoExecutableCandidates(binaryName) {
const candidates = [];
if (process.env.GOBIN) candidates.push(path.join(process.env.GOBIN, binaryName));
if (process.env.GOPATH) {
process.env.GOPATH.split(path.delimiter).filter(Boolean).forEach(goPath => {
candidates.push(path.join(goPath, 'bin', binaryName));
});
}
if (process.env.HOME) candidates.push(path.join(process.env.HOME, 'go', 'bin', binaryName));
if (process.env.SUDO_USER) candidates.push(path.join('/Users', process.env.SUDO_USER, 'go', 'bin', binaryName));
return candidates;
}
function getPrivilegedCommand(executablePath, args) {
if (process.getuid && process.getuid() === 0) {
return { command: executablePath, args };
}
return { command: 'sudo', args: ['-n', executablePath, ...args] };
}
function describeMissingExecutable(name, envVar) {
return `${name} was not found. Install it or set ${envVar} to the executable path.`;
}
function getBrewCommand(args) {
if (process.getuid && process.getuid() === 0) {
const sudoUser = process.env.SUDO_USER;
if (!sudoUser || sudoUser === 'root') return null;
return {
command: 'sudo',
args: ['-u', sudoUser, BREW_PATH, ...args],
env: { ...process.env, HOME: `/Users/${sudoUser}`, USER: sudoUser }
};
}
return { command: BREW_PATH, args, env: process.env };
}
function runBrewStep(args) {
return new Promise((resolve) => {
const commandSpec = getBrewCommand(args);
if (!BREW_PATH || !commandSpec) {
resolve({ success: false, error: 'Homebrew is unavailable or cannot be run from the current user context.' });
return;
}
const brew = spawn(commandSpec.command, commandSpec.args, { env: commandSpec.env });
brew.stdout.on('data', data => {
const text = data.toString().trim();
if (text) console.log(`[BREW] ${text}`);
});
brew.stderr.on('data', data => {
const text = data.toString().trim();
if (text) console.warn(`[BREW] ${text}`);
});
brew.on('error', error => resolve({ success: false, error: error.message }));
brew.on('close', code => resolve({ success: code === 0, error: code === 0 ? '' : `brew ${args.join(' ')} exited with code ${code}` }));
});
}
async function updateNmapFromHomebrew() {
if (!BREW_PATH) {
console.warn('Skipping Homebrew nmap upgrade: brew was not found.');
return;
}
const commandSpec = getBrewCommand(['update']);
if (!commandSpec) {
console.warn('Skipping Homebrew nmap upgrade: brew cannot run as root without SUDO_USER.');
return;
}
console.log('Startup - Running brew update && brew upgrade nmap...');
const update = await runBrewStep(['update']);
if (!update.success) {
console.warn(`Skipping brew upgrade nmap: ${update.error}`);
return;
}
const upgrade = await runBrewStep(['upgrade', 'nmap']);
if (!upgrade.success) {
console.warn(`Homebrew nmap upgrade did not complete: ${upgrade.error}`);
}
}
function updateNmapScriptDatabase() {
if (!NMAP_PATH) {
console.warn(describeMissingExecutable('nmap', 'NMAP_PATH'));
return;
}
console.log('Prescan - Updating scripts...');
const updateCommand = getPrivilegedCommand(NMAP_PATH, ['--script-updatedb']);
const updateProcess = spawn(updateCommand.command, updateCommand.args);
updateProcess.stderr.on('data', data => {
const text = data.toString();
if (isSudoAuthFailure(text)) {
console.warn('Skipping nmap script update: passwordless sudo is required.');
} else if (!text.includes('Warning: ')) {
console.warn(`[NMAP UPDATE] ${text.trim()}`);
}
});
updateProcess.on('error', error => console.warn(`Skipping nmap script update: ${error.message}`));
}
function isSudoAuthFailure(text) {
return /sudo:.*password|a password is required|no tty present|permission denied/i.test(text || '');
}
function requestJSON(url, timeoutMs = 1000) {
return new Promise((resolve) => {
const request = http.get(url, { timeout: timeoutMs }, response => {
let raw = '';
response.on('data', chunk => { raw += chunk.toString(); });
response.on('end', () => {
try {
resolve(JSON.parse(raw || '{}'));
} catch (error) {
resolve(null);
}
});
});
request.on('timeout', () => {
request.destroy();
resolve(null);
});
request.on('error', () => resolve(null));
});
}
function getPortListenerPids(port) {
return new Promise((resolve) => {
exec(`lsof -ti tcp:${Number(port)} -sTCP:LISTEN`, (error, stdout) => {
if (error || !stdout.trim()) {
resolve([]);
return;
}
resolve(stdout.trim().split(/\s+/).map(pid => Number(pid)).filter(Boolean));
});
});
}
async function stopExistingAppOnPort(port) {
const identity = await requestJSON(`http://127.0.0.1:${port}/api/app-identity`);
if (identity?.app !== APP_IDENTITY) {
return false;
}
const pids = (await getPortListenerPids(port)).filter(pid => pid !== process.pid);
if (pids.length === 0) return false;
console.warn(`Port ${port} is already used by ${identity.name || APP_IDENTITY}; stopping pid(s): ${pids.join(', ')}`);
pids.forEach(pid => {
try {
process.kill(pid, 'SIGTERM');
} catch (error) {
console.warn(`Failed to stop pid ${pid}: ${error.message}`);
}
});
await new Promise(resolve => setTimeout(resolve, 1200));
const remaining = (await getPortListenerPids(port)).filter(pid => pid !== process.pid);
remaining.forEach(pid => {
try {
process.kill(pid, 'SIGKILL');
} catch (error) {
console.warn(`Failed to force stop pid ${pid}: ${error.message}`);
}
});
return true;
}
function shellQuote(value) {
return `'${String(value).replace(/'/g, `'\\''`)}'`;
}
function escapeHtml(value) {
return String(value ?? '').replace(/[&<>"']/g, (char) => ({
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
})[char]);
}
function getChromeExecutable() {
const candidates = [
process.env.CHROME_PATH,
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/Applications/Chromium.app/Contents/MacOS/Chromium',
'/usr/bin/google-chrome',
'/usr/bin/chromium',
'/usr/bin/chromium-browser'
].filter(Boolean);
return candidates.find(candidate => fs.existsSync(candidate)) || null;
}
function createPdfExportHtml(reportPath) {
const source = fs.readFileSync(reportPath, 'utf8');
const exportStyle = `
<style id="tm-pdf-export-style">
.pdf-export nav { display: none !important; }
.pdf-export { background: #e9ebe0 !important; color: #25291f !important; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
.pdf-export .pdf-cover { display: flex !important; box-sizing: border-box !important; width: 100% !important; height: 279.4mm !important; min-height: 279.4mm !important; page-break-after: always !important; background: #414637 !important; color: #f5f6f3 !important; border: 1px solid #636b54 !important; margin: 0 !important; padding: 16mm !important; flex-direction: column !important; justify-content: space-between !important; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
.pdf-export .pdf-cover * { color: inherit !important; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
.pdf-export .pdf-cover-label { font-size: 10px !important; letter-spacing: 0.14em !important; text-transform: uppercase !important; color: #d8dbc7 !important; }
.pdf-export .pdf-cover-title { font-size: 38px !important; line-height: 0.95 !important; font-weight: 700 !important; margin-top: 8mm !important; margin-bottom: 4mm !important; }
.pdf-export .pdf-cover-subtitle { font-size: 16px !important; line-height: 1.1 !important; color: #e9ebe0 !important; }
.pdf-export .pdf-cover-meta { display: grid !important; grid-template-columns: repeat(4, minmax(0, 1fr)) !important; gap: 3mm !important; border-top: 1px solid #979f83 !important; padding-top: 5mm !important; }
.pdf-export .pdf-cover-meta div { background: rgba(245,246,243,0.08) !important; border: 1px solid rgba(216,219,199,0.35) !important; padding: 3.5mm !important; }
.pdf-export .pdf-cover-meta span { display: block !important; font-size: 7px !important; color: #d8dbc7 !important; text-transform: uppercase !important; letter-spacing: 0.08em !important; }
.pdf-export .pdf-cover-meta strong { display: block !important; font-size: 10px !important; line-height: 1.15 !important; margin-top: 2mm !important; word-break: break-word !important; }
.pdf-export .pdf-only { display: block !important; }
.pdf-export .pdf-fixed-header { display: flex !important; position: fixed !important; top: 0 !important; left: 0 !important; right: 0 !important; z-index: 1 !important; height: 12mm !important; align-items: center !important; justify-content: space-between !important; color: #f5f6f3 !important; font-size: 8px !important; font-weight: 700 !important; padding: 0 4mm !important; background: #414637 !important; border-bottom: 1px solid #636b54 !important; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
.pdf-export .pdf-fixed-header a { color: #d8dbc7 !important; text-decoration: none !important; font-weight: 500 !important; }
.pdf-export .pdf-fixed-footer { display: block !important; position: fixed !important; right: 2mm !important; bottom: 1.5mm !important; z-index: 1 !important; color: #636b54 !important; font-size: 7px !important; }
.pdf-export .report-shell.pt-24 { padding-top: 15mm !important; padding-left: 4mm !important; padding-right: 4mm !important; }
.pdf-export .end-of-report-page { display: flex !important; box-sizing: border-box !important; width: 100% !important; height: 279.4mm !important; min-height: 279.4mm !important; margin: 0 !important; page-break-before: always !important; align-items: center !important; justify-content: center !important; background: #e9ebe0 !important; color: #414637 !important; font-size: 24px !important; font-weight: 700 !important; letter-spacing: 0.14em !important; text-transform: uppercase !important; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
</style>`;
let html = source.includes('tm-pdf-export-style') ? source : source.replace('</head>', `${exportStyle}\n</head>`);
html = html.replace(/<body([^>]*)class="([^"]*)"/i, '<body$1class="pdf-export $2"');
if (html === source || !/class="pdf-export /.test(html)) {
html = html.replace(/<body([^>]*)>/i, '<body$1 class="pdf-export">');
}
const tempPath = path.join(path.dirname(reportPath), `.pdf-export-${path.basename(reportPath)}`);
fs.writeFileSync(tempPath, html);
return tempPath;
}
function generatePDF(reportPath, pdfPath, callback) {
const chromePath = getChromeExecutable();
if (chromePath) {
const reportUrl = `file://${reportPath}`;
const command = [
shellQuote(chromePath),
'--headless',
'--disable-gpu',
'--no-sandbox',
'--no-pdf-header-footer',
'--run-all-compositor-stages-before-draw',
'--virtual-time-budget=5000',
'--print-to-pdf-page-size=Letter',
`--print-to-pdf=${shellQuote(pdfPath)}`,
shellQuote(reportUrl)
].join(' ');
exec(command, callback);
return;
}
const pdfSourcePath = createPdfExportHtml(reportPath);
const cleanupCallback = (...args) => {
try { fs.unlinkSync(pdfSourcePath); } catch (error) {}
callback(...args);
};
const wkhtmltopdfCommand = [
'wkhtmltopdf',
'--enable-local-file-access',
'--print-media-type',
'--page-size', 'Letter',
'--orientation', 'Portrait',
'--margin-top', '0',
'--margin-right', '0',
'--margin-bottom', '0',
'--margin-left', '0',
'--javascript-delay', '3000',
'--no-stop-slow-scripts',
shellQuote(pdfSourcePath),
shellQuote(pdfPath)
].join(' ');
exec(wkhtmltopdfCommand, cleanupCallback);
}
function sanitizeReportSegment(value, fallback = 'unknown') {
const cleaned = String(value || '')
.trim()
.replace(/[^0-9A-Za-z_.-]+/g, '_')
.replace(/^_+|_+$/g, '');
return cleaned || fallback;
}
function formatReportTimestamp(date = new Date()) {
const pad = value => String(value).padStart(2, '0');
return [
date.getFullYear(),
pad(date.getMonth() + 1),
pad(date.getDate())
].join('') + '_' + [
pad(date.getHours()),
pad(date.getMinutes()),
pad(date.getSeconds())
].join('');
}
function formatReportDisplayTimestamp(date = new Date()) {
return date.toLocaleString('en-US', {
year: 'numeric',
month: 'short',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
timeZoneName: 'short'
});
}
function formatDriveDayFolder(date = new Date()) {
const pad = value => String(value).padStart(2, '0');
return [
date.getFullYear(),
pad(date.getMonth() + 1),
pad(date.getDate())
].join('-');
}
function getDriveMetadataPath(reportPath) {
return `${reportPath}.drive.json`;
}
function saveDriveMetadata(reportPath, result) {
if (!reportPath || !result?.success) return null;
const metadataPath = getDriveMetadataPath(reportPath);
const metadata = {
uploadedAt: new Date().toISOString(),
folderId: result.folder_id || null,
dayFolderId: result.day_folder_id || null,
links: (result.uploaded || []).map(file => ({
name: file.name || '',
webViewLink: file.webViewLink || '',
id: file.id || ''
})).filter(file => file.name || file.webViewLink || file.id)
};
saveJSON(metadataPath, metadata);
return metadata;
}
function loadDriveMetadata(reportPath) {
const metadata = loadJSON(getDriveMetadataPath(reportPath), null);
if (!metadata || !Array.isArray(metadata.links)) return null;
return metadata;
}
function findDriveLink(metadata, fileName) {
return (metadata?.links || []).find(file => file.name === fileName)?.webViewLink || null;
}
function getTopologyFingerprintParts() {
const hosts = discoveredHosts
.map(host => [host.ip, host.mac || '', host.vendor || '', host.hostname || ''].join('|'))
.sort();
const hops = cachedHops
.map(hop => `${hop.hop}:${hop.ip}`)
.sort();
return {
hosts,
hops,
network: cachedNetworkInfo ? `${cachedNetworkInfo.localIP || ''}|${cachedNetworkInfo.cidr || ''}|${cachedNetworkInfo.mask || ''}` : ''
};
}
function getCustomerFingerprintProfile() {
const publicIP = cachedPublicIP && cachedPublicIP !== 'Unknown' ? cachedPublicIP : 'unknown_wan';
const prefix = sanitizeReportSegment(customerProfileConfig.prefix || 'CSP', 'CSP');
const wan = sanitizeReportSegment(publicIP, 'unknown_wan');
const topology = getTopologyFingerprintParts();
const fingerprintSource = JSON.stringify({ publicIP, topology });
const fingerprint = crypto.createHash('sha256').update(fingerprintSource).digest('hex').slice(0, 8);
const baseName = `${prefix}_${wan}`;
const reportLabel = `${prefix}_(${wan})`;
return {
prefix,
publicIP,
wan,
fingerprint,
baseName,
reportLabel,
folderName: `${baseName}_${fingerprint}`,
topology
};
}
function runGoogleDriveHelper(args, input = null) {
return new Promise((resolve) => {
const child = spawn('python3', [path.join(__dirname, 'google_drive.py'), ...args, '--root', __dirname]);
let stdout = '';
let stderr = '';
child.stdout.on('data', data => { stdout += data.toString(); });
child.stderr.on('data', data => { stderr += data.toString(); });
child.on('close', (code) => {
try {
const payload = JSON.parse(stdout.trim() || '{}');
resolve({ ...payload, exitCode: code });
} catch (error) {
resolve({ success: false, exitCode: code, error: stderr.trim() || stdout.trim() || error.message });
}
});
if (input) child.stdin.end(input);
else child.stdin.end();
});
}
function getGoogleDriveRedirectUri() {
return `http://localhost:${PORT}/google-drive/oauth2callback`;
}
async function uploadReportFilesToDrive(socket, filePaths, profile, context = {}) {
const googleDrive = appConfig.googleDrive || {};
const label = context.label || 'report';
if (!googleDrive.enabled) {
logEvent(socket, 'report', `Google Drive sync disabled; skipping upload for ${label}.`);
return null;
}
const existingFiles = filePaths.filter(filePath => filePath && fs.existsSync(filePath));
if (existingFiles.length === 0) {
logEvent(socket, 'error', `Google Drive upload skipped for ${label}: no generated files were found.`);
return null;
}
const folderName = 'Nmap Reports';
const dayFolderName = context.dayFolderName || formatDriveDayFolder();
const args = ['upload', '--folder-name', folderName, '--day-folder-name', dayFolderName, '--files', ...existingFiles];
if (googleDrive.folderId) args.splice(1, 0, '--folder-id', googleDrive.folderId);
const fileNames = existingFiles.map(filePath => path.basename(filePath)).join(', ');
const destination = googleDrive.folderId ? `folder ID ${googleDrive.folderId}` : folderName;
logEvent(socket, 'report', `Google Drive upload starting for ${label}: ${fileNames} -> ${destination}`);
const result = await runGoogleDriveHelper(args);
if (result.success) {
if (result.folder_id && !googleDrive.folderId) saveGoogleDriveConfig({ folderId: result.folder_id });
const uploadedNames = (result.uploaded || []).map(file => file.name).filter(Boolean).join(', ') || `${existingFiles.length} file(s)`;
logEvent(socket, 'report', `Google Drive upload complete for ${label}: ${uploadedNames}${result.folder_id ? ` (folder ID ${result.folder_id})` : ''}`);
(result.uploaded || [])
.map(file => file.webViewLink)
.filter(Boolean)
.forEach(link => logEvent(socket, 'report', `Google Drive file link: ${link}`));
if (context.reportPath) {
saveDriveMetadata(context.reportPath, result);
io.emit('reports_refresh');
}
io.emit('google_drive_upload_complete', { ...result, label });
} else {
logEvent(socket, 'error', `Google Drive upload failed for ${label}: ${result.error || 'Unknown error'}`);
io.emit('google_drive_status', { ...result, label });
}
return result;
}
function isCompleteNmapXML(xmlPath) {
if (!fs.existsSync(xmlPath)) return false;
const xml = fs.readFileSync(xmlPath, 'utf8').trim();
return xml.includes('<nmaprun') && xml.endsWith('</nmaprun>');
}
function buildPhase2Args(usePn = false, fullPortScan = false, options = {}) {
const hostGroupArgs = options.hostGroup
? ['--min-hostgroup', '1', '--max-hostgroup', String(options.hostGroup)]
: [];
const scripts = options.disableScripts ? [] : (options.consolidateScripts ? ['default,vulners'] : ['vulners']);
const rateArgs = options.minRate ? ['--min-rate', String(options.minRate)] : [];
const defaultScriptArgs = options.includeDefaultScripts === false || options.consolidateScripts ? [] : ['-sC'];
const scriptArgs = scripts.length && options.scriptArgs !== false
? ['--script-args', options.scriptArgs || 'mincvss=0,threads=10']
: [];
const args = [
...(fullPortScan ? ['-p-'] : []),
'-sS', '-sV',
...defaultScriptArgs,
'-O',
...(usePn ? ['-Pn'] : []),
options.timing || '-T3',
...rateArgs,
...(options.maxParallelism ? ['--max-parallelism', String(options.maxParallelism)] : []),
...(options.maxRetries ? ['--max-retries', String(options.maxRetries)] : []),
...hostGroupArgs,
'--open',
...(scripts.length ? ['--script', scripts.join(',')] : []),
...scriptArgs,
'--stylesheet', 'nmap-modern.xsl',
'-oX', 'phase2_results.xml',
'-iL', 'targets.tmp'
];
return args;
}
function parseTargetInput(target) {
return String(target || '')
.split(/[,\n]+/)
.map(item => item.trim())
.filter(Boolean);
}
function formatTargetLabel(targets) {
return targets.length > 1 ? targets.join(', ') : targets[0];
}
function compactErrorText(value, maxLength = 4000) {
const text = String(value || '').replace(/\s+\n/g, '\n').trim();
if (text.length <= maxLength) return text;
return text.slice(-maxLength).trim();
}
function saveFailedScanHistory({ target, duration, hostCount, scanKind, customerProfile, error }) {
const history = loadJSON(HISTORY_PATH, []);
history.unshift({
timestamp: new Date().toISOString(),
target,
duration,
hostCount,
scanKind,
status: 'failed',
error: compactErrorText(error),
customerProfile
});
saveJSON(HISTORY_PATH, history.slice(0, 50));
io.emit('reports_refresh');
}
function setupAutoScan(config) {
if (autoScanTask) autoScanTask.stop();
autoScanTask = null;
const autoScan = config.autoScan || {};
if (!autoScan.enabled) return;
const startTime = autoScan.startTime || '01:00';
const [hour = '1', minute = '0'] = startTime.split(':');
const recurrence = ['hourly', 'daily', 'weekly', 'monthly'].includes(autoScan.recurrence)
? autoScan.recurrence
: 'daily';
const cronExpression = {
hourly: `${minute} * * * *`,
daily: `${minute} ${hour} * * *`,
weekly: `${minute} ${hour} * * 0`,
monthly: `${minute} ${hour} 1 * *`
}[recurrence];
autoScanTask = cron.schedule(cronExpression, () => {
const target = autoScan.target || cachedNetworkInfo?.cidr || '192.168.1.0/24';
logEvent(null, 'job', `Starting scheduled ${recurrence} Complete+PDF scan for ${target}...`);
startChainedScan(null, target, true);
});
console.log(`Auto-monitor scheduled ${recurrence} at ${startTime}.`);
}
function logEvent(socket, level, message) {
const entry = { timestamp: new Date().toISOString(), level, message };
console.log(`[${level.toUpperCase()}] ${message}`);
if (socket) socket.emit('log_entry', entry);
else io.emit('log_entry', entry);
}
function ipToInt(ip) {
const parts = String(ip).split('.').map(Number);
if (parts.length !== 4 || parts.some(part => !Number.isInteger(part) || part < 0 || part > 255)) return null;
return (((parts[0] << 24) >>> 0) + (parts[1] << 16) + (parts[2] << 8) + parts[3]) >>> 0;
}
function intToIp(value) {
return [
(value >>> 24) & 255,
(value >>> 16) & 255,
(value >>> 8) & 255,
value & 255
].join('.');
}
function maskHexToInfo(maskHex) {
const normalized = String(maskHex || '').replace(/^0x/i, '').padStart(8, '0').slice(-8);
const maskInt = parseInt(normalized, 16) >>> 0;
if (!Number.isFinite(maskInt)) return null;
const binary = maskInt.toString(2).padStart(32, '0');
if (!/^1*0*$/.test(binary)) return null;
const prefix = binary.indexOf('0') === -1 ? 32 : binary.indexOf('0');
return { maskInt, prefix, dotted: intToIp(maskInt) };
}
function getNetworkCidr(localIP, maskHex) {
const ipInt = ipToInt(localIP);
const maskInfo = maskHexToInfo(maskHex);
if (ipInt === null || !maskInfo) return '';
return `${intToIp((ipInt & maskInfo.maskInt) >>> 0)}/${maskInfo.prefix}`;
}
async function getNetworkInfo() {
return new Promise((resolve) => {
exec("route get default", (error, routeOutput) => {
const ifaceMatch = routeOutput && routeOutput.match(/interface:\s+(\w+)/);
const iface = ifaceMatch ? ifaceMatch[1] : 'en0';
exec(`ifconfig ${iface}`, (error, ifconfigOutput) => {
const ipMatch = ifconfigOutput && ifconfigOutput.match(/inet\s+([0-9.]+)/);
const maskMatch = ifconfigOutput && ifconfigOutput.match(/netmask\s+0x([0-9a-f]+)/);
const localIP = ipMatch ? ipMatch[1] : 'Unknown';
const maskInfo = maskMatch ? maskHexToInfo(maskMatch[1]) : null;
const cidr = maskMatch ? getNetworkCidr(localIP, maskMatch[1]) : '';
const result = {
localIP,
mask: maskInfo ? maskInfo.dotted : (maskMatch ? '0x' + maskMatch[1] : 'Unknown'),
cidr: cidr || '192.168.1.0/24'
};
cachedNetworkInfo = result;
resolve(result);
});
});
});
}
async function getPublicIP() {
try {
const response = await axios.get('https://api.ipify.org?format=json');
cachedPublicIP = response.data.ip;
return cachedPublicIP;
} catch (error) {
cachedPublicIP = 'Unknown';
return 'Unknown';
}
}
function runTraceroute() {
if (isTracerouteRunning) return;
if (!TRACEROUTE_PATH) {
console.warn(describeMissingExecutable('traceroute', 'TRACEROUTE_PATH'));
return;
}
isTracerouteRunning = true;
cachedHops = [];
const traceroute = spawn(TRACEROUTE_PATH, ['-m', '15', '-n', '-q', '1', '8.8.8.8']);
traceroute.stdout.on('data', (data) => {
const lines = data.toString().split('\n');
lines.forEach(line => {
const match = line.match(/^\s*(\d+)\s+([0-9.]+)/);
if (match) {
const hop = { hop: parseInt(match[1]), ip: match[2] };
if (!cachedHops.find(h => h.hop === hop.hop)) {
cachedHops.push(hop);
io.emit('traceroute_hop', hop);
}
}
});
});
traceroute.on('error', error => {
console.error(`[TRACEROUTE ERROR] ${error.message}`);
isTracerouteRunning = false;
});
traceroute.on('close', () => { isTracerouteRunning = false; });
}
function parseNmapXML(xmlPath, onParsed = null) {
if (!fs.existsSync(xmlPath)) {
console.log('XML result file not found at:', xmlPath);
return;
}
if (!isCompleteNmapXML(xmlPath)) {
console.log('XML parse error: Nmap XML is incomplete at:', xmlPath);
return;
}
const xml = fs.readFileSync(xmlPath, 'utf8');
const parser = new xml2js.Parser();
parser.parseString(xml, (err, result) => {
if (err || !result || !result.nmaprun || !result.nmaprun.host) {
console.log('XML parse error or no hosts found in XML');
return;
}
result.nmaprun.host.forEach(hostData => {
const ipData = hostData.address.find(a => a.$.addrtype === 'ipv4');
if (!ipData) return;
const ip = ipData.$.addr;
const macData = hostData.address.find(a => a.$.addrtype === 'mac');
const mac = macData ? macData.$.addr : '';
const vendor = macData ? macData.$.vendor : '';
const hostname = (hostData.hostnames && hostData.hostnames[0].hostname) ? hostData.hostnames[0].hostname[0].$.name : '';
let os = '--';
if (hostData.os && hostData.os[0].osmatch) {
os = hostData.os[0].osmatch[0].$.name;
}
const latency = hostData.times ? (parseFloat(hostData.times[0].$.srtt) / 1000).toFixed(2) + 'ms' : '--';
const ports = [];
const versions = [];
const highCVEs = new Set();
const lowCVEs = new Set();
if (hostData.ports && hostData.ports[0].port) {
hostData.ports[0].port.forEach(p => {
if (p.state[0].$.state === 'open') {
const portId = p.$.portid;
ports.push(portId);
if (p.service) {
const s = p.service[0].$;
const v = `${s.name} ${s.product || ''} ${s.version || ''}`.trim();
if (v) versions.push(`${portId}:${v}`);
}
if (p.script) {
p.script.forEach(s => {
if (s.$.id === 'vulners' && s.table) {
const vulnTables = s.table[0].table;
if (vulnTables) {
vulnTables.forEach(t => {
const getElemName = (elem) => elem.$.name || elem.$.key;
const cvssElem = t.elem ? t.elem.find(e => getElemName(e) === 'cvss') : null;
const idElem = t.elem ? t.elem.find(e => getElemName(e) === 'id') : null;
if (cvssElem && idElem) {
const score = parseFloat(cvssElem._);
const id = idElem._;
if (!id || !id.startsWith('CVE-') || Number.isNaN(score)) return;
if (score >= 7.0) {
highCVEs.add(`${id}(${score})`);
} else {
lowCVEs.add(id);
}
}
});
}
}
});
}
}
});
}
updateDiscoveredHost(ip, {
mac, vendor, hostname, os, latency,
ports: ports.join(', '),
version: versions.join(' | '),
highCVEs: Array.from(highCVEs).join(', '),
lowCVECount: lowCVEs.size
});
});
if (onParsed) onParsed(getScanStats());
});
}
function getWebTargetsFromDiscoveredHosts() {
const webPorts = new Set([80, 443, 3000, 5000, 8000, 8080, 8443, 8888, 9000, 9443]);
const targets = [];
discoveredHosts.forEach(host => {
const versionText = String(host.version || '').toLowerCase();
const serviceByPort = new Map();
versionText.split('|').forEach(chunk => {
const match = chunk.trim().match(/^(\d+):(.+)$/);
if (match) serviceByPort.set(Number(match[1]), match[2]);
});
const ports = String(host.ports || '')
.split(',')
.map(port => Number(String(port).trim()))
.filter(port => {
if (!Number.isInteger(port)) return false;
const serviceHint = serviceByPort.get(port) || '';
return webPorts.has(port) || /\bhttp\b|\bhttps\b/.test(serviceHint);
});
ports.forEach(port => {
const portHint = serviceByPort.get(port) || '';
const isHttps = [443, 8443, 9443].includes(port) || /\bssl\b|\bhttps\b/.test(portHint);
const scheme = isHttps ? 'https' : 'http';
const defaultPort = (scheme === 'http' && port === 80) || (scheme === 'https' && port === 443);
targets.push({
ip: host.ip,
port,
url: `${scheme}://${host.ip}${defaultPort ? '' : `:${port}`}`
});
});
});
return targets.slice(0, 40);
}
function listImageFiles(dirPath) {
if (!fs.existsSync(dirPath)) return [];
return fs.readdirSync(dirPath)
.filter(file => /\.(png|jpe?g|webp)$/i.test(file))
.map(file => ({
file,
path: path.join(dirPath, file),
mtime: fs.statSync(path.join(dirPath, file)).mtimeMs
}))
.sort((a, b) => b.mtime - a.mtime);
}
function runGowitnessCommand(args) {
return new Promise(resolve => {
execFile(GOWITNESS_PATH, args, { cwd: __dirname, timeout: 90000 }, (error, stdout, stderr) => {
resolve({ success: !error, error, stdout, stderr });
});
});
}
async function captureGowitnessTarget(target, screenshotDir, reportBaseName) {
const beforeFiles = new Set(listImageFiles(screenshotDir).map(item => item.file));
const safeName = sanitizeReportSegment(`${target.ip}_${target.port}`);
const explicitPath = path.join(screenshotDir, `${safeName}.png`);
const metaPath = path.join(screenshotDir, `${safeName}.jsonl`);
const commandAttempts = [
['scan', 'single', '--url', target.url, '--screenshot-path', screenshotDir, '--write-jsonl', '--write-jsonl-file', metaPath],
['single', '--url', target.url, '--screenshot-path', screenshotDir, '--write-jsonl', '--write-jsonl-file', metaPath],
['single', '--disable-db', '--screenshot-path', screenshotDir, target.url],
['single', '-o', explicitPath, target.url]
];
for (const args of commandAttempts) {
const result = await runGowitnessCommand(args);
if (!result.success) continue;
const files = listImageFiles(screenshotDir);
const created = files.find(item => !beforeFiles.has(item.file));
if (created) return created;
}
return null;
}
async function captureGowitnessScreenshots(socket, profile, reportBaseName) {
const startedAt = Date.now();
const finishPhase = (status, screenshotCount = 0) => {
const duration = ((Date.now() - startedAt) / 1000).toFixed(2);
io.emit('phase_complete', { phase: 3, duration, ...getScanStats(), screenshotCount, status });
return duration;
};
currentScanPhase = 3;
scanStartTime = startedAt;
io.emit('scan_started', { phase: 3, target: 'Web Services', startTime: scanStartTime, scanKind: currentScanKind });
if (!GOWITNESS_PATH) {
logEvent(socket, 'report', 'Phase 3 gowitness skipped: gowitness is not installed.');
finishPhase('skipped');
return [];
}
const targets = getWebTargetsFromDiscoveredHosts();
if (!targets.length) {
logEvent(socket, 'report', 'Phase 3 gowitness skipped: no web services were identified.');
finishPhase('skipped');
return [];
}