-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPowerShellTool.ps1
1088 lines (983 loc) · 42.3 KB
/
PowerShellTool.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
This tool is for collecting and validating information on OS internals for analysis
.DESCRIPTION
Documentation is in progress of being built!
The parameter sets are working.
This tool can:
Check Virus Total Signature information by MD5, SHA1, and SHA256
- Requires API Key
Get file hashes in MD5, SHA1, and SHA256
Check Bluetooth Devices
Check USB Devices
- Get possible device names for connection instances
- Show all USB devices
- Show detailed info for all drivers
- Check FS permissions for driver files
Check File Authenticode Signatures
View Network Profiles
- It can rename network profiles
- It can rename network profile descriptions
Get Verbose info about Network Adapters
See services in registry
Validate service installation
.PARAMETER services
To retrieve system service names. Called with no optional parameters,
This will retrieve all the registry key names for services in HKLM
Optional parameters:
-serviceName <service_name> - Name of service in registry
.PARAMETER servicesNotSigned
To go over the services in registry and determine if they are signed
by Microsoft. Note, this will show all svchost.exe executions and all
dllhost.exe executions. This is a work in progress.
.PARAMETER serviceName
To specify a single service for -services
.PARAMETER getAuthenticode
To get the authenticode signature for a given file
.PARAMETER hash
To hash a file using md5, sha1, or sha256
Required parameters one of [-md5 | -sha1 | -sha256]
.PARAMETER virusTotal
To query a file on virus total
Required parameters:
-vtAPIKey <api_key> - VirusTotal.com API key
-vtHash <file_hash> - File hash, can be md5, sha1, or sha256
-vtSigInfo - To display only the signature information
.PARAMETER getUSBInfo
To list USB devices and their DeviceIDs
#>
param (
[Parameter(ParameterSetName = "LogStdOutOnly", Mandatory = $true)]
[Parameter(ParameterSetName = "Registry", Mandatory = $false)]
[Parameter(ParameterSetName = "Service", Mandatory = $false)]
[Parameter(ParameterSetName = "Authenticode", Mandatory = $false)]
[Parameter(ParameterSetName = "Hash", Mandatory = $false)]
[Parameter(ParameterSetName = "FilePerms", Mandatory = $false)]
[Parameter(ParameterSetName = "INFInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "INFDeviceIds", Mandatory = $false)]
[Parameter(ParameterSetName = "VirusTotal", Mandatory = $false)]
[Parameter(ParameterSetName = "GetNetworkAdapters", Mandatory = $false)]
[Parameter(ParameterSetName = "ServicesNotSigned", Mandatory = $false)]
[Parameter(ParameterSetName = "GetUSBInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "GetAllUSBDeviceInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "DeviceInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "DriverInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "GetBluetoothDevices", Mandatory = $false)]
[Parameter(ParameterSetName = "GetNetworkProfiles", Mandatory = $false)]
[Parameter(ParameterSetName = "RenameNetworkProfiles", Mandatory = $false)]
[Parameter(ParameterSetname = "GetNetworkConnections", Mandatory = $false)]
[switch]$logStdOutOnly,
[Parameter(ParameterSetName = "LogFile", Mandatory = $false)]
[Parameter(ParameterSetName = "Registry", Mandatory = $false)]
[Parameter(ParameterSetName = "Service", Mandatory = $false)]
[Parameter(ParameterSetName = "Authenticode", Mandatory = $false)]
[Parameter(ParameterSetName = "Hash", Mandatory = $false)]
[Parameter(ParameterSetName = "FilePerms", Mandatory = $false)]
[Parameter(ParameterSetName = "INFInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "INFDeviceIds", Mandatory = $false)]
[Parameter(ParameterSetName = "VirusTotal", Mandatory = $false)]
[Parameter(ParameterSetName = "GetNetworkAdapters", Mandatory = $false)]
[Parameter(ParameterSetName = "ServicesNotSigned", Mandatory = $false)]
[Parameter(ParameterSetName = "GetUSBInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "GetAllUSBDeviceInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "DeviceInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "DriverInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "GetBluetoothDevices", Mandatory = $false)]
[Parameter(ParameterSetName = "GetNetworkProfiles", Mandatory = $false)]
[Parameter(ParameterSetName = "RenameNetworkProfiles", Mandatory = $false)]
[Parameter(ParameterSetname = "GetNetworkConnections", Mandatory = $false)]
[switch]$logFileOnly,
[Parameter(ParameterSetName = "LogFile", Mandatory = $true)]
[Parameter(ParameterSetName = "Registry", Mandatory = $false)]
[Parameter(ParameterSetName = "Service", Mandatory = $false)]
[Parameter(ParameterSetName = "Authenticode", Mandatory = $false)]
[Parameter(ParameterSetName = "Hash", Mandatory = $false)]
[Parameter(ParameterSetName = "FilePerms", Mandatory = $false)]
[Parameter(ParameterSetName = "INFInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "INFDeviceIds", Mandatory = $false)]
[Parameter(ParameterSetName = "VirusTotal", Mandatory = $false)]
[Parameter(ParameterSetName = "GetNetworkAdapters", Mandatory = $false)]
[Parameter(ParameterSetName = "ServicesNotSigned", Mandatory = $false)]
[Parameter(ParameterSetName = "GetUSBInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "GetAllUSBDeviceInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "DeviceInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "DriverInfo", Mandatory = $false)]
[Parameter(ParameterSetName = "GetBluetoothDevices", Mandatory = $false)]
[Parameter(ParameterSetName = "GetNetworkProfiles", Mandatory = $false)]
[Parameter(ParameterSetName = "RenameNetworkProfiles", Mandatory = $false)]
[Parameter(ParameterSetname = "GetNetworkConnections", Mandatory = $false)]
[string]$logFile,
[Parameter(ParameterSetName = "Registry", Mandatory = $true)]
[switch]$registry,
[Parameter(ParameterSetName = "Service", Mandatory = $true)]
[switch]$services,
[Parameter(ParameterSetName = "Service", Mandatory = $false)]
[Parameter(ParameterSetName = "Registry", Mandatory = $true)]
[string]$regPath,
[Parameter(ParameterSetName = "Service", Mandatory = $false)]
[string]$serviceName,
[Parameter(ParameterSetName = "Authenticode", Mandatory = $true)]
[switch]$getAuthenticode,
[Parameter(ParameterSetName = "Hash", Mandatory = $true)]
[switch]$hash,
[Parameter(ParameterSetName = "Hash", Mandatory = $false)]
[switch]$sha256,
[Parameter(ParameterSetName = "Hash", Mandatory = $false)]
[switch]$sha1,
[Parameter(ParameterSetName = "Hash", Mandatory = $false)]
[switch]$md5,
[Parameter(ParameterSetName = "Hash", Mandatory = $true)]
[Parameter(ParameterSetName = "Authenticode", Mandatory = $true)]
[Parameter(ParameterSetName = "FilePerms", Mandatory = $true)]
[Parameter(ParameterSetName = "INFInfo", Mandatory = $true)]
[Parameter(ParameterSetName = "INFDeviceIds", Mandatory = $true)]
[string]$filePath,
[Parameter(ParameterSetName = "FilePerms", Mandatory = $true)]
[switch]$getFilePerms,
[Parameter(ParameterSetName = "VirusTotal", Mandatory = $true)]
[switch]$virusTotal,
[Parameter(ParameterSetName = "VirusTotal", Mandatory = $false)]
[switch]$vtSigInfo,
[Parameter(ParameterSetName = "VirusTotal", Mandatory = $true)]
[string]$vtAPIKey,
[Parameter(ParameterSetName = "VirusTotal", Mandatory = $true)]
[string]$vtHash,
[Parameter(ParameterSetName = "ServicesNotSigned", Mandatory = $true)]
[switch]$servicesNotSigned,
[Parameter(ParameterSetName = "GetUSBInfo", Mandatory = $true)]
[switch]$getUSBInfo,
[Parameter(ParameterSetName = "GetAllUSBDeviceInfo", Mandatory = $true)]
[switch]$getAllUSBDeviceInfo,
[Parameter(ParameterSetName = "DeviceInfo", Mandatory = $true)]
[switch]$getDeviceInfo,
[Parameter(ParameterSetName = "DriverInfo", Mandatory = $true)]
[switch]$getDriverInfo,
[Parameter(ParameterSetName = "DriverInfo", Mandatory = $true)]
[Parameter(ParameterSetName = "DeviceInfo", Mandatory = $true)]
[string]$deviceId,
[Parameter(ParameterSetName = "INFInfo", Mandatory = $true)]
[switch]$getInfInfo,
[Parameter(ParameterSetName = "INFDeviceIds", Mandatory = $true)]
[switch]$getInfDeviceIds,
[Parameter(ParameterSetName = "GetBluetoothDevices", Mandatory = $true)]
[switch]$getBluetoothDevices,
[Parameter(ParameterSetName = "GetNetworkProfiles", Mandatory = $true)]
[switch]$getNetworkProfiles,
[Parameter(ParameterSetName = "GetNetworkAdapters", Mandatory = $true)]
[switch]$getNetworkAdapterInfo,
[Parameter(ParameterSetName = "GetNetworkAdapters", Mandatory = $false)]
[string]$adapterName,
[switch]$adapterDriverInfo,
[Parameter(ParameterSetName = "RenameNetworkProfiles", Mandatory = $true)]
[switch]$renameNetworkProfile,
[Parameter(ParameterSetName = "RenameNetworkProfiles", Mandatory = $true)]
[string]$npName,
[Parameter(ParameterSetName = "RenameNetworkProfiles", Mandatory = $true)]
[string]$npNameNew,
[Parameter(ParameterSetName = "RenameNetworkProfiles", Mandatory = $false)]
[string]$npDescNew,
[Parameter(ParameterSetname = "GetNetworkConnections", Mandatory = $true)]
[switch]$getNetworkConnections,
[Parameter(ParameterSetname = "GetNetworkConnections", Mandatory = $false)]
[string]$netProtocol,
[Parameter(ParameterSetname = "GetNetworkConnections", Mandatory = $false)]
[string]$netAddress,
[Parameter(ParameterSetname = "GetNetworkConnections", Mandatory = $false)]
[switch]$netGetServiceNames,
[Parameter(ParameterSetname = "GetNetworkConnections", Mandatory = $false)]
[string]$netServiceName,
[Parameter(ParameterSetname = "GetNetworkConnections", Mandatory = $false)]
[int]$netPid
)
$networkProfilesRegPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Profiles\"
$barLine = "================================================================================="
function Write-OutputLog {
param (
[Parameter(Mandatory = $false)]
[string]$Prefix = "",
[Parameter(ValueFromRemainingArguments = $true)]
[object[]]$Args
)
# Concatenate all arguments into a single line and remove extra whitespace
$output = ($Args -join " ").Trim()
$finalOutput = "$Prefix$output"
if ($logStdOutOnly) {
# Write to console
Write-Host $finalOutput
} elseif ($logFileOnly) {
# If -LogToFile is specified, write to the specified log file
if ($logFile) {
# Ensure the path is valid and write output to file
$finalOutput | Out-File -FilePath $logFile -Append -Encoding utf8
}
} else {
Write-Host $finalOutput
if ($logFile) {
# Ensure the path is valid and write output to file
$finalOutput | Out-File -FilePath $logFile -Append -Encoding utf8
}
}
}
function Write-OutputCapture {
param([object]$InputObject)
$outputString = $InputObject | Out-String
Write-OutputLog $outputString
}
function Get-PropertiesTwoLevelsDeep {
param (
[Parameter(Mandatory=$true)]
[object]$InputObject,
[int]$IndentLevel = 0, # Used for formatting output
[int]$MaxDepth = 2 # Maximum depth of recursion
)
# Helper function to create indented output
function Write-Indented {
param (
[string]$Text,
[int]$Level
)
Write-OutputLog (" " * $Level * $MaxDepth) $Text
}
# Get the properties of the input object
$properties = $InputObject | Get-Member -MemberType Properties
foreach ($property in $properties) {
$propertyName = $property.Name
try {
$propertyValue = $InputObject.$propertyName
} catch {
# Skip properties that can't be accessed
continue
}
if ($propertyValue) {
# Print the property name and value
Write-Indented "$propertyName : $propertyValue" $IndentLevel -No
# Recursively check if the current depth is less than the maximum depth
if ($IndentLevel -lt ($MaxDepth - 1) -and
$propertyValue -is [System.Collections.IEnumerable] -and
$propertyValue -notlike [string]) {
foreach ($item in $propertyValue) {
# Recursively call the function if the property is an object with its own properties
Get-PropertiesTwoLevelsDeep -InputObject $item -IndentLevel ($IndentLevel + 1) -MaxDepth $MaxDepth
}
}
}
}
return $properties
}
# Function to verify driver signature
function Verify-FileSignature {
param ($filePath)
Write-OutputLog "Verifying driver signature for $filePath..."
Get-ChildItem -Path "C:\Windows\System32\DriverStore\FileRepository\" -Recurse | Where-Object { $_.Name -like $filePath } | ForEach-Object {
$signature = Get-AuthenticodeSignature -FilePath $_.FullName
Write-OutputLog "Driver Path: " $_.FullName
if ($signature.Status -eq 'Valid') {
Write-OutputLog "Driver Valid: Driver signature is valid."
} else {
Write-OutputLog "Driver Valid: Driver signature is invalid or not found!"
}
}
}
# Function to check the driver file with VirusTotal or antivirus (mocked here)
function Analyze-DriverFile {
param ($driverFilePath)
Write-OutputLog "Analyzing driver file: $driverFilePath..."
# Here, you could upload to VirusTotal or run an antivirus scan on the file
# Example mock result:
Write-OutputLog "Virus scan recommended for $driverFilePath. Ensure it’s clean."
}
function Get-Perms {
param([string]$filePath)
if (Test-Path $filePath) {
$permissions = Get-Acl -Path $filePath
Write-OutputLog "File path found at: "$filePath
if ($permissions) {
Write-OutputLog "Permissions:"
$permissionsProperties = Get-PropertiesTwoLevelsDeep -InputObject $permissions -MaxDepth 1
} else {
Write-OutputLog "Could not find permissions"
}
} else {
Write-OutputLog "File not found at the expected path: $filePath"
}
}
# Function to check file installation path and permissions
function Get-FSPerms {
param ($filePath)
Write-OutputLog ""
Write-OutputLog "Checking file installation path and permissions for $filePath..."
Get-ChildItem -Path "C:\Windows\System32\DriverStore\FileRepository\" -Recurse | Where-Object { $_.Name -like $filePath } | ForEach-Object {
Get-Perms -filePath $_.FullName
}
}
function Get-PnPInfo {
if ($deviceId -and $getDeviceInfo) {
Write-OutputLog "Getting PnP Device Information: " $tempvid
$pnpDevice = Get-PnpDevice -InstanceId $deviceId
$pnpProperties = Get-PropertiesTwoLevelsDeep $pnpDevice -MaxDepth 1
# Extract relevant information
$hardwareId = ($device | Where-Object { $_.KeyName -eq "DEVPKEY_Device_HardwareIds" }).Data
$compatibleId = ($device | Where-Object { $_.KeyName -eq "DEVPKEY_Device_CompatibleIds" }).Data
# Display the IDs
Write-OutputLog "HardwareID: $hardwareId"
Write-OutputLog "CompatibleID: $compatibleId"
# Check for known device types
if ($hardwareId -match "Class_03&SubClass_01") {
Write-OutputLog "Device Type: Likely a Keyboard"
}
elseif ($hardwareId -match "Class_03&SubClass_02") {
Write-OutputLog "Device Type: Likely a Mouse"
}
elseif ($hardwareId -match "Class_06") {
Write-OutputLog "Device Type: Likely a Camera (Imaging Class)"
}
elseif ($compatibleId -match "USBSTOR") {
Write-OutputLog "Device Type: Likely a USB Storage Device"
}
else {
Write-OutputLog "Device Type: General HID or Unknown"
}
}
}
# Function to cross-reference device IDs
function CrossReference-DeviceIDs {
param ([string]$infFilePath)
Write-OutputLog "Cross-referencing device IDs in the INF file..."
$infFileContent = Get-Content -Path $infFilePath -Raw
$hardwareIdRegex = "(USB|PCI|ACPI|HID)\\VID_[A-Fa-f0-9]{4}(&PID_[A-Fa-f0-9]{4}(&MI_[A-Fa-f0-9]{2})?)?"
$matches = [regex]::Matches($infFileContent, $hardwareIdRegex)
$foundVIDs = $matches | Sort-Object -Unique
$vids = $($foundVIDs -join ', ')
Write-OutputLog "Found driver supported device IDs: "$vids
}
# Function to validate service installation
function Validate-ServiceInstallation {
param ($serviceName)
if (-not $serviceName) {
return
}
Write-OutputLog ""
Write-OutputLog "Validating service installation for $serviceName..."
$service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($service) {
Write-OutputLog "Service $serviceName is installed. Status: $($service.Status)"
$serviceProperties = Get-PropertiesTwoLevelsDeep $service -MaxDepth 1
} else {
Write-OutputLog "Service $serviceName is not found."
}
}
# Function to review event logs for driver installation
function Review-DriverEventLogs {
param ($driverFileName)
Write-OutputLog "Reviewing event logs for driver installation..."
Get-WinEvent -LogName System | Where-Object {
$_.Message -match $driverFileName -and $_.Id -eq 7045
} | Format-Table -Property TimeCreated, Id, LevelDisplayName, Message -AutoSize
}
function Get-INFData {
param([string] $infFilePath)
Write-OutputLog $infFilePath
if ($infFilePath) {
if (Test-Path -Path $infFilePath) {
Write-OutputLog "Continuing"
} else {
return
}
} else {
return
}
# Initialize variables
$driverFileNames = @()
$driverFileName = ""
$catalogFileName = ""
$driverDate = ""
$driverVersion = ""
$deviceVIDs = @()
$serviceNames = @()
# Read the INF file contents
$infFileContent = Get-Content -Path $infFilePath
# Parse each line in the INF file
foreach ($line in $infFileContent) {
# Check for driver version and date
if ($line -match "^DriverVer\s*=\s*([0-9/]+),(.+)$") {
$driverDate = $matches[1].Trim()
$driverVersion = $matches[2].Trim()
}
# Check for catalog file
elseif ($line -match "^CatalogFile\s*=\s*(.+)$") {
$catalogFileName = $matches[1].Trim()
}
# Check for driver file in [SourceDisksFiles] section
elseif ($line -match "^\s*(sshid\.sys)\s*=") {
$driverFileName = $matches[1].Trim()
}
# Check for all .sys files in [SourceDisksFiles] section
elseif ($line -match "^\s*(\S+\.sys)\s*=") {
$sysFile = $matches[1].Trim()
if ($driverFileNames -notcontains $sysFile) {
$driverFileNames += $sysFile
}
}
# Collect any hardware ID in a similar format, like USB\VID_xxxx&PID_xxxx
elseif ($line -match "(USB|PCI|ACPI|HID)\\(VID|VEN|DEV|PID)_\w+&[A-Z0-9]+") {
$hardwareID = $matches[0].Trim()
if ($deviceVIDs -notcontains $hardwareID) {
$deviceVIDs += $hardwareID
}
}
# Collect service names in [Services] section
elseif ($line -match "^AddService\s*=\s*([^,]+)") {
$serviceName = $matches[1].Trim()
if ($serviceNames -notcontains $serviceName) {
$serviceNames += $serviceName
}
}
}
# Define driver directory path (may vary depending on installation)
$driverDirectory = "C:\Windows\System32\DriverStore\FileRepository"
Write-OutputLog "Analyzing $infFilePath"
# Output the parsed information
Write-OutputLog "Driver File Name: $($driverFileNames -join ', ')"
Write-OutputLog "Catalog File Name: $catalogFileName"
Write-OutputLog "Driver Date: $driverDate"
Write-OutputLog "Driver Version: $driverVersion"
Write-OutputLog "Device VIDs: $($deviceVIDs -join ', ')"
Write-OutputLog "Service Names: $($serviceNames -join ', ')"
Write-OutputLog ""
Write-OutputLog ""
# Variables used in the forensic analysis script
#$catalogFilePath = Join-Path -Path $driverDirectory -ChildPath $catalogFileName
#$driverFilePath = Join-Path -Path $driverDirectory -ChildPath $driverFileName
# Run all checks
Verify-FileSignature -filePath $catalogFilePath
foreach ($checkPath in $driverFileNames) {
Analyze-DriverFile -driverFilePath $checkPath
Write-OutputLog ""
Verify-FileSignature -filePath $checkPath
# Write-OutputLog "Driver Permissions"
# Get-FSPerms -filePath $checkPath
}
Write-OutputLog ""
CrossReference-DeviceIDs -infFilePath $infFilePath -deviceVIDs $deviceVIDs
Write-OutputLog ""
$serviceNames | ForEach-Object { Validate-ServiceInstallation -serviceName $_ }
# Review-DriverEventLogs -driverFileName $driverFileName
}
function Get-NetworkAdapterInfo {
param($adapter)
#Write-OutputLog ""
#Write-OutputLog "Getting info for "$($adapter.Name)
#Write-OutputLog $barLine
if ($adapterDriverInfo) {
$adapterProperties = Get-PropertiesTwoLevelsDeep $adapter -MaxDepth 1
Write-OutputLog $barLine
Write-OutputLog ""
$macAddress = $($adapter.MacAddress -replace '-', ':')
$wmiInfo = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.MACAddress -eq $macAddress}
Write-OutputLog $barLine
Write-OutputLog ""
Write-OutputLog "Network Adapter Information"
$wmiProperties = Get-PropertiesTwoLevelsDeep $wmiInfo -MaxDepth 1
$cimInstance = Get-CimInstance -ClassName Win32_NetworkAdapter | Where-Object {$_.MACAddress -eq $macAddress}
Write-OutputLog $barLine
Write-OutputLog ""
Write-OutputLog "CIM Instance Properties"
$cimInstanceProperties = Get-PropertiesTwoLevelsDeep $cimInstance -MaxDepth 1
Write-OutputLog $barLine
Write-OutputLog ""
$ipAddresses = Get-NetIPAddress -InterfaceIndex $adapter.InterfaceIndex
foreach ($ipAddress in $ipAddresses) {
Write-OutputLog $barLine
Write-OutputLog "IP Address properties for " $($ipAddress.IPAddress)
$ipAddressProperties = Get-PropertiesTwoLevelsDeep $ipAddress -MaxDepth 1
Write-OutputLog $barLine
Write-OutputLog ""
}
$routes = Get-NetRoute -InterfaceIndex $adapter.InterfaceIndex | Format-Table -AutoSize
Write-OutputCapture -InputObject $routes
Write-OutputLog $barLine
$deviceId = $($adapter.PNPDeviceID)
Get-DriverInfo
} else {
Write-OutputLog $barLine
$properties = Get-PropertiesTwoLevelsDeep $adapter -MaxDepth 1
}
}
function Get-NetworkAdaptersInfo {
$adapters = $(Get-NetAdapter)
foreach ($adapterInfo in $adapters) {
if ($adapterName) {
if ($adapterName -eq $adapterInfo.Name) {
Get-NetworkAdapterInfo -adapter $adapterInfo
}
} else {
Get-NetworkAdapterInfo -adapter $adapterInfo
}
}
}
function Get-NetworkProfile {
param ([string]$profileName)
$regKeys = Get-ChildItem -Path $networkProfilesRegPath | Select-Object -ExpandProperty PSChildName
$foundGuid = $null
foreach ($profileGuid in $regKeys) {
$fullPath = "$networkProfilesRegPath$profileGuid" -replace "HKEY_LOCAL_MACHINE", "HKLM:\"
$details = $(Get-ItemProperty -Path $fullPath)
if ($details.ProfileName -eq $profileName) {
$foundGuid = $profileGuid
}
}
return $foundGuid
}
function Remove-NetworkProfile {
if ($removeNetworkProfile -and -$npName) {
$foundGuid = Get-NetworkProfile -profileName $npName
$fullPath = "$networkProfilesRegPath$profileGuid" -replace "HKEY_LOCAL_MACHINE", "HKLM:\"
if ($profileGuid) {
if (Test-Path -Path $fullPath) {
Remove-Item -Path $fullPath
}
}
}
}
function Rename-NetworkProfile {
if ($renameNetworkProfile -and $npName -and ($npNameNew -or $npDescNew) ) {
$profileGuid = Get-NetworkProfile -profileName $npName
$fullPath = "$networkProfilesRegPath$profileGuid" -replace "HKEY_LOCAL_MACHINE", "HKLM:\"
if ($profileGuid) {
if (Test-Path -Path $fullPath) {
if ($npNameNew) {
if ((Get-ItemProperty -Path $fullPath -Name "ProfileName" -ErrorAction SilentlyContinue) -ne $null) {
Set-ItemProperty -Path $fullPath -Name "ProfileName" -Value $npNameNew
Get-Item -Path $fullPath | Format-Table
} else {
"Profile name does not exist"
}
}
if ($npDescNew) {
if ((Get-ItemProperty -Path $fullPath -Name "Description" -ErrorAction SilentlyContinue) -ne $null) {
Set-ItemProperty -Path $fullPath -Name "Description" -Value $npDescNew
Get-Item -Path $fullPath | Format-Table
} else {
"Profile description does not exist"
}
}
}
} else {
Write-OutputLog "Could not find network profile by name"
}
}
}
function Get-NetworkProfiles {
$regKeys = Get-ChildItem -Path $networkProfilesRegPath | Select-Object -ExpandProperty PSChildName
foreach ($profileGuid in $regKeys) {
$fullPath = "$networkProfilesRegPath$profileGuid" -replace "HKEY_LOCAL_MACHINE", "HKLM:\"
Write-OutputLog $profileGuid
$details = $(Get-ItemProperty -Path $fullPath)
Write-OutputLog " Name: "$details.ProfileName
Write-OutputLog " Description: "$details.Description
$profile = Get-NetworkProfile -profileGuid $profileGuid
}
}
function Get-TCPConnections {
return Get-NetTCPConnection | Sort-Object -Property OwningProcess,RemoteAddress,LocalAddress -Descending | Select-Object @{Name='Protocol';Expression={'TCP'}}, LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess
}
function Get-UDPConnections {
return Get-NetUDPEndpoint | Sort-Object -Property OwningProcess -Descending | Select-Object @{Name='Protocol';Expression={'UDP'}}, LocalAddress, LocalPort, OwningProcess
}
function Get-TCPxorUDPConnections {
if ($netProtocol) {
if ($netProtocol -eq 'TCP') {
Write-OutputLog "Getting TCP Connections"
return Get-TCPConnections
} else {
Write-OutputLog "Getting UDP Connections"
return Get-UDPConnections
}
} else {
Write-OutputLog "Getting TCP Connections"
$tcp = Get-TCPConnections
Write-OutputLog "Getting UDP Connections"
$udp = Get-UDPConnections
$connections = $tcp + $udp
return $connections
}
}
function Get-NetworkConnections {
$connections = Get-TCPxorUDPConnections
if ($netGetServiceNames) {
Write-OutputLog "Getting Services"
$services = Get-WmiObject -Query "Select * from Win32_Service" | Select-Object -Property Name, DisplayName, ProcessId
}
# $services | Format-Table
Write-OutputLog "Sorting data"
$connections | ForEach-Object {
$matchCount = 0
$numParam = 0
if ($netProtocol) {
$numParam += 1
if ($_.Protocol -eq $netProtocol) {
$matchCount += 1
}
}
if ($netAddress) {
$numParam += 1
$protocolMatch = $false
if ($_.Protocol -eq 'TCP') {
if ($_.RemoteAddress -eq $netAddress) {
$protocolMatch = $true
}
}
if ($_.LocalAddress -eq $netAddress) {
$protocolMatch = $true
}
if ($protocolMatch -eq $true) {
$matchCount += 1
}
}
if ($netPid) {
$numParam += 1
if ($_.OwningProcess -eq $netPid) {
Write-OutputLog $_.OwningProcess " - " $netPid
$matchCount += 1
}
}
function Setup-OutputVariables {
param([switch]$useMatches,[int]$matchCount,[object]$serviceNames,[object]$process)
# Create a new object combining connection, process, matches, and service details
if ($useMatches) {
return [PSCustomObject]@{
Matches = $matchCount
Protocol = $_.Protocol
LocalAddress = $_.LocalAddress
LocalPort = $_.LocalPort
RemoteAddress = if ($_.Protocol -eq 'TCP') { $_.RemoteAddress } else { $null }
RemotePort = if ($_.Protocol -eq 'TCP') { $_.RemotePort } else { $null }
State = if ($_.Protocol -eq 'TCP') { $_.State } else { 'Listening' } # UDP endpoints default to Listening
ProcessName = if ($process) { $process.Name } else { 'Unknown' }
ProcessId = $_.OwningProcess
Services = if ($serviceNames) { $serviceNames -join ', ' } else { $null }
Path = if ($process) { $process.Path } else { 'Unknown' }
Modules = if ($process) { $($process.Modules | Select-Object FileName ) -join ', ' } else { 'Unknown' }
}
} else {
return [PSCustomObject]@{
Protocol = $_.Protocol
LocalAddress = $_.LocalAddress
LocalPort = $_.LocalPort
RemoteAddress = if ($_.Protocol -eq 'TCP') { $_.RemoteAddress } else { $null }
RemotePort = if ($_.Protocol -eq 'TCP') { $_.RemotePort } else { $null }
State = if ($_.Protocol -eq 'TCP') { $_.State } else { 'Listening' } # UDP endpoints default to Listening
ProcessName = if ($process) { $process.Name } else { 'Unknown' }
ProcessId = $_.OwningProcess
Services = if ($serviceNames) { $serviceNames -join ', ' } else { $null }
Path = if ($process) { $process.Path } else { 'Unknown' }
Modules = if ($process) { $($process.Modules | Select-Object FileName ) -join ', ' } else { 'Unknown' }
}
}
}
$currentPid = $_.OwningProcess
# Get the process details using the OwningProcess (PID)
$process = Get-Process -Id $currentPid -ErrorAction SilentlyContinue
# $processProperties = Get-PropertiesTwoLevelsDeep $process -MaxDepth 2
$serviceMatch = $false
if ($netGetServiceNames) {
$serviceNames = $services | Where-Object { $_.ProcessId -eq $currentPid } | ForEach-Object { $_.DisplayName }
foreach ($service in $serviceNames) {
if ($service -eq $netServiceName) {
$serviceMatch = $true
}
}
} else {
$serviceNames = ''
}
if ($netServiceName) {
$numParam += 1
if ($serviceMatch -eq $false) {
return
} else {
$matchCount += 1
}
}
if (($netAddress) -or ($netProtocol) -or ($netPid) -or ($netServiceName)) {
if ($matchCount -lt $numParam) {
return
}
return Setup-OutputVariables -process $process -serviceNames $serviceNames -useMatches -matchCount $matchCount | Sort-Object -Property Services, ProcessId, LocalAddress, LocalPort, Protocol | Sort-Object Matches
} else {
return Setup-OutputVariables -process $process -serviceNames $serviceNames | Sort-Object -Property Services, ProcessId, LocalAddress, LocalPort, Protocol
}
} | Format-Table -AutoSize
}
# Define the C# code to import necessary Windows API functions
$code = @"
using System;
using System.Text;
using System.Runtime.InteropServices;
public class ResourceLoader
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool FreeLibrary(IntPtr hModule);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int LoadString(IntPtr hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax);
}
"@
# Add the C# code to PowerShell
Add-Type -TypeDefinition $code -Language CSharp
# Function to expand a resource string
function Expand-ResourceString {
param (
[string]$resourcePath
)
# Extract the DLL path and the resource ID
if ($resourcePath -match '^@(.*?),(.*)') {
$dllPath = $matches[1] -replace "%SystemRoot%", $Env:SystemRoot
$resourceID = [int]$matches[2] -as [uint32]
# Load the DLL
$hModule = [ResourceLoader]::LoadLibrary($dllPath)
if ($hModule -eq [IntPtr]::Zero) {
Write-OutputLog "Failed to load library: $dllPath"
returns
}
# Load the string resource
$buffer = New-Object System.Text.StringBuilder 256
$result = [ResourceLoader]::LoadString($hModule, $resourceID, $buffer, $buffer.Capacity)
# Free the DLL
[ResourceLoader]::FreeLibrary($hModule)
# Check if the string was loaded successfully
if ($result -gt 0) {
return $buffer.ToString()
} else {
Write-OutputLog "Failed to load resource string: ID $resourceID"
}
} else {
Write-OutputLog "Invalid resource path format"
}
}
function Is-DLLImport {
param(
[string]$importPath
)
# Adjusted regular expression to match a more flexible path pattern
$regex = '^@[a-zA-Z0-9%\\]+\\[^,]+\.dll,-\d+$'
# Test if the string matches the format
if ($importPath -match $regex) {
return $true
} else {
return $false
}
}
function Is-MicrosoftSigned {
param([string]$imagePath)
# Resolve to a full path if necessary
if ($imagePath -like "\SystemRoot\*") {
$fullPath = $imagePath -replace "\\SystemRoot", $Env:SystemRoot
} elseif ($imagePath -like "System32\*") {
$fullPath = $imagePath -replace "^System32", "C:\Windows\System32\"
} else {
$fullPath = $imagePath
}
# Check if the file exists before verifying
try {
if (Test-Path -Path $fullPath) {
# Check the digital signature
$signature = Get-AuthenticodeSignature -FilePath $fullPath
# Determine if the signer is Microsoft
if ($signature.SignerCertificate.Subject -match "CN=Microsoft") {
return 1
} else {
return 0
}
} else {
return 2
}
}
catch [System.Exception] {
return 2
}
}
function Get-USBInfo {
$usbDevices = Get-WmiObject Win32_PnPEntity | Where-Object { $_.DeviceID -match '^USB' } | Select-Object Name, DeviceID
return $usbDevices
}
function Search-Directory {
param([string]$inputPath,
[string]$fileName)
if ($fileName -and (Test-Path -Path $inputPath)) {
$files = Get-ChildItem -Path $inputPath | Where-Object { $_.Name -like "$fileName" } | ForEach-Object { Get-INFData -infFilePath $_.FullName }
}
}
function Get-DriverInfo {
if ($deviceId) {
# Replace "YOUR_DEVICE_INSTANCE_ID" with the actual InstanceId from Get-PnpDevice
$deviceInfo = Get-WmiObject Win32_PnPSignedDriver | Where-Object { $_.DeviceID -eq $deviceId } | Select-Object DeviceName, DriverVersion, Manufacturer, DriverProviderName, InfName
Write-OutputLog "Device Info"
$driverProperties = Get-PropertiesTwoLevelsDeep $deviceInfo -MaxDepth 1
$fileName = [System.IO.Path]::GetFileNameWithoutExtension($deviceInfo.InfName)
$driverDirectories = @(
"C:\Windows\System32\DriverStore\FileRepository\",
"C:\Windows\INF\",
"C:\Windows\System32\drivers\",
"C:\Windows\System32\spool\drivers\",
"C:\Windows\System32\DriverStore\Temp\",
"C:\Windows\System32\DRVSTORE\",
"$env:SystemRoot\OEMDrv\" # Use environment variable for dynamic system root
)
foreach ($driversDir in $driverDirectories) {
$infPath = $(Search-Directory -inputPath $driversDir -fileName $($deviceInfo.InfName))
}
}
}
function Get-FirmwareInfo {
if ($deviceId -and $getDeviceInfo) {
# Replace "YOUR_DEVICE_INSTANCE_ID" with the actual InstanceId from Get-PnpDevice
$deviceInfo = Get-WmiObject Win32_PnPEntity | Where-Object { $_.DeviceID -like $deviceId } | Select-Object Name, DeviceID, Description
return $deviceInfo
}
}
function Get-BluetoothDevices {
return Get-PnpDevice -Class Bluetooth
}
$servicePath = "HKLM:\SYSTEM\CurrentControlSet\Services"
if ($services) {
$inputPath = $servicePath
} else {
$inputPath = $regPath
}
if ($serviceName) {
$inputPath = "$inputPath\$serviceName"
}
if ($virusTotal) {
if ($vtHash) {
# VirusTotal API URL for hash lookup
$vtApiUrl = "https://www.virustotal.com/api/v3/files/{0}" -f $($vtHash)
# Set up headers with the API key
$headers = @{
"x-apikey" = $vtAPIKey
"Content-Type" = "application/json"
}
Write-OutputLog $vtApiUrl
$response = Invoke-RestMethod -Uri $vtApiUrl -Headers $headers -Method Get
if ($vtSigInfo) {
$response.data.attributes.signature_info | Format-List
} else {
$attributesProperties = Get-PropertiesTwoLevelsDeep $response.data.attributes -maxDepth 1
$signatureInfoProperties = Get-PropertiesTwoLevelsDeep $response.data.attributes.signature_info -maxDepth 1
$lastResultsProperties = Get-PropertiesTwoLevelsDeep $response.data.attributes.last_analysis_results -maxDepth 1
}
}
} elseif ($hash) {
if ($filePath) {
if ($sha256) {
$hashAlgol = 'SHA256'
} elseif ($sha1) {
$hashAlgol = 'SHA1'
} elseif ($md5) {
$hashAlgol = 'MD5'
}
if ($hashAlgol) {
$fileHash = (Get-FileHash -Path $filePath -Algorithm SHA256).Hash
$fileHash | Format-List
} else {
Write-OutputLog "Please supply a hash algorithm"
}
} else {
Write-OutputLog "Please supply a path"
}
} elseif ($getAuthenticode) {
Write-OutputLog "Authenticode"
if ($filePath) {
$signature = Get-AuthenticodeSignature -FilePath $filePath
$signature | Format-List
} else {
Write-OutputLog "Please supply an input path"
}
} elseif ($services -or $registry) {
Write-OutputLog "Services"
if ($serviceName) {