-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathsnafflerParser.ps1
More file actions
3192 lines (2677 loc) · 105 KB
/
snafflerParser.ps1
File metadata and controls
3192 lines (2677 loc) · 105 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
<#
.Synopsis
Snaffler output file parser
.Description
Split, sort and beautify the Snaffler output.
Adds explorer++ integration for easy file and share browsing (runas /netonly support)
.Parameter outformat
Output options:
- all : write txt, csv, html and json
- txt : write txt
- csv : write csv
- json : write json
- html : write html
- default : write txt, csv, html
.Parameter in
Input file (full path or file name)
Defaults to snafflerout.txt
.Parameter sort
Field to sort output:
- modified: File modified date (default)
- keyword: Snaffler keyword
- unc: File UNC Path
- rule: Snaffler rule name
.Parameter split
Will create splitted (by severity black, red, yellow, green) export files
.Parameter gridview
Analyze the file and display in PS gridview
.Parameter gridviewload
Switch to load an existing PS gridview output (CSV)
.Parameter gridin
Input file (full path or filename)
Defaults to snafflerout.txt_loot_gridview.csv
.Parameter pte
pte (pass to explorer) exports the shares to Explorer++ as bookmarks (grouped by host)
Explorer++ must be configured to be in Portable mode (settings saved in xml file) and only one instance is allowed.
.Parameter snaffel
Run Snaffler and execute parser with default settings.
.Example
.\snafflerparser.ps1
(will try to load snafflerout.txt and output in HTML, CSV and TXT format)
.Example
.\snafflerparser.ps1 -in mysnaffleroutput.tvs
(will try to load mysnaffleroutput.tvs in HTML, CSV and TXT format)
.Example
.\snafflerparser.ps1 outformat csv -split
(will store results as CSV and split the files by severity)
.Example
.\snafflerparser.ps1 -sort unc
(will sort by the column unc)
.Example
.\snafflerparser.ps1 -gridview
(Will additionally show the output in PS Gridview and save the gridview for later use)
.Example
.\snafflerparser.ps1 -gridviewload
(Load a existing gridview (defaults to snafflerout.txt_loot_gridview.csv))
.Example
.\snafflerparser.ps1 -gridviewload -gridin mygridviewfile.csv
(Load specific gridview file)
.Example
.\snafflerparser.ps1 -pte
(Add Shares as Bookmarks to explorer++)
.LINK
https://github.com/zh54321/snaffler_parser
#>
Param (
[String]
$in = 'snafflerout.txt',
[ValidateSet("modified", "keyword", "rule", "unc")]
[String]
$sort = "modified",
[ValidateSet("all", "csv", "txt", "json","html","default")]
[String]
$outformat = "default",
[switch]
$gridview,
[switch]
$gridviewload,
[switch]
$split,
[String]
$gridin = 'snafflerout.txt_loot_gridview.csv',
[String]
$exlorerpp = '.\Explorer++.exe',
[switch]
$pte,
[switch]
$snaffel,
[switch]
$help
)
# Resolve input file path
if ([System.IO.Path]::IsPathRooted($in)) {
# Absolute path provided
$inPath = $in
} else {
# Relative path or filename only → current directory
$inPath = Join-Path -Path (Get-Location) -ChildPath $in
}
# Normalize (removes .\, ..\, etc.)
$inPath = [System.IO.Path]::GetFullPath($inPath)
# Function section-----------------------------------------------------------------------------------
function Format-TimePrettyUtc {
param([object]$value)
if ($null -eq $value -or [string]::IsNullOrWhiteSpace([string]$value)) { return "" }
try {
switch ($value.GetType().FullName) {
'System.DateTimeOffset' { return $value.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss 'UTC'") }
'System.DateTime' { return ([DateTime]$value).ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss 'UTC'") }
default {
# Try to parse string as DateTimeOffset first (handles Z nicely)
$dto = [DateTimeOffset]::Parse(
[string]$value,
[System.Globalization.CultureInfo]::InvariantCulture,
[System.Globalization.DateTimeStyles]::AssumeUniversal
)
return $dto.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss 'UTC'")
}
}
} catch {
# If parsing fails, just return original string
return [string]$value
}
}
function Format-DurationPretty {
param([TimeSpan]$ts)
if ($null -eq $ts) { return "" }
$parts = @()
if ($ts.Days -gt 0) { $parts += "$($ts.Days)d" }
if ($ts.Hours -gt 0) { $parts += "$($ts.Hours)h" }
if ($ts.Minutes -gt 0) { $parts += "$($ts.Minutes)m" }
# Round to whole seconds (0.5s rounds up)
$totalSecondsRounded = [int][math]::Round($ts.TotalSeconds, 0, [MidpointRounding]::AwayFromZero)
if ($parts.Count -gt 0) {
# show remaining seconds within the minute (also whole)
$secWithinMinute = $totalSecondsRounded % 60
$parts += ("{0}s" -f $secWithinMinute)
} else {
# only seconds (whole)
$parts += ("{0}s" -f $totalSecondsRounded)
}
return ($parts -join " ")
}
function gridview($action){
if ($action -eq "load") {
write-host "[*] Loading stored Gridview file: $($gridin)"
if (!(Test-Path -LiteralPath $inpath -PathType Leaf)) {
write-host "[-] Input file not found $($gridin) use -gridin to specify the file csv"
exit
}
write-host "[*] Starting Gridview (opens in background)"
$passthruobjec = Import-Csv -Path "$($gridin)" | Out-GridView -Title "FullView" -PassThru
} elseif ($action -eq "start") {
write-host "[*] Writing Gridview output file for further use"
$fulloutput | select-object severity,rule,keyword,modified,extension,unc,content | Export-Csv -Path "$($outputname)_loot_gridview.csv" -NoTypeInformation
write-host "[*] Starting Gridview (opens in background)"
$passthruobjec = $fulloutput | select-object severity,rule,keyword,modified,extension,unc,content | Out-GridView -Title "FullView" -PassThru
}
$countpassthruobjec = $passthruobjec | Measure-Object -Line -Property unc
if ($countpassthruobjec.lines -ge 1) {
if (!(Test-Path -Path $exlorerpp -PathType Leaf)) {
write-host "[-] Explorer++ not found at $exlorerpp use -explorerpp to specify the exe file"
exit
} else {
write-host "[-] Explorer++ found at $exlorerpp"
write-host "[*] Found $($countpassthruobjec.lines) object. Trying to open them in Explorer++ "
write-host "[i] Start the script in console window runas ... /netonly to access the files as different user"
write-host "[i] Disables the 'Allow multiple instance' in Explorer++ to open multiple location in tabs "
foreach ($path in $passthruobjec.unc) {
$pathtoopen = (Split-Path -Path $path -Parent)
# Danger danger Invoke-Expression
& $exlorerpp $pathtoopen
Start-Sleep -Milliseconds 500
}
}
} else {
write-host "[!] No PassThru object found"
}
write-host "[*] Exiting"
exit
}
function explorerpp($objects) {
$explorerppfolder = Split-Path $exlorerpp
$configPath = Join-Path $explorerppfolder "config.xml"
# If exlorerpp is ".\Explorer++.exe", Split-Path returns "."
if ($explorerppfolder -eq ".") {
$configPath = Join-Path $pwd "config.xml"
}
# -----------------------------
# Default config.xml template
# -----------------------------
$defaultConfig = @'
<?xml version="1.0"?>
<!-- Preference file for Explorer++ generated by Snafflerparser-->
<ExplorerPlusPlus>
<Settings>
<Setting name="AllowMultipleInstances">yes</Setting>
<Setting name="AlwaysOpenInNewTab">no</Setting>
<Setting name="AlwaysShowTabBar">yes</Setting>
<Setting name="AutoArrangeGlobal">yes</Setting>
<Setting name="CheckBoxSelection">no</Setting>
<Setting name="CloseMainWindowOnTabClose">yes</Setting>
<Setting name="ConfirmCloseTabs">no</Setting>
<Setting name="DisableFolderSizesNetworkRemovable">no</Setting>
<Setting name="DisplayCentreColor" r="255" g="255" b="255"/>
<Setting name="DisplayFont" Height="-13" Width="0" Weight="500" Italic="no" Underline="no" Strikeout="no" Font="Segoe UI"/>
<Setting name="DisplaySurroundColor" r="0" g="94" b="138"/>
<Setting name="DisplayTextColor" r="0" g="0" b="0"/>
<Setting name="DisplayWindowWidth">300</Setting><Setting name="DisplayWindowHeight">90</Setting>
<Setting name="DisplayWindowVertical">no</Setting>
<Setting name="DoubleClickTabClose">yes</Setting>
<Setting name="ExtendTabControl">no</Setting>
<Setting name="ForceSameTabWidth">no</Setting>
<Setting name="ForceSize">no</Setting>
<Setting name="HandleZipFiles">no</Setting>
<Setting name="HideLinkExtensionGlobal">no</Setting>
<Setting name="HideSystemFilesGlobal">no</Setting>
<Setting name="InfoTipType">0</Setting>
<Setting name="InsertSorted">yes</Setting>
<Setting name="Language">9</Setting>
<Setting name="LargeToolbarIcons">no</Setting>
<Setting name="LastSelectedTab">0</Setting>
<Setting name="LockToolbars">yes</Setting>
<Setting name="NextToCurrent">no</Setting>
<Setting name="NewTabDirectory">::{20D04FE0-3AEA-1069-A2D8-08002B30309D}</Setting>
<Setting name="OneClickActivate">no</Setting>
<Setting name="OneClickActivateHoverTime">500</Setting>
<Setting name="OverwriteExistingFilesConfirmation">yes</Setting>
<Setting name="PlayNavigationSound">yes</Setting>
<Setting name="ReplaceExplorerMode">1</Setting>
<Setting name="ShowAddressBar">yes</Setting>
<Setting name="ShowApplicationToolbar">yes</Setting>
<Setting name="ShowBookmarksToolbar">yes</Setting>
<Setting name="ShowDrivesToolbar">yes</Setting>
<Setting name="ShowDisplayWindow">yes</Setting>
<Setting name="ShowExtensions">yes</Setting>
<Setting name="ShowFilePreviews">yes</Setting>
<Setting name="ShowFolders">yes</Setting>
<Setting name="ShowFolderSizes">no</Setting>
<Setting name="ShowFriendlyDates">yes</Setting>
<Setting name="ShowFullTitlePath">no</Setting>
<Setting name="ShowGridlinesGlobal">yes</Setting>
<Setting name="ShowHiddenGlobal">yes</Setting>
<Setting name="ShowInfoTips">yes</Setting>
<Setting name="ShowInGroupsGlobal">no</Setting>
<Setting name="ShowPrivilegeLevelInTitleBar">no</Setting>
<Setting name="ShowStatusBar">yes</Setting>
<Setting name="ShowTabBarAtBottom">no</Setting>
<Setting name="ShowTaskbarThumbnails">yes</Setting>
<Setting name="ShowToolbar">yes</Setting>
<Setting name="ShowUserNameTitleBar">no</Setting>
<Setting name="SizeDisplayFormat">1</Setting>
<Setting name="SortAscendingGlobal">yes</Setting>
<Setting name="StartupMode">1</Setting>
<Setting name="SynchronizeTreeview">yes</Setting>
<Setting name="TVAutoExpandSelected">no</Setting>
<Setting name="UseFullRowSelect">no</Setting>
<Setting name="IconTheme">0</Setting>
<Setting name="ToolbarState" Button0="Back" Button1="Forward" Button2="Up" Button3="Separator" Button4="Folders" Button5="Separator" Button6="Cut" Button7="Copy" Button8="Paste" Button9="Delete" Button10="Delete Permanently" Button11="Properties" Button12="Search" Button13="Separator" Button14="New Folder" Button15="Copy To" Button16="Move To" Button17="Separator" Button18="Views" Button19="Open Command Prompt" Button20="Refresh" Button21="Separator" Button22="Bookmark the current tab" Button23="Organize Bookmarks"/>
<Setting name="TreeViewDelayEnabled">no</Setting>
<Setting name="TreeViewWidth">208</Setting>
<Setting name="ViewModeGlobal">1</Setting>
</Settings>
<WindowPosition>
<Setting name="Position" Flags="0" ShowCmd="1" MinPositionX="0" MinPositionY="0" MaxPositionX="-1" MaxPositionY="-1" NormalPositionLeft="68" NormalPositionTop="64" NormalPositionRight="3368" NormalPositionBottom="1113"/>
</WindowPosition>
<Tabs>
<Tab name="0" Directory="::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" ApplyFilter="no" AutoArrange="yes" Filter="" FilterCaseSensitive="no" ShowHidden="yes" ShowInGroups="no" SortAscending="yes" SortMode="1" ViewMode="1" Locked="no" AddressLocked="no" UseCustomName="no" CustomName="">
<Columns>
<Column name="Generic" Name="yes" Name_Width="150" Type="yes" Type_Width="150" Size="yes" Size_Width="150" DateModified="yes" DateModified_Width="150" Attributes="no" Attributes_Width="150" SizeOnDisk="no" SizeOnDisk_Width="150" ShortName="no" ShortName_Width="150" Owner="no" Owner_Width="150" ProductName="no" ProductName_Width="150" Company="no" Company_Width="150" Description="no" Description_Width="150" FileVersion="no" FileVersion_Width="150" ProductVersion="no" ProductVersion_Width="150" ShortcutTo="no" ShortcutTo_Width="150" HardLinks="no" HardLinks_Width="150" Extension="no" Extension_Width="150" Created="no" Created_Width="150" Accessed="no" Accessed_Width="150" Title="no" Title_Width="150" Subject="no" Subject_Width="150" Author="no" Author_Width="150" Keywords="no" Keywords_Width="150" Comment="no" Comment_Width="150" CameraModel="no" CameraModel_Width="150" DateTaken="no" DateTaken_Width="150" Width="no" Width_Width="150" Height="no" Height_Width="150" MediaBitrate="no" MediaBitrate_Width="150" MediaCopyright="no" MediaCopyright_Width="150" MediaDuration="no" MediaDuration_Width="150" MediaProtected="no" MediaProtected_Width="150" MediaRating="no" MediaRating_Width="150" MediaAlbumArtist="no" MediaAlbumArtist_Width="150" MediaAlbum="no" MediaAlbum_Width="150" MediaBeatsPerMinute="no" MediaBeatsPerMinute_Width="150" MediaComposer="no" MediaComposer_Width="150" MediaConductor="no" MediaConductor_Width="150" MediaDirector="no" MediaDirector_Width="150" MediaGenre="no" MediaGenre_Width="150" MediaLanguage="no" MediaLanguage_Width="150" MediaBroadcastDate="no" MediaBroadcastDate_Width="150" MediaChannel="no" MediaChannel_Width="150" MediaStationName="no" MediaStationName_Width="150" MediaMood="no" MediaMood_Width="150" MediaParentalRating="no" MediaParentalRating_Width="150" MediaParentalRatingReason="no" MediaParentalRatingReason_Width="150" MediaPeriod="no" MediaPeriod_Width="150" MediaProducer="no" MediaProducer_Width="150" MediaPublisher="no" MediaPublisher_Width="150" MediaWriter="no" MediaWriter_Width="150" MediaYear="no" MediaYear_Width="150"/>
<Column name="MyComputer" Name="yes" Name_Width="150" Type="yes" Type_Width="150" TotalSize="yes" TotalSize_Width="150" FreeSpace="yes" FreeSpace_Width="150" VirtualComments="no" VirtualComments_Width="150" FileSystem="no" FileSystem_Width="150"/>
<Column name="ControlPanel" Name="yes" Name_Width="150" VirtualComments="yes" VirtualComments_Width="150"/>
<Column name="RecycleBin" Name="yes" Name_Width="150" OriginalLocation="yes" OriginalLocation_Width="150" DateDeleted="yes" DateDeleted_Width="150" Size="yes" Size_Width="150" Type="yes" Type_Width="150" DateModified="yes" DateModified_Width="150"/>
<Column name="Printers" Name="yes" Name_Width="150" Documents="yes" Documents_Width="150" Status="yes" Status_Width="150" PrinterComments="yes" PrinterComments_Width="150" PrinterLocation="yes" PrinterLocation_Width="150" PrinterModel="yes" PrinterModel_Width="150"/>
<Column name="Network" Name="yes" Name_Width="150" Type="yes" Type_Width="150" NetworkAdaptorStatus="yes" NetworkAdaptorStatus_Width="150" Owner="yes" Owner_Width="150"/>
<Column name="NetworkPlaces" Name="yes" Name_Width="150" VirtualComments="yes" VirtualComments_Width="150"/>
</Columns>
</Tab>
</Tabs>
<DefaultColumns>
<Column name="Generic" Name="yes" Name_Width="150" Type="yes" Type_Width="150" Size="yes" Size_Width="150" DateModified="yes" DateModified_Width="150" Attributes="no" Attributes_Width="150" SizeOnDisk="no" SizeOnDisk_Width="150" ShortName="no" ShortName_Width="150" Owner="no" Owner_Width="150" ProductName="no" ProductName_Width="150" Company="no" Company_Width="150" Description="no" Description_Width="150" FileVersion="no" FileVersion_Width="150" ProductVersion="no" ProductVersion_Width="150" ShortcutTo="no" ShortcutTo_Width="150" HardLinks="no" HardLinks_Width="150" Extension="no" Extension_Width="150" Created="no" Created_Width="150" Accessed="no" Accessed_Width="150" Title="no" Title_Width="150" Subject="no" Subject_Width="150" Author="no" Author_Width="150" Keywords="no" Keywords_Width="150" Comment="no" Comment_Width="150" CameraModel="no" CameraModel_Width="150" DateTaken="no" DateTaken_Width="150" Width="no" Width_Width="150" Height="no" Height_Width="150" MediaBitrate="no" MediaBitrate_Width="150" MediaCopyright="no" MediaCopyright_Width="150" MediaDuration="no" MediaDuration_Width="150" MediaProtected="no" MediaProtected_Width="150" MediaRating="no" MediaRating_Width="150" MediaAlbumArtist="no" MediaAlbumArtist_Width="150" MediaAlbum="no" MediaAlbum_Width="150" MediaBeatsPerMinute="no" MediaBeatsPerMinute_Width="150" MediaComposer="no" MediaComposer_Width="150" MediaConductor="no" MediaConductor_Width="150" MediaDirector="no" MediaDirector_Width="150" MediaGenre="no" MediaGenre_Width="150" MediaLanguage="no" MediaLanguage_Width="150" MediaBroadcastDate="no" MediaBroadcastDate_Width="150" MediaChannel="no" MediaChannel_Width="150" MediaStationName="no" MediaStationName_Width="150" MediaMood="no" MediaMood_Width="150" MediaParentalRating="no" MediaParentalRating_Width="150" MediaParentalRatingReason="no" MediaParentalRatingReason_Width="150" MediaPeriod="no" MediaPeriod_Width="150" MediaProducer="no" MediaProducer_Width="150" MediaPublisher="no" MediaPublisher_Width="150" MediaWriter="no" MediaWriter_Width="150" MediaYear="no" MediaYear_Width="150"/>
<Column name="MyComputer" Name="yes" Name_Width="150" Type="yes" Type_Width="150" TotalSize="yes" TotalSize_Width="150" FreeSpace="yes" FreeSpace_Width="150" VirtualComments="no" VirtualComments_Width="150" FileSystem="no" FileSystem_Width="150"/>
<Column name="ControlPanel" Name="yes" Name_Width="150" VirtualComments="yes" VirtualComments_Width="150"/>
<Column name="RecycleBin" Name="yes" Name_Width="150" OriginalLocation="yes" OriginalLocation_Width="150" DateDeleted="yes" DateDeleted_Width="150" Size="yes" Size_Width="150" Type="yes" Type_Width="150" DateModified="yes" DateModified_Width="150"/>
<Column name="Printers" Name="yes" Name_Width="150" Documents="yes" Documents_Width="150" Status="yes" Status_Width="150" PrinterComments="yes" PrinterComments_Width="150" PrinterLocation="yes" PrinterLocation_Width="150" PrinterModel="yes" PrinterModel_Width="150"/>
<Column name="Network" Name="yes" Name_Width="150" Type="yes" Type_Width="150" NetworkAdaptorStatus="yes" NetworkAdaptorStatus_Width="150" Owner="yes" Owner_Width="150"/>
<Column name="NetworkPlaces" Name="yes" Name_Width="150" VirtualComments="yes" VirtualComments_Width="150"/>
</DefaultColumns>
<Bookmarksv2>
<PermanentItem name="BookmarksToolbar" DateCreatedLow="1671045276" DateCreatedHigh="31227119" DateModifiedLow="1671045276" DateModifiedHigh="31227119">
</PermanentItem>
<PermanentItem name="BookmarksMenu" DateCreatedLow="1671045276" DateCreatedHigh="31227119" DateModifiedLow="1671045276" DateModifiedHigh="31227119">
</PermanentItem>
<PermanentItem name="OtherBookmarks" DateCreatedLow="1671045276" DateCreatedHigh="31227119" DateModifiedLow="1671045276" DateModifiedHigh="31227119">
</PermanentItem>
</Bookmarksv2>
<ApplicationToolbar>
<ApplicationButton name="Notepad" Command="C:\Windows\System32\notepad.exe" ShowNameOnToolbar="yes"/>
<ApplicationButton name="Notepad++" Command=""C:\Program Files\Notepad++\notepad++.exe"" ShowNameOnToolbar="yes"/>
</ApplicationToolbar>
<Toolbars>
<Toolbar name="0" id="0" Style="769" Length="604"/>
<Toolbar name="1" id="1" Style="257" Length="0"/>
<Toolbar name="2" id="2" Style="769" Length="0"/>
<Toolbar name="3" id="3" Style="769" Length="84"/>
<Toolbar name="4" id="4" Style="777" Length="0"/>
</Toolbars>
<ColorRules>
<ColorRule name="Compressed files" FilenamePattern="" CaseInsensitive="no" Attributes="2048" r="0" g="0" b="255"/>
<ColorRule name="Encrypted files" FilenamePattern="" CaseInsensitive="no" Attributes="16384" r="0" g="128" b="0"/>
</ColorRules>
<State>
</State>
</ExplorerPlusPlus>
'@
# -----------------------------
# Load or create config.xml
# -----------------------------
if (-not (Test-Path -LiteralPath $configPath -PathType Leaf)) {
Write-Host "[*] Explorer++ config.xml not found. Creating default at: $configPath"
$defaultConfig | Out-File -FilePath $configPath -Encoding UTF8
} else {
Write-Host "[*] Found Explorer++ config.xml: $configPath"
}
# Load XML
try {
$xmlfile = [xml](Get-Content -LiteralPath $configPath)
} catch {
Write-Host "[-] Failed to read XML at $configPath"
Write-Host " $($_.Exception.Message)"
exit
}
# -----------------------------
# Ensure Settings/ShowBookmarksToolbar=yes
# -----------------------------
$settingsNode = $xmlfile.SelectSingleNode("/ExplorerPlusPlus/Settings")
if (-not $settingsNode) {
$settingsNode = $xmlfile.CreateElement("Settings")
[void]$xmlfile.ExplorerPlusPlus.AppendChild($settingsNode)
}
$showBm = $xmlfile.SelectSingleNode("/ExplorerPlusPlus/Settings/Setting[@name='ShowBookmarksToolbar']")
if (-not $showBm) {
$showBm = $xmlfile.CreateElement("Setting")
[void]$showBm.SetAttribute("name", "ShowBookmarksToolbar")
$showBm.InnerText = "yes"
[void]$settingsNode.AppendChild($showBm)
Write-Host "[*] Added Setting ShowBookmarksToolbar=yes"
} else {
if ($showBm.InnerText -ne "yes") {
$showBm.InnerText = "yes"
Write-Host "[*] Updated Setting ShowBookmarksToolbar=yes"
}
}
# -----------------------------
# Ensure Bookmarksv2 + BookmarksToolbar node exists
# -----------------------------
$bmRoot = $xmlfile.SelectSingleNode("/ExplorerPlusPlus/Bookmarksv2")
if (-not $bmRoot) {
$bmRoot = $xmlfile.CreateElement("Bookmarksv2")
[void]$xmlfile.ExplorerPlusPlus.AppendChild($bmRoot)
}
$toolbarNode = $xmlfile.SelectSingleNode("/ExplorerPlusPlus/Bookmarksv2/PermanentItem[@name='BookmarksToolbar']")
if (-not $toolbarNode) {
$toolbarNode = $xmlfile.CreateElement("PermanentItem")
[void]$toolbarNode.SetAttribute("name", "BookmarksToolbar")
# Minimal timestamps (Explorer++ seems fine with any ints; keeping your style)
[void]$toolbarNode.SetAttribute("DateCreatedLow", "3561811627")
[void]$toolbarNode.SetAttribute("DateCreatedHigh", "3561811627")
[void]$toolbarNode.SetAttribute("DateModifiedLow", "3561811627")
[void]$toolbarNode.SetAttribute("DateModifiedHigh", "3561811627")
[void]$bmRoot.AppendChild($toolbarNode)
Write-Host "[*] Created BookmarksToolbar container"
}
# -----------------------------
# Delete existing bookmarks ONLY under BookmarksToolbar
# -----------------------------
Write-Host "[*] Deleting existing bookmarks in BookmarksToolbar"
$existing = $toolbarNode.SelectNodes("./Bookmark")
foreach ($node in @($existing)) {
[void]$toolbarNode.RemoveChild($node)
}
# -----------------------------
# Add new bookmarks grouped by host
# -----------------------------
$counteruncstats = 0
$counterhosts = 0
# We'll keep folder "name" indexes stable per host, and bookmark "name" indexes per folder
$hostFolders = @{} # server => folderNode
$hostCounters = @{} # server => nextBookmarkIndex
foreach ($element in $objects.unc) {
if ([string]::IsNullOrWhiteSpace($element)) { continue }
# Isolate Server: \\server\share\...
$server = $null
if ($element -match '^\\\\([^\\]+)\\') {
$server = $Matches[1]
} else {
# If it's not a UNC, just bucket it under "(local/other)"
$server = "(other)"
}
if (-not $hostFolders.ContainsKey($server)) {
# Create folder bookmark (Type=0) under BookmarksToolbar
$folder = $xmlfile.CreateElement("Bookmark")
[void]$folder.SetAttribute("name", [string]$counterhosts)
[void]$folder.SetAttribute("Type", "0")
[void]$folder.SetAttribute("GUID", ([guid]::NewGuid().ToString()))
[void]$folder.SetAttribute("ItemName", $server)
[void]$folder.SetAttribute("DateCreatedLow", "3561811627")
[void]$folder.SetAttribute("DateCreatedHigh", "3561811627")
[void]$folder.SetAttribute("DateModifiedLow", "3561811627")
[void]$folder.SetAttribute("DateModifiedHigh", "3561811627")
[void]$toolbarNode.AppendChild($folder)
$hostFolders[$server] = $folder
$hostCounters[$server] = 0
$counterhosts++
}
# Add the actual bookmark (Type=1) inside the server folder
$folderNode = $hostFolders[$server]
$idx = [int]$hostCounters[$server]
$bm = $xmlfile.CreateElement("Bookmark")
[void]$bm.SetAttribute("name", [string]$idx)
[void]$bm.SetAttribute("Type", "1")
[void]$bm.SetAttribute("GUID", ([guid]::NewGuid().ToString()))
[void]$bm.SetAttribute("ItemName", $element)
[void]$bm.SetAttribute("Location", $element)
[void]$bm.SetAttribute("DateCreatedLow", "3561811627")
[void]$bm.SetAttribute("DateCreatedHigh", "3561811627")
[void]$bm.SetAttribute("DateModifiedLow", "3561811627")
[void]$bm.SetAttribute("DateModifiedHigh", "3561811627")
[void]$folderNode.AppendChild($bm)
$hostCounters[$server] = $idx + 1
$counteruncstats++
}
# -----------------------------
# Save
# -----------------------------
try {
$xmlfile.Save($configPath)
Write-Host "[+] Added $counterhosts bookmark-folders with $counteruncstats bookmarks"
Write-Host "[+] Saved: $configPath"
} catch {
Write-Host "[-] Failed to save XML: $($_.Exception.Message)"
exit
}
}
# Function to export as CSV
function exportcsv($object ,$name){
write-host "[*] Storing: $($outputname)_loot_$($name).csv"
$object | select-object severity,rule,keyword,modified,extension,unc,content | Export-Csv -Path "$($outputname)_loot_$($name).csv" -NoTypeInformation
}
# Function to export as TXT
function exporttxt($object ,$name){
write-host "[*] Storing: $($outputname)_loot_$($name).txt"
$object | Format-Table severity,rule,keyword,modified,extension,unc,content -AutoSize | Out-String -Width 10000 | Out-File -FilePath "$($outputname)_loot_$($name).txt"
}
# Function to export as JSON
function exportjson($object ,$name){
write-host "[*] Storing: $($outputname)_loot_$($name).json"
$object | select-object severity,rule,keyword,modified,extension,unc,content | ConvertTo-Json -depth 50 | Out-File -FilePath "$($outputname)_loot_$($name).json"
}
# Function to export as HTML
function exporthtml($object ,$name){
# ---------------- JS: data-driven table with pagination ----------------
$Header = @'
<meta charset="utf-8">
<script>
document.addEventListener("DOMContentLoaded", () => {
// ----------------------------
// Data bootstrap
// ----------------------------
const dataEl = document.getElementById("loot-data");
if (!dataEl) {
console.error("loot-data element not found");
return;
}
const data = JSON.parse(dataEl.textContent);
// ----------------------------
// Report identity + storage keys
// ----------------------------
function getReportSha256() {
const el = document.getElementById("report-sha256");
const sha = (el ? el.textContent : "").trim();
return sha || "";
}
function getCurrentFileName() {
const path = window.location.pathname;
return path.substring(path.lastIndexOf("/") + 1);
}
function getProgressKey() {
const sha = getReportSha256();
return sha
? `snaffler_progress::sha256::${sha}`
: `snaffler_progress::file::${getCurrentFileName()}`;
}
// ----------------------------
// Column visibility
// ----------------------------
const COLS = [
{ key: "check", label: "\u2605 (flagged)" },
{ key: "done", label: "\u2713 (done)" },
{ key: "severity", label: "Severity" },
{ key: "rule", label: "Rule" },
{ key: "keyword", label: "Keyword" },
{ key: "modified", label: "Modified" },
{ key: "unc", label: "UNC" },
{ key: "extension", label: "Extensions" },
{ key: "actions", label: "Actions" },
{ key: "content", label: "Content" }
];
function getColsKey() {
const sha = getReportSha256();
return sha ? `snaffler_cols::${sha}` : `snaffler_cols::${getCurrentFileName()}`;
}
let visibleCols = new Set(COLS.map(c => c.key)); // default: all
function loadCols() {
try {
const raw = localStorage.getItem(getColsKey());
if (!raw) return;
const arr = JSON.parse(raw);
if (Array.isArray(arr) && arr.length) visibleCols = new Set(arr);
} catch {}
}
function saveCols() {
try {
localStorage.setItem(getColsKey(), JSON.stringify(Array.from(visibleCols)));
} catch {}
}
function applyColsToTable() {
const t = document.getElementById("loot-table");
if (!t) return;
// remove any previous hide-col-* classes
t.className = t.className
.split(/\s+/)
.filter(c => c && !c.startsWith("hide-col-"))
.join(" ");
// add hide classes for columns NOT in visibleCols
for (const c of COLS) {
if (!visibleCols.has(c.key)) t.classList.add(`hide-col-${c.key}`);
}
}
// ----------------------------
// Progress persistence (check/done)
// ----------------------------
let progressSaveTimer = null;
function loadProgressFromLocalStorage() {
try {
const raw = localStorage.getItem(getProgressKey());
if (!raw) return;
const saved = JSON.parse(raw);
// saved.items is array of { i, c, d } where i = row index
if (!saved || !Array.isArray(saved.items)) return;
for (const it of saved.items) {
const i = it.i;
if (!Number.isInteger(i) || i < 0 || i >= data.length) continue;
data[i].check = !!it.c;
data[i].done = !!it.d;
}
} catch (e) {
console.warn("Failed to load progress:", e);
}
}
function saveProgressToLocalStorageDebounced() {
clearTimeout(progressSaveTimer);
progressSaveTimer = setTimeout(() => {
try {
// store only rows that have check or done = true (keeps storage small)
const items = [];
for (let i = 0; i < data.length; i++) {
const r = data[i];
if (r.check || r.done) items.push({ i, c: r.check ? 1 : 0, d: r.done ? 1 : 0 });
}
localStorage.setItem(getProgressKey(), JSON.stringify({ v: 1, items }));
} catch (e) {
console.warn("Failed to save progress:", e);
}
}, 150);
}
function resetProgressEverywhere() {
// clear memory
for (let i = 0; i < data.length; i++) {
data[i].check = false;
data[i].done = false;
}
// clear storage
try { localStorage.removeItem(getProgressKey()); } catch {}
// refresh UI
page = 1;
applyAll();
}
// ----------------------------
// Small UI helpers
// ----------------------------
function flashCopied(btn) {
if (!btn) return;
const ico = btn.querySelector(".ico");
if (!ico) return;
if (!btn.dataset.orig) btn.dataset.orig = ico.textContent;
ico.textContent = "\u2705";
btn.classList.add("copied", "show-tip");
clearTimeout(btn._copiedTimer);
btn._copiedTimer = setTimeout(() => {
ico.textContent = btn.dataset.orig;
btn.classList.remove("copied", "show-tip");
}, 800);
}
// faster compares than localeCompare on every call
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
function toTime(s) {
if (!s) return 0;
const iso = String(s).replace(" ", "T");
const t = Date.parse(iso);
return Number.isFinite(t) ? t : 0;
}
// ----------------------------
// State
// ----------------------------
const severityOrder = { Black: 0, Red: 1, Yellow: 2, Green: 3 };
let sortCol = "modified";
let sortDir = "desc"; // default for modified
let severityPrimary = true; // default on load
let page = 1;
let pageSize = parseInt(document.getElementById("pageSize").value, 10);
let searchQ = "";
let searchTimer = null;
let actionsWired = false;
// Filters
let selectedSeverities = new Set(["Black", "Red", "Yellow", "Green"]);
let selectedYears = null; // Set, built from data
let selectedExtensions = null; // Set, built from data
let filterCheckOnly = false;
let filterHideDone = false;
const DEFAULT_SEVERITIES = ["Black", "Red", "Yellow", "Green"];
let view = []; // indexes into data[]
// ----------------------------
// Readable content toggle
// ----------------------------
const READABLE_KEY = (() => {
const sha = getReportSha256();
return sha ? `snaffler_readable::${sha}` : `snaffler_readable::${getCurrentFileName()}`;
})();
let readableMode = false;
// ----------------------------
// Theme
// ----------------------------
const THEME_KEY = "snaffler_theme";
function applyTheme(theme) {
const t = (theme === "light") ? "light" : "dark";
document.documentElement.setAttribute("data-theme", t);
localStorage.setItem(THEME_KEY, t);
// update button label if it exists
const btn = document.getElementById("theme-toggle");
if (btn) btn.textContent = (t === "dark") ? "Light mode" : "Dark mode";
}
function initTheme() {
const saved = localStorage.getItem(THEME_KEY);
applyTheme(saved || "dark");
}
// ----------------------------
// Data helpers
// ----------------------------
function getYear(modified) {
const s = String(modified ?? "");
const m = s.match(/(19|20)\d{2}/);
return m ? m[0] : "(unknown)";
}
function normSeverity(s) {
const x = String(s ?? "").trim().toLowerCase();
if (x === "black") return "Black";
if (x === "red") return "Red";
if (x === "yellow") return "Yellow";
if (x === "green") return "Green";
return "";
}
function escapeHtml(s) {
return String(s ?? "")
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function applyReadableMode(on) {
readableMode = !!on;
document.documentElement.classList.toggle("readable-on", readableMode);
const btn = document.getElementById("toggle-readable");
if (btn) btn.textContent = readableMode ? "Unescape: ON" : "Unescape: OFF";
try { localStorage.setItem(READABLE_KEY, readableMode ? "1" : "0"); } catch {}
}
function initReadableMode() {
try {
const raw = localStorage.getItem(READABLE_KEY);
applyReadableMode(raw === "1");
} catch {
applyReadableMode(false);
}
}
// Function to unescape snaffler preview text
function makeReadablePreviewText(input) {
let s = String(input ?? "");
if (!s) return "";
// 1) Normalize PowerShell line-continuation + escaped newline: `\r\n -> \n
s = s.replace(/`\r\n/g, "\n");
// 2) Convert escaped newlines into real newlines
s = s.replace(/\\r\\n/g, "\n");
s = s.replace(/\\n/g, "\n");
// 3) Convert escaped tabs to real tabs
s = s.replace(/\\t/g, "\t");
// 4) Convert escaped spaces "\ " to real spaces
s = s.replace(/\\ /g, " ");
// unescape common "backslash-escaped" punctuation: \$ \. \{ \} \( \) etc.
s = s.replace(/\\([#$.{},()[\]|+*?^=!<>:;'"`-])/g, "$1");
// unescape double-backslashes to single backslash (\\ -> \)
s = s.replace(/\\\\/g, "\\");
// 5) Merge multiple newlines into a single newline
s = s.replace(/\n{2,}/g, "\n");
return s;
}
function highlightKeyword(content, keyword) {
const safe = escapeHtml(content);
if (!keyword) return safe;
const k = String(keyword).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const re = new RegExp(`(${k})`, "gi");
return safe.replace(re, `<span style="color:red;">$1</span>`);
}
function highlightSearchEscaped(escapedText, query) {
// escapedText MUST already be escaped via escapeHtml()
const q = String(query || "").trim();
if (!q) return escapedText;
const tokens = q.toLowerCase().split(/\s+/).filter(t => t.length >= 2);
if (!tokens.length) return escapedText;
let out = escapedText;
for (const tok of tokens) {
const re = new RegExp(`(${tok.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})`, "gi");
out = out.replace(re, `<mark class="hit">$1</mark>`);
}
return out;
}
function parentOfUNC(unc) {
if (!unc) return "";
const p = unc.lastIndexOf("\\");
return p > 1 ? unc.slice(0, p) : unc;
}
// ----------------------------
// Actions column + clipboard helpers
// ----------------------------
function fallbackCopy(text) {
const ta = document.createElement("textarea");
ta.value = text;
ta.setAttribute("readonly", "");
ta.style.position = "fixed";
ta.style.top = "-9999px";
document.body.appendChild(ta);
ta.select();
try { document.execCommand("copy"); } catch {}
document.body.removeChild(ta);
}
function copyToClipboard(text) {
const t = String(text || "");
if (!t) return;
// Modern clipboard API (works in secure contexts; file:// may vary)
if (navigator.clipboard) {
navigator.clipboard.writeText(t).catch(() => fallbackCopy(t));
} else {
fallbackCopy(t);
}
}
function openLink(unc) {
const parent = parentOfUNC(unc).replaceAll(" ", "%20");
return `<a class="act act-open"
target="_blank"
href="file://${parent}/"
title="Open folder"
aria-label="Open folder">
📂
</a>`;
}
function saveLink(unc) {
const u = (unc || "").replaceAll(" ", "%20");
return `<a class="act act-save"
target="_blank"
href="file://${u}"
download
title="Save file"
aria-label="Save file">
💾
</a>`;
}
function actionsHtml(unc) {
const u = String(unc || "");
const parent = parentOfUNC(u);
const uAttr = escapeHtml(u);
const pAttr = escapeHtml(parent);
return `
<div class="row-actions" data-unc="${uAttr}" data-parent="${pAttr}">
<button class="act act-copy-unc" type="button" title="Copy UNC">
<span class="ico">📋</span><span class="tip">Copied</span>
</button>
<button class="act act-copy-parent" type="button" title="Copy parent UNC">
<span class="ico">📝</span><span class="tip">Copied</span>
</button>
${openLink(u)}
${saveLink(u)}
</div>
`;
}
function colorSeverityVisible() {
document.querySelectorAll("#loot-body tr td:nth-child(3)").forEach(td => {
// ALWAYS reset first
td.style.backgroundColor = "";
td.style.color = "";
const sev = td.textContent.trim();
switch (sev) {
case "Black":
td.style.backgroundColor = "#333";
td.style.color = "white";
break;
case "Red":
td.style.backgroundColor = "#d9534f";
td.style.color = "white";
break;
case "Yellow":
td.style.backgroundColor = "#CFAD01";
td.style.color = "white";
break;
case "Green":
td.style.backgroundColor = "#79C55B";
td.style.color = "white";
break;
}
});
}
// ----------------------------
// Save HTML (with embedded state)
// ----------------------------
function updateCheckboxAttributesForSave() {
// Ensure current page checkboxes have checked attrs
document.querySelectorAll("#loot-body input[type='checkbox']").forEach(cb => {
if (cb.checked) cb.setAttribute("checked", "checked");
else cb.removeAttribute("checked");
});
// IMPORTANT: write all checkbox states into JSON blob so saved HTML reloads state
dataEl.textContent = JSON.stringify(data);
}
function saveStateToHTML() {
updateCheckboxAttributesForSave();
const html = document.documentElement.outerHTML;
const blob = new Blob([html], { type: "text/html" });
const currentFileName = getCurrentFileName();
const newFileName = currentFileName.replace(/\.html$/, "") + "_save.html";
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = newFileName;
link.click();
}
// ----------------------------
// Export current view to CSV
// ----------------------------
function csvEscape(v) {
const s = String(v ?? "");
// Always quote; escape quotes by doubling them
return `"${s.replace(/"/g, '""')}"`;
}
function buildCsvFromRows(rows) {
// Keep stable ordering, but only include visible columns
const cols = COLS.filter(c => visibleCols.has(c.key));
// Map column keys to row fields (actions is UI-only)
const headers = cols
.filter(c => c.key !== "actions")
.map(c => c.key);
let csv = headers.join(",") + "\r\n";
for (const r of rows) {