forked from f-bader/XDRStoryParser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2736 lines (2322 loc) · 98.8 KB
/
script.js
File metadata and controls
2736 lines (2322 loc) · 98.8 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
/**
* XDR Story Parser - Main JavaScript Module
* Handles file upload, parsing, and process tree visualization
*/
class XDRTreeVisualizer {
constructor() {
this.data = null;
this.originalData = null;
this.isAnonymized = false;
this.isZoomedMode = false;
this.zoomedNodeId = null;
this.stats = {
total: 0,
processes: 0,
files: 0,
accounts: 0,
networks: 0,
registry: 0,
others: 0
};
this.expandedNodes = new Set();
this.anonymizationInfo = {
usernames: new Set(),
domains: new Set(),
deviceIds: new Set(),
deviceNames: new Set(),
sids: new Set()
};
this.initializeEventListeners();
this.initializeTheme();
}
/**
* Initialize all event listeners for the application
*/
initializeEventListeners() {
const uploadArea = document.getElementById('upload-area');
const fileInput = document.getElementById('file-input');
if (!uploadArea || !fileInput) {
console.error('Required DOM elements not found');
return;
}
// File input change event
fileInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) {
this.handleFile(e.target.files[0]);
}
});
// Drag and drop events
uploadArea.addEventListener('dragover', (e) => {
e.preventDefault();
e.stopPropagation();
if (uploadArea.classList.contains('minimized')) {
this.restoreUploadSection();
}
uploadArea.classList.add('dragover');
});
uploadArea.addEventListener('dragleave', (e) => {
e.preventDefault();
e.stopPropagation();
uploadArea.classList.remove('dragover');
});
uploadArea.addEventListener('drop', (e) => {
e.preventDefault();
e.stopPropagation();
uploadArea.classList.remove('dragover');
const files = e.dataTransfer.files;
if (files.length > 0) {
this.handleFile(files[0]);
}
});
// Click to upload
uploadArea.addEventListener('click', (e) => {
if (e.target.tagName !== 'BUTTON') {
if (uploadArea.classList.contains('minimized')) {
this.restoreUploadSection();
return;
}
fileInput.click();
}
});
// Keyboard accessibility
uploadArea.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
fileInput.click();
}
});
// Anonymization toggle
const anonymizeCheckbox = document.getElementById('anonymize-checkbox');
if (anonymizeCheckbox) {
anonymizeCheckbox.addEventListener('change', (e) => {
this.toggleAnonymization(e.target.checked);
});
}
}
/**
* Handle file selection and processing
* @param {File} file - The selected file
*/
async handleFile(file) {
// Validate file type
if (!this.isValidFileType(file.name)) {
this.showError('Please select a valid JSON or JSONC file.');
return;
}
// Validate file size (max 50MB)
if (file.size > 50 * 1024 * 1024) {
this.showError('File size too large. Please select a file smaller than 50MB.');
return;
}
this.showLoading();
try {
const text = await this.readFile(file);
// Clean JSONC content first
let jsonText = this.fixForwardSlashes(text);
// Try parsing with basic cleaning first
try {
this.originalData = JSON.parse(jsonText);
this.data = JSON.parse(jsonText);
} catch (parseError) {
console.warn('Basic parsing failed, applying forward slash fix:', parseError.message);
// Simple fix: escape forward slashes in JSON string values
jsonText = this.fixForwardSlashes(jsonText);
try {
this.originalData = JSON.parse(jsonText);
this.data = JSON.parse(jsonText);
} catch (secondParseError) {
console.warn('Forward slash fix failed, attempting deep cleaning:', secondParseError.message);
// Fallback to existing deep cleaning
jsonText = this.deepCleanJson(jsonText);
try {
this.originalData = JSON.parse(jsonText);
this.data = JSON.parse(jsonText);
} catch (thirdParseError) {
console.warn('Deep cleaning failed, attempting JSON repair:', thirdParseError.message);
// Last resort: try to repair the JSON structure
jsonText = this.repairJson(jsonText);
this.originalData = JSON.parse(jsonText);
this.data = JSON.parse(jsonText);
}
}
}
this.validateDataStructure();
this.extractAnonymizationInfo();
this.processData();
this.renderTree();
} catch (error) {
console.error('Error processing file:', error);
this.showError(`Error parsing file: ${error.message}`);
}
}
/**
* Fix forward slashes by escaping them throughout the JSON
* @param {string} jsonText - JSON text that may contain unescaped forward slashes
* @returns {string} - JSON text with all forward slashes escaped
*/
fixForwardSlashes(jsonText) {
console.log('Fixing forward slashes by escaping all / to \/...');
// Global replacement: / -> \/
let fixed = jsonText.replace(/\//g, '\\/');
console.log('Forward slash fix complete');
return fixed;
}
/**
* Check if file type is valid
* @param {string} filename - The filename to check
* @returns {boolean} - Whether the file type is valid
*/
isValidFileType(filename) {
const validExtensions = ['.json', '.jsonc'];
return validExtensions.some(ext => filename.toLowerCase().endsWith(ext));
}
/**
* Read file contents
* @param {File} file - The file to read
* @returns {Promise<string>} - The file contents
*/
readFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.onerror = () => reject(new Error('Failed to read file'));
reader.readAsText(file);
});
}
/**
* Clean JSONC content by removing comments, trailing commas, and handling control characters
* @param {string} text - The JSONC text to clean
* @returns {string} - Clean JSON text
*/
cleanJsonC(text) {
console.log('Starting conservative JSON cleaning...');
// Basic JSONC cleaning
let cleaned = text
.replace(/\/\*[\s\S]*?\*\//g, '') // Remove /* */ comments
.replace(/\/\/.*$/gm, '') // Remove // comments
.replace(/,(\s*[}\]])/g, '$1'); // Remove trailing commas
console.log('JSON cleaning completed');
return cleaned;
}
/**
* Deep clean JSON with more aggressive fixes for problematic content
* @param {string} text - The JSON text to deep clean
* @returns {string} - Deeply cleaned JSON text
*/
deepCleanJson(text) {
let cleaned = text;
try {
console.log('Starting conservative deep JSON cleaning...');
// Handle structural issues
cleaned = cleaned
.replace(/,(\s*[}\]])/g, '$1') // Remove trailing commas
.replace(/([{\[])\s*,/g, '$1') // Remove commas right after opening brackets
.trim();
} catch (cleaningError) {
console.warn('Deep cleaning encountered issues:', cleaningError);
}
return cleaned;
}
/**
* Last resort JSON repair for severely malformed JSON
* @param {string} text - The malformed JSON text
* @returns {string} - Repaired JSON text
*/
repairJson(text) {
console.log('Attempting JSON repair...');
try {
// Try to extract and repair the main structure
let repaired = text.trim();
// Find the main JSON object boundaries more carefully
let depth = 0;
let start = -1;
let end = -1;
let inString = false;
let escape = false;
for (let i = 0; i < repaired.length; i++) {
const char = repaired[i];
if (escape) {
escape = false;
continue;
}
if (char === '\\') {
escape = true;
continue;
}
if (char === '"' && !escape) {
inString = !inString;
continue;
}
if (!inString) {
if (char === '{') {
if (start === -1) start = i;
depth++;
} else if (char === '}') {
depth--;
if (depth === 0 && start !== -1) {
end = i;
break;
}
}
}
}
if (start !== -1 && end !== -1) {
repaired = repaired.substring(start, end + 1);
console.log('Extracted main JSON object');
}
repaired = repaired
// Fix incomplete key-value pairs
.replace(/:\s*$/gm, ': ""')
.replace(/:\s*,/g, ': "",')
.replace(/:\s*}/g, ': ""}')
.replace(/:\s*]/g, ': ""]')
// Fix incomplete arrays and objects
.replace(/,\s*}/g, '}')
.replace(/,\s*]/g, ']')
// Fix missing quotes on keys
.replace(/([{,]\s*)([a-zA-Z_][a-zA-Z0-9_]*)\s*:/g, '$1"$2":')
// Remove trailing commas
.replace(/,(\s*[}\]])/g, '$1');
console.log('JSON repair completed');
return repaired;
} catch (repairError) {
console.error('JSON repair failed:', repairError);
// Ultimate fallback: return a minimal valid JSON
return '{"error": "Failed to parse malformed JSON", "items": []}';
}
}
/**
* Extract information that should be anonymized
*/
extractAnonymizationInfo() {
this.anonymizationInfo = {
usernames: new Set(),
domains: new Set(),
deviceIds: new Set(),
deviceNames: new Set(),
sids: new Set()
};
// Extract from main user and device info
if (this.data.mainUser) {
if (this.data.mainUser.name && !this.isSystemAccount(this.data.mainUser.name)) {
this.anonymizationInfo.usernames.add(this.data.mainUser.name);
}
if (this.data.mainUser.domainName && !this.isSystemDomain(this.data.mainUser.domainName)) {
this.anonymizationInfo.domains.add(this.data.mainUser.domainName);
}
if (this.data.mainUser.sid) this.anonymizationInfo.sids.add(this.data.mainUser.sid);
}
if (this.data.deviceId) this.anonymizationInfo.deviceIds.add(this.data.deviceId);
if (this.data.deviceName) {
// Add the full device name for redaction
this.anonymizationInfo.deviceNames.add(this.data.deviceName);
// For FQDN device names, also add just the hostname part
const deviceParts = this.data.deviceName.split('.');
if (deviceParts.length > 1) {
// Add just the hostname (first part) for separate redaction
const hostname = deviceParts[0];
this.anonymizationInfo.deviceNames.add(hostname);
// Domain extraction - only add proper domains, not infrastructure components
if (deviceParts.length >= 3) {
const potentialDomain = deviceParts.slice(-2).join('.');
// Only add if it looks like a proper domain and isn't a system domain
if (potentialDomain.match(/^[a-zA-Z0-9-]+\.[a-zA-Z]{2,}$/) &&
!this.isSystemDomain(potentialDomain)) {
this.anonymizationInfo.domains.add(potentialDomain);
}
}
}
}
// Extract from all items recursively
if (this.data.items) {
this.data.items.forEach(item => this.extractItemAnonymizationInfo(item));
}
}
/**
* Extract anonymization info from individual items
*/
extractItemAnonymizationInfo(item) {
if (!item) return;
// Extract from entity
if (item.entity) {
if (item.entity.User) {
// Skip system usernames
if (item.entity.User.UserName && !this.isSystemAccount(item.entity.User.UserName)) {
this.anonymizationInfo.usernames.add(item.entity.User.UserName);
}
// Skip system domains
if (item.entity.User.DomainName && !this.isSystemDomain(item.entity.User.DomainName)) {
this.anonymizationInfo.domains.add(item.entity.User.DomainName);
}
if (item.entity.User.Sid) this.anonymizationInfo.sids.add(item.entity.User.Sid);
}
}
// Process children and nested items
if (item.children) {
item.children.forEach(child => this.extractItemAnonymizationInfo(child));
}
if (item.nestedItems) {
item.nestedItems.forEach(nested => this.extractItemAnonymizationInfo(nested));
}
}
/**
* Check if a username is a system account that shouldn't be redacted
*/
isSystemAccount(username) {
const systemAccounts = [
'SYSTEM',
'LOCAL SERVICE',
'NETWORK SERVICE',
'ANONYMOUS LOGON',
'SERVICE',
'BATCH',
'DIALUP',
'EVERYONE',
'AUTHENTICATED USERS',
'IUSR',
'IWAM',
'ASPNET',
'KRBTGT',
'GUEST'
];
return systemAccounts.includes(username.toUpperCase());
}
/**
* Check if a domain name is a system domain that shouldn't be redacted
*/
isSystemDomain(domainName) {
const systemDomains = [
'NT AUTHORITY',
'NT SERVICE',
'BUILTIN'
];
return systemDomains.includes(domainName.toUpperCase());
}
/**
* Toggle anonymization on/off
*/
toggleAnonymization(enable) {
this.isAnonymized = enable;
if (enable) {
this.data = this.createAnonymizedData(JSON.parse(JSON.stringify(this.originalData)));
} else {
this.data = JSON.parse(JSON.stringify(this.originalData));
}
this.updateInvestigationInfo();
this.renderTree();
}
/**
* Create anonymized version of the data
*/
createAnonymizedData(data) {
const anonymized = JSON.parse(JSON.stringify(data));
// Recursively anonymize all string values in the entire JSON structure
this.deepAnonymizeObject(anonymized);
return anonymized;
}
/**
* Recursively anonymize all string values in an object/array
*/
deepAnonymizeObject(obj) {
if (obj === null || obj === undefined) return;
if (typeof obj === 'string') {
return this.anonymizeString(obj);
}
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i++) {
if (typeof obj[i] === 'string') {
obj[i] = this.anonymizeString(obj[i]);
} else if (typeof obj[i] === 'object') {
this.deepAnonymizeObject(obj[i]);
}
}
} else if (typeof obj === 'object') {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'string') {
obj[key] = this.anonymizeString(obj[key]);
} else if (typeof obj[key] === 'object') {
this.deepAnonymizeObject(obj[key]);
}
}
}
}
}
/**
* Anonymize individual item (legacy method - now uses deepAnonymizeObject)
*/
anonymizeItem(item) {
if (!item) return;
this.deepAnonymizeObject(item);
}
/**
* Anonymize a string by replacing sensitive information
*/
anonymizeString(str) {
let result = str;
// Replace device names first (before domains) to handle FQDNs properly
this.anonymizationInfo.deviceNames.forEach(deviceName => {
const regex = new RegExp(this.escapeRegExp(deviceName), 'gi');
result = result.replace(regex, 'REDACTED');
});
// Replace usernames
this.anonymizationInfo.usernames.forEach(username => {
const regex = new RegExp(this.escapeRegExp(username), 'gi');
result = result.replace(regex, 'REDACTED');
});
// Replace domains - use word boundaries for short domains to prevent partial matches
this.anonymizationInfo.domains.forEach(domain => {
// For very short domain components (3 chars or less), use word boundaries
if (domain.length <= 3) {
const regex = new RegExp('\\b' + this.escapeRegExp(domain) + '\\b', 'gi');
result = result.replace(regex, 'REDACTED');
} else {
const regex = new RegExp(this.escapeRegExp(domain), 'gi');
result = result.replace(regex, 'REDACTED');
}
});
// Replace device IDs
this.anonymizationInfo.deviceIds.forEach(deviceId => {
const regex = new RegExp(this.escapeRegExp(deviceId), 'gi');
result = result.replace(regex, 'REDACTED');
});
// Replace SIDs
this.anonymizationInfo.sids.forEach(sid => {
const regex = new RegExp(this.escapeRegExp(sid), 'gi');
result = result.replace(regex, 'REDACTED');
});
return result;
}
/**
* Escape special regex characters
*/
escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* Update the investigation info display
*/
updateInvestigationInfo() {
const investigationInfo = document.getElementById('investigation-info');
if (this.data && (this.data.mainUser || this.data.deviceId || this.data.deviceName)) {
investigationInfo.style.display = 'block';
// Main user info
const mainUser = this.data.mainUser;
const userName = document.getElementById('main-user-name');
const userDomain = document.getElementById('main-user-domain');
const userSid = document.getElementById('main-user-sid');
if (userName) userName.textContent = mainUser?.name || '-';
if (userDomain) userDomain.textContent = mainUser?.domainName || '-';
if (userSid) userSid.textContent = mainUser?.sid || '-';
// Device info
const deviceName = document.getElementById('device-name');
const deviceId = document.getElementById('device-id');
if (deviceName) deviceName.textContent = this.data.deviceName || '-';
if (deviceId) deviceId.textContent = this.data.deviceId || '-';
// Add redacted styling if anonymized
const valueElements = investigationInfo.querySelectorAll('.info-value');
valueElements.forEach(el => {
if (this.isAnonymized && el.textContent === 'REDACTED') {
el.classList.add('redacted');
} else {
el.classList.remove('redacted');
}
});
} else {
investigationInfo.style.display = 'none';
}
}
/**
* Validate that the data structure matches expected XDR story format
*/
validateDataStructure() {
if (!this.data) {
throw new Error('No data found in file');
}
if (!this.data.items || !Array.isArray(this.data.items)) {
throw new Error('Invalid data structure: missing or invalid "items" array');
}
if (this.data.items.length === 0) {
throw new Error('No items found in the data');
}
}
/**
* Process the data and calculate statistics
*/
processData() {
// Reset statistics
this.stats = {
total: 0,
processes: 0,
files: 0,
accounts: 0,
networks: 0,
registry: 0,
others: 0
};
// Process all items recursively
if (this.data && this.data.items) {
this.data.items.forEach(item => this.countItems(item));
}
console.log('Data processing complete:', this.stats);
}
/**
* Recursively count items by type
* @param {Object} item - The item to count
*/
countItems(item) {
if (!item) return;
this.stats.total++;
// Determine item type
const type = this.getItemType(item);
switch (type) {
case 'process':
this.stats.processes++;
break;
case 'file':
this.stats.files++;
break;
case 'account':
this.stats.accounts++;
break;
case 'network':
this.stats.networks++;
break;
case 'registry':
this.stats.registry++;
break;
default:
this.stats.others++;
}
// Process children recursively
if (item.children && Array.isArray(item.children)) {
item.children.forEach(child => this.countItems(child));
}
// Process nested items
if (item.nestedItems && Array.isArray(item.nestedItems)) {
item.nestedItems.forEach(nested => this.countItems(nested));
}
}
/**
* Determine the type of an item
* @param {Object} item - The item to analyze
* @returns {string} - The item type
*/
getItemType(item) {
return item.type || item.actionType || 'other';
}
/**
* Render the complete tree visualization
*/
renderTree() {
const treeContainer = document.getElementById('tree-content');
const processTree = document.getElementById('process-tree');
if (!treeContainer || !processTree) {
console.error('Required DOM elements not found');
return;
}
// Update statistics display
this.updateStatsDisplay();
// Update investigation info
this.updateInvestigationInfo();
// Clear previous content
treeContainer.innerHTML = '';
// Render tree nodes - all children will be shown by default
if (this.data && this.data.items) {
const fragment = document.createDocumentFragment();
this.data.items.forEach(item => {
this.renderNode(item, fragment, 0);
});
treeContainer.appendChild(fragment);
}
// Show the tree container
processTree.style.display = 'block';
// Show the type legend
const typeLegend = document.querySelector('.type-legend');
if (typeLegend) {
typeLegend.style.display = 'block';
}
// Show the tree visualization
const treeVisualization = document.querySelector('.tree-visualization');
if (treeVisualization) {
treeVisualization.style.display = 'block';
}
// Show the download button
const downloadBtn = document.getElementById('download-json-btn');
if (downloadBtn) {
downloadBtn.style.display = 'inline-block';
}
// Show the analysis tools section
const analysisSection = document.getElementById('analysis-tools');
if (analysisSection) {
analysisSection.style.display = 'block';
}
// Minimize the upload section
this.minimizeUploadSection();
// Scroll to tree with smooth animation
setTimeout(() => {
processTree.scrollIntoView({ behavior: 'smooth', block: 'start' });
}, 100);
}
/**
* Update the statistics display
*/
updateStatsDisplay() {
const elements = {
'total-items': this.stats.total,
'process-count': this.stats.processes,
'file-count': this.stats.files
};
Object.entries(elements).forEach(([id, value]) => {
const element = document.getElementById(id);
if (element) {
element.textContent = value.toLocaleString();
}
});
}
/**
* Get a consistent node ID
* @param {Object} node - The node
* @returns {string} - Consistent node ID
*/
getNodeId(node) {
return node.id || `node-${node.title?.main || 'unknown'}-${Date.now()}-${Math.random().toString(36).substr(2, 5)}`;
}
/**
* Render a single node and its children
* @param {Object} node - The node to render
* @param {DocumentFragment|HTMLElement} container - The container to append to
* @param {number} level - The nesting level
*/
renderNode(node, container, level) {
if (!node) return;
// Filter out specific node types we don't want to display
const nodeTitle = this.getNodeTitle(node);
const nodeSubtitle = this.getNodeSubtitle(node);
// Skip nodes with "PE metadata" or "User" in their intro/subtitle
if (nodeSubtitle && (nodeSubtitle.includes('PE metadata') || nodeSubtitle.includes('User') || nodeSubtitle.includes('Web data file'))) {
// Still process children if any
if (node.children && Array.isArray(node.children)) {
node.children.forEach(child => {
this.renderNode(child, container, level);
});
}
if (node.nestedItems && Array.isArray(node.nestedItems)) {
node.nestedItems.forEach(nested => {
this.renderNode(nested, container, level);
});
}
return;
}
const nodeDiv = document.createElement('div');
nodeDiv.className = 'tree-node';
const nodeId = this.getNodeId(node);
nodeDiv.dataset.nodeId = nodeId;
// Create tree structure visualization
const indent = this.createIndentation(level);
// Get node information
const type = this.getItemType(node);
const icon = this.getNodeIcon(type, node);
const title = this.getNodeTitle(node);
const subtitle = this.getNodeSubtitle(node);
const commandLine = this.getNodeCommandLine(node);
const time = this.formatTime(node.time);
// Check if this node or any descendants have alerts
const hasAlertsInTree = this.nodeHasAlertsInTree(node);
// Check if node has details to show
const hasDetails = this.nodeHasDetails(node);
// Check if node has any children (both direct children and nested items)
const hasChildren = (node.children && Array.isArray(node.children) && node.children.length > 0);
const hasNestedItems = (node.nestedItems && Array.isArray(node.nestedItems) && node.nestedItems.length > 0);
const hasAnyChildren = hasChildren || hasNestedItems;
// Build expand button for any children
const expandButton = hasAnyChildren ?
`<span class="expand-button" onclick="xdrVisualizer.toggleNodeChildren('${nodeId}')" title="Click to expand/collapse children">▼</span>` : '';
// Build node HTML
nodeDiv.innerHTML = `
<div class="node-buttons">
<span class="tree-indent">${indent}</span>
${expandButton}
<span class="tree-icon">${icon}</span>
${hasAnyChildren ? `<span class="zoom-button" onclick="xdrVisualizer.zoomToNode('${nodeId}')" title="Zoom to this node and its children">🔍</span>` : '<span class="zoom-placeholder"></span>'}
</div>
<div class="node-content ${type}" ${hasDetails ? `onclick="xdrVisualizer.toggleNodeDetails('${nodeId}')"` : ''} title="${hasDetails ? 'Click for details' : ''}">
<div class="node-title-row">
<div class="node-title">
${hasAlertsInTree ? '<span class="alert-indicator">🚨</span>' : ''}
${this.formatTimelineTitle(title, node)}
</div>
${time ? `<div class="node-time">${time}</div>` : ''}
</div>
${subtitle ? `<div class="node-subtitle">${this.escapeHtml(subtitle)}</div>` : ''}
${commandLine ? `<div class="node-commandline">${this.escapeHtml(this.unescapeForwardSlashes(commandLine))}</div>` : ''}
</div>
`;
// Add details panel if there are details to show
if (hasDetails) {
const detailsPanel = document.createElement('div');
detailsPanel.className = 'details-panel';
detailsPanel.style.display = 'none'; // Start collapsed
detailsPanel.innerHTML = this.renderNodeDetails(node);
nodeDiv.appendChild(detailsPanel);
}
container.appendChild(nodeDiv);
// Add associated alerts as adjacent nodes
if (node.associatedAlerts && Array.isArray(node.associatedAlerts) && node.associatedAlerts.length > 0) {
node.associatedAlerts.forEach(alert => {
if (alert.alertDisplayName) {
const alertDiv = document.createElement('div');
alertDiv.className = 'tree-node alert-node';
const alertNodeId = `alert-${nodeId}-${Math.random().toString(36).substr(2, 5)}`;
alertDiv.dataset.nodeId = alertNodeId;
alertDiv.innerHTML = `
<span class="tree-indent">${this.createIndentation(level)}</span>
<span class="expand-placeholder"></span>
<span class="tree-icon">🚨</span>
<div class="node-content alert">
<div class="node-title">${this.escapeHtml(alert.alertDisplayName)}</div>
</div>
`;
container.appendChild(alertDiv);
}
});
}
// Create children container for all types of children
if (hasAnyChildren) {
const childrenContainer = document.createElement('div');
childrenContainer.className = 'children-container';
childrenContainer.dataset.nodeId = nodeId;
// By default, nothing is collapsed (as requested)
childrenContainer.style.display = 'block';
// Add direct children first
if (hasChildren) {
node.children.forEach(child => {
this.renderNode(child, childrenContainer, level + 1);
});
}
// Add nested items
if (hasNestedItems) {
node.nestedItems.forEach(nested => {
this.renderNode(nested, childrenContainer, level + 1);
});
}
container.appendChild(childrenContainer);
}
}
/**
* Create indentation string for tree structure
* @param {number} level - The nesting level
* @returns {string} - The indentation string
*/
createIndentation(level) {
if (level === 0) return '';
let indent = '';
for (let i = 0; i < level - 1; i++) {
indent += ' '; // 4 spaces for each level
}
indent += '└── '; // Clean L-shaped connector
return indent;
}
/**
* Check if node has children or nested items
* @param {Object} node - The node to check
* @returns {boolean} - Whether the node has children
*/
nodeHasChildren(node) {
return (node.children && node.children.length > 0) ||
(node.nestedItems && node.nestedItems.length > 0);
}
/**
* Check if node has details to display
* @param {Object} node - The node to check
* @returns {boolean} - Whether the node has details
*/
nodeHasDetails(node) {
const hasNodeDetails = node.details && Array.isArray(node.details) && node.details.length > 0;
const hasAdditionalDetails = node.additionalDetails && Array.isArray(node.additionalDetails) && node.additionalDetails.length > 0;
const hasEntityDetails = node.entity && this.entityHasMeaningfulData(node.entity);
return hasNodeDetails || hasAdditionalDetails || hasEntityDetails;
}
/**
* Check if entity has meaningful data to display
* @param {Object} entity - The entity to check
* @returns {boolean} - Whether the entity has meaningful data
*/
entityHasMeaningfulData(entity) {
if (!entity) return false;
// Check for ImageFile information
if (entity.ImageFile) {
const img = entity.ImageFile;
if (img.FullPath || img.Size || img.Sha256 || img.Sha1 || img.Md5 || img.CreationTime) {
return true;
}
}
// Check for User information
if (entity.User) {