-
Notifications
You must be signed in to change notification settings - Fork 1
/
TSPersistentService.psm1
704 lines (654 loc) · 24.4 KB
/
TSPersistentService.psm1
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
<#
TSPersistentService
Proof-of-concept script for live analysis of persistent
Windows Services [MITRE T1543.003] as presented in the
2021 SEC-T Conference.
Developed by:
Alexander Andersson (@mranderssona)
TRUESEC DFIR
Credits and thanks to:
- Jared Atkinson for the v2-compatible Get-Hash function
- Boe Prox for the Get-RegistryTimestamp function
Required Dependencies:
None
#>
#region Functions
Function Get-RegistryKeyTimestamp {
<#
Get the timestamp of a registry key
Author: Boe Prox
Links: https://learn-powershell.net/2014/12/18/retrieving-a-registry-key-lastwritetime-using-powershell/
#>
[OutputType('Microsoft.Registry.Timestamp')]
[cmdletbinding(
DefaultParameterSetName = 'ByValue'
)]
Param (
[parameter(ValueFromPipeline=$True, ParameterSetName='ByValue')]
[Microsoft.Win32.RegistryKey]$RegistryKey,
[parameter(ParameterSetName='ByPath')]
[string]$SubKey,
[parameter(ParameterSetName='ByPath')]
[Microsoft.Win32.RegistryHive]$RegistryHive,
[parameter(ParameterSetName='ByPath')]
[string]$Computername
)
Begin {
#region Create Win32 API Object
Try {
[void][advapi32]
} Catch {
#region Module Builder
$Domain = [AppDomain]::CurrentDomain
$DynAssembly = New-Object System.Reflection.AssemblyName('RegAssembly')
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) # Only run in memory
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('RegistryTimeStampModule', $False)
#endregion Module Builder
#region DllImport
$TypeBuilder = $ModuleBuilder.DefineType('advapi32', 'Public, Class')
#region RegQueryInfoKey Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
'RegQueryInfoKey', #Method Name
[Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
[IntPtr], #Method Return Type
[Type[]] @(
[Microsoft.Win32.SafeHandles.SafeRegistryHandle], #Registry Handle
[System.Text.StringBuilder], #Class Name
[UInt32 ].MakeByRefType(), #Class Length
[UInt32], #Reserved
[UInt32 ].MakeByRefType(), #Subkey Count
[UInt32 ].MakeByRefType(), #Max Subkey Name Length
[UInt32 ].MakeByRefType(), #Max Class Length
[UInt32 ].MakeByRefType(), #Value Count
[UInt32 ].MakeByRefType(), #Max Value Name Length
[UInt32 ].MakeByRefType(), #Max Value Name Length
[UInt32 ].MakeByRefType(), #Security Descriptor Size
[long].MakeByRefType() #LastWriteTime
) #Method Parameters
)
$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
[Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
[Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
)
$FieldValueArray = [Object[]] @(
'RegQueryInfoKey', #CASE SENSITIVE!!
$True
)
$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
$DllImportConstructor,
@('advapi32.dll'),
$FieldArray,
$FieldValueArray
)
$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
#endregion RegQueryInfoKey Method
[void]$TypeBuilder.CreateType()
#endregion DllImport
}
#endregion Create Win32 API object
}
Process {
#region Constant Variables
$ClassLength = 255
[long]$TimeStamp = $null
#endregion Constant Variables
#region Registry Key Data
If ($PSCmdlet.ParameterSetName -eq 'ByPath') {
#Get registry key data
$RegistryKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($RegistryHive, $Computername).OpenSubKey($SubKey)
If ($RegistryKey -isnot [Microsoft.Win32.RegistryKey]) {
Throw "Cannot open or locate $SubKey on $Computername"
}
}
$ClassName = New-Object System.Text.StringBuilder $RegistryKey.Name
$RegistryHandle = $RegistryKey.Handle
#endregion Registry Key Data
#region Retrieve timestamp
$Return = [advapi32]::RegQueryInfoKey(
$RegistryHandle,
$ClassName,
[ref]$ClassLength,
$Null,
[ref]$Null,
[ref]$Null,
[ref]$Null,
[ref]$Null,
[ref]$Null,
[ref]$Null,
[ref]$Null,
[ref]$TimeStamp
)
Switch ($Return) {
0 {
#Convert High/Low date to DateTime Object
$LastWriteTime = [datetime]::FromFileTime($TimeStamp)
#Return object
$LastWriteTime
#$Object.pstypenames.insert(0,'Microsoft.Registry.Timestamp')
#$Object
}
122 {
Throw "ERROR_INSUFFICIENT_BUFFER (0x7a)"
}
Default {
Throw "Error ($return) occurred"
}
}
#endregion Retrieve timestamp
}
}
function Get-FileInfo($fullPath) {
<#
Get forensically useful information about a file.
The input can be a file, or a command line. In case it is a
command line it will get the info for the image path.
#>
try {
$imagePath = Get-ImagePath "$fullPath"
} catch {
Write-Warning "Error when extracting imagepath from command line `"$fullPath`""
}
if($imagePath) {
$signature = Get-AuthenticodeSignature -FilePath $imagePath -ErrorAction SilentlyContinue
if($signature) {
$signed = switch ($signature.Status) {
'Valid' {
$true
break
}
'NotSigned' {
$false
break
}
default {
$false
}
}
$IsSigned = $signed
$IsOSBinary = $signature.IsOSBinary
$SignatureSubject = $signature.SignerCertificate.Subject
$SignatureIssuer = $signature.SignerCertificate.IssuerName.Name
} else {
$IsSigned = "Error"
$IsOSBinary = "Error"
$SignatureSubject = "Error"
$SignatureIssuer = "Error"
}
$i = get-item -LiteralPath "$imagePath" -ErrorAction SilentlyContinue
$attributes = [PSCustomObject]@{
FullName = $i."FullName"
CreationTimeUtc = ($i."CreationTimeUtc").ToString("yyyy-MM-dd HH:mm:ss")
LastWriteTimeUtc = ($i."LastWriteTimeUtc").ToString("yyyy-MM-dd HH:mm:ss")
LastAccessTimeUtc = ($i."LastAccessTimeUtc").ToString("yyyy-MM-dd HH:mm:ss")
Owner = (Get-Acl -Path "$imagePath" ).Owner
Mode = $i."Mode"
MD5 = (Get-Hash -FilePath "$imagePath" -Algorithm MD5).Hash
SHA1 = (Get-Hash -FilePath "$imagePath" -Algorithm SHA1).Hash
LinkType = $i."LinkType"
Length = $i."Length"
FileDescription = ($i."VersionInfo")."FileDescription"
ProductName = ($i."VersionInfo")."ProductName"
IsSigned = $signed
IsOSBinary = $signature.IsOSBinary
SignatureSubject = $signature.SignerCertificate.Subject
SignatureIssuer = $signature.SignerCertificate.IssuerName.Name
}
}
else {
Write-Warning "Failed to extract imagepath from command line `"$fullPath`""
$attributes = $null
}
$attributes
}
function Get-ImagePath($string) {
<#
Extract the image path from a command line.
E.g. if command line is
C:\WINDOWS\system32\svchost.exe -k LocalServiceNetworkRestricted
then we want it to return
C:\WINDOWS\system32\svchost.exe
This function handles most, but not all cases.
Disclaimer: This script is a PoC, there will be LoTR-style dragons in this function :-)
#>
$result = $null
$string = $string.ToLower()
if( $string -like 'hklm:*' -or $string -like 'hkcc:*' -or $string -like 'hkcr:*' -or $string -like 'hku:*' -or $string -like "{*") {
$result = $null
} else {
# Fix relative drivers references
if( $string -like "\SystemRoot\System32\drivers\*.sys") {
$expanded = "$env:SystemRoot\System32\drivers\"
$string = $string.Replace("\systemroot\system32\drivers\",$expanded)
}
if( $string -like "System32\drivers\*.sys") {
$expanded = "$env:SystemRoot\System32\drivers\"
$string = $string.Replace("system32\drivers\",$expanded)
}
if( $string -like "\SystemRoot\System32\DriverStore\*.sys") {
$expanded = "$env:SystemRoot\System32\DriverStore\"
$string = $string.Replace("\systemroot\system32\driverstore\",$expanded)
}
# Path prefixes and legacy paths
if( $string -like "\??\UNC\*") {
$string = $string.Replace("\??\UNC\","\\")
}
if( $string -like "\??\*") {
$string = $string.Replace("\??\","")
}
if( $string -like "\\?\*") {
$string = $string.Replace("\?\","")
}
if( $string -like "\\.\*") {
$string = $string.Replace("\\.\","")
}
if( $string -like "\Global??\C:*") {
$string = $string.Replace("\Global??\C:","C:")
}
if( $string -like "\\127.0.0.1\c$*") {
$string = $string.Replace("\\127.0.0.1\","C:")
}
if( $string -like "127.0.0.1\c$*") {
$string = $string.Replace("127.0.0.1\c$","C:")
}
if( $string -like "\\LOCALHOST\c$*") {
$string = $string.Replace("\\LOCALHOST\c$","C:")
}
if( $string -like "LOCALHOST\c$*") {
$string = $string.Replace("LOCALHOST\c$","C:")
}
# Resolve CMD variables
$string = [System.Environment]::ExpandEnvironmentVariables($string)
# Remove irrelevant characters
$string = $string.Replace('"','')
$string = $string.Replace('*','')
$string = $string.Replace('>','')
$string = $string.Replace('<','')
$string = $string.Replace('?','')
if($string.Length -le 1) {
$result = $null
}
elseif( $string -like "\\*" ) {
# Never look up UNC paths
$result = $null
}
else {
try {
# Guess your way to the right number of whitepaces
$spaces = ($string -Split ' ')
for($x = 0; $x -lt $spaces.length; $x++){
$string = $spaces[0]
for($y = 1; $y -lt $x+1; $y++){
$string = "$string $($spaces[$y])"
}
$isCommand = get-command "$string" -ErrorAction SilentlyContinue
if($isCommand) {
$string = $isCommand.Definition
}
$isFile = Get-Item "$string" -ErrorAction SilentlyContinue
if($isFile -and !($isFile.PsIsContainer)) {
$result = $string
break
}
}
} catch { $result = $null }
}
}
"$result"
}
function Get-Hash {
<#
PowerShell v2 port of the Get-FileHash function. This version of Get-Hash supports hashing files and strings.
Link: https://gist.github.com/jaredcatkinson/7d561b553a04501238f8e4f061f112b7
Author: Jared Atkinson (@jaredcatkinson)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
#>
param
(
[Parameter(Mandatory = $true, ParameterSetName = 'Object')]
$InputObject,
[Parameter(Mandatory = $true, ParameterSetName = 'File')]
[string]
[ValidateNotNullOrEmpty()]
$FilePath,
[Parameter(Mandatory = $true, ParameterSetName = 'Text')]
[string]
[ValidateNotNullOrEmpty()]
$Text,
[Parameter(ParameterSetName = 'Text')]
[string]
[ValidateSet('ASCII', 'BigEndianUnicode', 'Default', 'Unicode', 'UTF32', 'UTF7', 'UTF8')]
$Encoding = 'Unicode',
[Parameter()]
[string]
[ValidateSet("MACTripleDES", "MD5", "RIPEMD160", "SHA1", "SHA256", "SHA384", "SHA512")]
$Algorithm = "SHA256"
)
switch($PSCmdlet.ParameterSetName)
{
File
{
try
{
$FullPath = Resolve-Path -Path $FilePath -ErrorAction Stop
$InputObject = [System.IO.File]::OpenRead($FilePath)
Get-Hash -InputObject $InputObject -Algorithm $Algorithm
}
catch
{
$retVal = New-Object -TypeName psobject -Property @{
Algorithm = $Algorithm.ToUpperInvariant()
Hash = $null
}
}
}
Text
{
$InputObject = [System.Text.Encoding]::$Encoding.GetBytes($Text)
Get-Hash -InputObject $InputObject -Algorithm $Algorithm
}
Object
{
if($InputObject.GetType() -eq [Byte[]] -or $InputObject.GetType().BaseType -eq [System.IO.Stream])
{
# Construct the strongly-typed crypto object
$hasher = [System.Security.Cryptography.HashAlgorithm]::Create($Algorithm)
# Compute file-hash using the crypto object
[Byte[]] $computedHash = $Hasher.ComputeHash($InputObject)
[string] $hash = [BitConverter]::ToString($computedHash) -replace '-',''
$retVal = New-Object -TypeName psobject -Property @{
Algorithm = $Algorithm.ToUpperInvariant()
Hash = $hash
}
$retVal
}
}
}
}
Add-Type @"
[System.FlagsAttribute]
public enum ServiceAccessFlags : uint
{
QueryConfig = 1,
ChangeConfig = 2,
QueryStatus = 4,
EnumerateDependents = 8,
Start = 16,
Stop = 32,
PauseContinue = 64,
Interrogate = 128,
UserDefinedControl = 256,
Delete = 65536,
ReadControl = 131072,
WriteDac = 262144,
WriteOwner = 524288,
Synchronize = 1048576,
AccessSystemSecurity = 16777216,
GenericAll = 268435456,
GenericExecute = 536870912,
GenericWrite = 1073741824,
GenericRead = 2147483648
}
"@
function Get-ServiceAcl($key) {
<#
Get the ACL of a service
#>
$security = Get-ItemProperty -Path "$key\Security" -ErrorAction SilentlyContinue
if(!($security -and $security.Security)) {
return
} else {
$Sddl = $security.Security
try {
$Dacl = New-Object System.Security.AccessControl.RawSecurityDescriptor($Sddl, 0)
}
catch {
Write-Warning "Failed to get security descriptor for service '$key': $Sddl"
return
}
$result = New-Object -TypeName PSObject -Property (@{
ControlFlags = $Dacl.ControlFlags
Owner = $Dacl.Owner.Value
Group = $Dacl.Group.Value
ResourceManagerControl = $Dacl.ResourceManagerControl
})
$access = @()
$Dacl.DiscretionaryAcl | ForEach-Object {
$CurrentDacl = $_
try {
$IdentityReference = $CurrentDacl.SecurityIdentifier.Translate([System.Security.Principal.NTAccount])
}
catch {
$IdentityReference = $CurrentDacl.SecurityIdentifier
}
$access += (New-Object -TypeName PSObject -Property (@{
AccessControlType = $CurrentDacl.AceType | % { "{0}" -f $_ }
IdentityReference = $IdentityReference.Value
ServiceRights = [ServiceAccessFlags] $CurrentDacl.AccessMask | % { "{0}" -f $_ }
}))
}
$null = $result | Add-Member -MemberType NoteProperty -Name Access -Value $access
$result
}
}
#endregion Functions
#region Main
function Get-TSPersistentService {
<#
Get detailed information about services
#>
[CmdletBinding()]
$ServiceStartModeEnum = [pscustomobject]@{
0="Boot"
1="System"
2="Auto"
3="Manual"
4="Disabled"
}
$ServiceTypeEnum = [pscustomobject]@{
0="Unknown"
1="KernelDriver"
2="FileSystemDriver"
4="Adapter"
8="RecognizerDriver"
16="Win32OwnProcess"
32="Win32ShareProcess"
256="InteractiveProcess"
}
$ServiceProtectedEnum = [pscustomobject]@{
0="NONE"
1="WINDOWS"
2="WINDOWS_LIGHT"
3="ANTIMALWARE_LIGHT"
}
(Get-Item -Path 'HKLM:\System\CurrentControlSet\Services').GetSubKeyNames() | ForEach-Object {
$ServiceName = $_
$key = "HKLM:\System\CurrentControlSet\Services\$ServiceName"
# Get service type
try {
$Type = Get-ItemProperty -Path $key -Name Type -ErrorAction Stop
} catch {
$Type = 0
}
$category = $ServiceTypeEnum."$($Type.Type)"
# Get regkey timestamp
try {
$reglastwrite = (Get-Item "$key" | Get-RegistryKeyTimestamp).ToString("yyyy-MM-dd HH:mm:ss")
}
catch {
$reglastwrite = "ERROR"
}
# Get service imagepath
$imagepath = Get-ItemProperty -Path "$key" -Name ImagePath -ErrorAction SilentlyContinue
if($imagepath) {
$imgpath = $imagepath.ImagePath
$imgpathinfo = Get-FileInfo "$imgpath"
}
else {
$imgpath = $null
$imgpathinfo = $null
}
# Get dependencies
$dependonservice = Get-ItemProperty -Path "$key" -Name DependOnService -ErrorAction SilentlyContinue
if($dependonservice) { $dependonserviceval = $dependonservice.DependOnService }
else {$dependonserviceval = @() }
# Get required privileges
$requiredprivs = Get-ItemProperty -Path "$key" -Name RequiredPrivileges -ErrorAction SilentlyContinue
if($requiredprivs) { $requiredprivileges = $requiredprivs.RequiredPrivileges }
else {$requiredprivileges = @() }
# Get ACL
$serviceacl = Get-ServiceAcl -key "$key"
if($serviceacl) {
$serviceowner = $serviceacl.Owner
$servicecontrolflags = $serviceacl.ControlFlags
$serviceaccess = $serviceacl.Access
} else {
$serviceowner = "?"
$servicecontrolflags = ""
$serviceaccess = @()
}
# Get service dll
$servicedll = Get-ItemProperty -Path "$key/Parameters" -Name ServiceDll -ErrorAction SilentlyContinue
if($servicedll) {
$serviceDllPath = $servicedll.ServiceDll
$serviceDllDetails = Get-FileInfo "$serviceDllPath"
}
else {
$serviceDllPath = $null
$serviceDllDetails = $null
}
# Check if it is a protected service
$protected = Get-ItemProperty -Path "$key" -Name LaunchProtected -ErrorAction SilentlyContinue
if($protected -and $protected.LaunchProtected) {
$protected = $protected.LaunchProtected
} else {
$protected = 0
}
# Get start mode
$start = Get-ItemProperty -Path "$key" -Name Start -ErrorAction SilentlyContinue
if($start) { $startMode = $ServiceStartModeEnum."$($start.start)" }
else {$startMode = '?'}
# Get start user
$objectname = Get-ItemProperty -Path "$key" -Name ObjectName -ErrorAction SilentlyContinue
if($objectname) { $startUser = $objectname.objectname }
else {$startUser = '?' }
# Print results as an object
[pscustomobject]@{
Name = $ServiceName
Category = $category
RegPath = $key
RegLastWriteTimeUTC = $reglastwrite
StartMode = $startMode
StartUser = $startUser
Protected = $ServiceProtectedEnum."$protected"
Owner = $serviceowner
Access = $serviceaccess
ControlFlags = $servicecontrolflags | % { "{0}" -f $_ }
DependOnService = $dependonserviceval
RequiredPrivileges = $requiredprivileges
CommandLine = $imgpath
CommandLineDetails = $imgpathinfo
ServiceDLLPath = $serviceDllPath
ServiceDLLDetails = $serviceDllDetails
}
}
}
function ConvertTo-TSTimeline {
<#
Convert the result of Get-TSPersistentService to a timeline
#>
[CmdletBinding()]
param(
[Parameter( Mandatory=$true, ValueFromPipeline=$true )]
[pscustomobject]$Services
)
Begin
{
$timeline = New-Object -TypeName "System.Collections.ArrayList"
}
Process
{
if($_.ServiceDLLDetails) {
$servicedllmd5 = "$($_.ServiceDLLDetails.MD5)"
} else {
$servicedllmd5 = $null
}
if($_.CommandLineDetails) {
$imagemd5 = $_.CommandLineDetails.MD5
} else {
$servicedllmd5 = $null
}
if($_.ServiceDLLDetails) {
# Create row for service dll last write time
$timeline.Add([pscustomobject]@{
Timestamp = $_.ServiceDLLDetails.LastWriteTimeUTC
Event = "Servicedll last write"
Name = $_.Name
Category = $_.Category
StartMode = $_.StartMode
CommandLine = $_.CommandLine
ImagePathMD5 = $imagemd5
ServiceDLL = $_.ServiceDLLPath
ServiceDLLMD5 = $servicedllmd5
}) | out-null
# Create row for service dll creation time
$timeline.Add([pscustomobject]@{
Timestamp = $_.ServiceDLLDetails.CreationTimeUTC
Event = "Servicedll creation"
Name = $_.Name
Category = $_.Category
StartMode = $_.StartMode
CommandLine = $_.CommandLine
ImagePathMD5 = $imagemd5
ServiceDLL = $_.ServiceDLLPath
ServiceDLLMD5 = $servicedllmd5
}) | out-null
}
if($_.CommandLineDetails) {
# Create row for image path last write time
$timeline.Add([pscustomobject]@{
Timestamp = $_.CommandLineDetails.LastWriteTimeUTC
Event = "Service imagepath last write"
Name = $_.Name
Category = $_.Category
StartMode = $_.StartMode
CommandLine = $_.CommandLine
ImagePathMD5 = $imagemd5
ServiceDLL = $_.ServiceDLLPath
ServiceDLLMD5 = $servicedllmd5
}) | out-null
# Create row for image path creation time
$timeline.Add([pscustomobject]@{
Timestamp = $_.CommandLineDetails.CreationTimeUTC
Event = "Service imagepath creation"
Name = $_.Name
Category = $_.Category
StartMode = $_.StartMode
CommandLine = $_.CommandLine
ImagePathMD5 = $imagemd5
ServiceDLL = $_.ServiceDLLPath
ServiceDLLMD5 = $servicedllmd5
}) | out-null
}
# Create row for registry key last write time
$timeline.Add([pscustomobject]@{
Timestamp = $_.reglastwritetimeutc
Event = "Service regkey last write"
Name = $_.Name
Category = $_.Category
StartMode = $_.StartMode
CommandLine = $_.CommandLine
ImagePathMD5 = $imagemd5
ServiceDLL = $_.ServiceDLLPath
ServiceDLLMD5 = $servicedllmd5
}) | out-null
}
End
{
# sort and write results to file
$timeline | Sort-Object -Property Timestamp
}
}
#endregion Main