-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPSEndpointForensics.ps1
More file actions
541 lines (464 loc) · 20.7 KB
/
Copy pathPSEndpointForensics.ps1
File metadata and controls
541 lines (464 loc) · 20.7 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
# Define function to retrieve network connection information
function Get-NetworkConnections {
# Pre-fetch process information
$processes = Get-Process | Select-Object Id, ProcessName
$processNameMap = @{}
foreach ($process in $processes) {
$processNameMap[$process.Id] = $process.ProcessName
}
# Get TCP connections
Write-Host "Getting TCP connections..."
$tcpConnections = Get-NetTCPConnection -State Established | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess
# Get UDP listeners (exclude system processes)
Write-Host "Getting UDP listeners..."
$udpListeners = Get-NetUDPEndpoint | Where-Object { $_.OwningProcess -ne 4 } | Select-Object LocalAddress, LocalPort, OwningProcess
# Get TCP Listeners
Write-Host "Getting TCP listeners..."
$tcpListeners = Get-NetTCPConnection -State Listen | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess
# Output TCP connections
$tcpConnectionsTable = $tcpConnections | ForEach-Object {
$processName = $processNameMap[[int]$_.OwningProcess]
[PSCustomObject]@{
LocalAddress = [System.Net.IPAddress]::Parse($_.LocalAddress).ToString()
LocalPort = $_.LocalPort
RemoteAddress = [System.Net.IPAddress]::Parse($_.RemoteAddress).ToString()
RemotePort = $_.RemotePort
State = $_.State
OwningProcess = $_.OwningProcess
ProcessName = $processName
}
}
# Output TCP listeners
$tcpListenersTable = $tcpListeners | ForEach-Object {
$processName = $processNameMap[[int]$_.OwningProcess]
[PSCustomObject]@{
LocalAddress = [System.Net.IPAddress]::Parse($_.LocalAddress).ToString()
LocalPort = $_.LocalPort
RemoteAddress = [System.Net.IPAddress]::Parse($_.RemoteAddress).ToString()
RemotePort = $_.RemotePort
State = $_.State
OwningProcess = $_.OwningProcess
ProcessName = $processName
}
}
# Output UDP listeners
$udpListenersTable = $udpListeners | ForEach-Object {
$processName = $processNameMap[[int]$_.OwningProcess]
[PSCustomObject]@{
LocalAddress = [System.Net.IPAddress]::Parse($_.LocalAddress).ToString()
LocalPort = $_.LocalPort
OwningProcess = $_.OwningProcess
ProcessName = $processName
}
}
return $tcpConnectionsTable, $udpListenersTable, $tcpListenersTable
}
# Define function to retrieve persistence registry keys
function Get-PersistenceRegistryKeys {
$persistenceKeys = @()
#
# LOW-NOISE autorun locations only
#
$registryPaths = @(
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce'
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce'
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnceEx'
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run'
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run'
'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run'
'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\RunOnce'
)
#
# Standard Run / RunOnce enumeration
#
foreach ($path in $registryPaths) {
if (Test-Path $path) {
$keys = Get-ItemProperty -Path $path -ErrorAction SilentlyContinue
if ($keys) {
foreach ($prop in $keys.PSObject.Properties) {
if ($prop.Name -notin @(
'PSPath',
'PSParentPath',
'PSChildName',
'PSDrive',
'PSProvider'
)) {
$persistenceKeys += [PSCustomObject]@{
Hive = $path.Substring(0, $path.IndexOf(':'))
Path = $path
ValueName = $prop.Name
ValueData = if ($null -ne $prop.Value) {
$prop.Value -join ', '
} else {
''
}
}
}
}
}
}
}
#
# IFEO — only Debugger hijacks
#
$ifeoBase = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options'
if (Test-Path $ifeoBase) {
Get-ChildItem -Path $ifeoBase -ErrorAction SilentlyContinue | ForEach-Object {
$childProps = Get-ItemProperty -Path $_.PSPath -ErrorAction SilentlyContinue
if ($childProps.Debugger) {
$persistenceKeys += [PSCustomObject]@{
Hive = 'HKLM'
Path = "$ifeoBase\$($_.PSChildName)"
ValueName = 'Debugger'
ValueData = $childProps.Debugger
}
}
}
}
#
# Winlogon — ONLY persistence-relevant values
#
$winlogonPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
$winlogonValues = @(
'Shell'
'Userinit'
'Notify'
'System'
'Taskman'
'AppSetup'
'VmApplet'
)
foreach ($name in $winlogonValues) {
try {
$value = (Get-ItemProperty -Path $winlogonPath -Name $name -ErrorAction Stop).$name
if ($null -ne $value -and $value -ne '') {
$persistenceKeys += [PSCustomObject]@{
Hive = 'HKLM'
Path = $winlogonPath
ValueName = $name
ValueData = $value -join ', '
}
}
}
catch {}
}
#
# Session Manager — ONLY true persistence values
#
$smPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager'
$sessionManagerValues = @(
'BootExecute'
'Execute'
'PendingFileRenameOperations'
'SetupExecute'
'S0InitialCommand'
)
foreach ($name in $sessionManagerValues) {
try {
$value = (Get-ItemProperty -Path $smPath -Name $name -ErrorAction Stop).$name
if ($null -ne $value -and $value -ne '') {
$persistenceKeys += [PSCustomObject]@{
Hive = 'HKLM'
Path = $smPath
ValueName = $name
ValueData = $value -join ', '
}
}
}
catch {}
}
return $persistenceKeys
}
# Load Assemblies
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# Create a Form
$form = New-Object System.Windows.Forms.Form
$form.Text = "PowerShell System Forensics by James A. Chambers"
$form.Size = New-Object System.Drawing.Size(1600, 900)
$form.StartPosition = "CenterScreen"
$form.FormBorderStyle = 'Sizable'
# Create Tab Control
$tabControl = New-Object System.Windows.Forms.TabControl
$tabControl.Dock = "Fill"
# First Tab - Non-default Services #########################################################################################################################
$tabPage1 = New-Object System.Windows.Forms.TabPage
$tabPage1.Text = "Non-default Services"
# Code to get Non-default Services
Write-Host "Getting non-default services..."
$NonDefaultServices = Get-WmiObject win32_service | Where-Object {
$_.Caption -notmatch "Windows" -and $_.PathName -notmatch "Windows" -and
$_.PathName -notmatch "policyhost.exe" -and $_.PathName -notmatch "EdgeUpdate" -and $_.Name -ne "MicrosoftEdgeElevationService" -and
$_.Name -ne "LSM" -and $_.PathName -notmatch "OSE.EXE" -and $_.PathName -notmatch "OSPPSVC.EXE" -and
$_.PathName -notmatch "Microsoft Security Client" -and
$_.PathName -notmatch "Microsoft GameInput"
} | Select-Object -Property Name, ProcessId, StartMode, State, Status, AcceptStop, Caption, Description, PathName
# Create DataGridView for Non-default Services
$servicesGridView = New-Object System.Windows.Forms.DataGridView
$servicesGridView.Dock = 'Fill'
$servicesGridView.AutoGenerateColumns = $false
$servicesGridView.AllowUserToOrderColumns = $true
# Add Columns and Data for Non-default Services (only if entries exist)
if ($NonDefaultServices.Count -gt 0) {
$null = $NonDefaultServices[0].PSObject.Properties | ForEach-Object {
$servicesGridView.Columns.Add($_.Name, $_.Name)
}
$null = $NonDefaultServices | ForEach-Object {
$row = $_
$rowData = @()
$row.PSObject.Properties | ForEach-Object {
$rowData += $_.Value
}
$servicesGridView.Rows.Add($rowData)
}
}
# Add DataGridView to Tab Page
$tabPage1.Controls.Add($servicesGridView)
# Second Tab - Non-default Scheduled Tasks #########################################################################################################################
$tabPage2 = New-Object System.Windows.Forms.TabPage
$tabPage2.Text = "Non-default Scheduled Tasks"
# Code to get Non-default Scheduled Tasks
Write-Host "Getting non-default scheduled tasks..."
$nonDefaultTasks = Get-ScheduledTask | Where-Object { $_.TaskPath -notlike '\Microsoft\Windows*' -and
$_.TaskName -notlike 'MicrosoftEdge*' -and
$_.TaskName -notlike 'OneDrive *' -and
$_.TaskName -ne 'XblGameSaveTask'
} | Select-Object -Property TaskName, TaskPath, Author, State, Date, Triggers, Description
# Create DataGridView for Non-default Scheduled Tasks
$tasksGridView = New-Object System.Windows.Forms.DataGridView
$tasksGridView.Dock = 'Fill'
$tasksGridView.AutoGenerateColumns = $false
$tasksGridView.AllowUserToOrderColumns = $true
# Add Columns and Data for Non-default Scheduled Tasks (only if entries exist)
if ($nonDefaultTasks.Count -gt 0) {
$null = $nonDefaultTasks[0].PSObject.Properties | ForEach-Object {
$tasksGridView.Columns.Add($_.Name, $_.Name)
}
$null = $nonDefaultTasks | ForEach-Object {
$row = $_
$rowData = @()
$row.PSObject.Properties | ForEach-Object {
$rowData += $_.Value
}
$tasksGridView.Rows.Add($rowData)
}
}
# Add DataGridView to Tab Page
$tabPage2.Controls.Add($tasksGridView)
# Third Tab - Non-default Processes #########################################################################################################################
$tabPage3 = New-Object System.Windows.Forms.TabPage
$tabPage3.Text = "Non-default Processes"
# Code to get Non-default Processes
Write-Host "Getting non-default processes..."
$nonDefaultProcesses = Get-Process | Where-Object {
$_.Product -notlike 'Microsoft*Operating System' -and
$_.Product -notlike 'Microsoft Gaming Install Services' -and $_.Product -notlike 'Game Bar' -and
$_.Name -notin @('explorer', 'svchost', 'conhost', 'AggregatorHost', 'ctfmon', 'blnsvr', 'dwm', 'lsass', 'fontdrvhost', 'csrss', 'smss', 'OneDrive', 'FileCoAuth', 'MPDefenderCoreService', 'WmiPrvSE', 'winlogon', 'wininit', 'System', 'Idle', 'Registry', 'services', 'Memory Compression', 'MsMpEng', 'NisSrv', 'SecurityHealthService', 'SearchFilterHost', 'SearchIndexer', 'SearchProtocolHost', 'WidgetService', 'msedge', 'msedgewebview2', 'MicrosoftEdgeUpdate')
} | Select-Object -Property Name, Id, Company, Path, Description, MainWindowTitle, Product, CommandLine
# Create DataGridView for Non-default Processes
$processesGridView = New-Object System.Windows.Forms.DataGridView
$processesGridView.Dock = 'Fill'
$processesGridView.AutoGenerateColumns = $false
$processesGridView.AllowUserToOrderColumns = $true
# Add Columns and Data for Non-default Processes (only if entries exist)
$ProcessCmdLine = Get-CimInstance -ClassName Win32_Process
if ($nonDefaultProcesses.Count -gt 0) {
$null = $nonDefaultProcesses[0].PSObject.Properties | ForEach-Object {
$processesGridView.Columns.Add($_.Name, $_.Name)
}
$null = $nonDefaultProcesses | ForEach-Object {
$row = $_
$row.CommandLine = $ProcessCmdLine | Where-Object { $_.ProcessId -eq $row.Id } | Select-Object -ExpandProperty CommandLine
$rowData = @()
$row.PSObject.Properties | ForEach-Object {
$rowData += $_.Value
}
$processesGridView.Rows.Add($rowData)
}
}
# End 3rd tab #########################################################################################################################
# Add DataGridView to Tab Page
$tabPage3.Controls.Add($processesGridView)
# Fourth Tab - Persistence Registry Keys #########################################################################################################################
$tabPage4 = New-Object System.Windows.Forms.TabPage
$tabPage4.Text = "Persistence Registry"
# Code to get Persistence Registry Keys
Write-Host "Getting persistence registry keys..."
$persistenceRegistryKeys = Get-PersistenceRegistryKeys
# Create DataGridView for Persistence Registry Keys
$registryGridView = New-Object System.Windows.Forms.DataGridView
$registryGridView.Dock = 'Fill'
$registryGridView.AutoGenerateColumns = $false
$registryGridView.AllowUserToOrderColumns = $true
# Add Columns and Data for Persistence Registry Keys (only if entries exist)
if ($persistenceRegistryKeys.Count -gt 0) {
$null = $persistenceRegistryKeys[0].PSObject.Properties | ForEach-Object {
$registryGridView.Columns.Add($_.Name, $_.Name)
}
$null = $persistenceRegistryKeys | ForEach-Object {
$row = $_
$rowData = @()
$row.PSObject.Properties | ForEach-Object {
$rowData += $_.Value
}
$registryGridView.Rows.Add($rowData)
}
}
# Add DataGridView to Tab Page
$tabPage4.Controls.Add($registryGridView)
# Add Tab Pages to Tab Control
$tabControl.TabPages.Add($tabPage1)
$tabControl.TabPages.Add($tabPage2)
$tabControl.TabPages.Add($tabPage3)
$tabControl.TabPages.Add($tabPage4)
# End 4th tab ###############################################################################################################################
# Begin networking tabs #########################################################################################################################
# Create TCP tab
$tcpTabPage = New-Object System.Windows.Forms.TabPage
$tcpTabPage.Text = "TCP"
$tabControl.TabPages.Add($tcpTabPage)
# Create Button for resolving DNS
$resolveDNSButton = New-Object System.Windows.Forms.Button
$resolveDNSButton.Text = "Resolve DNS"
$resolveDNSButton.Location = New-Object System.Drawing.Point(570, 3)
$resolveDNSButton.Size = New-Object System.Drawing.Size(120, 18)
# Add Button to TCP tab
$tcpTabPage.Controls.Add($resolveDNSButton)
# Create UDP tab
$udpTabPage = New-Object System.Windows.Forms.TabPage
$udpTabPage.Text = "UDP"
$tabControl.TabPages.Add($udpTabPage)
# Create TCP Listener tab
$tcpListenerTabPage = New-Object System.Windows.Forms.TabPage
$tcpListenerTabPage.Text = "TCP Listen"
$tabControl.TabPages.Add($tcpListenerTabPage)
# Create DataGridView for TCP
$dataGridViewTCP = New-Object System.Windows.Forms.DataGridView
$dataGridViewTCP.Dock = "Fill"
$tcpTabPage.Controls.Add($dataGridViewTCP)
# Create DataGridView for UDP
$dataGridViewUDP = New-Object System.Windows.Forms.DataGridView
$dataGridViewUDP.Dock = "Fill"
$udpTabPage.Controls.Add($dataGridViewUDP)
# Create DataGridView for TCP Listener
$dataGridViewTCPListener = New-Object System.Windows.Forms.DataGridView
$dataGridViewTCPListener.Dock = "Fill"
$tcpListenerTabPage.Controls.Add($dataGridViewTCPListener)
# Set DataGridView properties
foreach ($dataGridView in @($dataGridViewTCP, $dataGridViewUDP, $dataGridViewTCPListener)) {
$dataGridView.AutoSizeColumnsMode = [System.Windows.Forms.DataGridViewAutoSizeColumnsMode]::Fill
$dataGridView.AllowUserToAddRows = $false
$dataGridView.AllowUserToDeleteRows = $false
$dataGridView.RowHeadersVisible = $false
}
# Add columns to DataGridView for TCP, UDP, and TCP Listener
$columns = @("LocalAddress", "LocalPort", "RemoteAddress", "RemotePort", "State", "OwningProcess", "ProcessName")
foreach ($dataGridView in @($dataGridViewTCP, $dataGridViewUDP, $dataGridViewTCPListener)) {
foreach ($colName in $columns) {
$column = New-Object System.Windows.Forms.DataGridViewTextBoxColumn
$column.HeaderText = $colName
$column.Name = $colName
$null = $dataGridView.Columns.Add($column)
}
}
# Hide irrelevant commons from certain views
$dataGridViewUDP.Columns["RemoteAddress"].Visible = $false
$dataGridViewUDP.Columns["RemotePort"].Visible = $false
$dataGridViewUDP.Columns["State"].Visible = $false
$dataGridViewTCPListener.Columns["RemotePort"].Visible = $false
# Populate DataGridView with network connection information
$tcpConnections, $udpListeners, $tcpListeners = Get-NetworkConnections
foreach ($entry in $tcpConnections) {
$null = $dataGridViewTCP.Rows.Add($entry.LocalAddress, $entry.LocalPort, $entry.RemoteAddress, $entry.RemotePort, $entry.State, $entry.OwningProcess, $entry.ProcessName)
}
foreach ($entry in $udpListeners) {
$null = $dataGridViewUDP.Rows.Add($entry.LocalAddress, $entry.LocalPort, $null, $null, $null, $entry.OwningProcess, $entry.ProcessName)
}
foreach ($entry in $tcpListeners) {
$null = $dataGridViewTCPListener.Rows.Add("0.0.0.0", $entry.LocalPort, $entry.RemoteAddress, $null, $entry.State, $entry.OwningProcess, $entry.ProcessName)
}
$resolveDNSButton.Add_Click({
$resolveDNSButton.Enabled = $false;
$jobs = @()
$id = 0;
foreach ($row in $dataGridViewTCP.Rows) {
$ipAddress = $row.Cells["RemoteAddress"].Value -replace '\s*\(.*', ''
if ($ipAddress -ne "127.0.0.1") {
# Start a background job to resolve DNS asynchronously
$job = Start-Job -ScriptBlock {
param($ipAddress, $rowId)
# Define function to resolve DNS
try {
$hostEntry = [System.Net.Dns]::GetHostEntry($ipAddress)
#return $hostEntry.HostName
return [PSCustomObject]@{
HostName = $hostEntry.HostName
rowId = $rowId
}
}
catch {
return [PSCustomObject]@{
HostName = "Unable to resolve"
rowId = $rowId
}
}
} -ArgumentList $ipAddress, $id
# Add the job to the array
$jobs += $job
}
$id++;
}
while ($true) {
$notfinished = 0;
foreach ($job in $jobs) {
if ($null -ne $job -and $job.State -eq "Completed") {
$job | Wait-Job | ForEach-Object {
$resolvedDNS = Receive-Job -Job $_
if ($resolvedDNS.HostName -ne $null) {
Write-Host ('Job #{0} ({1}) complete.' -f $resolvedDNS.HostName, $resolvedDNS.rowId)
$dataGridViewTCP.Rows[[int]$resolvedDNS.rowId].Cells["RemoteAddress"].Value = "$($dataGridViewTCP.Rows[[int]$resolvedDNS.rowId].Cells["RemoteAddress"].Value) ($($resolvedDNS.HostName))"
$dataGridViewTCP.Refresh()
}
}
} else {
$notfinished++;
}
}
if ($notfinished -eq 0) {
break;
}
Start-Sleep -Milliseconds 100
[System.Windows.Forms.Application]::DoEvents()
}
# Remove jobs to clean up resources
foreach ($job in $jobs) {
Remove-Job -Job $job -Force
}
$resolveDNSButton.Enabled = $true;
})
# End networking tabs #########################################################################################################################
$tabControl.Add_SelectedIndexChanged(
{
$servicesGridView.AutoResizeColumns()
$tasksGridView.AutoResizeColumns()
$processesGridView.AutoResizeColumns()
$registryGridView.AutoResizeColumns()
$dataGridViewUDP.AutoResizeColumns()
$dataGridViewTCP.AutoResizeColumns()
$dataGridViewTCPListener.AutoResizeColumns()
} )
# Add Tab Control to Form
$form.Controls.Add($tabControl)
# Add event handlers to autosize tabs
$form.Add_Shown(
{
$servicesGridView.AutoResizeColumns()
$registryGridView.AutoResizeColumns()
$dataGridViewTCP.Sort($dataGridViewTCP.Columns["LocalAddress"], [System.ComponentModel.ListSortDirection]::Ascending)
$dataGridViewUDP.Sort($dataGridViewUDP.Columns["LocalAddress"], [System.ComponentModel.ListSortDirection]::Ascending)
$dataGridViewTCPListener.Sort($dataGridViewTCPListener.Columns["LocalAddress"], [System.ComponentModel.ListSortDirection]::Ascending)
} )
# Show the Form
$form.ShowDialog() | Out-Null