Repository navigation
Expand file tree
/
Copy pathheadless_batch_extractor.ps1
More file actions
2230 lines (1895 loc) · 92.8 KB
/
Copy pathheadless_batch_extractor.ps1
File metadata and controls
2230 lines (1895 loc) · 92.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
<#
.SYNOPSIS
Headless batch extractor for PE files using IDA Pro.
.DESCRIPTION
Automates PE file analysis using IDA Pro in headless mode with concurrent processing.
Extracts function signatures, assembly code, dangerous APIs, strings, control flow,
and other results into SQLite databases.
.PARAMETER ExtractDir
One or more directory paths to scan for PE files (.exe, .dll, .sys) without recursion
(top-level only). Accepts a comma-separated list. Can be combined with -ExtractDirRecursive.
.PARAMETER ExtractDirRecursive
One or more directory paths to scan recursively for PE files (.exe, .dll, .sys), including
all subdirectories. Accepts a comma-separated list. Can be combined with -ExtractDir.
.PARAMETER FilesToAnalyze
Path to a text file containing a list of PE file paths to analyze (one per line).
.PARAMETER TargetPid
One or more Process IDs (PIDs) to extract loaded modules from. Accepts a comma-separated list
of PIDs. Modules from all processes are merged into a single batch and deduplicated.
.PARAMETER StorageDir
Directory where analysis results will be stored (SQLite databases, logs, IDB cache).
.PARAMETER IdaPath
Path to IDA Pro executable (idat.exe or idat64.exe). If not specified, the script auto-detects the latest IDA 9.x installation.
.PARAMETER MaxConcurrentProcesses
Maximum number of concurrent IDA processes to run (default: 4). Adjust based on system resources.
.PARAMETER TimeoutHours
Maximum number of hours each IDA process may run before being terminated (default: 6).
.PARAMETER LoopAnalysisMaxDepth
Maximum recursion depth for loop analysis graph traversal. Overrides the extractor default.
.PARAMETER MaxXrefs
Maximum xrefs serialized per JSON xref field. Overrides the extractor default.
.PARAMETER Help
Display detailed help information with usage examples.
.PARAMETER NoDownloadSymbols
Skip automatic symbol (PDB) downloading before analysis. Symbols are downloaded by default.
.PARAMETER SymbolStorePath
Local symbol store directory where PDB files are cached (default: C:\symbols).
.PARAMETER SymchkPath
Path to symchk.exe from the Windows SDK Debugging Tools. Auto-detected if not specified.
.PARAMETER SymbolServerUrl
Symbol server URL to download PDBs from (default: https://msdl.microsoft.com/download/symbols).
.EXAMPLE
.\headless_batch_extractor.ps1 -ExtractDirRecursive "C:\Windows\System32" -StorageDir "C:\Analysis"
.EXAMPLE
.\headless_batch_extractor.ps1 -ExtractDir "C:\Windows" -ExtractDirRecursive "C:\Windows\System32","C:\Windows\SystemApps" -StorageDir "C:\Analysis"
.EXAMPLE
.\headless_batch_extractor.ps1 -FilesToAnalyze "files.txt" -StorageDir "C:\Analysis"
.EXAMPLE
.\headless_batch_extractor.ps1 -TargetPid 1234,5678 -StorageDir "C:\Analysis"
.EXAMPLE
.\headless_batch_extractor.ps1 -ExtractDir "C:\Binaries" -StorageDir "C:\Analysis" -IdaPath "C:\IDA92\idat64.exe"
.EXAMPLE
.\headless_batch_extractor.ps1 -ExtractDirRecursive "C:\Large\Dataset" -StorageDir "C:\Analysis" -MaxConcurrentProcesses 8
.EXAMPLE
.\headless_batch_extractor.ps1 -ExtractDirRecursive "C:\Large\Dataset" -StorageDir "C:\Analysis" -TimeoutHours 50
#>
[CmdletBinding(DefaultParameterSetName = 'Directory')]
param(
# Directory-based extraction: non-recursive (flat, top-level only)
[Parameter(ParameterSetName = 'Directory', HelpMessage = "One or more directory paths to scan for PE files (non-recursive)")]
[string[]]$ExtractDir,
# Directory-based extraction: recursive (includes subdirectories)
[Parameter(ParameterSetName = 'Directory', HelpMessage = "One or more directory paths to scan recursively for PE files")]
[string[]]$ExtractDirRecursive,
# Parameter set for file-list based extraction
[Parameter(Mandatory = $true, ParameterSetName = 'FileList', HelpMessage = "Path to text file containing list of PE files to analyze")]
[ValidateScript({
if (-not (Test-Path $_ -PathType Leaf)) {
throw "File '$_' does not exist."
}
return $true
})]
[string]$FilesToAnalyze,
# Parameter set for PID-based extraction (accepts one or more PIDs)
[Parameter(Mandatory = $true, ParameterSetName = 'Pid', HelpMessage = "One or more Process IDs to extract loaded modules from")]
[ValidateNotNullOrEmpty()]
[int[]]$TargetPid,
[Parameter(Mandatory = $true, ParameterSetName = 'Directory', HelpMessage = "Directory where analysis results will be stored")]
[Parameter(Mandatory = $true, ParameterSetName = 'FileList')]
[Parameter(Mandatory = $true, ParameterSetName = 'Pid')]
[Parameter(ParameterSetName = 'Help')]
[ValidateNotNullOrEmpty()]
[string]$StorageDir,
[Parameter(HelpMessage = "Path to IDA Pro executable (idat.exe). Auto-detected if not specified.")]
[ValidateScript({
if ($_ -and -not (Test-Path $_ -PathType Leaf)) {
throw "IDA executable not found at '$_'."
}
return $true
})]
[string]$IdaPath,
[Parameter(HelpMessage = "Maximum number of concurrent IDA processes (default: 4)")]
[ValidateRange(1, 32)]
[int]$MaxConcurrentProcesses = 4,
[Parameter(HelpMessage = "Maximum number of hours each IDA process may run before being terminated (default: 6)")]
[ValidateRange(1, [int]::MaxValue)]
[int]$TimeoutHours = 6,
[Parameter(HelpMessage = "Maximum recursion depth for loop analysis graph traversal (0 = extractor default)")]
[int]$LoopAnalysisMaxDepth = 0,
[Parameter(HelpMessage = "Maximum xrefs serialized per JSON xref field (0 = extractor default)")]
[int]$MaxXrefs = 0,
# Display help
[Parameter(ParameterSetName = 'Help', HelpMessage = "Display detailed help information")]
[Alias('h', '?')]
[switch]$Help,
# Analysis Feature Flags
[Parameter(HelpMessage = "Skip extraction of dangerous API calls")] [switch]$NoExtractDangerousApis,
[Parameter(HelpMessage = "Skip string extraction")] [switch]$NoExtractStrings,
[Parameter(HelpMessage = "Skip stack frame analysis")] [switch]$NoExtractStackFrame,
[Parameter(HelpMessage = "Skip global variable extraction")] [switch]$NoExtractGlobals,
[Parameter(HelpMessage = "Skip loop analysis")] [switch]$NoAnalyzeLoops,
[Parameter(HelpMessage = "Skip PE header information extraction")] [switch]$NoPeInfo,
[Parameter(HelpMessage = "Skip PE metadata extraction")] [switch]$NoPeMetadata,
[Parameter(HelpMessage = "Skip advanced PE analysis")] [switch]$NoAdvancedPe,
[Parameter(HelpMessage = "Skip runtime information extraction")] [switch]$NoRuntimeInfo,
[Parameter(HelpMessage = "Force re-analysis of previously analyzed files")] [switch]$ForceReanalyze,
[Parameter(HelpMessage = "Skip C++ file generation from decompiled code")] [switch]$NoGenerateCpp,
[Parameter(HelpMessage = "Enable assembly (.asm) file generation (disabled by default)")] [switch]$GenerateAsm,
[Parameter(HelpMessage = "Write CLAUDE.md so the output directory can host the DeepExtract AI Analysis Runtime (disabled by default)")] [switch]$EnableAI,
# Symbol Download Options
[Parameter(HelpMessage = "Skip automatic symbol (PDB) downloading before analysis (enabled by default)")]
[switch]$NoDownloadSymbols,
[Parameter(HelpMessage = "Local symbol store directory (default: C:\symbols)")]
[ValidateNotNullOrEmpty()]
[string]$SymbolStorePath = "C:\symbols",
[Parameter(HelpMessage = "Path to symchk.exe. Auto-detected from Windows SDK if not specified.")]
[ValidateScript({
if ($_ -and -not (Test-Path $_ -PathType Leaf)) {
throw "symchk.exe not found at '$_'."
}
return $true
})]
[string]$SymchkPath,
[Parameter(HelpMessage = "Symbol server URL (default: Microsoft public symbol server)")]
[ValidateNotNullOrEmpty()]
[string]$SymbolServerUrl = "https://msdl.microsoft.com/download/symbols"
)
# Show-Help function
function Show-Help {
Write-Host ""
Write-Host "===============================================================================" -ForegroundColor Cyan
Write-Host " DeepExtract - Headless Batch Extractor for IDA Pro" -ForegroundColor Cyan
Write-Host "===============================================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "DESCRIPTION:" -ForegroundColor Yellow
Write-Host " Automates PE file analysis using IDA Pro in headless mode with concurrent"
Write-Host " processing. Extracts function signatures, assembly code, dangerous APIs,"
Write-Host " strings, control flow, and other results into SQLite databases."
Write-Host ""
Write-Host "EXTRACTION MODES:" -ForegroundColor Yellow
Write-Host ""
Write-Host " 1. Directory Scan Mode" -ForegroundColor Green
Write-Host " Scans one or more directories for PE files (.exe, .dll, .sys)"
Write-Host " -ExtractDir <path>[,...] Non-recursive (top-level only)"
Write-Host " -ExtractDirRecursive <path>[,...] Recursive (includes subdirectories)"
Write-Host " Both parameters can be combined in a single invocation."
Write-Host ""
Write-Host " 2. File List Mode" -ForegroundColor Green
Write-Host " Processes files listed in a text file (one path per line)"
Write-Host " Usage: -FilesToAnalyze <file.txt>"
Write-Host ""
Write-Host " 3. PID Mode" -ForegroundColor Green
Write-Host " Extracts all modules loaded by one or more running processes"
Write-Host " Usage: -TargetPid <pid>[,<pid2>,...]"
Write-Host ""
Write-Host "COMMON PARAMETERS:" -ForegroundColor Yellow
Write-Host " -StorageDir <path> Output directory for analysis results (required)"
Write-Host " -IdaPath <path> Path to IDA Pro executable (auto-detected if not specified)"
Write-Host " -MaxConcurrentProcesses Number of parallel IDA processes (default: 4)"
Write-Host " -TimeoutHours <hours> Per-process timeout before termination (default: 6)"
Write-Host " -LoopAnalysisMaxDepth Loop analysis recursion depth guard (extractor default if omitted)"
Write-Host " -MaxXrefs <count> Maximum xrefs serialized per JSON xref field (extractor default if omitted)"
Write-Host " -Help Display this help message"
Write-Host ""
Write-Host "ANALYSIS FLAGS (disable specific features):" -ForegroundColor Yellow
Write-Host " -NoExtractDangerousApis Skip dangerous API detection"
Write-Host " -NoExtractStrings Skip string literal extraction"
Write-Host " -NoExtractStackFrame Skip stack frame analysis"
Write-Host " -NoExtractGlobals Skip global variable tracking"
Write-Host " -NoAnalyzeLoops Skip loop analysis (Tarjan algorithm)"
Write-Host " -NoPeInfo Skip PE version info extraction"
Write-Host " -NoPeMetadata Skip PE metadata extraction"
Write-Host " -NoAdvancedPe Skip Rich header/TLS callbacks"
Write-Host " -NoRuntimeInfo Skip .NET/delay-load analysis"
Write-Host " -ForceReanalyze Force re-analysis of all files"
Write-Host " -NoGenerateCpp Skip C++ code generation"
Write-Host " -GenerateAsm Enable assembly (.asm) file generation"
Write-Host " -EnableAI Write CLAUDE.md for DeepExtract AI Analysis Runtime"
Write-Host ""
Write-Host "SYMBOL DOWNLOAD OPTIONS:" -ForegroundColor Yellow
Write-Host " Symbols (PDBs) are automatically downloaded before analysis using symchk.exe."
Write-Host " This enables IDA Pro to produce richer analysis with proper function names."
Write-Host ""
Write-Host " -NoDownloadSymbols Skip automatic symbol downloading (enabled by default)"
Write-Host " -SymbolStorePath <path> Local symbol cache directory (default: C:\symbols)"
Write-Host " -SymchkPath <path> Path to symchk.exe (auto-detected from Windows SDK)"
Write-Host " -SymbolServerUrl <url> Symbol server URL (default: Microsoft public server)"
Write-Host ""
Write-Host " Sets _NT_SYMBOL_PATH environment variable at user level (no admin required)."
Write-Host " Requires symchk.exe from Windows SDK Debugging Tools."
Write-Host ""
Write-Host "EXAMPLES:" -ForegroundColor Yellow
Write-Host ""
Write-Host " # Recursive scan of System32 (symbols auto-downloaded)" -ForegroundColor Gray
Write-Host " .\headless_batch_extractor.ps1 -ExtractDirRecursive 'C:\Windows\System32' -StorageDir 'C:\Analysis'"
Write-Host ""
Write-Host " # Non-recursive scan (top-level PE files only)" -ForegroundColor Gray
Write-Host " .\headless_batch_extractor.ps1 -ExtractDir 'C:\Windows' -StorageDir 'C:\Analysis'"
Write-Host ""
Write-Host " # Mix recursive and non-recursive directories" -ForegroundColor Gray
Write-Host " .\headless_batch_extractor.ps1 -ExtractDir 'C:\Windows' -ExtractDirRecursive 'C:\Windows\System32' -StorageDir 'C:\Analysis'"
Write-Host ""
Write-Host " # Analyze files from a list" -ForegroundColor Gray
Write-Host " .\headless_batch_extractor.ps1 -FilesToAnalyze 'targets.txt' -StorageDir 'C:\Analysis'"
Write-Host ""
Write-Host " # Extract modules from multiple processes" -ForegroundColor Gray
Write-Host " .\headless_batch_extractor.ps1 -TargetPid 1234,5678 -StorageDir 'C:\Analysis'"
Write-Host ""
Write-Host " # Skip symbol downloading (faster startup, less accurate analysis)" -ForegroundColor Gray
Write-Host " .\headless_batch_extractor.ps1 -ExtractDirRecursive 'C:\Binaries' -StorageDir 'C:\Analysis' -NoDownloadSymbols"
Write-Host ""
Write-Host " # Use a custom symbol store path" -ForegroundColor Gray
Write-Host " .\headless_batch_extractor.ps1 -ExtractDirRecursive 'C:\Binaries' -StorageDir 'C:\Analysis' -SymbolStorePath 'D:\MySymbols'"
Write-Host ""
Write-Host " # Allow very large modules to run longer before timeout" -ForegroundColor Gray
Write-Host " .\headless_batch_extractor.ps1 -ExtractDirRecursive 'C:\Binaries' -StorageDir 'C:\Analysis' -TimeoutHours 50"
Write-Host ""
Write-Host " # Increase loop analysis depth for complex CFGs" -ForegroundColor Gray
Write-Host " .\headless_batch_extractor.ps1 -ExtractDirRecursive 'C:\Binaries' -StorageDir 'C:\Analysis' -LoopAnalysisMaxDepth 10000"
Write-Host ""
Write-Host " # Increase xref serialization limit for dense modules" -ForegroundColor Gray
Write-Host " .\headless_batch_extractor.ps1 -ExtractDirRecursive 'C:\Binaries' -StorageDir 'C:\Analysis' -MaxXrefs 1000000"
Write-Host ""
Write-Host " # Skip string extraction to reduce analysis time" -ForegroundColor Gray
Write-Host " .\headless_batch_extractor.ps1 -ExtractDir 'C:\Binaries' -StorageDir 'C:\Analysis' -NoExtractStrings"
Write-Host ""
Write-Host " # Use a specific IDA installation" -ForegroundColor Gray
Write-Host " .\headless_batch_extractor.ps1 -ExtractDir 'C:\Binaries' -StorageDir 'C:\Analysis' -IdaPath 'C:\IDA92\idat64.exe'"
Write-Host ""
Write-Host " # Extract the full Windows usermode codebase (recursive + non-recursive)" -ForegroundColor Gray
Write-Host " .\headless_batch_extractor.ps1 ``"
Write-Host " -ExtractDirRecursive 'C:\Windows\System32','C:\Windows\SystemApps','C:\Program Files\Common Files','C:\Windows\IME','C:\Windows\ImmersiveControlPanel' ``"
Write-Host " -ExtractDir 'C:\Windows' ``"
Write-Host " -StorageDir 'F:\Analysis\win11_full' -MaxConcurrentProcesses 8"
Write-Host ""
Write-Host " # Extended: add SysWOW64 (32-bit) and kernel drivers" -ForegroundColor Gray
Write-Host " .\headless_batch_extractor.ps1 ``"
Write-Host " -ExtractDirRecursive 'C:\Windows\System32','C:\Windows\SysWOW64','C:\Windows\System32\drivers','C:\Windows\SystemApps','C:\Program Files\Common Files','C:\Windows\IME','C:\Windows\ImmersiveControlPanel' ``"
Write-Host " -ExtractDir 'C:\Windows' ``"
Write-Host " -StorageDir 'F:\Analysis\win11_full_extended' -MaxConcurrentProcesses 8"
Write-Host ""
Write-Host "OUTPUT STRUCTURE:" -ForegroundColor Yellow
Write-Host " <storageDir>/"
Write-Host " +-- extraction_report.json Summary report"
Write-Host " +-- extracted_dbs/ SQLite analysis databases"
Write-Host " +-- extracted_code/ Generated C++ code"
Write-Host " +-- logs/ IDA analysis logs"
Write-Host " +-- idb_cache/ IDA database files (.i64)"
Write-Host ""
Write-Host "MORE HELP:" -ForegroundColor Yellow
Write-Host " Get-Help .\headless_batch_extractor.ps1 -Detailed"
Write-Host ""
Write-Host "===============================================================================" -ForegroundColor Cyan
Write-Host ""
}
# Check for -Help parameter
if ($Help) {
Show-Help
exit 0
}
# ============================================================================
# Script Constants
# ============================================================================
# Exit codes
$script:EXIT_SUCCESS = 0
$script:EXIT_VALIDATION_ERROR = 1 # Parameter validation, invalid paths, etc.
$script:EXIT_IDA_NOT_FOUND = 2 # IDA Pro installation not found
$script:EXIT_PYTHON_ERROR = 3 # Python not installed or script error
$script:EXIT_PERMISSION_ERROR = 4 # Admin privileges required but not available
$script:EXIT_SCRIPT_MISSING = 5 # Required script files not found
$script:EXIT_PROCESS_ERROR = 6 # Error starting or managing IDA processes
# Timeout for IDA processes.
$script:IDA_PROCESS_TIMEOUT_SECONDS = $TimeoutHours * 60 * 60
# Length of hash prefix used for unique file naming (from MD5 hash)
$script:HASH_PREFIX_LENGTH = 10
# Process management constants
$script:PROCESS_KILL_WAIT_MS = 5000 # Wait time for graceful process termination
$script:PROCESS_CLEANUP_WAIT_MS = 3000 # Wait time during cleanup termination
$script:STATUS_UPDATE_INTERVAL_SECONDS = 300 # How often to print status updates (5 minutes)
$script:PROCESS_POLL_INTERVAL_SECONDS = 5 # Polling interval in final wait loop
# Validate that at least one directory source is provided in Directory mode
if ($PSCmdlet.ParameterSetName -eq 'Directory') {
if (-not $ExtractDir -and -not $ExtractDirRecursive) {
Write-Error "At least one of -ExtractDir or -ExtractDirRecursive must be specified."
Write-Host ""
Write-Host "Usage examples:"
Write-Host " Non-recursive: .\headless_batch_extractor.ps1 -ExtractDir 'C:\Windows' -StorageDir 'C:\Analysis'"
Write-Host " Recursive: .\headless_batch_extractor.ps1 -ExtractDirRecursive 'C:\Windows\System32' -StorageDir 'C:\Analysis'"
Write-Host " Mixed: .\headless_batch_extractor.ps1 -ExtractDir 'C:\Windows' -ExtractDirRecursive 'C:\Windows\System32' -StorageDir 'C:\Analysis'"
exit $script:EXIT_VALIDATION_ERROR
}
}
# Auto-detect IDA Pro installation
function Find-LatestIDA {
# Strategy 1: Check PATH environment variable first
$idaInPath = Get-Command -Name "idat.exe", "idat64.exe" -ErrorAction SilentlyContinue | Select-Object -First 1
if ($idaInPath) {
Write-Host "Found IDA in PATH: $($idaInPath.Source)" -ForegroundColor Gray
return $idaInPath.Source
}
# Strategy 2: Check Windows Registry for IDA installation
$registryPaths = @(
"HKLM:\SOFTWARE\Hex-Rays\IDA",
"HKLM:\SOFTWARE\WOW6432Node\Hex-Rays\IDA",
"HKCU:\SOFTWARE\Hex-Rays\IDA"
)
foreach ($regPath in $registryPaths) {
try {
$regKey = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
if ($regKey -and $regKey.InstallDir) {
$idatPath = Join-Path $regKey.InstallDir "idat.exe"
$idat64Path = Join-Path $regKey.InstallDir "idat64.exe"
if (Test-Path $idatPath) {
Write-Host "Found IDA via registry: $idatPath" -ForegroundColor Gray
return $idatPath
}
if (Test-Path $idat64Path) {
Write-Host "Found IDA via registry: $idat64Path" -ForegroundColor Gray
return $idat64Path
}
}
}
catch {
# Registry key doesn't exist or can't be read, continue
}
}
# Strategy 3: Search common installation directories
$searchPaths = @(
"C:\Program Files\IDA Professional 9.*",
"C:\Program Files\IDA Pro 9.*",
"C:\Program Files (x86)\IDA Professional 9.*",
"C:\Program Files (x86)\IDA Pro 9.*",
# Additional common locations
"D:\Program Files\IDA Professional 9.*",
"D:\Program Files\IDA Pro 9.*",
"C:\Tools\IDA*",
"D:\Tools\IDA*"
)
$idaInstallations = @()
foreach ($pattern in $searchPaths) {
$found = Get-Item -Path $pattern -ErrorAction SilentlyContinue
if ($found) {
$idaInstallations += $found
}
}
if ($idaInstallations.Count -eq 0) {
return $null
}
# Sort by version number (extract numeric version from folder name) and get the latest
$latestIDA = $idaInstallations | Sort-Object {
# Extract version number like "9.1" or "9.2" from the path
if ($_.Name -match '(\d+\.\d+)') {
[version]$matches[1]
}
else {
[version]"0.0"
}
} -Descending | Select-Object -First 1
$idatPath = Join-Path $latestIDA.FullName "idat.exe"
if (Test-Path $idatPath) {
return $idatPath
}
# Fallback to idat64.exe if idat.exe not found
$idat64Path = Join-Path $latestIDA.FullName "idat64.exe"
if (Test-Path $idat64Path) {
return $idat64Path
}
return $null
}
# Auto-detect symchk.exe from Windows SDK Debugging Tools
function Find-Symchk {
# Strategy 1: Check PATH environment variable first
$symchkInPath = Get-Command -Name "symchk.exe" -ErrorAction SilentlyContinue | Select-Object -First 1
if ($symchkInPath) {
Write-Host "Found symchk.exe in PATH: $($symchkInPath.Source)" -ForegroundColor Gray
return $symchkInPath.Source
}
# Strategy 2: Search common Windows SDK Debugger installation directories
# Prefer x64 over x86
$searchPaths = @(
"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\symchk.exe",
"C:\Program Files (x86)\Windows Kits\10\Debuggers\x86\symchk.exe",
"C:\Program Files\Windows Kits\10\Debuggers\x64\symchk.exe",
"C:\Program Files\Windows Kits\10\Debuggers\x86\symchk.exe"
)
foreach ($path in $searchPaths) {
if (Test-Path $path -PathType Leaf) {
Write-Host "Found symchk.exe: $path" -ForegroundColor Gray
return $path
}
}
return $null
}
# Set _NT_SYMBOL_PATH environment variable (user-level, no admin required)
function Set-SymbolPath {
param(
[Parameter(Mandatory = $true)]
[string]$SymbolStorePath,
[Parameter(Mandatory = $true)]
[string]$SymbolServerUrl
)
$symbolPathValue = "srv*$SymbolStorePath*$SymbolServerUrl"
# Check if already set to the same value
$currentValue = [System.Environment]::GetEnvironmentVariable('_NT_SYMBOL_PATH', 'User')
if ($currentValue -eq $symbolPathValue) {
Write-Host "_NT_SYMBOL_PATH already set (user-level): $symbolPathValue" -ForegroundColor Gray
}
else {
# Set persistent user-level environment variable (no admin required)
try {
[System.Environment]::SetEnvironmentVariable('_NT_SYMBOL_PATH', $symbolPathValue, 'User')
Write-Host "Set _NT_SYMBOL_PATH (user-level): $symbolPathValue" -ForegroundColor Green
}
catch {
Write-Warning "Could not set persistent _NT_SYMBOL_PATH: $($_.Exception.Message)"
Write-Warning "The variable will only be set for the current session."
}
}
# Always set in current process so IDA picks it up immediately
$env:_NT_SYMBOL_PATH = $symbolPathValue
Write-Host "_NT_SYMBOL_PATH set for current process." -ForegroundColor Gray
}
# Download symbols for a list of files using symchk.exe
# Runs one symchk process per file with concurrency throttling
function Start-SymbolDownload {
param(
[Parameter(Mandatory = $true)]
[System.IO.FileInfo[]]$Files,
[Parameter(Mandatory = $true)]
[string]$SymchkExePath,
[Parameter(Mandatory = $true)]
[string]$SymbolStorePath,
[Parameter(Mandatory = $true)]
[string]$SymbolServerUrl,
[Parameter(Mandatory = $true)]
[string]$LogsDir,
[int]$MaxConcurrent = 10
)
if ($Files.Count -eq 0) {
Write-Host "No files to download symbols for." -ForegroundColor Yellow
return
}
# Ensure the symbol store directory exists
if (-not (Test-Path $SymbolStorePath)) {
try {
New-Item -ItemType Directory -Path $SymbolStorePath -Force -ErrorAction Stop | Out-Null
Write-Host "Created symbol store directory: $SymbolStorePath"
}
catch {
Write-Error "Failed to create symbol store directory '$SymbolStorePath': $($_.Exception.Message)"
return
}
}
$symbolServerArg = "srv*$SymbolStorePath*$SymbolServerUrl"
$timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'
Write-Host ""
Write-Host "=== Symbol Download ===" -ForegroundColor Cyan
Write-Host "Downloading symbols for $($Files.Count) file(s) (max $MaxConcurrent concurrent)"
Write-Host "Symbol store: $SymbolStorePath"
Write-Host "Symbol server: $SymbolServerUrl"
Write-Host ""
$downloadStartTime = Get-Date
# Track active and completed processes
$activeProcesses = [System.Collections.Generic.List[hashtable]]::new()
$succeeded = 0
$failed = 0
$totalStarted = 0
foreach ($file in $Files) {
$fileName = $file.Name
$filePath = $file.FullName
# Throttle: wait for a slot to open if at max concurrency
while ($activeProcesses.Count -ge $MaxConcurrent) {
# Check for completed processes
$stillRunning = [System.Collections.Generic.List[hashtable]]::new()
foreach ($entry in $activeProcesses) {
if ($entry.Process.HasExited) {
$exitCode = $entry.Process.ExitCode
# .Result blocks until ReadToEndAsync fully drains the closed stream — guaranteed complete
$stdoutContent = $entry.StdoutTask.Result
$stderrContent = $entry.StderrTask.Result
try { $stdoutContent | Out-File -FilePath $entry.LogFile -Encoding UTF8 -Force } catch { }
if (-not [string]::IsNullOrWhiteSpace($stderrContent)) {
try { $stderrContent | Out-File -FilePath "$($entry.LogFile).err" -Encoding UTF8 -Force } catch { }
}
try { $entry.Process.Dispose() } catch { }
if ($exitCode -eq 0) {
$succeeded++
}
else {
$failed++
Write-Host " No symbols: $($entry.FileName) (exit code: $exitCode)" -ForegroundColor Yellow
}
}
else {
$stillRunning.Add($entry)
}
}
$activeProcesses = $stillRunning
if ($activeProcesses.Count -ge $MaxConcurrent) {
Start-Sleep -Milliseconds 500
}
}
# Create a sanitized filename for the log
$sanitizedName = $fileName -replace '[\\/:*?"<>|]', '_'
$logFile = Join-Path $LogsDir "symchk_${sanitizedName}_${timestamp}.log"
$symchkArgsStr = "/v /s `"$symbolServerArg`" `"$filePath`""
try {
# Use System.Diagnostics.Process directly instead of Start-Process
# Start-Process with -RedirectStandardOutput breaks .ExitCode retrieval
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $SymchkExePath
$psi.Arguments = $symchkArgsStr
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$proc = New-Object System.Diagnostics.Process
$proc.StartInfo = $psi
$proc.Start() | Out-Null
# ReadToEndAsync runs on the .NET ThreadPool — no shared PS event runspace,
# no race condition. .Result on harvest blocks until the stream is fully closed.
$stdoutTask = $proc.StandardOutput.ReadToEndAsync()
$stderrTask = $proc.StandardError.ReadToEndAsync()
$activeProcesses.Add(@{
Process = $proc
FileName = $fileName
FilePath = $filePath
LogFile = $logFile
StdoutTask = $stdoutTask
StderrTask = $stderrTask
})
$totalStarted++
# Print progress periodically (every 50 files)
if ($totalStarted % 50 -eq 0) {
Write-Host " Started $totalStarted / $($Files.Count) symchk processes..." -ForegroundColor Gray
}
}
catch {
Write-Warning "Failed to start symchk for '$filePath': $($_.Exception.Message)"
}
}
# Wait for remaining active processes to finish
if ($activeProcesses.Count -gt 0) {
Write-Host " Waiting for final $($activeProcesses.Count) symchk process(es)..."
}
foreach ($entry in $activeProcesses) {
try {
$entry.Process.WaitForExit()
}
catch {
Write-Warning "Error waiting for symchk process: $($_.Exception.Message)"
}
$exitCode = $entry.Process.ExitCode
# .Result blocks until ReadToEndAsync fully drains the closed stream — guaranteed complete
$stdoutContent = $entry.StdoutTask.Result
$stderrContent = $entry.StderrTask.Result
try { $stdoutContent | Out-File -FilePath $entry.LogFile -Encoding UTF8 -Force } catch { }
if (-not [string]::IsNullOrWhiteSpace($stderrContent)) {
try { $stderrContent | Out-File -FilePath "$($entry.LogFile).err" -Encoding UTF8 -Force } catch { }
}
try { $entry.Process.Dispose() } catch { }
if ($exitCode -eq 0) {
$succeeded++
}
else {
$failed++
Write-Host " No symbols: $($entry.FileName) (exit code: $exitCode)" -ForegroundColor Yellow
}
}
$downloadDuration = (Get-Date) - $downloadStartTime
$durationStr = if ($downloadDuration.TotalMinutes -lt 1) {
"{0:N0} seconds" -f $downloadDuration.TotalSeconds
}
else {
"{0:N1} minutes" -f $downloadDuration.TotalMinutes
}
Write-Host ""
Write-Host "Symbol download completed in $durationStr. $succeeded succeeded, $failed had no symbols available." -ForegroundColor Cyan
if ($failed -gt 0) {
Write-Host "Note: Missing symbols are normal - not all PE files have public symbols available." -ForegroundColor Yellow
}
Write-Host ""
}
# Determine IDA path: use provided path or auto-detect
if ($IdaPath) {
# User provided explicit path
$IDA_PATH = $IdaPath
Write-Host "Using specified IDA Pro: $IDA_PATH" -ForegroundColor Green
}
else {
# Auto-detect IDA installation
$IDA_PATH = Find-LatestIDA
if (-not $IDA_PATH) {
Write-Error "Could not auto-detect IDA Pro installation."
Write-Error "IDA Pro was not found via:"
Write-Error " - PATH environment variable (idat.exe, idat64.exe)"
Write-Error " - Windows Registry (HKLM/HKCU\SOFTWARE\Hex-Rays\IDA)"
Write-Error " - Standard installation directories:"
Write-Error " - C:\Program Files\IDA Professional 9.*"
Write-Error " - C:\Program Files\IDA Pro 9.*"
Write-Error " - C:\Tools\IDA*"
Write-Error ""
Write-Error "Please either:"
Write-Error " 1. Add IDA Pro to your PATH environment variable, or"
Write-Error " 2. Install IDA Pro 9.x to a standard location, or"
Write-Error " 3. Specify the path manually with -IdaPath parameter"
Write-Error ""
Write-Error "Example: .\headless_batch_extractor.ps1 -ExtractDir 'C:\path' -StorageDir 'C:\output' -IdaPath 'D:\Custom\IDA\idat64.exe'"
exit $script:EXIT_IDA_NOT_FOUND
}
Write-Host "Auto-detected IDA Pro: $IDA_PATH" -ForegroundColor Green
}
function Confirm-DirectoryExists {
param([string]$path, [bool]$create = $false)
if (-not (Test-Path $path)) {
if ($create) {
try {
New-Item -ItemType Directory -Path $path -Force -ErrorAction Stop | Out-Null
Write-Host "Created directory: $path"
}
catch {
Write-Error "Failed to create directory: $path"
Write-Error $_.Exception.Message
exit $script:EXIT_VALIDATION_ERROR
}
}
else {
Write-Error "Directory does not exist: $path"
exit $script:EXIT_VALIDATION_ERROR
}
}
}
# Function to get candidate files by scanning a directory
function Get-CandidateFilesFromDirectory {
param(
[Parameter(Mandatory = $true)]
[string]$ExtractDir,
[Parameter()]
[switch]$Recursive
)
Write-Host "Searching for files in: $ExtractDir"
Write-Host "Recursive search: $($Recursive.IsPresent)"
# List all .exe, .sys, and .dll files in the extract directory
$searchParams = @{
Path = $ExtractDir
File = $true
}
if ($Recursive) {
$searchParams['Recurse'] = $true
}
$allFiles = Get-ChildItem @searchParams -ErrorAction SilentlyContinue |
Where-Object { $_.Extension.ToLower() -in '.exe', '.sys', '.dll' }
Write-Host "Found $($allFiles.Count) total files matching extension criteria"
return $allFiles
}
# Function to get candidate files from a list in a file
function Get-CandidateFilesFromFileList {
param(
[Parameter(Mandatory = $true)]
[string]$filePath
)
Write-Host "Reading file list from: $filePath"
$filePaths = Get-Content -Path $filePath
$candidateFiles = [System.Collections.Generic.List[System.IO.FileInfo]]::new()
foreach ($path in $filePaths) {
if ([string]::IsNullOrWhiteSpace($path)) {
continue
}
$fileInfo = Get-Item -Path $path.Trim() -ErrorAction SilentlyContinue
if ($fileInfo -and $fileInfo.Exists -and ($fileInfo.Extension.ToLower() -in '.exe', '.sys', '.dll')) {
$candidateFiles.Add($fileInfo)
}
else {
Write-Warning "Skipping invalid, non-existent, or non-matching file path from list: $path"
}
}
Write-Host "Found $($candidateFiles.Count) valid files in the list."
return [array]$candidateFiles
}
function Get-CandidateFilesFromPid {
param(
[Parameter(Mandatory = $true)]
[int]$ProcessId,
[Parameter(Mandatory = $true)]
[string]$StorageDir
)
Write-Host "Enumerating modules from process ID: $ProcessId"
try {
$process = Get-Process -Id $ProcessId -ErrorAction Stop
Write-Host "Target process: $($process.ProcessName) (PID: $ProcessId)"
# Get all loaded modules
$modules = $process.Modules | Where-Object {
$_.FileName -match '\.(exe|dll|sys)$' -and
$_.FileName -notmatch '\\Windows\\Installer\\' # Skip temp installer files
}
if ($modules.Count -eq 0) {
Write-Warning "No PE modules found for process $ProcessId"
return @{
Files = @()
ProcessName = $process.ProcessName
ProcessId = $ProcessId
}
}
Write-Host "Found $($modules.Count) modules loaded by process"
# Convert modules to FileInfo objects
$candidateFiles = [System.Collections.Generic.List[System.IO.FileInfo]]::new()
foreach ($module in $modules) {
try {
$fileInfo = Get-Item -Path $module.FileName -ErrorAction Stop
$candidateFiles.Add($fileInfo)
}
catch {
Write-Warning "Cannot access module file: $($module.FileName)"
}
}
Write-Host "Ready to analyze $($candidateFiles.Count) modules"
# Return structured result instead of using script-scoped side effects
return @{
Files = [array]$candidateFiles
ProcessName = $process.ProcessName
ProcessId = $ProcessId
}
}
catch {
Write-Error "Failed to enumerate modules from process $ProcessId : $($_.Exception.Message)"
exit $script:EXIT_PERMISSION_ERROR
}
}
# Function selects files that have not been analyzed yet from the candidate list
function Select-UnprocessedFiles {
param(
[Parameter(Mandatory = $true)]
[System.IO.FileInfo[]]$candidateFiles,
[Parameter(Mandatory = $true)]
[string]$StorageDir,
[Parameter(Mandatory = $true)]
[hashtable]$analysisFlags
)
if ($candidateFiles.Count -eq 0) {
Write-Warning "No candidate files provided for processing!"
return @()
}
# If forcing reanalysis, skip the check and return all candidates.
if ($analysisFlags.force_reanalyze) {
Write-Host "Forcing re-analysis for all $($candidateFiles.Count) candidate files."
return $candidateFiles
}
$commonDbPath = Join-Path $StorageDir "analyzed_files.db"
# Early check: If the database doesn't exist, all files need analysis
# This avoids unnecessary processing and the "analyzing xx files" message
try {
if (-not (Test-Path $commonDbPath -PathType Leaf)) {
Write-Host "No previous analysis database found at '$commonDbPath'. All $($candidateFiles.Count) candidate files will be analyzed."
return $candidateFiles
}
}
catch {
Write-Warning "Error checking for analysis database at '$commonDbPath': $($_.Exception.Message)"
Write-Host "Proceeding with analysis of all $($candidateFiles.Count) candidate files."
return $candidateFiles
}
$checkerScriptPath = Join-Path $PSScriptRoot "deep_extract\utils\check_analyzed_files.py"
# Convert flags to Base64-encoded JSON for command line
$flagsJson = $analysisFlags | ConvertTo-Json -Compress
$flagsJsonBytes = [System.Text.Encoding]::UTF8.GetBytes($flagsJson)
$flagsJsonBase64 = [System.Convert]::ToBase64String($flagsJsonBytes)
# Get the full paths of all candidate files and join them with newlines
$candidatePaths = $candidateFiles.FullName -join [Environment]::NewLine
Write-Host "Calling batch checker for $($candidateFiles.Count) files..."
# Use & operator to capture output directly without Start-Process redirection conflicts
$pythonCommand = "python.exe"
$pythonArgs = @($checkerScriptPath, $commonDbPath, $flagsJsonBase64)
try {
$result = $candidatePaths | & $pythonCommand @pythonArgs 2>&1
# Separate stdout and stderr from the combined result
$stdOut = ""
$stdErr = ""
foreach ($line in $result) {
if ($line -is [System.Management.Automation.ErrorRecord]) {
$stdErr += $line.ToString() + [Environment]::NewLine
}
else {
$stdOut += $line.ToString() + [Environment]::NewLine
}
}
if (-not [string]::IsNullOrWhiteSpace($stdErr)) {
Write-Warning "The following messages were reported by the Python checker script:"
Write-Warning $stdErr.Trim()
}
$filesToProcessPaths = $stdOut -split '[\r\n]+' | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
}
catch {
Write-Error "Failed to run Python checker script: $($_.Exception.Message)"
Write-Error "Ensure Python is installed and accessible in PATH."
Write-Error "Cannot safely determine which files need analysis - aborting to prevent re-analyzing already processed files."
Write-Error "If you want to force re-analysis of all files, use the -ForceReanalyze parameter."
exit $script:EXIT_PYTHON_ERROR
}
$filesToProcess = [System.Collections.Generic.List[System.IO.FileInfo]]::new()
$skippedCount = 0
foreach ($path in $filesToProcessPaths) {
try {
$fileInfo = Get-Item -Path $path -ErrorAction Stop
$filesToProcess.Add($fileInfo)
}
catch {
# File may have been deleted between Python check and now, or is inaccessible
Write-Warning "Cannot access file '$path': $($_.Exception.Message)"
$skippedCount++
}
}
if ($skippedCount -gt 0) {
Write-Warning "Skipped $skippedCount file(s) that became inaccessible during processing."
}
Write-Host "Found $($filesToProcess.Count) files requiring analysis after filtering."
return [array]$filesToProcess
}
function Confirm-RequiredPaths {
param(
[Parameter(Mandatory = $false)][string]$ExtractDir,
[Parameter(Mandatory = $true)][string]$StorageDir
)
Write-Host "Using storage directory: $StorageDir"
if (-not ([string]::IsNullOrEmpty($ExtractDir))) {
Confirm-DirectoryExists -path $ExtractDir -create $false
}
# Create storage directory and subdirectories
Confirm-DirectoryExists -path $StorageDir -create $true
Confirm-DirectoryExists -path (Join-Path $StorageDir "extracted_dbs") -create $true
Confirm-DirectoryExists -path (Join-Path $StorageDir "extracted_code") -create $true
Confirm-DirectoryExists -path (Join-Path $StorageDir "logs") -create $true
Confirm-DirectoryExists -path (Join-Path $StorageDir "idb_cache") -create $true
Write-Host "SQLite databases will be stored in: $(Join-Path $StorageDir 'extracted_dbs')"
Write-Host "Generated C++ code will be stored in: $(Join-Path $StorageDir 'extracted_code')"
Write-Host "IDA logs will be stored in: $(Join-Path $StorageDir 'logs')"
Write-Host "IDA databases (.i64) will be stored in: $(Join-Path $StorageDir 'idb_cache')"
}
$script:TranscriptStarted = $false
$script:TranscriptPath = $null
function Start-ExecutionTranscript {
param(
[Parameter(Mandatory = $true)]
[string]$StorageDir
)
$timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'
$logsDir = Join-Path $StorageDir "logs"
$logPath = Join-Path $logsDir "batch_extractor_${timestamp}.log"
try {
Start-Transcript -Path $logPath -Append -ErrorAction Stop | Out-Null
$script:TranscriptStarted = $true
$script:TranscriptPath = $logPath
Write-Host "Execution log: $logPath" -ForegroundColor Gray
}
catch {