-
Notifications
You must be signed in to change notification settings - Fork 14
/
RetrievIR.ps1
1529 lines (1429 loc) · 68.1 KB
/
RetrievIR.ps1
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
RetrievIR is an evidence-collection utility designed to collect forensic artifacts from local and remote hosts.
.PARAMETER evidence_dir
The fully-qualified file-path where evidence should be stored.
.PARAMETER config
The fully-qualified path to a JSON configuration file or a directory containing multiple configuration files.
Example: .\RetrievIR.ps1 -config C:\myconfig.json
Example: .\RetrievIR.ps1 -config C:\configs
.PARAMETER targets
Specify collection-targets as hostnames or IP addresses in a comma-delimited manner.
Example: .\RetrievIR.ps1 -targets hostname1,hostname2
.PARAMETER target_file
Specify a file containing line-delimited hostnames.
Example: .\RetrievIR.ps1 -target_file C:\targets.txt
.PARAMETER creds
Tells RetrievIR to prompt for new credentials to execute as.
Example: .\RetrievIR.ps1 -creds
.PARAMETER noshadow
Tells RetrievIR to not create a Shadow Copy - this will remove the capability to collect certain artifacts.
Example: .\RetrievIR.ps1 -noshadow
.PARAMETER simulate
Tells RetrievIR to skip actual collection actions and calculate the total size of data to be collected based on the specified configuration.
Example: .\RetrievIR.ps1 -simulate
.PARAMETER categoryscan
Tells RetrievIR to list out all categories available in the specified configuration.
Example: .\RetrievIR.ps1 -categoryscan
.PARAMETER tagscan
Tells RetrievIR to list out all tags available in the specified configuration.
Example: .\RetrievIR.ps1 -tagscan
.PARAMETER categories
Provide a comma-delimited list of categories - only objectives which match will be executed.
Example: .\RetrievIR.ps1 -categories antivirus,recentfiles
.PARAMETER tags
Provide a comma-delimited list of tags - only objectives which match will be executed.
Example: .\RetrievIR.ps1 -tags sans_triage
.EXAMPLE
.\RetrievIR.ps1 -tags sans_triage - Capture most artifacts described in the SANS Triage package within KAPE
.EXAMPLE
.\RetrievIR.ps1 -categories antivirus,recentfiles : Specify to only collect evidence when the category is within the provided values.
.EXAMPLE
.\RetrievIR.ps1 -tags sans_triage -simulate : Find out how much size the total data collection will consume without actually executing it.
.OUTPUTS
None
.NOTES
None
.INPUTS
None
.LINK
https://github.com/joeavanzato/RetrievIR
#>
# General Thought Process
# Configuration file will specify files, registry keys or commands to execute on local or remote hosts
# Target List will be provided via command-line or file - no list means localhost only
# If targeting is specified, user should specify whether SMB or WinRM will be used for file-transfer capabilities to retrieve evidence from remote hosts (TODO)
# If none is specified, SMB will be assumed.
[CmdletBinding()]
param
(
[Parameter(Mandatory = $false, HelpMessage = 'The fully-qualified file-path where evidence should be stored, defaults to $PSScriptRoot\evidence')]
[string]$evidence_dir = "$PSScriptRoot\evidence",
[Parameter(Mandatory = $false, HelpMessage = 'The fully-qualified file-path for the configuration file, defaults to $PSScriptRoot\configs')]
[string]$config = "$PSScriptRoot\configs",
[Parameter(Mandatory = $false, HelpMessage = 'Comma-delimited list of target computers - leaving blank will only target "127.0.0.1" (localhost).')]
[array]$targets,
[Parameter(Mandatory = $false, HelpMessage = 'Line-delimited list of target computers - if specified, -targets parameter will be ignored.')]
[string]$target_file,
[Parameter(Mandatory = $false, HelpMessage = 'If specified, will prompt for credentials to use for remote operations (if not using current user). [TODO]')]
[switch]$creds,
[Parameter(Mandatory = $false, HelpMessage = 'If specified, will not create Shadow Copy to access locked system files.')]
[switch]$noshadow,
[Parameter(Mandatory = $false, HelpMessage = 'If specified, will skip any "interactive" prompts.')]
[switch]$nointeract,
[Parameter(Mandatory = $false, HelpMessage = 'Return information on how many files and total size of data that would be collected with specified configuration.')]
[switch]$simulate,
[Parameter(Mandatory = $false, HelpMessage = 'Return information on categories available for use with -categories argument from specified configuration file(s).')]
[switch]$categoryscan,
[Parameter(Mandatory = $false, HelpMessage = 'Return information on tags available for use with -tags argument from specified configuration file(s).')]
[switch]$tagscan,
[Parameter(Mandatory = $false, HelpMessage = 'Only use directives which have one or more of the specified tags.')]
[array]$tags = @("*"),
[Parameter(Mandatory = $false, HelpMessage = 'If specified, RetrievIR will hash all collected files via SHA256.')]
[switch]$hash,
[Parameter(Mandatory = $false, HelpMessage = 'Select specific directive-categories to run using comma-delimited arguments - only directives which are contained within the list will be executed.')]
[array]$categories = @("*")
)
if ($tags.GetType().Name -eq "String"){
$tags = @($tags)
}
if ($categories.GetType().Name -eq "String"){
$categories = @($categories)
}
$global_configuration = [hashtable]::Synchronized(@{})
$global_configuration.hostname = hostname
$log_path = $PSScriptRoot + "\RetrievIRAudit.log"
$shadow_stamp = (Get-Date).toString("HH:mm:ss") -replace (":","_")
$shadowcopy_name = "retrievir_copy_$shadow_stamp"
$shadowcopy_output_status_file = "retrievir_vss_status_$shadow_stamp"
# We will send the functions to a remote computer and output the result to $shadowcopy_output_status_file
# If shadow creation is successful, file contents will contain below:
# SUCCESS:$SHADOWID
# If it is a failure, instead we will store only the below:
# FAILURE:
# Below functions modified From JJ Fulmer awesome answer at https://stackoverflow.com/questions/14207788/accessing-volume-shadow-copy-vss-snapshots-from-powershell
$new_shadow_script = "
function New-ShadowLink {
`$linkPath=`"`$(`$ENV:SystemDrive)\$shadowcopy_name`"
try {
`$class=[WMICLASS]`"root\cimv2:win32_shadowcopy`";
`$result = `$class.create(`"`$ENV:SystemDrive\`", `"ClientAccessible`");
`$shadow = Get-CimInstance -ClassName Win32_ShadowCopy | Where-Object ID -eq `$result.ShadowID
`$target = `"`$(`$shadow.DeviceObject)\`";
`$shadowid = `$shadow.ID
Invoke-Expression -Command `"cmd /c mklink /j '`$linkPath' '`$target'`";
Set-Content -Path C:\Windows\Temp\$shadowcopy_output_status_file.txt -Value SUCCESS:`$shadowid
} catch {
Set-Content -Path C:\Windows\Temp\$shadowcopy_output_status_file.txt -Value 'FAILURE:'
}
}
New-ShadowLink
"
$new_shadow_bytes = [System.Text.Encoding]::Unicode.GetBytes($new_shadow_script)
$new_shadow_b64 = [Convert]::ToBase64String($new_shadow_bytes)
$new_shadow_command = "powershell.exe -NoLogo -NonInteractive -ExecutionPolicy Unrestricted -WindowStyle Hidden -EncodedCommand " + $new_shadow_b64
$remove_shadow_script = "
function Remove-ShadowLink {
`$linkPath=`"`$(`$ENV:SystemDrive)\$shadowcopy_name`"
`$data = Get-Content C:\Windows\Temp\$shadowcopy_output_status_file.txt
`$split = `$data -split `":`"
if (`$split[0] -eq `"SUCCESS`"){
`$shadowid = `$split[1]
vssadmin delete shadows /shadow=`$shadowid /quiet
try {
Remove-Item -Force -Recurse `$linkPath -ErrorAction Stop;
}
catch {
Invoke-Expression -Command `"cmd /c rmdir /S /Q '`$linkPath'`";
}
} else {
}
}
Remove-ShadowLink
"
$remove_shadow_bytes = [System.Text.Encoding]::Unicode.GetBytes($remove_shadow_script)
$remove_shadow_b64 = [Convert]::ToBase64String($remove_shadow_bytes)
$remove_shadow_command = "powershell.exe -NoLogo -NonInteractive -ExecutionPolicy Unrestricted -WindowStyle Hidden -EncodedCommand " + $remove_shadow_b64
function Create-Directory ($dir) {
#Log-Message "[+] Creating Evidence Directory: $dir" -quiet $true
if (Test-Path $dir){
#Log-Message "[!] Directory already exists: $dir" -quiet $true
return
}
try {
New-Item -Path $dir -ItemType Directory | Out-Null
Log-Message "[!] Evidence Directory Created: $dir" -quiet $true
}catch{
Log-Message "[!] Could not create directory: $dir" $true
}
}
function Log-Message ($msg, $error, $color, $quiet){
$timestamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
if (-not $color){
$color = "White"
}
if (-not $quiet){
$quiet = $false
}
if ($error){
Write-Warning $msg
} elseif ($quiet){
} else{
Write-Host $msg -ForegroundColor $color
}
Add-Content -Path $log_path -Value "$timestamp - $msg"
}
function Summarize-Configuration ($data){
Log-Message "[!] Configuration Summary:"
$category_list = New-Object -TypeName 'System.Collections.ArrayList'
$tag_list = New-Object -TypeName 'System.Collections.ArrayList'
if ($data.files){
$file_directives = 0
ForEach ($object in $data.files){
$name = $object.psobject.Properties.Name
ForEach ($j in $name){
ForEach ($k in $object.$j){
ForEach ($directive in $k){
if (-not ($directive.category -in $category_list)){
$category_list.Add($directive.category) | Out-Null
}
if ($directive.tags){
ForEach ($t in $directive.tags){
if (-not ($t -in $tag_list)){
$tag_list.Add($t) | Out-Null
}
}
}
if ($tags[0] -eq "*"){
} elseif ($tags){
if ($directive.tags){
$pass = $true
ForEach ($t in $directive.tags){
if ($t -in $tags){
$pass = $false
}
}
} else {
continue
}
if ($pass){
continue
}
}
if (-not ($categories[0] -eq '*') -and -not ($directive.category -in $categories)) {
continue
}
$file_directives += 1
}
}
}
#$file_dir_count = $name | Measure-Object
}
Log-Message "[+] File Objectives: $file_directives"
} else {
Log-Message "[+] File Objectives: 0"
}
if ($data.registry){
$regdirectives = 0
ForEach ($i in $data.registry){
$name = $i.psobject.Properties.Name
#$reg_dir_count = $name | Measure-Object
ForEach ($j in $name){
ForEach ($k in $i.$j){
ForEach ($directive in $k){
if (-not ($directive.category -in $category_list)){
$category_list.Add($directive.category) | Out-Null
}
if ($directive.tags){
ForEach ($t in $directive.tags){
if (-not ($t -in $tag_list)){
$tag_list.Add($t) | Out-Null
}
}
}
if ($tags[0] -eq "*"){
} elseif ($tags){
if ($directive.tags){
$pass = $true
ForEach ($t in $directive.tags){
if ($t -in $tags){
$pass = $false
}
}
} else {
continue
}
if ($pass){
continue
}
}
if (-not ($categories[0] -eq '*') -and -not ($directive.category -in $categories)) {
continue
}
$regdirectives += 1
}
}
}
}
Log-Message "[+] Registry Objectives: $regdirectives"
} else {
Log-Message "[+] Registry Objectives: 0"
}
if ($data.commands){
$cmddirectives = 0
ForEach ($i in $data.commands){
$name = $i.psobject.Properties.Name
#$command_count = $name | Measure-Object
ForEach ($j in $name){
ForEach ($k in $i.$j){
ForEach ($directive in $k){
if (-not ($directive.category -in $category_list)){
$category_list.Add($directive.category) | Out-Null
}
if ($directive.tags){
ForEach ($t in $directive.tags){
if (-not ($t -in $tag_list)){
$tag_list.Add($t) | Out-Null
}
}
}
if ($tags[0] -eq "*"){
} elseif ($tags){
if ($directive.tags){
$pass = $true
ForEach ($t in $directive.tags){
if ($t -in $tags){
$pass = $false
}
}
} else {
continue
}
if ($pass){
continue
}
}
if (-not ($categories[0] -eq '*') -and -not ($directive.category -in $categories)) {
continue
}
$cmddirectives += 1
}
}
}
}
Log-Message "[+] Command Objectives: $cmddirectives"
} else {
Log-Message "[+] Command Objectives: 0"
}
if ($categoryscan){
Log-Message "[!] Available Categories in Scanned Configs: $($category_list -join ', ')"
exit
}
if ($tagscan){
Log-Message "[!] Available Tags in Scanned Configs: $($tag_list -join ', ')"
exit
}
if ($file_directives -eq 0 -and $regdirectives -eq 0 -and $cmddirectives -eq 0){
Log-Message "[!] No objectives match specified configs/categories/tags!"
Log-Message "[!] Exiting!"
exit
}
}
function Merge ($target, $source, $index) {
$source.psobject.Properties | % {
if ($_.TypeNameOfValue -eq 'System.Management.Automation.PSCustomObject' -and $target."$($_.Name)" ) {
if ($($_.Name) -in "files","registry","commands"){
Merge $target."$($_.Name)" $_.Value
} else {
"[!] Duplicate Module Name Detected between configurations: $($_.Name)"
"[!] Source File: $($file_list[$counter])"
"[!] First detected module will be used: $($module_first_seen[$_.Name])"
}
}
else {
$target | Add-Member -MemberType $_.MemberType -Name $_.Name -Value $_.Value -Force
}
}
}
function Get-Configuration {
# This function will first validate that the specified configuration path/file is a valid path
# Then it will acquire a list of all files in that directory
# Then it will read / import each JSON and merge them into a growing PowerShell object
# The Merge function will handle duplicately-named keys - these will be alerted to and only the first key will be used for each collection directive
if (-not (Test-Path $config)){
Log-Message "Could not find specified configuration path: $config" $true
Log-Message "[*] Please double check the specified file exists!"
Log-Message "[!] Exiting..."
exit
}
<# try {
$data = Get-Content $config -Raw | ConvertFrom-Json
} catch {
Log-Message "[!] Error reading/parsing specified configuration file!" $true
Log-Message "[!] Exiting..."
exit
}#>
try {
$file_list = Get-ChildItem -Path $config -Filter *.json | Where-Object {! $_.PSIsContainer } | Select-Object -ExpandProperty FullName
} catch {
Log-Message "[!] Error reading specified configuration path" $true
Log-Message "[!] Exiting..."
exit
}
$module_first_seen = @{}
if ($file_list.GetType().Name -eq "String"){
# In case there is only a single configuration file.
$file_list = @($file_list)
}
$data = New-Object PSObject
For ($counter=0; $counter -lt $file_list.Count; $counter++){
$tmp_data = Get-Content -Raw -Path $file_list[$counter] | ConvertFrom-Json
ForEach ($module in $tmp_data){
ForEach ($type in "files","registry","commands"){
if ($module.$type){
ForEach ($item in $module.$type){
$name = $item.psobject.Properties.Name
ForEach ($n in $name){
if (-not ($module_first_seen.ContainsKey($n))){
$module_first_seen[$n] = $file_list[$counter]
#Write-Host " $($n) : $($file_list[$counter])"
}
}
}
}
}
}
Merge $data $tmp_data $counter
}
Summarize-Configuration $data
Log-Message "[!] Targeted Directive Categories: $categories"
Log-Message "[!] Targeted Directive Tags: $tags"
Build-Registry-Script $data
return $data
}
function Build-Registry-Script ($data) {
# This function is responsible for building a stand-alone script block that will be copied to remote hosts and executed via WMI
# This script block will process all registry directives based on category/tag filters and output the results to a single JSON file, described at $registry_output
# The script relies on a serialized version of the registry directives, category filter and tag filter to function correctly.
$directive_list = New-Object -TypeName 'System.Collections.ArrayList'
ForEach ($object in $data.registry) {
$obj_names = $object.psobject.Properties.Name
ForEach ($module in $obj_names){
ForEach ($objective in $object.$module){
$components = New-Object -TypeName 'System.Collections.ArrayList'
ForEach ($inner_objective in $objective){
if ($categories[0] -eq '*') { } elseif ($inner_objective.category -in $categories) { } else {continue }
if ($tags[0] -eq '*'){
} elseif ($tags){
if ($inner_objective.tags){
$pass = $true
ForEach ($t in $inner_objective.tags){
if ($t -in $tags){
$pass = $false
}
}
} else {
continue
}
if ($pass){
continue
} else {
$components.Add($inner_objective) | Out-Null
}
}
}
if ($components.Count -ne 0){
$tmp = [pscustomobject]@{
name = $module
objects = $components
}
$directive_list.Add($tmp) | Out-Null
}
}
}
}
$tmp_timestamp = (Get-Date).toString("HH:mm:ss") -replace (":","_")
$script:registry_output = "C:\Windows\temp\retrievir_registry_output_$tmp_timestamp.json"
$Serialized_reg_data = [System.Management.Automation.PSSerializer]::Serialize($directive_list)
$Bytes_reg_data = [System.Text.Encoding]::Unicode.GetBytes($Serialized_reg_data)
$EncodedRegData = [Convert]::ToBase64String($Bytes_reg_data)
$Serialized_category = [System.Management.Automation.PSSerializer]::Serialize($categories)
$bytes_categories = [System.Text.Encoding]::Unicode.GetBytes($Serialized_category)
$encoded_category = [Convert]::ToBase64String($bytes_categories)
$Serialized_tags = [System.Management.Automation.PSSerializer]::Serialize($tags)
$bytes_tags = [System.Text.Encoding]::Unicode.GetBytes($Serialized_tags)
$encoded_tags = [Convert]::ToBase64String($bytes_tags)
# Old method - all detected directives sent over in file and iterated through at target - instead, we will only find relevant ones that match provides tags/categories and send those.
if ($blah){
$script:read_registry_script = "
`$Serialized = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String('$EncodedRegData'))
`$directives = [System.Management.Automation.PSSerializer]::Deserialize(`$Serialized)
`$Serialized_category = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String('$encoded_category'))
`$categories = [System.Management.Automation.PSSerializer]::Deserialize(`$Serialized_category)
`$Serialized_tags = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String('$encoded_tags'))
`$tags = [System.Management.Automation.PSSerializer]::Deserialize(`$Serialized_tags)
`$output_path = '$registry_output'
`$type_mapping = @{
3 = 'BINARY'
4 = 'DWORD'
2 = 'EXPAND_SZ'
7 = 'MULTI_SZ'
-1 = 'NONE'
11 = 'QWORD'
1 = 'SZ'
0 = 'UNKNOWN'
}
`$primary_object = New-Object -TypeName 'System.Collections.ArrayList'
ForEach (`$object in `$directives) {
`$obj_names = `$object.psobject.Properties.Name
ForEach (`$module in `$obj_names){
ForEach (`$objective in `$object.`$module){
ForEach (`$inner_objective in `$objective){
`$primary_module_object = [PSCustomObject]@{
name = `$module
category = `$inner_objective.category
items = New-Object -TypeName 'System.Collections.ArrayList'
}
if (`$categories[0] -eq '*') { } elseif (`$inner_objective.category -in `$categories) { } else {continue }
if (`$tags[0] -eq '*'){
} elseif (`$tags){
if (`$inner_objective.tags){
`$pass = `$true
ForEach (`$t in `$inner_objective.tags){
if (`$t -in `$tags){
`$pass = `$false
}
}
} else {
continue
}
if (`$pass){
continue
}
}
`$recurse = `$inner_objective.recursive
`$category = `$inner_objective.category
`$paths = `$inner_objective.paths
`$key_filter = `$inner_objective.keys
`$data_list = New-Object -TypeName 'System.Collections.ArrayList'
ForEach (`$path in `$paths){
`$data = `$null
if (`$recurse){
`$data = Get-ChildItem -Path `"Registry::`$path`" -Recurse -ErrorAction SilentlyContinue
} else {
`$data = Get-ChildItem -Path `"Registry::`$path`" -ErrorAction SilentlyContinue
}
`$current = `$null
`$current = Get-Item -Path `"Registry::`$path`" -ErrorAction SilentlyContinue
if (`$data){
ForEach (`$1 in `$data){
`$data_list.Add(`$1) | Out-Null
}
}
if (`$current){
ForEach (`$1 in `$current){
`$data_list.Add(`$1) | Out-Null
}
}
ForEach (`$item in `$data_list){
`$key_object = [PSCustomObject]@{
path = `$item.Name
values = New-Object -TypeName 'System.Collections.ArrayList'
}
try{
`$values = `$item.GetValueNames()
} catch {
`$values = @()
`$new_value = @{
name = 'ERROR RETRIEVING VALUES'
value = 'ERROR RETRIEVING VALUES'
}
`$key_object.values.Add(`$new_value) | Out-Null
}
if (`$values.Count -eq 0 -and -not `$directive.store_empty){
continue
}
ForEach (`$value in `$values){
if (-not (`$key_filter -contains `$value) -and `$key_filter[0] -ne '*'){
continue
}
try{
`$new_value = @{
name = `$value
value = `$item.GetValue(`$value)
type = `$type_mapping[[int]`$item.GetValueKind(`$value)]
}
} catch {
`$new_value = @{
name = `$value
value = 'ERROR RETRIEVING VALUE'
type = 'ERROR RETRIEVING TYPE'
}
}
`$key_object.values.Add(`$new_value) | Out-Null
}
`$primary_module_object.items.Add(`$key_object) | Out-Null
}
}
`$primary_object.Add(`$primary_module_object) | Out-Null
}
}
}
}
`$primary_object | ConvertTo-Json -Depth 6 | Add-Content -Path `$output_path
"
}
$script:read_registry_script = "
`$Serialized = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String('$EncodedRegData'))
`$directives = [System.Management.Automation.PSSerializer]::Deserialize(`$Serialized)
`$Serialized_category = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String('$encoded_category'))
`$categories = [System.Management.Automation.PSSerializer]::Deserialize(`$Serialized_category)
`$Serialized_tags = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String('$encoded_tags'))
`$tags = [System.Management.Automation.PSSerializer]::Deserialize(`$Serialized_tags)
`$output_path = '$registry_output'
`$type_mapping = @{
3 = 'BINARY'
4 = 'DWORD'
2 = 'EXPAND_SZ'
7 = 'MULTI_SZ'
-1 = 'NONE'
11 = 'QWORD'
1 = 'SZ'
0 = 'UNKNOWN'
}
`$primary_object = New-Object -TypeName 'System.Collections.ArrayList'
ForEach (`$object in `$directives) {
`$module = `$object.name
`$primary_module_object = [PSCustomObject]@{
name = `$module
category = `$inner_objective.category
items = New-Object -TypeName 'System.Collections.ArrayList'
}
ForEach (`$inner_objective in `$object.objects){
`$recurse = `$inner_objective.recursive
`$category = `$inner_objective.category
`$paths = `$inner_objective.paths
`$key_filter = `$inner_objective.keys
`$data_list = New-Object -TypeName 'System.Collections.ArrayList'
ForEach (`$path in `$paths){
if (-not (Test-Path `"Registry::`$path`")){
continue
}
`$data = `$null
if (`$recurse){
`$data = Get-ChildItem -Path `"Registry::`$path`" -Recurse -ErrorAction SilentlyContinue
} else {
`$data = Get-ChildItem -Path `"Registry::`$path`" -ErrorAction SilentlyContinue
}
`$current = `$null
`$current = Get-Item -Path `"Registry::`$path`" -ErrorAction SilentlyContinue
if (`$data){
ForEach (`$1 in `$data){
`$data_list.Add(`$1) | Out-Null
}
}
if (`$current){
ForEach (`$1 in `$current){
`$data_list.Add(`$1) | Out-Null
}
}
ForEach (`$item in `$data_list){
`$key_object = [PSCustomObject]@{
path = `$item.Name
values = New-Object -TypeName 'System.Collections.ArrayList'
}
try{
`$values = `$item.GetValueNames()
} catch {
`$values = @()
`$new_value = @{
name = 'ERROR RETRIEVING VALUES'
value = 'ERROR RETRIEVING VALUES'
}
`$key_object.values.Add(`$new_value) | Out-Null
}
if (`$values.Count -eq 0 -and -not `$directive.store_empty){
continue
}
ForEach (`$value in `$values){
if (-not (`$key_filter -contains `$value) -and `$key_filter[0] -ne '*'){
continue
}
try{
`$new_value = @{
name = `$value
value = `$item.GetValue(`$value)
type = `$type_mapping[[int]`$item.GetValueKind(`$value)]
}
} catch {
`$new_value = @{
name = `$value
value = 'ERROR RETRIEVING VALUE'
type = 'ERROR RETRIEVING TYPE'
}
}
`$key_object.values.Add(`$new_value) | Out-Null
}
`$primary_module_object.items.Add(`$key_object) | Out-Null
}
}
`$primary_object.Add(`$primary_module_object) | Out-Null
}
}
`$primary_object | ConvertTo-Json -Depth 6 | Add-Content -Path `$output_path
"
}
function Get-Targets {
$target_list = New-Object -TypeName "System.Collections.ArrayList"
if (-not $targets -and -not $target_file){
$target_list.Add($global_configuration.hostname) | Out-Null
return $target_list
} elseif ($target_file){
if (-not (Test-Path $target_file)){
Log-Message "[!] Could not find specified target file: $target_file" $true
Log-Message "[!] Exiting..."
exit
}
$targets = Get-Content $target_file
return $targets
} elseif ($targets){
if ($targets -match ","){
$targets_new = $targets.Split(",")
return $targets_new
} else {
$target_list.Add($targets) | Out-Null
return $target_list
}
}
}
function Hash-File ($file){
if ($hash){
try {
$t = Get-FileHash -Path "$file" -Algorithm SHA256
return $t.Hash
} catch {
return "N/A"
}
} else {
return "N/A"
}
}
function Start-Jobs ($computer_targets){
$script:total_files_collected = 0
$script:total_file_size = 0
Log-Message "[+] Starting Collection..."
$evidence_dir_replace = $evidence_dir -Replace (":", "$")
$share_map_script = "
New-PSDrive -Credential $($global_configuration.credential) -Name PowerHaulDrive -PSProvider FileSystem -Root '\\$($global_configuration.hostname)\$evidence_dir_replace';
"
$script_bytes = [System.Text.Encoding]::Unicode.GetBytes($share_map_script)
$base64_script = [Convert]::ToBase64String($script_bytes)
$full_command = "powershell.exe -NoLogo -NonInteractive -ExecutionPolicy Unrestricted -WindowStyle Hidden -EncodedCommand "+$base64_script
#Write-Host $full_command
$file_success_output = $evidence_dir + "\successful_file_copies.csv"
$file_failures_output = $evidence_dir + "\failed_file_copies.csv"
$script:file_copy_success_main = New-Object -TypeName 'System.Collections.ArrayList'
$script:file_copy_failures_main = New-Object -TypeName 'System.Collections.ArrayList'
foreach ($target in $computer_targets){
Log-Message "[+] Targeting: $target"
$current_evidence_dir = $evidence_dir + "\" + $target
Create-Directory $current_evidence_dir
if (-not $simulate -and -not $noshadow){
$status = Create-Shadow $target
}
if ($simulate){
Log-Message "[!] Simulation Enabled"
}
if ($status -eq 1 -and -not ($noshadow)){
Log-Message "[!] [$target] Shadow Created Successfully!"
Get-Files $target $current_evidence_dir $true
} else {
Log-Message "[!] [$target] Shadow Failure - System/Locked Files will be unavailable!"
Get-Files $target $current_evidence_dir $false
}
if (-not $simulate){
Run-Commands $target $current_evidence_dir
Get-Registry $target $current_evidence_dir
} else {
Log-Message "[!] Skipping Registry/Command Collection due to simulation!"
}
if (-not $simulate -and -not $noshadow){
Delete-Shadow $target
}
}
if ($simulate){
Log-Message "[!] Total Files to be Collected: $total_files_collected"
$size_in_mb = $total_file_size / 1MB
Log-Message "[!] Total File Size: $([math]::Round($size_in_mb, 2)) Megabytes"
}
$file_copy_success_main | Export-Csv -NoTypeInformation -Path "$file_success_output"
$file_copy_failures_main | Export-Csv -NoTypeInformation -Path "$file_failures_output"
}
function Remove-Front-Dirs ($path, $count, $tmp_dir, $shadow){
# Receives a fully-qualified path to a file as well as a count of how many 'segments' should be removed from the front
# Helps with 'relative' copy-paste operations where we want to maintain a certain structure beyond a point.
# For example, passing "C:\Windows\App\Test\icon.png",3 will return "Test\icon.png"
# Passing "C:\Windows\App\Test\icon.png",2 would return "App\Test\icon.png"
#Write-Host $path
$removes = 0
$max_index = $count - 1 + 4
if ($shadow){
$max_index += 1
}
$split_path = $path.Split("\")
For ($counter=0; $counter -lt $max_index; $counter++){
$first, $split_path = $split_path
}
$new_path = ""
$last_element = $split_path[-1]
ForEach($path_element in $split_path){
if ($path_element -eq $last_element){
$new_path += $path_element
} else {
$new_path += $path_element + "\"
$tmp_dir_evidence = $tmp_dir + "\" + $new_path.Trim("\")
Create-Directory $tmp_dir_evidence
}
}
#$new_path = $new_path.Trim("\")
#Write-Host $new_path
return $new_path
}
function Get-Files ($target, $current_evidence_dir, $root_replace) {
# Iterates through configuration and finds appropriate directives based on categories and tags specified at input
# Finds relevant files based on directive objectives
#
ForEach ($object in $global_configuration.config.files){
$obj_names = $object.psobject.Properties.Name
ForEach ($category in $obj_names){
$collected = 0
ForEach ($item in $object.$category){
ForEach ($directive in $item){
$file_evidence_dir = $current_evidence_dir + "\" + $directive.category + "\" + $category
if ($categories[0] -eq '*') { } elseif ($directive.category -in $categories) { } else {
#Log-Message "[+] [$target] Skipping: $category - Not in specified arguments!"
continue
}
if ($tags[0] -eq "*"){
} elseif ($tags){
if ($directive.tags){
$pass = $true
ForEach ($t in $directive.tags){
if ($t -in $tags){
$pass = $false
}
}
} else {
continue
}
if ($pass){
continue
}
}
if (-not ($root_replace) -and $directive.shadow -and -not $simulate){
Log-Message "[+] [$target] Skipping: $category - Requires Volume Shadow which was unsuccessful!"
continue
}
if ($collected -eq 0){
Log-Message "[+] [$target] Collecting: $category"
$collected = 1
}
#Log-Message "[+] [$target] Collecting: $category"
ForEach ($path in $directive.paths){
if ($root_replace -and $directive.shadow){
$shadow_ok = $true
$tmp_path = $path -replace ("%HOMEDRIVE%", "\\$target\C$\$shadowcopy_name")
}
else {
$shadow_ok = $false
$tmp_path = $path -replace ("%HOMEDRIVE%", "\\$target\C$")
}
$path_replace = $tmp_path -replace ("\*",".*")
if ($global_configuration.credential){
Write-Host "CREDS"
# TODO - possibly map drive but probably not required in most situations if access is already present.
}
try {
$file_list_map = @{}
$file_list = New-Object -TypeName "System.Collections.ArrayList"
ForEach ($filter in $directive.filter){
$files = $null
$FailedItems = $null
try {
if ($directive.recursive){
$files = Get-ChildItem -Path "$tmp_path" -Recurse -Filter $filter -Force -ErrorVariable FailedItems -ErrorAction SilentlyContinue | Where {! $_.PSIsContainer }
} else {
$files = Get-ChildItem -Path "$tmp_path" -Filter $filter -Force -ErrorVariable FailedItems -ErrorAction SilentlyContinue | Where {! $_.PSIsContainer }
}
} catch {
#Log-Message $_.Exception.GetType().FullName $true
}
ForEach ($failure in $FailedItems){
if ($failure.Exception -is [UnauthorizedAccessException]){
Log-Message "[!] [$target] Unauthorized Access Exception (Reading): $($failure.TargetObject)" $false "red"
} elseif ($failure.Exception -is [ArgumentException]){
Log-Message "[!] [$target] Invalid Argument Specified (Reading): $($failure.TargetObject)" $false "red"
} elseif ($failure.Exception -is [System.Management.Automation.ItemNotFoundException]){
} else {
Log-Message $failure.Exception.GetType().FullName $true "red"
}
}
foreach ($f in $files){
$file_list.Add($f) | Out-Null
}
}
} catch {
Log-Message "Unknown Error Processing Path: $tmp_path" $true
}
if ($file_list.Count -ne 0){
Create-Directory $file_evidence_dir
}
#Write-Host "FILES TO COPY: $($file_list.Count)"
ForEach ($file in $file_list){
$script:total_files_collected += 1
if ($simulate){
$script:total_file_size += $file.Length
continue
}
# If the file we are attempting to copy exists under a specific user directory (Jumplists, etc) then we will store it under the relevant users name - $evidence_dir\jumplists\$USERNAME\$file
try {
if ($($file.FullName) -match ".*\\users\\(?<user>[^\\]*)\\.*"){
$tmp_user_evidence_dir = $file_evidence_dir + "\" + $Matches.user
$username = $Matches.user
Create-Directory $tmp_user_evidence_dir
if ($directive.dir_removals){
$new_dest_path = Remove-Front-Dirs $file.FullName $directive.dir_removals $tmp_user_evidence_dir $shadow_ok
$dest_path = $tmp_user_evidence_dir + "\" + $new_dest_path
} else {
$dest_path = $tmp_user_evidence_dir
}
} else {
$username = "N/A"
if ($directive.dir_removals){
$new_dest_path = Remove-Front-Dirs $file.FullName $directive.dir_removals $file_evidence_dir $shadow_ok
$dest_path = $file_evidence_dir + "\" + $new_dest_path
} else {
$dest_path = $file_evidence_dir
}
}
} catch{
Log-Message "[!] [$target] Error processing file: $($file.FullName)" $false "red"
continue
}
$FailedCopies = $null
try {
Copy-Item "$($file.FullName)" "$dest_path" -Force -ErrorVariable FailedCopies -ErrorAction SilentlyContinue
$tmp_success_name = Split-Path -Leaf $file.FullName
$tmp_dest_leaf = Split-Path -Leaf $dest_path
$tmp_destination_name = "$dest_path\$tmp_success_name"
if ($tmp_dest_leaf -eq $tmp_success_name){
$destination_file_path = $dest_path
} else {
$destination_file_path = $tmp_destination_name
}
if (Test-Path $destination_file_path){
$tmp = [PSCustomObject]@{
DirectiveName = $category
Computer = $target
FileName = $destination_file_path
Category = if($directive.category){$directive.category}else{'N/A'}
Type = if($directive.type){$directive.type}else{'N/A'}
Parser = if($directive.parser){$directive.parser}else{'N/A'}