-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathGet Process Durations.ps1
1725 lines (1506 loc) · 72.3 KB
/
Get Process Durations.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
#requires -version 3
<#
Show process durations via security event logs when process creation/termination auditing is enabled
@guyrleech 2019
Modification History:
10/05/2019 GRL Added subject logon id to grid view output
Added enable/disable of process creatiuon and termination auditing
12/05/2019 GRL Remove process termination events from array for speed increase
Enable cmd line auditing when -enable specified
13/05/2019 GRL Added creation and modification times of executables & executable summary option
Added multiple computer capability
23/05/2019 GRL Added option for processing saved event log files
Added option for having no exe file details
13/06/2019 GRL Moved end event cache to hash table for considerable speed improvement
14/06/2019 GRL Fixed bug giving negative durations. Filtering on process stop collection building
24/07/2019 GRL Added time frames via logon sessions from LSASS
Added -listSessions to just show LSASS sessions retrieved
Changed -logon to -logonTimes and -boot to -bootTimes
01/08/2019 GRL Added microsecond granularity to logon times displayed
03/08/19 GRL Added elevation information and -elevated
Added -parents and -notparents
04/08/19 GRL Added -notProcessNames, -notsigned and -nostop
18/08/19 GRL Fixed logic bug with -nostop not giving process durations when not specified
04/09/19 GRL Fixed bug with -processNames and -notProcessNames
09/10/19 GRL Added -duration parameter
03/06/20 GRL Added -sinceBoot and -crashes
05/06/20 GRL Shows process which ended but start event not in the time window
If username in process exit different to starting username then displays this different user name
Only get logon sessions if logn times or sessions requested as very slow when sessions are high
23/02/21 GRL Moved win32_systemaccount query to be run only if the hashtable is required
13/08/21 GRL Added -allTerminations
#>
<#
.SYNOPSIS
Retrieve process start events from the security event log, try and find corresponding process exit and optionally also show start time relative to that user's logon and/or computer boot
.PARAMETER usernames
Only include processes for users which match this regular expression
.PARAMETER processNames
Only include processes which have a match in this comma separated list of regular expressions
.PARAMETER notProcessNames
Exclude processes which have a match in this comma separated list of regular expressions
.PARAMETER eventLog
The path to an event log file containing saved events
.PARAMETER noStop
Do not include details of the process end, duration or exit code
.PARAMETER notSigned
Only include executables which are not signed or the certificates are invalid
.PARAMETER start
Only retrieve processes started after this date/time
.PARAMETER end
Only retrieve processes started before this date/time
.PARAMETER last
Show processes started in the preceding period where 's' is seconds, 'm' is minutes, 'h' is hours, 'd' is days, 'w' is weeks and 'y' is years so 12h will retrieve all in the last 12 hours.
.PARAMETER listSessions
Just list the interactive logon sessions found on each computer
.PARAMETER parents
A comma separated list of parent process names to include only children of these in the output. Use =notself= to exclude processes where the child is the same as the specified parent
.PARAMETER notParents
A comma separated list of processes which if the process has a parent of one of these it will be excluded. Use =self= to exclude processes where the child is the same as the specified parent
.PARAMETER elevated
Only include processes which are run elevated
.PARAMETER logonTimes
Include the logon time and the time since logon for the process creation for the logon session this process belongs to
.PARAMETER bootTimes
Include the boot time and the time since boot for the process creation
.PARAMETER enable
Enable process creation and termination auditing
.PARAMETER disable
Disable process creation and termination auditing
.PARAMETER sinceBoot
Show process launches starting from the boot time
.PARAMETER crashes
Cross reference process exits to crash events in the Application log
.PARAMETER outputFile
Write the results to the specified csv file
.PARAMETER noGridview
Output the results to the pipeline rather than a grid view
.PARAMETER excludeSystem
Do not include processes run by the system account
.PARAMETER duration
Show events logged from the start specified via -start for the specified period where 's' is seconds, 'm' is minutes, 'h' is hours, 'd' is days, 'w' is weeks and 'y' is years so 2m will retrieve events for 2 minutes from the given start time
.PARAMETER noFileInfo
Do not include exe file information
.PARAMETER summary
Show a summary by executable including number of executions and file details
.PARAMETER computers
A comma separated list of computers to run query the security event logs of. Firewall must allow Remote Eventlog.
.PARAMETER allTerminations
Search for process termination events up to the current time rather than just in the time window specified by -start and -end
.EXAMPLE
& '.\Get Process Durations.ps1' -last 2d -logon -username billybob -boot
Find all process creations and corresponding terminations for the user billybob in the last 2 days, calculate the start time relative to logon for that user's session and relative to the the boot time and display in a grid view
.EXAMPLE
& '.\Get Process Durations.ps1' -enable
Enable process creation and termination auditing
.EXAMPLE
& '.\Get Process Durations.ps1' -notParents explorer.exe,cmd.exe,powershell.exe,=self= -processNames powershell.exe,cmd.exe,powershell_ise.exe
Show all instances of powershell.exe, cmd.exe and powershell_ise.exe processes where the parent process is not one of those listed and not one of the processes listed via -processNames
.EXAMPLE
& '.\Get Process Durations.ps1' -parents winword.exe,excel.exe,outlook.exe.powerpnt.exe,excel.exe,=notself= -notProcesses conhost.exe
Show all instances of processes, except conhost.exe, where the parent process is one of those listed as long as it is not another instance of the same process.
.EXAMPLE
& '.\Get Process Durations.ps1' -elevated -excludeSystem
Show all processes which were run elevated but not using the system account
.EXAMPLE
& '.\Get Process Durations.ps1' -notsigned -noStop
Show all processes where the executable is not signed but do not include process end, duration or exit codes
.EXAMPLE
& '.\Get Process Durations.ps1' -listSessions
Show all interactive logon sessions from LSASS since last boot
.EXAMPLE
& '.\Get Process Durations.ps1' -summary -start "08:00" -computers xa1,xa2
Find all process creations on computers xa1 and xa2 since 0800 today and produce a grid view summarising per unique executable
.NOTES
Must have process creation and process termination auditing enabled although this script can enable/disable if required
If process command line auditing is enabled then the command line will be included. See https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/manage/component-updates/command-line-process-auditing
Enable/Disable of auditing will not work in non-English locales
When run for multiple computers, the file information is only taken from the first instance of that executable encountered so not compared across computers
#>
[CmdletBinding()]
Param
(
[string]$username ,
[string[]]$processNames ,
[string[]]$notProcessNames ,
[string[]]$pids ,
[string]$start ,
[string]$end ,
[string]$last ,
[string]$duration ,
[string]$eventLog ,
[string]$logonOf ,
[int]$beforeSeconds = 30 ,
[int]$afterSeconds = 120 ,
[string]$logonAround ,
[int]$skipLogons = 0 ,
[switch]$listSessions ,
[string[]]$parents ,
[string[]]$notParents ,
[string[]]$computers = @( $env:COMPUTERNAME ) ,
[switch]$elevated ,
[switch]$notSigned ,
[switch]$logonTimes ,
[switch]$bootTimes ,
[switch]$sinceBoot ,
[switch]$crashes ,
[switch]$noStop ,
[switch]$enable ,
[switch]$disable ,
[switch]$summary ,
[string]$outputFile ,
[switch]$nogridview ,
[switch]$noFileInfo ,
[switch]$excludeSystem ,
[switch]$allTerminations
)
[string[]]$startPropertiesMap = @(
'SubjectUserSid' , ## 0
'SubjectUserName' , ## 1
'SubjectDomainName' , ## 2
'SubjectLogonId' , ## 3
'NewProcessId' , ## 4
'NewProcessName' , ## 5
'TokenElevationType' ,## 6
'ProcessId' , ## 7
'CommandLine' , ## 8
'TargetUserSid' , ## 9
'TargetUserName' , ## 10
'TargetDomainName' , ## 11
'TargetLogonId' , ## 12
'ParentProcessName' ## 13
)
Set-Variable -Name 'endSubjectUserSid' -Value 0 -Option ReadOnly -ErrorAction SilentlyContinue
Set-Variable -Name 'endSubjectUserName' -Value 1 -Option ReadOnly -ErrorAction SilentlyContinue
Set-Variable -Name 'endSubjectDomainName' -Value 2 -Option ReadOnly -ErrorAction SilentlyContinue
Set-Variable -Name 'endSubjectLogonId' -Value 3 -Option ReadOnly -ErrorAction SilentlyContinue
Set-Variable -Name 'endStatus' -Value 4 -Option ReadOnly -ErrorAction SilentlyContinue
Set-Variable -Name 'endProcessId' -Value 5 -Option ReadOnly -ErrorAction SilentlyContinue
Set-Variable -Name 'endProcessName' -Value 6 -Option ReadOnly -ErrorAction SilentlyContinue
[hashtable]$auditingGuids = @{
'Process Creation' = '{0CCE922C-69AE-11D9-BED3-505054503030}'
'Process Termination' = '{0CCE922C-69AE-11D9-BED3-505054503030}' }
## https://www.codeproject.com/Articles/18179/Using-the-Local-Security-Authority-to-Enumerate-Us
$LSADefinitions = @'
[DllImport("secur32.dll", SetLastError = false)]
public static extern uint LsaFreeReturnBuffer(IntPtr buffer);
[DllImport("Secur32.dll", SetLastError = false)]
public static extern uint LsaEnumerateLogonSessions
(out UInt64 LogonSessionCount, out IntPtr LogonSessionList);
[DllImport("Secur32.dll", SetLastError = false)]
public static extern uint LsaGetLogonSessionData(IntPtr luid,
out IntPtr ppLogonSessionData);
[StructLayout(LayoutKind.Sequential)]
public struct LSA_UNICODE_STRING
{
public UInt16 Length;
public UInt16 MaximumLength;
public IntPtr buffer;
}
[StructLayout(LayoutKind.Sequential)]
public struct LUID
{
public UInt32 LowPart;
public UInt32 HighPart;
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_LOGON_SESSION_DATA
{
public UInt32 Size;
public LUID LoginID;
public LSA_UNICODE_STRING Username;
public LSA_UNICODE_STRING LoginDomain;
public LSA_UNICODE_STRING AuthenticationPackage;
public UInt32 LogonType;
public UInt32 Session;
public IntPtr PSiD;
public UInt64 LoginTime;
public LSA_UNICODE_STRING LogonServer;
public LSA_UNICODE_STRING DnsDomainName;
public LSA_UNICODE_STRING Upn;
}
public enum SECURITY_LOGON_TYPE : uint
{
Interactive = 2, //The security principal is logging on
//interactively.
Network, //The security principal is logging using a
//network.
Batch, //The logon is for a batch process.
Service, //The logon is for a service account.
Proxy, //Not supported.
Unlock, //The logon is an attempt to unlock a workstation.
NetworkCleartext, //The logon is a network logon with cleartext
//credentials.
NewCredentials, //Allows the caller to clone its current token and
//specify new credentials for outbound connections.
RemoteInteractive, //A terminal server session that is both remote
//and interactive.
CachedInteractive, //Attempt to use the cached credentials without
//going out across the network.
CachedRemoteInteractive,// Same as RemoteInteractive, except used
// internally for auditing purposes.
CachedUnlock // The logon is an attempt to unlock a workstation.
}
'@
<#
Function Load-GUI( $inputXml )
{
$form = $NULL
[xml]$XAML = $inputXML -replace 'mc:Ignorable="d"' , '' -replace 'x:N' ,'N' -replace '^<Win.*' , '<Window'
$reader = New-Object Xml.XmlNodeReader $xaml
try
{
$form = [Windows.Markup.XamlReader]::Load( $reader )
}
catch
{
Write-Error -Message "Unable to load Windows.Markup.XamlReader. Double-check syntax and ensure .NET is installed.`n$_"
return $null
}
if( $form )
{
$xaml.SelectNodes('//*[@Name]') | ForEach-Object `
{
Set-Variable -Name "WPF$($_.Name)" -Value $Form.FindName($_.Name) -Scope Global
}
}
return $form
}
#>
Function Get-FileInfo
{
Param
(
[ref]$started
)
[bool]$excluded = $false
if( ! ( $exeProperties = $fileProperties[ $started.Value.NewProcessName ] ) )
{
if( $remoteParam.Count )
{
if( $result = Invoke-Command @remoteParam -ScriptBlock { Get-ItemProperty -Path $($using:started).NewProcessName -ErrorAction SilentlyContinue } )
{
## This is a deserialised object which doesn't seem to persist new properties added so we will make a local copy
$exeProperties = New-Object -TypeName 'PSCustomObject'
$result.PSObject.Properties | Where-Object MemberType -Match 'property$' | Foreach-ObjectFast `
{
if( $_.Name -eq 'VersionInfo' ) ## has been flattened into a string so need to unflatten
{
[int]$added = 0
$versionInfo = New-Object -TypeName 'PSCustomObject'
$_.Value -split "`n" | Foreach-ObjectFast `
{
[string[]]$split = $_ -split ':',2 ## will be : in file names so only split on first
if( $split -and $split.Count -eq 2 )
{
Add-Member -InputObject $versionInfo -MemberType NoteProperty -Name $split[0] -Value ($split[1]).Trim()
$added++
}
}
if( $added )
{
Add-Member -InputObject $exeProperties -MemberType NoteProperty -Name VersionInfo -Value $versionInfo
}
}
else
{
Add-Member -InputObject $exeProperties -MemberType NoteProperty -Name $_.Name -Value $_.Value
}
}
}
}
elseif( $started.Value.NewProcessName )
{
$exeProperties = Get-ItemProperty -Path $started.Value.NewProcessName -ErrorAction SilentlyContinue
}
if( $exeProperties )
{
try
{
if( $remoteParam.Count )
{
$signature = Invoke-Command @remoteParam -ScriptBlock { Get-AuthenticodeSignature -FilePath $($using:exeProperties).FullName -ErrorAction SilentlyContinue }
}
else
{
$signature = Get-AuthenticodeSignature -FilePath $exeProperties.FullName -ErrorAction SilentlyContinue
}
}
catch
{
$signature = $null
}
if( $remoteParam.Count )
{
$owner = Invoke-Command @remoteParam -ScriptBlock { Get-Acl -Path $($using:started).NewProcessName -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Owner }
}
else
{
$owner = Get-Acl -Path $started.Value.NewProcessName -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Owner
}
$extraProperties = Add-Member -PassThru -InputObject $exeProperties -Force -NotePropertyMembers @{
'Vendor' = $(if( $signature -and $signature.SignerCertificate -and ( $signature.SignerCertificate.Subject -cmatch 'CN=(.*),\s*OU=' -or $signature.SignerCertificate.Subject -cmatch 'CN=(.*),\s*O=' ) ) { $Matches[1].Trim( '"' ) })
'Signed' = $(if( $signature -and $signature.Status.ToString() -eq 'Valid' ) { 'Yes' } else { 'No' })
'Occurrences' = ([int]1)
'Owner' = $owner
}
$fileProperties.Add( $started.Value.NewProcessName , $extraProperties )
}
}
else
{
$exeProperties.Occurrences += 1
}
if( $exeProperties )
{
$started.Value += @{
'Exe Signed' = $exeProperties.Signed
'Exe Created' = $exeProperties.CreationTime
'Exe Modified' = $exeProperties.LastWriteTime
'Exe Company' = $exeProperties.VersionInfo|Select-Object -ExpandProperty CompanyName -ErrorAction SilentlyContinue
'Exe Vendor' = $exeProperties.Vendor
'Exe File Owner' = $exeProperties.Owner }
if( $notSigned -and $exeProperties.PSObject.Properties[ 'Signed' ] -and $exeProperties.Signed -eq 'Yes' )
{
$excluded = $true
}
}
$excluded
}
Function Get-AuditSetting
{
[CmdletBinding()]
Param
(
[string]$GUID
)
[string[]]$fields = ( auditpol.exe /get /subcategory:"$GUID" /r | Select-Object -Skip 1 ) -split ',' ## Don't use ConvertFrom-CSV as makes it harder to get the column we want
if( $fields -and $fields.Count -ge 6 )
{
## Machine Name,Policy Target,Subcategory,Subcategory GUID,Inclusion Setting,Exclusion Setting
## DESKTOP2,System,Process Termination,{0CCE922C-69AE-11D9-BED3-505054503030},No Auditing,
$fields[5] ## get a blank field at the start
}
else
{
Write-Warning "Unable to determine audit setting"
}
}
## http://powershell.one/tricks/performance/pipeline from @TobiasPSP
function Foreach-ObjectFast
{
param
(
[ScriptBlock]
$Process,
[ScriptBlock]
$Begin,
[ScriptBlock]
$End
)
begin
{
# construct a hard-coded anonymous simple function from
# the submitted scriptblocks:
$code = @"
& {
begin
{
$Begin
}
process
{
$Process
}
end
{
$End
}
}
"@
# turn code into a scriptblock and invoke it
# via a steppable pipeline so we can feed in data
# as it comes in via the pipeline:
$pip = [ScriptBlock]::Create($code).GetSteppablePipeline()
$pip.Begin($true)
}
process
{
# forward incoming pipeline data to the custom scriptblock:
$pip.Process($_)
}
end
{
$pip.End()
}
}
[datetime]$startTime = Get-Date
if( $enable -and $disable )
{
Throw 'Cannot enable and disable in same call'
}
if( $summary -and $noFileInfo )
{
Throw 'Cannot specify -noFileInfo with -summary'
}
if( $notSigned -and $noFileInfo )
{
Throw 'Cannot specify -notSigned with -noFileInfo'
}
if( $enable -or $disable )
{
[hashtable]$requiredAuditEvents = @{
'Process Creation' = '0cce922b-69ae-11d9-bed3-505054503030'
'Process Termination' = '0cce922c-69ae-11d9-bed3-505054503030'
}
[string]$state = $(if( $enable ) { 'Enable' } else { 'Disable' })
[int]$errors = 0
ForEach( $requiredAuditEvent in $requiredAuditEvents.GetEnumerator() )
{
$process = Start-Process -FilePath auditpol.exe -ArgumentList "/set /subcategory:{$($requiredAuditEvent.Value)} /success:$state" -Wait -WindowStyle Hidden -PassThru
if( ! $process -or $process.ExitCode )
{
Write-Error "Error running auditpol.exe to set $($requiredAuditEvent.Name) auditing to $state - error $($process|Select-Object -ExpandProperty ExitCode)"
$errors++
}
}
if( $enable )
{
[void](New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit' -Name 'ProcessCreationIncludeCmdLine_Enabled' -Value 1 -PropertyType 'DWord' -Force)
}
Exit $errors
}
if( $PSBoundParameters[ 'last' ] -and ( $PSBoundParameters[ 'start' ] -or $PSBoundParameters[ 'end' ] -or $PSBoundParameters[ 'sinceBoot' ] ) )
{
Throw "Cannot use -last when -start, -sinceboot or -end are also specified"
}
if( $PSBoundParameters[ 'nostop' ] -and $PSBoundParameters[ 'crashes' ] )
{
Throw "Cannot use -nostop and -crashes"
}
[hashtable]$startEventFilter = @{
'Id' = 4688
}
[int]$secondsAgo = 0
if( ! [string]::IsNullOrEmpty( $last ) )
{
## see what last character is as will tell us what units to work with
[int]$multiplier = 0
switch( $last[-1] )
{
"s" { $multiplier = 1 }
"m" { $multiplier = 60 }
"h" { $multiplier = 3600 }
"d" { $multiplier = 86400 }
"w" { $multiplier = 86400 * 7 }
"y" { $multiplier = 86400 * 365 }
default { Throw "Unknown multiplier `"$($last[-1])`"" }
}
$endDate = Get-Date
if( $last.Length -le 1 )
{
$secondsAgo = $multiplier
}
else
{
$secondsAgo = ( ( $last.Substring( 0 , $last.Length - 1 ) -as [decimal] ) * $multiplier )
}
$startDate = $endDate.AddSeconds( -$secondsAgo )
$startEventFilter.Add( 'StartTime' , $startDate )
## if using event log file so -last is relative to the latest event in the file so -1h means 0700 if latest event is 0800 but we'll calculate this when we process that computer (which is probably local anyway) and change STartTime
}
$closest = $null
if( $PSBoundParameters[ 'logonOf' ] )
{
if( $computers -and ( $computers.Count -gt 1 -or ( $computers[0] -ne '.' -and $computers[0] -ne $env:COMPUTERNAME ) ) )
{
Throw "Cannot use -logonOf with -computers"
}
if( ! ( ([System.Management.Automation.PSTypeName]'Win32.Secure32').Type ) )
{
Add-Type -MemberDefinition $LSADefinitions -Name 'Secure32' -Namespace 'Win32' -UsingNamespace System.Text -Debug:$false
}
$count = [UInt64]0
$luidPtr = [IntPtr]::Zero
[uint64]$ntStatus = [Win32.Secure32]::LsaEnumerateLogonSessions( [ref]$count , [ref]$luidPtr )
if( $ntStatus )
{
Write-Error "LsaEnumerateLogonSessions failed with error $ntStatus"
}
elseif( ! $count )
{
Write-Error "No sessions returned by LsaEnumerateLogonSessions"
}
elseif( $luidPtr -eq [IntPtr]::Zero )
{
Write-Error "No buffer returned by LsaEnumerateLogonSessions"
}
else
{
Write-Debug "$count sessions retrieved from LSASS"
[IntPtr]$iter = $luidPtr
$earliestSession = $null
[array]$lsaSessions = @( For ([uint64]$i = 0; $i -lt $count; $i++)
{
$sessionData = [IntPtr]::Zero
$ntStatus = [Win32.Secure32]::LsaGetLogonSessionData( $iter , [ref]$sessionData )
if( ! $ntStatus -and $sessionData -ne [IntPtr]::Zero )
{
$data = [System.Runtime.InteropServices.Marshal]::PtrToStructure( $sessionData , [type][Win32.Secure32+SECURITY_LOGON_SESSION_DATA] )
if ($data.PSiD -ne [IntPtr]::Zero)
{
$sid = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList $Data.PSiD
#extract some useful information from the session data struct
[datetime]$loginTime = [datetime]::FromFileTime( $data.LoginTime )
$thisUser = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($data.Username.buffer) #get the account name
$thisDomain = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($data.LoginDomain.buffer) #get the domain name
try
{
$secType = [Win32.Secure32+SECURITY_LOGON_TYPE]$data.LogonType
}
catch
{
$secType = 'Unknown'
}
if( ! $earliestSession -or $loginTime -lt $earliestSession )
{
$earliestSession = $loginTime
}
if( $secType -match 'Interactive' )
{
$authPackage = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($data.AuthenticationPackage.buffer) #get the authentication package
$session = $data.Session # get the session number
$logonServer = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($data.LogonServer.buffer) #get the logon server
$DnsDomainName = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($data.DnsDomainName.buffer) #get the DNS Domain Name
$upn = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($data.upn.buffer) #get the User Principal Name
[pscustomobject]@{
'Sid' = $sid
'Username' = $thisUser
'Domain' = $thisDomain
'Session' = $session
'LoginId' = [uint64]( $loginID = [Int64]("0x{0:x8}{1:x8}" -f $data.LoginID.HighPart , $data.LoginID.LowPart) )
'LogonServer' = $logonServer
'DnsDomainName' = $DnsDomainName
'UPN' = $upn
'AuthPackage' = $authPackage
'SecurityType' = $secType
'Type' = $data.LogonType
'LoginTime' = [datetime]$loginTime
}
}
}
[void][Win32.Secure32]::LsaFreeReturnBuffer( $sessionData )
$sessionData = [IntPtr]::Zero
}
$iter = $iter.ToInt64() + [System.Runtime.InteropServices.Marshal]::SizeOf([type][Win32.Secure32+LUID]) # move to next pointer
}) | Sort-Object -Descending -Property 'LoginTime'
[void]([Win32.Secure32]::LsaFreeReturnBuffer( $luidPtr ))
$luidPtr = [IntPtr]::Zero
Write-Verbose "Found $(if( $lsaSessions ) { $lsaSessions.Count } else { 0 }) LSA sessions, earliest session $(if( $earliestSession ) { Get-Date $earliestSession -Format G } else { 'never' })"
## Now find the requested session
if( $PSBoundParameters[ 'logonAround' ] )
{
[datetime]$targetLogonTime = Get-Date -Date $logonAround -ErrorAction Stop
}
[int]$logonCount = 0
ForEach( $lsaSession in $lsaSessions )
{
if( $lsaSession.Username -eq $logonOf )
{
$logonCount++
if( $PSBoundParameters[ 'logonAround' ] )
{
if( $closest )
{
$thisCloseness = [math]::Abs( ( New-TimeSpan -Start $lsaSession.LoginTime -End $targetLogonTime ).TotalSeconds )
$otherCloseness = [math]::Abs( ( New-TimeSpan -Start $closest.LoginTime -End $targetLogonTime ).TotalSeconds )
if( $thisCloseness -lt $otherCloseness )
{
$closest = $lsaSession
}
}
elseif( $logonCount -gt $skipLogons )
{
$closest = $lsaSession
}
}
elseif( $logonCount -gt $skipLogons ) ## get the last logon for the user
{
$closest = $lsaSession
break
}
}
}
if( $closest )
{
Write-Verbose "Using logon for $($closest.Domain)\$($closest.Username) at $(Get-Date -Date $closest.LoginTime -Format G)"
$startEventFilter.Add( 'StartTime' , $closest.LoginTime.AddSeconds( -$beforeSeconds ) )
$startEventFilter.Add( 'EndTime' , $closest.LoginTime.AddSeconds( $afterSeconds ) )
}
else
{
[datetime]$bootTime = Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -ExpandProperty LastBootupTime
Throw "Unable to find a logon for $logonOf in $(if( $lsaSessions ) { $lsaSessions.Count } else { 0 }) LSA sessions, earliest session $(if( $earliestSession ) { Get-Date $earliestSession -Format G } else { 'never' }), boot at $(Get-Date -Date $bootTime -Format G)"
}
}
}
if( $PSBoundParameters[ 'start' ] )
{
$startEventFilter.Add( 'StartTime' , (Get-Date -Date $start ))
}
elseif( $PSBoundParameters[ 'sinceBoot' ] )
{
if( $lastboot = Get-CimInstance -ClassName Win32_operatingsystem | Select-Object -ExpandProperty LastBootupTime )
{
$startEventFilter.Add( 'StartTime' , $lastboot )
}
else
{
Throw "Unable to get last boot time"
}
}
if( $PSBoundParameters[ 'duration' ] )
{
if( $PSBoundParameters[ 'end' ] )
{
Throw 'Cannot use both -duration and -end'
}
if( ! $startEventFilter[ 'StartTime' ] )
{
Throw 'Must specify -start when using -duration'
}
[int]$multiplier = 0
switch( $duration[-1] )
{
's' { $multiplier = 1 }
'm' { $multiplier = 60 }
'h' { $multiplier = 3600 }
'd' { $multiplier = 86400 }
'w' { $multiplier = 86400 * 7 }
'y' { $multiplier = 86400 * 365 }
default { Throw "Unknown multiplier `"$($duration[-1])`"" }
}
if( $duration.Length -le 1 )
{
$secondsDuration = $multiplier
}
else
{
$secondsDuration = ( ( $duration.Substring( 0 , $duration.Length - 1 ) -as [decimal] ) * $multiplier )
}
$startEventFilter.Add( 'EndTime' , ( $startEventFilter[ 'StartTime' ]).AddSeconds( $secondsDuration ))
}
elseif( $PSBoundParameters[ 'end' ] )
{
$startEventFilter.Add( 'EndTime' , (Get-Date -Date $end ))
}
[bool]$differentUserName = $false
[int]$counter = 0
[int]$index = 0
[hashtable]$fileProperties = @{}
[hashtable]$allSessions = @{}
if( $PSBoundParameters[ 'eventLog' ] )
{
$startEventFilter.Add( 'Path' , $eventLog )
}
else
{
$startEventFilter.Add( 'LogName', 'Security' )
}
## If called via scheduled task, arrays aren't passed as arrarys so split back out
if( $processNames -and $processNames.Count -and $processNames[0].IndexOf( ',' ) -ge 0 )
{
$processNames = $processNames -split ','
}
if( $pids -and $pids.Count -and $pids[0].IndexOf( ',' ) -ge 0 )
{
[int[]]$pids = [int[]]$pids -split ','
}
else
{
[int[]]$pids = $pids
}
if( $notProcessNames -and $notProcessNames.Count -and $notProcessNames[0].IndexOf( ',' ) -ge 0 )
{
$notProcessNames = $notProcessNames -split ','
}
if( $computers -and $computers.Count -and $computers[0].IndexOf( ',' ) -ge 0 )
{
$computers = $computers -split ','
}
if( $parents -and $parents.Count -and $parents[0].IndexOf( ',' ) -ge 0 )
{
$parents = $parents -split ','
}
if( $notParents -and $notParents.Count -and $notParents[0].IndexOf( ',' ) -ge 0 )
{
$notParents = $notParents -split ','
}
[array]$processes = @( ForEach( $computer in $computers )
{
if( $computer -eq '.' )
{
$computer = $env:COMPUTERNAME
}
$counter++
Write-Verbose "Checking $counter / $($computers.Count ) : $computer"
[string]$machineAccount = $computer + '$'
[hashtable]$remoteParam = @{}
if( $computer -ne '.' -and $computer -ne $env:COMPUTERNAME )
{
$remoteParam.Add( 'ComputerName' , $computer )
}
[hashtable]$systemAccounts = @{}
## if cross referencing to crashes, get that data
[array]$processCrashes = $null
if( $PSBoundParameters[ 'crashes' ] )
{
[hashtable]$crashParameters = @{ 'Providername' = 'Windows Error Reporting' ; Id = 1001 }
if( $startEventFilter[ 'StartTime' ] )
{
$crashParameters.Add( 'StartTime' , $startEventFilter.StartTime )
}
if( $startEventFilter[ 'EndTime' ] )
{
$crashParameters.Add( 'EndTime' , $startEventFilter.EndTime )
}
$processCrashes = @( Get-WinEvent -FilterHashtable $crashParameters -ErrorAction SilentlyContinue | Where-Object { ! $_.processNames -or ! $_.processNames.Count -or [system.io.path]::GetFileNameWithoutExtension( $_.Properties[5].Value ) -in $processNames } )
Write-Verbose "Got $($processCrashes.Count) process crashes on $computer"
}
## If using event log file and -last then we need to get the date of the newest event as -last will be relative to that
if( $PSBoundParameters[ 'last' ] -and $PSBoundParameters[ 'eventLog' ] )
{
## Remove start time from hash table
$startEventFilter.Remove( 'StartTime' )
$latestEventHere = Get-WinEvent @remoteParam -FilterHashtable $startEventFilter -ErrorAction SilentlyContinue -MaxEvents 1
if( $latestEventHere )
{
$startEventFilter.Add( 'StartTime' , $latestEventHere.TimeCreated.AddSeconds( - $secondsAgo ) )
}
}
## Get Oldest event before we filter on date so can report oldest
Write-Verbose -Message "$(Get-Date -Format G): getting oldest start event"
$earliestEvent = $null
$earliestEventHere = Get-WinEvent @remoteParam -FilterHashtable $startEventFilter -Oldest -ErrorAction SilentlyContinue -MaxEvents 1
if( ! $earliestEvent -or $earliestEventHere -lt $earliestEvent )
{
$earliestEvent = $earliestEventHere
}
if( $earliestEvent )
{
Write-Verbose -Message "$(Get-Date -Format G): earliest event is $(Get-Date -Date $earliestEvent.TimeCreated -Format G)"
}
else
{
Write-Warning -Message "Got no events"
}
[hashtable]$logons = @{}
if( $logonTimes -or $listSessions )
{
[array]$loggedOnUsers = @( Get-CimInstance @remoteParam -Classname win32_loggedonuser )
## get logons so we can cross reference to the id of the logon
Get-CimInstance @remoteParam -Classname win32_logonsession -Filter "LogonType='10' or LogonType='12' or LogonType='2' or LogonType='11'" | ForEach-Object `
{
$session = $_
[array]$users = @( $loggedOnUsers.Where( { $_.Dependent -match "`"$($session.LogonId)`"" } ) | . { Process `
{
if( $_.Antecedent -match 'Name = "(.*)", Domain = "(.*)"' )
{
[pscustomobject]@{ 'LogonTime' = $session.StartTime ; 'Domain' = $Matches[2] ; 'UserName' = $Matches[1] ; 'Computer' = $computer }
}
else
{
Write-Warning "Unexpected antecedent format `"$($_.Antecedent)`""
}
}})
if( $users -and $users.Count )
{
$logons.Add( $session.LogonId , $users )
}
}
}