-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1169 lines (1023 loc) · 42.7 KB
/
script.js
File metadata and controls
1169 lines (1023 loc) · 42.7 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
// DOM Elements
const startScanBtn = document.getElementById('startScan');
const stopScanBtn = document.getElementById('stopScan');
const clearResultsBtn = document.getElementById('clearResults');
const targetIPInput = document.getElementById('targetIP');
const scanTypeSelect = document.getElementById('scanType');
const portsInput = document.getElementById('ports');
const scanTimingSelect = document.getElementById('scanTiming');
const skipDiscoveryCheckbox = document.getElementById('skipDiscovery');
const terminal = document.getElementById('terminal');
const resultsContainer = document.getElementById('resultsContainer');
const sourceIPSpan = document.getElementById('sourceIP');
const scanStatusSpan = document.getElementById('scanStatus');
const hostsFoundSpan = document.getElementById('hostsFound');
const nmapStatusSpan = document.getElementById('nmapStatus');
// Proxychains elements
const proxychainsToggle = document.getElementById('proxychainsEnabled');
const proxychainsConfig = document.getElementById('proxychainsConfig');
const chainTypeSelect = document.getElementById('chainType');
const proxyEntriesContainer = document.getElementById('proxyEntries');
const addProxyBtn = document.getElementById('addProxy');
const importProxiesBtn = document.getElementById('importProxies');
const proxyFileInput = document.getElementById('proxyFileInput');
const proxychainsStatusSpan = document.getElementById('proxychainsStatus');
// Export Buttons
const exportJSONBtn = document.getElementById('exportJSON');
const exportCSVBtn = document.getElementById('exportCSV');
const exportPDFBtn = document.getElementById('exportPDF');
// Visualization Elements
const vizTabs = document.querySelectorAll('.viz-tab');
const networkMapCanvas = document.getElementById('networkMap');
const portChartCanvas = document.getElementById('portChart');
const serviceChartCanvas = document.getElementById('serviceChart');
const osChartCanvas = document.getElementById('osChart');
const vulnChartCanvas = document.getElementById('vulnChart');
// State
let isScanning = false;
let scanAbortController = null;
let scanResults = [];
let networkChart = null;
let portChart = null;
let serviceChart = null;
let osChart = null;
let vulnChart = null;
let vizUpdatePending = false;
// Security: HTML Sanitization to prevent XSS
function sanitizeHTML(str) {
if (!str) return '';
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
// Input validation
function validateIPTarget(target) {
const ipPattern = /^(\d{1,3}\.){3}\d{1,3}$/;
const cidrPattern = /^(\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/;
const rangePattern = /^(\d{1,3}\.){3}\d{1,3}-(\d{1,3}\.){3}\d{1,3}$/;
const hostnamePattern = /^[a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?)*$/;
return ipPattern.test(target) || cidrPattern.test(target) ||
rangePattern.test(target) || hostnamePattern.test(target);
}
// Show loading state
function setLoadingState(isLoading) {
const loadingIndicator = document.getElementById('loadingIndicator');
if (loadingIndicator) {
loadingIndicator.style.display = isLoading ? 'flex' : 'none';
}
}
// API Configuration - resolves correctly for both standalone and reverse proxy (e.g., HA ingress)
const API_BASE_URL = new URL('api', window.location.href).pathname;
// Initialize - fetch server status
document.addEventListener('DOMContentLoaded', async () => {
updateVisualizations();
try {
const resp = await fetch(`${API_BASE_URL}/health`);
if (resp.ok) {
const health = await resp.json();
// Display source IP
if (sourceIPSpan && health.source_ip) {
sourceIPSpan.textContent = health.source_ip;
}
// Display nmap status
if (nmapStatusSpan) {
if (health.nmap?.available) {
nmapStatusSpan.textContent = `v${health.nmap.version}`;
nmapStatusSpan.className = 'status-value nmap-ok';
if (!health.privileges?.root) {
nmapStatusSpan.textContent += ' (limited)';
nmapStatusSpan.className = 'status-value nmap-warn';
}
} else {
nmapStatusSpan.textContent = 'NOT INSTALLED';
nmapStatusSpan.className = 'status-value nmap-error';
}
}
// Display proxychains status
if (proxychainsStatusSpan) {
if (health.proxychains?.available) {
proxychainsStatusSpan.textContent = health.proxychains.path || 'Available';
proxychainsStatusSpan.className = 'status-value nmap-ok';
} else {
proxychainsStatusSpan.textContent = 'NOT INSTALLED';
proxychainsStatusSpan.className = 'status-value nmap-error';
if (proxychainsToggle) proxychainsToggle.disabled = true;
}
}
// Log startup info
const proxyStatus = health.proxychains?.available ? 'proxychains ready' : 'no proxychains';
addTerminalLine('INFO',
`Connected to backend. nmap ${health.nmap?.available ? 'v' + health.nmap.version : 'NOT FOUND'}` +
` | ${health.privileges?.root ? 'root' : 'unprivileged'} | ${proxyStatus}`, 'green');
if (!health.nmap?.available) {
addTerminalLine('ERROR', 'nmap is not installed. Install: sudo apt install nmap', 'red');
} else if (!health.privileges?.root) {
addTerminalLine('WARNING', 'Running without root. Some scans limited (stealth, OS, UDP, aggressive).', 'yellow');
}
}
} catch (e) {
addTerminalLine('ERROR', 'Cannot connect to backend. Is server.py running?', 'red');
if (nmapStatusSpan) {
nmapStatusSpan.textContent = 'OFFLINE';
nmapStatusSpan.className = 'status-value nmap-error';
}
}
});
// Event Listeners
startScanBtn.addEventListener('click', startScan);
stopScanBtn.addEventListener('click', stopScan);
clearResultsBtn.addEventListener('click', clearResults);
exportJSONBtn.addEventListener('click', exportJSON);
exportCSVBtn.addEventListener('click', exportCSV);
exportPDFBtn.addEventListener('click', exportPDF);
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key === 'Enter' && !isScanning) {
startScan();
}
if (e.key === 'Escape' && isScanning) {
stopScan();
}
});
// Proxychains toggle
if (proxychainsToggle) {
proxychainsToggle.addEventListener('change', () => {
if (proxychainsConfig) {
proxychainsConfig.style.display = proxychainsToggle.checked ? 'block' : 'none';
}
});
}
// Add proxy entry
if (addProxyBtn) {
addProxyBtn.addEventListener('click', () => {
const entries = proxyEntriesContainer.querySelectorAll('.proxy-entry');
if (entries.length >= 10) return; // Max 10 proxies
addProxyEntry();
updateRemoveButtons();
});
}
// Remove proxy entry (event delegation)
if (proxyEntriesContainer) {
proxyEntriesContainer.addEventListener('click', (e) => {
if (e.target.classList.contains('btn-remove-proxy') && !e.target.disabled) {
e.target.closest('.proxy-entry').remove();
updateRemoveButtons();
}
});
}
// Import proxies from file
if (importProxiesBtn && proxyFileInput) {
importProxiesBtn.addEventListener('click', () => {
proxyFileInput.value = '';
proxyFileInput.click();
});
proxyFileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
// 100KB limit
if (file.size > 102400) {
addTerminalLine('ERROR', 'Proxy file too large (max 100KB)', 'red');
return;
}
const reader = new FileReader();
reader.onload = (evt) => {
const text = evt.target.result;
const parsed = parseProxyFile(text);
if (parsed.length === 0) {
addTerminalLine('WARNING', 'No valid proxies found in file. Supported formats: "socks5 host port", "socks5://host:port", or "host:port"', 'yellow');
return;
}
// Clear existing entries before importing
proxyEntriesContainer.innerHTML = '';
// Cap at 10
const toAdd = parsed.slice(0, 10);
toAdd.forEach(proxy => addProxyEntry(proxy.type, proxy.host, proxy.port));
updateRemoveButtons();
const skipped = parsed.length - toAdd.length;
let msg = `Imported ${toAdd.length} proxies from ${file.name}`;
if (skipped > 0) msg += ` (${skipped} skipped, max 10)`;
addTerminalLine('SUCCESS', msg, 'green');
};
reader.onerror = () => {
addTerminalLine('ERROR', 'Failed to read proxy file', 'red');
};
reader.readAsText(file);
});
}
function parseProxyFile(text) {
const validTypes = ['socks4', 'socks5', 'http', 'https'];
const proxies = [];
const lines = text.split(/\r?\n/);
for (const raw of lines) {
const line = raw.trim();
// Skip empty lines and comments
if (!line || line.startsWith('#') || line.startsWith('//') || line.startsWith(';')) continue;
let type = null, host = null, port = null;
// Format: type://host:port
const uriMatch = line.match(/^(socks[45]|https?):\/\/([^:\/\s]+):(\d+)/i);
if (uriMatch) {
type = uriMatch[1].toLowerCase();
host = uriMatch[2];
port = parseInt(uriMatch[3]);
}
// Format: type host port (space or tab separated)
if (!type) {
const parts = line.split(/[\s\t]+/);
if (parts.length >= 3 && validTypes.includes(parts[0].toLowerCase())) {
type = parts[0].toLowerCase();
host = parts[1];
port = parseInt(parts[2]);
}
}
// Format: host:port (default to socks5)
if (!type) {
const simpleMatch = line.match(/^([^:\/\s]+):(\d+)$/);
if (simpleMatch) {
type = 'socks5';
host = simpleMatch[1];
port = parseInt(simpleMatch[2]);
}
}
// Normalize https -> http for proxychains compatibility
if (type === 'https') type = 'http';
// Validate
if (type && host && port && port >= 1 && port <= 65535) {
if (!['socks4', 'socks5', 'http'].includes(type)) continue;
if (!/^[a-zA-Z0-9]([a-zA-Z0-9.\-]*[a-zA-Z0-9])?$/.test(host)) continue;
if (host.length > 253) continue;
proxies.push({ type, host, port });
}
}
return proxies;
}
function addProxyEntry(type = 'socks5', host = '', port = '') {
const entry = document.createElement('div');
entry.className = 'proxy-entry';
const typeOptions = ['socks5', 'socks4', 'http'].map(t =>
`<option value="${t}"${t === type ? ' selected' : ''}>${t.toUpperCase()}</option>`
).join('');
entry.innerHTML = `
<select class="proxy-type">${typeOptions}</select>
<input type="text" class="proxy-host" placeholder="127.0.0.1" maxlength="253" value="${sanitizeHTML(String(host))}">
<input type="number" class="proxy-port" placeholder="9050" min="1" max="65535" value="${port ? Number(port) : ''}">
<button class="btn-remove-proxy" title="Remove proxy">×</button>
`;
proxyEntriesContainer.appendChild(entry);
}
function updateRemoveButtons() {
const entries = proxyEntriesContainer?.querySelectorAll('.proxy-entry') || [];
entries.forEach(entry => {
const btn = entry.querySelector('.btn-remove-proxy');
if (btn) btn.disabled = entries.length <= 1;
});
}
function getProxyConfig() {
if (!proxychainsToggle?.checked) return null;
const entries = proxyEntriesContainer?.querySelectorAll('.proxy-entry') || [];
const proxies = [];
entries.forEach(entry => {
const type = entry.querySelector('.proxy-type')?.value || 'socks5';
const host = entry.querySelector('.proxy-host')?.value.trim();
const port = parseInt(entry.querySelector('.proxy-port')?.value);
if (host && port && port >= 1 && port <= 65535) {
proxies.push({ type, host, port });
}
});
if (proxies.length === 0) return null;
return {
enabled: true,
chainType: chainTypeSelect?.value || 'dynamic',
proxies
};
}
// Input validation visual feedback
targetIPInput.addEventListener('input', () => {
const value = targetIPInput.value.trim();
if (value && !validateIPTarget(value)) {
targetIPInput.style.borderColor = '#ff5555';
targetIPInput.setAttribute('aria-invalid', 'true');
} else {
targetIPInput.style.borderColor = '#00ff41';
targetIPInput.setAttribute('aria-invalid', 'false');
}
});
// Visualization Tab Switching
const validTabs = ['network', 'ports', 'services', 'os', 'vulns'];
vizTabs.forEach(tab => {
tab.addEventListener('click', () => {
const targetTab = tab.dataset.tab;
if (!validTabs.includes(targetTab)) return;
vizTabs.forEach(t => t.classList.remove('active'));
tab.classList.add('active');
document.querySelectorAll('.viz-panel').forEach(panel => {
panel.classList.remove('active');
});
document.getElementById(`${targetTab}Tab`).classList.add('active');
});
});
// Start Scan
async function startScan() {
const target = targetIPInput.value.trim();
const scanType = scanTypeSelect.value;
const ports = portsInput.value.trim();
const timing = parseInt(scanTimingSelect.value) || 3;
const skipDiscovery = skipDiscoveryCheckbox?.checked || false;
if (!target) {
addTerminalLine('ERROR', 'Target IP/Range is required', 'red');
targetIPInput.focus();
return;
}
if (!validateIPTarget(target)) {
addTerminalLine('ERROR', 'Invalid target format. Use IP, CIDR, range, or hostname.', 'red');
targetIPInput.focus();
return;
}
// Validate proxychains config
const proxyConfig = getProxyConfig();
if (proxychainsToggle?.checked && !proxyConfig) {
addTerminalLine('ERROR', 'Proxychains enabled but no valid proxies configured. Add at least one proxy (host + port).', 'red');
return;
}
isScanning = true;
scanAbortController = new AbortController();
// Update UI
startScanBtn.disabled = true;
stopScanBtn.disabled = false;
scanStatusSpan.textContent = 'SCANNING';
scanStatusSpan.className = 'status-value status-scanning';
setLoadingState(true);
// Clear previous results
scanResults = [];
resultsContainer.innerHTML = '';
const proxyLabel = proxyConfig ? ` via proxychains (${proxyConfig.chainType})` : '';
addTerminalLine('INFO', `Starting ${scanType.toUpperCase()} scan on ${target}${proxyLabel}`, 'cyan');
try {
const requestBody = {
target: target,
scanType: scanType,
ports: ports,
timing: timing,
skipDiscovery: skipDiscovery
};
if (proxyConfig) {
requestBody.proxychains = proxyConfig;
}
const response = await fetch(`${API_BASE_URL}/scan`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestBody),
signal: scanAbortController.signal
});
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
throw new Error(errData.error || `Server error (${response.status})`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop();
const completeLines = lines.filter(line => line.trim());
for (const line of completeLines) {
try {
const data = JSON.parse(line);
handleScanData(data);
} catch (e) {
console.error('Error parsing scan data:', e);
}
}
}
scanStatusSpan.textContent = 'COMPLETE';
scanStatusSpan.className = 'status-value status-complete';
addTerminalLine('SUCCESS', 'Scan completed successfully', 'green');
updateVisualizations();
} catch (error) {
if (error.name === 'AbortError') {
addTerminalLine('WARNING', 'Scan stopped by user', 'yellow');
} else {
addTerminalLine('ERROR', `Scan failed: ${error.message}`, 'red');
}
} finally {
stopScan();
setLoadingState(false);
}
}
// Stop Scan
function stopScan() {
if (scanAbortController) {
scanAbortController.abort();
}
isScanning = false;
startScanBtn.disabled = false;
stopScanBtn.disabled = true;
setLoadingState(false);
if (scanStatusSpan.textContent === 'SCANNING') {
scanStatusSpan.textContent = 'STOPPED';
scanStatusSpan.className = 'status-value status-idle';
}
}
// Handle Scan Data
function handleScanData(data) {
if (data.type === 'log') {
addTerminalLine(data.level || 'INFO', data.message, data.color || 'cyan');
} else if (data.type === 'host') {
scanResults.push(data);
displayHostResult(data);
updateStatistics();
scheduleVizUpdate();
}
}
// Debounce visualization updates
function scheduleVizUpdate() {
if (!vizUpdatePending) {
vizUpdatePending = true;
requestAnimationFrame(() => {
updateVisualizations();
vizUpdatePending = false;
});
}
}
// Display Host Result
function displayHostResult(host) {
const noResults = resultsContainer.querySelector('.no-results');
if (noResults) noResults.remove();
const hostCard = document.createElement('div');
hostCard.className = 'host-card';
const validStatuses = ['up', 'down'];
const safeStatus = validStatuses.includes(host.status) ? host.status : '';
let html = `
<div class="host-header">
<span class="host-ip">${sanitizeHTML(host.ip)}</span>
<span class="host-status ${safeStatus}">${sanitizeHTML(host.status?.toUpperCase())}</span>
</div>
<div class="host-info">
${host.hostname ? `<div class="info-item"><span class="info-label">Hostname</span><span class="info-value">${sanitizeHTML(host.hostname)}</span></div>` : ''}
${host.os ? `<div class="info-item"><span class="info-label">OS</span><span class="info-value">${sanitizeHTML(host.os)}${host.os_accuracy ? ` <span class="os-accuracy">(${sanitizeHTML(host.os_accuracy)}% confidence)</span>` : ''}</span></div>` : ''}
${host.mac ? `<div class="info-item"><span class="info-label">MAC Address</span><span class="info-value">${sanitizeHTML(host.mac)}${host.vendor ? ` <span class="vendor-name">(${sanitizeHTML(host.vendor)})</span>` : ''}</span></div>` : ''}
${host.status_reason ? `<div class="info-item"><span class="info-label">Reason</span><span class="info-value">${sanitizeHTML(host.status_reason)}</span></div>` : ''}
</div>`;
// OS alternatives
if (host.os_alternatives && host.os_alternatives.length > 0) {
html += `<div class="os-alternatives">
<span class="info-label">OS Alternatives:</span>
${host.os_alternatives.map(alt =>
`<span class="os-alt-item">${sanitizeHTML(alt.name)} (${sanitizeHTML(alt.accuracy)}%)</span>`
).join(', ')}
</div>`;
}
// Ports table
if (host.ports && host.ports.length > 0) {
html += `
<table class="ports-table">
<thead><tr>
<th>Port</th><th>State</th><th>Protocol</th><th>Service</th><th>Version</th><th>Reason</th>
</tr></thead>
<tbody>
${host.ports.map(port => {
const validStates = ['open', 'filtered', 'closed', 'open|filtered', 'closed|filtered'];
const safeState = validStates.includes(port.state) ? port.state : 'filtered';
const stateClass = safeState === 'open' ? 'open' :
safeState === 'closed' ? 'closed' : 'filtered';
return `<tr>
<td>${sanitizeHTML(String(port.port))}</td>
<td><span class="port-state-${stateClass}">${sanitizeHTML(port.state)}</span></td>
<td>${sanitizeHTML(port.protocol || 'tcp')}</td>
<td>${sanitizeHTML(port.service) || 'unknown'}</td>
<td>${sanitizeHTML(port.version) || '-'}</td>
<td class="port-reason">${sanitizeHTML(port.reason) || '-'}</td>
</tr>`;
}).join('')}
</tbody>
</table>`;
}
// Vulnerabilities
if (host.vulnerabilities && host.vulnerabilities.length > 0) {
html += `<div class="vuln-section">
<h4 class="vuln-header">Vulnerabilities Found (${host.vulnerabilities.length})</h4>
${host.vulnerabilities.map(v => {
const validSeverities = ['critical', 'high', 'medium', 'low'];
const safeSev = validSeverities.includes(v.severity) ? v.severity : '';
return `<div class="vuln-item">
<span class="vuln-severity ${safeSev}">${sanitizeHTML(v.severity?.toUpperCase())}</span>
<span class="vuln-cve">${sanitizeHTML(v.cve)}</span>
<span class="vuln-name">${sanitizeHTML(v.name)}</span>
${v.port ? `<span class="vuln-port">Port ${sanitizeHTML(String(v.port))}</span>` : ''}
${v.description ? `<details class="vuln-details"><summary>Details</summary><pre class="vuln-output">${sanitizeHTML(v.description)}</pre></details>` : ''}
</div>`;
}).join('')}
</div>`;
}
// Traceroute
if (host.traceroute && host.traceroute.length > 0) {
html += `<div class="traceroute-section">
<h4 class="traceroute-header">Traceroute (${host.traceroute.length} hops)</h4>
<div class="traceroute-hops">
${host.traceroute.map(hop => `<div class="traceroute-hop">
<span class="hop-num">${sanitizeHTML(String(hop.hop))}</span>
<span class="hop-ip">${sanitizeHTML(hop.ip)}</span>
<span class="hop-rtt">${hop.rtt ? sanitizeHTML(hop.rtt) : '* * *'}</span>
${hop.hostname ? `<span class="hop-host">${sanitizeHTML(hop.hostname)}</span>` : ''}
</div>`).join('')}
</div>
</div>`;
}
hostCard.innerHTML = html;
resultsContainer.appendChild(hostCard);
}
// Add Terminal Line
function addTerminalLine(level, message, color = 'cyan') {
const line = document.createElement('div');
line.className = 'terminal-line';
const timestamp = new Date().toLocaleTimeString();
const allowedColors = ['cyan', 'green', 'yellow', 'red', 'white'];
const safeColor = allowedColors.includes(color) ? color : 'cyan';
const promptSpan = document.createElement('span');
promptSpan.className = 'prompt';
promptSpan.textContent = `[${level}]`;
const messageSpan = document.createElement('span');
messageSpan.className = `text-${safeColor}`;
messageSpan.textContent = `[${timestamp}] ${message}`;
line.appendChild(promptSpan);
line.appendChild(messageSpan);
terminal.appendChild(line);
// Limit terminal lines to prevent memory leak during long scans
const MAX_TERMINAL_LINES = 500;
while (terminal.children.length > MAX_TERMINAL_LINES) {
terminal.removeChild(terminal.firstChild);
}
terminal.scrollTop = terminal.scrollHeight;
}
// Clear Terminal
function clearTerminal() {
terminal.innerHTML = `
<div class="terminal-line">
<span class="prompt">[NetScanner]$</span>
<span class="text-green">System initialized. Ready for reconnaissance...</span>
</div>
`;
}
// Clear Results
function clearResults() {
scanResults = [];
resultsContainer.innerHTML = `
<div class="no-results">
<span class="icon">🔍</span>
<p>No scan results yet. Start a scan to see data.</p>
</div>
`;
clearTerminal();
hostsFoundSpan.textContent = '0';
if (networkChart) networkChart.destroy();
if (portChart) portChart.destroy();
if (serviceChart) serviceChart.destroy();
if (osChart) osChart.destroy();
if (vulnChart) vulnChart.destroy();
updateVisualizations();
}
// Update Statistics
function updateStatistics() {
const hostsUp = scanResults.filter(h => h.status === 'up').length;
hostsFoundSpan.textContent = hostsUp;
}
// ── Visualization Functions ─────────────────────────────────────────────
const chartFont = { family: 'Fira Code' };
const chartColors = {
green: 'rgba(0, 255, 65, 0.8)',
red: 'rgba(255, 85, 85, 0.8)',
cyan: 'rgba(0, 255, 255, 0.8)',
pink: 'rgba(255, 0, 128, 0.8)',
orange: 'rgba(255, 170, 0, 0.8)',
purple: 'rgba(128, 0, 255, 0.8)',
yellow: 'rgba(255, 255, 0, 0.8)',
blue: 'rgba(0, 128, 255, 0.8)',
};
function updateVisualizations() {
if (typeof Chart === 'undefined') return; // CDN not loaded
updateNetworkMap();
updatePortChart();
updateServiceChart();
updateOSChart();
updateVulnChart();
}
// Network Map - Bubble chart
function updateNetworkMap() {
const ctx = networkMapCanvas.getContext('2d');
if (networkChart) networkChart.destroy();
const hostsUp = scanResults.filter(h => h.status === 'up');
const hostsDown = scanResults.filter(h => h.status === 'down');
if (hostsUp.length === 0 && hostsDown.length === 0) {
networkChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['No Data'],
datasets: [{ data: [1], backgroundColor: ['rgba(85,85,85,0.5)'], borderWidth: 0 }]
},
options: {
responsive: true, maintainAspectRatio: true,
plugins: {
legend: { labels: { color: '#00ff41', font: chartFont } },
title: { display: true, text: 'Network Overview', color: '#00ff41', font: { ...chartFont, size: 18 } }
}
}
});
return;
}
const upData = hostsUp.map((h, i) => ({
x: i,
y: h.ports?.length || 0,
r: Math.max(5, Math.min(25, (h.ports?.length || 1) * 3)),
label: h.ip
}));
const downData = hostsDown.map((h, i) => ({
x: hostsUp.length + i,
y: 0,
r: 5,
label: h.ip
}));
networkChart = new Chart(ctx, {
type: 'bubble',
data: {
datasets: [
{
label: 'Hosts Up',
data: upData,
backgroundColor: chartColors.green,
borderColor: '#00ff41',
borderWidth: 1
},
{
label: 'Hosts Down',
data: downData,
backgroundColor: chartColors.red,
borderColor: '#ff5555',
borderWidth: 1
}
]
},
options: {
responsive: true, maintainAspectRatio: true,
scales: {
y: {
beginAtZero: true, title: { display: true, text: 'Open Ports', color: '#00ff41', font: chartFont },
ticks: { color: '#00ff41', font: chartFont, stepSize: 1 },
grid: { color: 'rgba(0,255,65,0.1)' }
},
x: {
title: { display: true, text: 'Host Index', color: '#00ff41', font: chartFont },
ticks: { color: '#00ff41', font: chartFont },
grid: { color: 'rgba(0,255,65,0.1)' }
}
},
plugins: {
legend: { labels: { color: '#00ff41', font: chartFont } },
title: { display: true, text: 'Network Topology (bubble size = open ports)', color: '#00ff41', font: { ...chartFont, size: 16 } },
tooltip: {
callbacks: {
label: (ctx) => {
const d = ctx.raw;
return `${d.label}: ${d.y} open ports`;
}
}
}
}
}
});
}
// Port Distribution Chart
function updatePortChart() {
const ctx = portChartCanvas.getContext('2d');
if (portChart) portChart.destroy();
const portCounts = {};
scanResults.forEach(host => {
if (host.ports) {
host.ports.forEach(port => {
if (port.state === 'open') {
const key = `${port.port}/${port.protocol || 'tcp'}`;
portCounts[key] = (portCounts[key] || 0) + 1;
}
});
}
});
const sortedPorts = Object.entries(portCounts).sort((a, b) => b[1] - a[1]).slice(0, 15);
portChart = new Chart(ctx, {
type: 'bar',
data: {
labels: sortedPorts.map(([port]) => port),
datasets: [{
label: 'Occurrences',
data: sortedPorts.map(([, count]) => count),
backgroundColor: chartColors.pink,
borderColor: '#ff0080',
borderWidth: 2
}]
},
options: {
responsive: true, maintainAspectRatio: true, indexAxis: 'y',
scales: {
x: { beginAtZero: true, ticks: { color: '#00ff41', font: chartFont }, grid: { color: 'rgba(0,255,65,0.1)' } },
y: { ticks: { color: '#00ff41', font: chartFont }, grid: { color: 'rgba(0,255,65,0.1)' } }
},
plugins: {
legend: { labels: { color: '#00ff41', font: chartFont } },
title: { display: true, text: 'Top Open Ports', color: '#00ff41', font: { ...chartFont, size: 18 } }
}
}
});
}
// Service Analysis Chart
function updateServiceChart() {
const ctx = serviceChartCanvas.getContext('2d');
if (serviceChart) serviceChart.destroy();
const serviceCounts = {};
scanResults.forEach(host => {
if (host.ports) {
host.ports.forEach(port => {
if (port.state === 'open') {
const service = port.service || 'unknown';
serviceCounts[service] = (serviceCounts[service] || 0) + 1;
}
});
}
});
const sortedServices = Object.entries(serviceCounts).sort((a, b) => b[1] - a[1]).slice(0, 10);
const colors = Object.values(chartColors);
serviceChart = new Chart(ctx, {
type: 'polarArea',
data: {
labels: sortedServices.map(([service]) => service.toUpperCase()),
datasets: [{
data: sortedServices.map(([, count]) => count),
backgroundColor: sortedServices.map((_, i) => colors[i % colors.length]),
borderColor: '#00ff41', borderWidth: 2
}]
},
options: {
responsive: true, maintainAspectRatio: true,
plugins: {
legend: { labels: { color: '#00ff41', font: chartFont } },
title: { display: true, text: 'Service Distribution', color: '#00ff41', font: { ...chartFont, size: 18 } }
},
scales: { r: { ticks: { color: '#00ff41', backdropColor: 'transparent' }, grid: { color: 'rgba(0,255,65,0.2)' } } }
}
});
}
// OS Distribution Chart
function updateOSChart() {
const ctx = osChartCanvas.getContext('2d');
if (osChart) osChart.destroy();
const osCounts = {};
scanResults.forEach(host => {
if (host.os) {
osCounts[host.os] = (osCounts[host.os] || 0) + 1;
}
});
const sortedOS = Object.entries(osCounts).sort((a, b) => b[1] - a[1]).slice(0, 10);
const colors = Object.values(chartColors);
osChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: sortedOS.length > 0 ? sortedOS.map(([os]) => os) : ['No OS Data'],
datasets: [{
data: sortedOS.length > 0 ? sortedOS.map(([, count]) => count) : [1],
backgroundColor: sortedOS.length > 0
? sortedOS.map((_, i) => colors[i % colors.length])
: ['rgba(85,85,85,0.5)'],
borderColor: '#0a0e27', borderWidth: 3
}]
},
options: {
responsive: true, maintainAspectRatio: true,
plugins: {
legend: { position: 'right', labels: { color: '#00ff41', font: chartFont, padding: 12 } },
title: { display: true, text: 'OS Distribution', color: '#00ff41', font: { ...chartFont, size: 18 } }
}
}
});
}
// Vulnerability Severity Chart
function updateVulnChart() {
const ctx = vulnChartCanvas.getContext('2d');
if (vulnChart) vulnChart.destroy();
const sevCounts = { critical: 0, high: 0, medium: 0, low: 0 };
scanResults.forEach(host => {
if (host.vulnerabilities) {
host.vulnerabilities.forEach(v => {
if (v.severity in sevCounts) sevCounts[v.severity]++;
});
}
});
const total = Object.values(sevCounts).reduce((a, b) => a + b, 0);
const sevColors = {
critical: 'rgba(220, 38, 38, 0.9)',
high: 'rgba(255, 85, 85, 0.9)',
medium: 'rgba(255, 170, 0, 0.9)',
low: 'rgba(0, 200, 255, 0.9)'
};
vulnChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Critical', 'High', 'Medium', 'Low'],
datasets: [{
label: 'Vulnerabilities',
data: [sevCounts.critical, sevCounts.high, sevCounts.medium, sevCounts.low],
backgroundColor: Object.values(sevColors),
borderColor: Object.values(sevColors).map(c => c.replace('0.9', '1')),
borderWidth: 2,
borderRadius: 4
}]
},
options: {
responsive: true, maintainAspectRatio: true,
scales: {
y: { beginAtZero: true, ticks: { color: '#00ff41', font: chartFont, stepSize: 1 }, grid: { color: 'rgba(0,255,65,0.1)' } },
x: { ticks: { color: '#00ff41', font: chartFont }, grid: { color: 'rgba(0,255,65,0.1)' } }
},
plugins: {
legend: { display: false },
title: {
display: true,
text: total > 0 ? `Vulnerability Severity (${total} total)` : 'Vulnerability Severity (run vuln/aggressive scan)',
color: total > 0 ? '#ff5555' : '#888',
font: { ...chartFont, size: 16 }
}
}
}
});
}
// ── Export Functions ─────────────────────────────────────────────────────
function exportJSON() {
if (scanResults.length === 0) {
addTerminalLine('WARNING', 'No results to export', 'yellow');
return;
}
const exportData = {
timestamp: new Date().toISOString(),
target: targetIPInput.value,
scanType: scanTypeSelect.value,
totalHosts: scanResults.length,
hostsUp: scanResults.filter(h => h.status === 'up').length,
results: scanResults
};
const dataStr = JSON.stringify(exportData, null, 2);
const blob = new Blob([dataStr], { type: 'application/json' });
downloadFile(blob, `netscan_${Date.now()}.json`);
addTerminalLine('SUCCESS', 'Results exported to JSON', 'green');
exportJSONBtn.classList.add('export-success');
setTimeout(() => exportJSONBtn.classList.remove('export-success'), 500);
}
function sanitizeCSVValue(val) {
let str = String(val ?? '');
// Prevent CSV injection
if (/^[=+\-@\t\r]/.test(str)) {
str = "'" + str;
}
// RFC 4180: escape quotes and wrap in quotes if contains comma, quote, or newline
if (/[",\n\r]/.test(str)) {
str = '"' + str.replace(/"/g, '""') + '"';
}