-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGet-RDPForensics.ps1
More file actions
1526 lines (1329 loc) · 77.7 KB
/
Get-RDPForensics.ps1
File metadata and controls
1526 lines (1329 loc) · 77.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
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 -RunAsAdministrator
function Get-RDPForensics {
<#
.SYNOPSIS
Comprehensive RDP forensics analysis tool for Windows systems.
.DESCRIPTION
This script collects and analyzes RDP connection logs from various Windows Event Logs
following forensic best practices. It tracks all stages of RDP connections:
1. Network Connection (EventID 1149)
2. Credential Validation (EventID 4776)
3. Authentication (EventID 4624, 4625, 4648)
4. Logon (EventID 21, 22)
5. Lock/Unlock (EventID 4800, 4801)
6. Session Disconnect/Reconnect (EventID 24, 25, 39, 40, 4778, 4779)
7. Logoff (EventID 23, 4634, 4647, 9009)
.PARAMETER StartDate
The start date for log collection. Defaults to beginning of current day.
.PARAMETER EndDate
The end date for log collection. Defaults to current time.
.PARAMETER ExportPath
Optional path to export results to CSV files.
.PARAMETER Username
Filter results for a specific username.
.PARAMETER SourceIP
Filter results for a specific source IP address.
.PARAMETER LogonID
Filter results for a specific LogonID (e.g., '0x6950A4').
Only applicable when using -GroupBySession.
RECOMMENDED: LogonID provides the most reliable correlation as it persists across disconnect/reconnect cycles.
Cannot be used together with -SessionID (mutually exclusive).
.PARAMETER SessionID
Filter results for a specific Terminal Services SessionID (e.g., '5').
Only applicable when using -GroupBySession.
NOTE: SessionID changes on disconnect/reconnect. Use -LogonID for tracking full session lifecycle.
Cannot be used together with -LogonID (mutually exclusive).
.PARAMETER IncludeOutbound
Include outbound RDP connection logs from the client side.
.PARAMETER GroupBySession
Group events by ActivityID/LogonID/SessionID to show correlated session lifecycles.
Uses Windows Event Correlation ActivityID for precise cross-log correlation, with fallback to LogonID and SessionID.
Displays session summary with duration, lifecycle stages, and completeness indicators.
Exports to separate CSV file (RDP_Sessions_<timestamp>.csv) when used with -ExportPath.
.PARAMETER IncludeCredentialValidation
Include pre-authentication events in the analysis:
- EventID 4768-4772 (Kerberos authentication: TGT, service tickets, failures)
- EventID 4776 (NTLM Credential Validation - used when Kerberos fails/unavailable)
⚠️ IMPORTANT: These events are logged on the DOMAIN CONTROLLER, not the Terminal Server.
When running this tool on a Terminal Server, these events will be EMPTY (count: 0).
Only use this parameter when:
- Running on a Domain Controller to analyze authentication patterns
- Analyzing logs exported from a Domain Controller
Shows complete authentication story:
- Kerberos attempts (4768 TGT request, 4769 service ticket)
- Kerberos failures (4771 pre-auth failed) that trigger NTLM fallback
- NTLM authentication (4776) when Kerberos unavailable or fails
Correlation Strategy:
- Pre-authentication events (4768-4772, 4776) use username + timestamp matching
- Terminal Server events (4624, 4778, etc.) use ActivityID correlation
- ActivityID cannot correlate across machines (DC vs Terminal Server)
- All pre-auth events matched within 0-10 second window before RDP session start
- Automatically filters out non-RDP authentications (SMB, SQL, Exchange, etc.)
- Only shows pre-auth events that correlate to RDP Logon Type 10/7/3/5
.EXAMPLE
Get-RDPForensics
Get all RDP events for today.
.EXAMPLE
Get-RDPForensics -StartDate (Get-Date).AddDays(-7) -ExportPath "C:\RDP_Reports"
Get last 7 days of RDP events and export to CSV files.
.EXAMPLE
Get-RDPForensics -Username "john.doe" -StartDate (Get-Date).AddMonths(-1)
Get RDP events for specific user in the last month.
.EXAMPLE
Get-RDPForensics -GroupBySession
Display events grouped by session with complete lifecycle tracking.
.EXAMPLE
Get-RDPForensics -StartDate (Get-Date).AddDays(-7) -GroupBySession -ExportPath "C:\Reports"
Analyze last 7 days of sessions and export both events and session summaries.
.EXAMPLE
Get-RDPForensics -IncludeCredentialValidation -GroupBySession
Include Kerberos (4768-4772) and NTLM (4776) authentication events with time-based correlation.
⚠️ NOTE: Only works when running on Domain Controller. Will return 0 events on Terminal Server.
.EXAMPLE
Get-RDPForensics -GroupBySession -LogonID "0x6950A4"
Display all events for a specific LogonID-based session.
.EXAMPLE
Get-RDPForensics -GroupBySession -SessionID "5"
Display all events for a specific SessionID-based session.
.NOTES
Author: Jan Tiedemann
Version: 1.0.8
Based on: https://woshub.com/rdp-connection-logs-forensics-windows/
Requires: Administrator privileges to read Security event logs
#>
[CmdletBinding(DefaultParameterSetName = 'Default')]
param(
[Parameter()]
[DateTime]$StartDate = (Get-Date -Hour 0 -Minute 0 -Second 0),
[Parameter()]
[DateTime]$EndDate = (Get-Date),
[Parameter()]
[string]$ExportPath,
[Parameter()]
[string]$Username,
[Parameter()]
[string]$SourceIP,
[Parameter(ParameterSetName = 'ByLogonID')]
[string]$LogonID,
[Parameter(ParameterSetName = 'BySessionID')]
[string]$SessionID,
[Parameter()]
[switch]$IncludeOutbound,
[Parameter()]
[switch]$GroupBySession,
[Parameter()]
[switch]$IncludeCredentialValidation
)
# Error handling preference
$ErrorActionPreference = 'Continue'
# Emoji support for both PowerShell 5.1 and 7.x
function Get-Emoji {
param([string]$Name)
if ($PSVersionTable.PSVersion.Major -ge 6) {
$emojis = @{
'shield' = [char]::ConvertFromUtf32(0x1F6E1) + [char]::ConvertFromUtf32(0xFE0F)
'magnify' = [char]::ConvertFromUtf32(0x1F50D)
'check' = [char]::ConvertFromUtf32(0x2705)
'cross' = [char]::ConvertFromUtf32(0x274C)
'warning' = [char]::ConvertFromUtf32(0x26A0) + [char]::ConvertFromUtf32(0xFE0F)
'clock' = [char]::ConvertFromUtf32(0x23F1) + [char]::ConvertFromUtf32(0xFE0F)
'computer' = [char]::ConvertFromUtf32(0x1F4BB)
'lock' = [char]::ConvertFromUtf32(0x1F512)
'key' = [char]::ConvertFromUtf32(0x1F511)
'chart' = [char]::ConvertFromUtf32(0x1F4CA)
'folder' = [char]::ConvertFromUtf32(0x1F4C1)
'rocket' = [char]::ConvertFromUtf32(0x1F680)
}
}
else {
# PowerShell 5.1 - Use Unicode symbols that work in Windows Console
$emojis = @{
'shield' = "$([char]0x25A0)" # Black square
'magnify' = "$([char]0x25CE)" # Bullseye
'check' = "$([char]0x221A)" # Square root (checkmark-like)
'cross' = "$([char]0x00D7)" # Multiplication sign
'warning' = "$([char]0x203C)" # Double exclamation
'clock' = "$([char]0x25D4)" # Circle with upper right quadrant
'computer' = "$([char]0x25A3)" # White square with rounded corners
'lock' = "$([char]0x25A6)" # Square with vertical fill
'key' = "$([char]0x2020)" # Dagger
'chart' = "$([char]0x25A0)" # Black square
'folder' = "$([char]0x25B6)" # Right-pointing triangle
'rocket' = "$([char]0x25BA)" # Right-pointing pointer
}
}
return $emojis[$Name]
}
# Function to correlate events across log sources using LogonID and SessionID
function Get-CorrelatedSessions {
param([array]$Events)
# Group events by LogonID (priority 1) or SessionID (priority 2)
# Secondary correlation then merges SessionID sessions into LogonID sessions (same user + time proximity)
$sessionMap = @{}
foreach ($event in $Events) {
# Determine correlation key with priority: LogonID > SessionID (ActivityID kept for reference only)
$correlationKey = $null
# Priority 1: Use LogonID from Security log events (best cross-log correlation)
# Exception: Event 4648 uses SubjectLogonID (not the session LogonID) - skip direct correlation
if ($event.EventID -ne 4648 -and $event.LogonID -and $event.LogonID -ne 'N/A' -and $event.LogonID -ne $null) {
$correlationKey = "LogonID:$($event.LogonID)"
}
# Priority 2: Use SessionID from TerminalServices events
elseif ($event.SessionID -and $event.SessionID -ne 'N/A' -and $event.SessionID -ne $null) {
$correlationKey = "SessionID:$($event.SessionID)"
}
# Note: ActivityID is preserved in events for forensic analysis but not used for correlation
# as it's provider-specific and doesn't reliably match across Security/TerminalServices logs
# Note: Event 4648 uses time-based correlation instead (SubjectLogonID ≠ session LogonID)
if ($correlationKey) {
if (-not $sessionMap.ContainsKey($correlationKey)) {
$sessionMap[$correlationKey] = @{
CorrelationKey = $correlationKey
Events = @()
User = $null
SourceIP = $null
StartTime = $null
EndTime = $null
Duration = $null
ActivityID = $event.ActivityID
LogonID = $event.LogonID
SessionID = $event.SessionID
Lifecycle = @{
ConnectionAttempt = $false
Authentication = $false
Logon = $false
Active = $false
Disconnect = $false
Logoff = $false
}
}
}
# Add event to session
$sessionMap[$correlationKey].Events += $event
# Update correlation IDs if not yet set (for sessions grouped by different keys)
if (-not $sessionMap[$correlationKey].ActivityID -and $event.ActivityID) {
$sessionMap[$correlationKey].ActivityID = $event.ActivityID
}
if (-not $sessionMap[$correlationKey].LogonID -and $event.LogonID -and $event.LogonID -ne 'N/A') {
$sessionMap[$correlationKey].LogonID = $event.LogonID
}
if (-not $sessionMap[$correlationKey].SessionID -and $event.SessionID -and $event.SessionID -ne 'N/A') {
$sessionMap[$correlationKey].SessionID = $event.SessionID
}
# Track lifecycle stages
# Note: Event 4648 excluded from direct correlation - uses time-based correlation instead
switch ($event.EventID) {
1149 { $sessionMap[$correlationKey].Lifecycle.ConnectionAttempt = $true }
{ $_ -in 4624, 4776 } { $sessionMap[$correlationKey].Lifecycle.Authentication = $true }
{ $_ -in 21, 22 } { $sessionMap[$correlationKey].Lifecycle.Logon = $true }
{ $_ -in 24, 25, 4778, 4801 } { $sessionMap[$correlationKey].Lifecycle.Active = $true }
{ $_ -in 39, 40, 4779, 4800 } { $sessionMap[$correlationKey].Lifecycle.Disconnect = $true }
{ $_ -in 23, 4634, 4647, 9009 } { $sessionMap[$correlationKey].Lifecycle.Logoff = $true }
}
# Update session metadata
if ($event.User -and $event.User -ne 'N/A') {
$sessionMap[$correlationKey].User = $event.User
}
if ($event.SourceIP -and $event.SourceIP -ne 'N/A' -and $event.SourceIP -ne '-' -and $event.SourceIP -ne 'LOCAL') {
$sessionMap[$correlationKey].SourceIP = $event.SourceIP
}
}
}
# Time-based correlation for pre-authentication and credential events
# These events have different LogonIDs/ActivityIDs than the actual session:
# - 4768-4772, 4776: Pre-auth events logged on DC
# - 4648: Credential submission with SubjectLogonID (not the new session LogonID)
# Match these events to sessions within 10 seconds before session start with matching username/IP
# IMPORTANT: Only include pre-auth events that correlate to RDP sessions (Logon Type 10/7/3/5)
$preAuthEvents = $Events | Where-Object {
$_.EventID -in 4648, 4768, 4769, 4770, 4771, 4772, 4776 -and
-not $_.CorrelationKey
}
$correlatedPreAuthEventIDs = @() # Track which pre-auth events matched RDP sessions
foreach ($preAuthEvent in $preAuthEvents) {
$matchedSession = $null
$closestTimeDiff = [TimeSpan]::MaxValue
# Find the closest RDP session that starts within 10 seconds after this pre-auth event
foreach ($sessionKey in $sessionMap.Keys) {
$session = $sessionMap[$sessionKey]
$matchUser = $session.User -eq $preAuthEvent.User
$matchIP = (-not $preAuthEvent.SourceIP -or $preAuthEvent.SourceIP -eq 'N/A' -or
$session.SourceIP -eq $preAuthEvent.SourceIP)
if ($matchUser -and $matchIP) {
$sessionStart = ($session.Events | Sort-Object TimeCreated | Select-Object -First 1).TimeCreated
$timeDiff = $sessionStart - $preAuthEvent.TimeCreated
# Pre-auth/credential events should be 0-10 seconds BEFORE session start
if ($timeDiff.TotalSeconds -ge 0 -and $timeDiff.TotalSeconds -le 10) {
if ($timeDiff -lt $closestTimeDiff) {
$closestTimeDiff = $timeDiff
$matchedSession = $sessionKey
}
}
}
}
# Add pre-auth event to matched RDP session
if ($matchedSession) {
$sessionMap[$matchedSession].Events += $preAuthEvent
$sessionMap[$matchedSession].Lifecycle.Authentication = $true
$correlatedPreAuthEventIDs += $preAuthEvent.GetHashCode() # Track this event as matched
# Mark event as correlated (for filtering in non-grouped output)
$preAuthEvent | Add-Member -NotePropertyName 'CorrelatedToRDP' -NotePropertyValue $true -Force
}
}
# Filter out uncorrelated pre-auth events from the Events array
# Only keep pre-auth events that matched to RDP sessions (Logon Type 10/7/3/5)
$Events = $Events | Where-Object {
# Keep all non-pre-auth events
($_.EventID -notin 4648, 4768, 4769, 4770, 4771, 4772, 4776) -or
# OR keep pre-auth events that were correlated to RDP sessions
($_.CorrelatedToRDP -eq $true)
}
# Secondary Correlation: Merge SessionID-based sessions into LogonID-based sessions
# This handles the case where TerminalServices events (21-25) have SessionID but no LogonID
# while Security events (4624, 4778, 4779, 4634) have LogonID
# Match sessions based on: Username + Time Proximity (within 10 seconds) + RDP LogonType
$sessionIDSessions = @($sessionMap.Keys | Where-Object { $_ -like "SessionID:*" })
$logonIDSessions = @($sessionMap.Keys | Where-Object { $_ -like "LogonID:*" })
foreach ($sessionIDKey in $sessionIDSessions) {
$sessionIDSession = $sessionMap[$sessionIDKey]
# Find matching LogonID session
$matchedLogonIDKey = $null
$bestMatchScore = 0 # Track number of synchronized event pairs
foreach ($logonIDKey in $logonIDSessions) {
$logonIDSession = $sessionMap[$logonIDKey]
# Match criteria: Same user + synchronized events
if ($logonIDSession.User -eq $sessionIDSession.User) {
# Check if this LogonID session has RDP events (4624/4778/4779)
$hasRDPLogonType = $logonIDSession.Events | Where-Object {
($_.EventID -eq 4624 -and $_.Details -match 'RemoteInteractive|Unlock/Reconnect|Network') -or
($_.EventID -in @(4778, 4779))
}
if ($hasRDPLogonType) {
# Count synchronized events (events within 3 seconds of each other)
$synchronizedCount = 0
foreach ($sessionIDEvent in $sessionIDSession.Events) {
foreach ($logonIDEvent in $logonIDSession.Events) {
$timeDiff = [Math]::Abs(($logonIDEvent.TimeCreated - $sessionIDEvent.TimeCreated).TotalSeconds)
if ($timeDiff -le 3) {
$synchronizedCount++
break # Only count each SessionID event once
}
}
}
# If we found multiple synchronized events, this is a strong match
if ($synchronizedCount -ge 2 -and $synchronizedCount -gt $bestMatchScore) {
$bestMatchScore = $synchronizedCount
$matchedLogonIDKey = $logonIDKey
}
}
}
}
# Merge SessionID events into LogonID session
if ($matchedLogonIDKey) {
$sessionMap[$matchedLogonIDKey].Events += $sessionIDSession.Events
# Update SessionID in LogonID session
if (-not $sessionMap[$matchedLogonIDKey].SessionID -or $sessionMap[$matchedLogonIDKey].SessionID -eq 'N/A') {
$sessionMap[$matchedLogonIDKey].SessionID = $sessionIDSession.SessionID
}
# Merge lifecycle flags
foreach ($key in $sessionIDSession.Lifecycle.Keys) {
if ($sessionIDSession.Lifecycle[$key]) {
$sessionMap[$matchedLogonIDKey].Lifecycle[$key] = $true
}
}
# Remove the SessionID session (merged into LogonID session)
$sessionMap.Remove($sessionIDKey)
}
}
# Calculate session durations and create session objects
$sessions = foreach ($key in $sessionMap.Keys) {
$session = $sessionMap[$key]
$sortedEvents = $session.Events | Sort-Object TimeCreated
if ($sortedEvents.Count -gt 0) {
$session.StartTime = $sortedEvents[0].TimeCreated
$session.EndTime = $sortedEvents[-1].TimeCreated
if ($session.StartTime -and $session.EndTime) {
$session.Duration = $session.EndTime - $session.StartTime
}
}
# Create session object
[PSCustomObject]@{
CorrelationKey = $session.CorrelationKey
ActivityID = $session.ActivityID
User = $session.User
SourceIP = $session.SourceIP
LogonID = $session.LogonID
SessionID = $session.SessionID
StartTime = $session.StartTime
EndTime = $session.EndTime
Duration = if ($session.Duration) {
"{0:hh\:mm\:ss}" -f $session.Duration
}
else {
'N/A'
}
EventCount = $session.Events.Count
ConnectionAttempt = $session.Lifecycle.ConnectionAttempt
Authentication = $session.Lifecycle.Authentication
Logon = $session.Lifecycle.Logon
Active = $session.Lifecycle.Active
Disconnect = $session.Lifecycle.Disconnect
Logoff = $session.Lifecycle.Logoff
# Lifecycle is complete if session has minimum viable stages (Auth + Logon/Active)
# OR if session was terminated (has Logoff)
# This avoids false warnings for active sessions or time-window limitations
LifecycleComplete = ($session.Lifecycle.Authentication -and ($session.Lifecycle.Logon -or $session.Lifecycle.Active)) -or
$session.Lifecycle.Logoff
Events = $session.Events
}
}
# Return sessions and the filtered events array
return @{
Sessions = ($sessions | Sort-Object StartTime -Descending)
FilteredEvents = $Events
}
}
# ASCII Art Header
Write-Host "`n" -NoNewline
$topLeft = [char]0x2554; $topRight = [char]0x2557; $bottomLeft = [char]0x255A; $bottomRight = [char]0x255D
$horizontal = [string][char]0x2550; $vertical = [char]0x2551
Write-Host "$topLeft$($horizontal * 67)$topRight" -ForegroundColor Cyan
Write-Host "$vertical" -ForegroundColor Cyan -NoNewline
Write-Host " RDP FORENSICS ANALYSIS TOOL v1.0.8 " -ForegroundColor White -NoNewline
Write-Host "$vertical" -ForegroundColor Cyan
Write-Host "$vertical" -ForegroundColor Cyan -NoNewline
Write-Host " Security Investigation & Audit Toolkit " -ForegroundColor Yellow -NoNewline
Write-Host "$vertical" -ForegroundColor Cyan
Write-Host "$bottomLeft$($horizontal * 67)$bottomRight" -ForegroundColor Cyan
Write-Host ""
Write-Host "$(Get-Emoji 'clock') Analysis Period: " -ForegroundColor Cyan -NoNewline
Write-Host "$($StartDate.ToString('yyyy-MM-dd HH:mm:ss'))" -ForegroundColor White -NoNewline
Write-Host " to " -ForegroundColor Gray -NoNewline
Write-Host "$($EndDate.ToString('yyyy-MM-dd HH:mm:ss'))" -ForegroundColor White
Write-Host ""
# Function to parse EventID 1149 - RDP Connection Attempts
function Get-RDPConnectionAttempts {
param([DateTime]$Start, [DateTime]$End)
Write-Host "$(Get-Emoji 'rocket') [1/6] Collecting RDP Connection Attempts (EventID 1149)..." -ForegroundColor Yellow
try {
$events = Get-WinEvent -FilterHashtable @{
LogName = 'Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational'
Id = 1149
StartTime = $Start
EndTime = $End
} -ErrorAction SilentlyContinue
if ($events) {
[xml[]]$xml = $events | ForEach-Object { $_.ToXml() }
$results = foreach ($event in $xml.Event) {
# Extract ActivityID from Correlation element
$activityID = if ($event.System.Correlation.ActivityID) {
$event.System.Correlation.ActivityID
}
else {
$null
}
[PSCustomObject]@{
TimeCreated = [DateTime]::Parse($event.System.TimeCreated.SystemTime)
EventID = 1149
EventType = 'Connection Attempt'
User = $event.UserData.EventXML.Param1
Domain = $event.UserData.EventXML.Param2
SourceIP = $event.UserData.EventXML.Param3
SessionID = $null
LogonID = $null
ActivityID = $activityID
Details = "User authentication succeeded"
}
}
Write-Host " $(Get-Emoji 'check') Found " -ForegroundColor Green -NoNewline
Write-Host "$($results.Count)" -ForegroundColor White -NoNewline
Write-Host " connection attempts" -ForegroundColor Green
return $results
}
else {
Write-Host " $(Get-Emoji 'cross') No connection attempts found" -ForegroundColor DarkGray
return @()
}
}
catch {
Write-Warning "Error collecting connection attempts: $_"
return @()
}
}
# Function to parse EventID 4624, 4625, 4648, 4776, 4768-4772 - Authentication Events
function Get-RDPAuthenticationEvents {
param(
[DateTime]$Start,
[DateTime]$End,
[bool]$IncludeKerberosAndNTLM = $false
)
$eventList = if ($IncludeKerberosAndNTLM) { "4624, 4625, 4648, 4768-4772, 4776" } else { "4624, 4625, 4648" }
Write-Host "$(Get-Emoji 'key') [2/7] Collecting RDP Authentication Events (EventID $eventList)..." -ForegroundColor Yellow
try {
# Collect logon events (4624/4625) and explicit credential usage (4648)
$logonEvents = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
Id = 4624, 4625, 4648
StartTime = $Start
EndTime = $End
} -ErrorAction SilentlyContinue | Where-Object {
# Filter for RDP LogonTypes: 10 (RemoteInteractive), 7 (Unlock/Reconnect), 3 (Network-can be RDP), 5 (Service/Console)
# For Event 4648, include all (no logon type)
$_.Id -eq 4648 -or $_.Message -match 'Logon Type:\s+(10|7|3|5)'
}
# Optionally collect Kerberos and NTLM pre-authentication events
$kerberosEvents = @()
$credentialEvents = @()
if ($IncludeKerberosAndNTLM) {
# Kerberos authentication events (4768-4772)
$kerberosEvents = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
Id = 4768, 4769, 4770, 4771, 4772
StartTime = $Start
EndTime = $End
} -ErrorAction SilentlyContinue
# NTLM credential validation events (4776)
$credentialEvents = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
Id = 4776
StartTime = $Start
EndTime = $End
} -ErrorAction SilentlyContinue | Where-Object {
# Include events where Source Workstation is not empty and not local machine
# (4776 fires for all NTLM auth, we want remote/RDP-related ones)
$_.Message -match 'Source Workstation:\s+\S+' -and
$_.Message -notmatch 'Source Workstation:\s+(LOCAL|LOCALHOST|127\.0\.0\.1|-)'
}
}
# Combine all event types
$events = @($logonEvents) + @($kerberosEvents) + @($credentialEvents)
if ($events -and $events.Count -gt 0) {
$results = foreach ($event in $events) {
$message = $event.Message
# Extract ActivityID from XML
[xml]$eventXml = $event.ToXml()
$activityID = if ($eventXml.Event.System.Correlation.ActivityID) {
$eventXml.Event.System.Correlation.ActivityID
}
else {
$null
}
# Handle different event types
switch ($event.Id) {
4768 {
# Kerberos TGT Request
$userName = if ($message -match 'Account Name:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$userDomain = if ($message -match 'Account Domain:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$sourceIP = if ($message -match 'Client Address:\s+::ffff:([^\r\n]+)') { $matches[1].Trim() }
elseif ($message -match 'Client Address:\s+([^\r\n]+)') { $matches[1].Trim() }
else { 'N/A' }
$statusCode = if ($message -match 'Result Code:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$ticketOptions = if ($message -match 'Ticket Options:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$eventType = if ($statusCode -eq '0x0') { 'Kerberos TGT Success' } else { 'Kerberos TGT Failed' }
$details = "Result: $statusCode | Options: $ticketOptions"
[PSCustomObject]@{
TimeCreated = $event.TimeCreated
EventID = $event.Id
EventType = $eventType
User = $userName
Domain = $userDomain
SourceIP = $sourceIP
SessionID = $null
LogonID = $null
ActivityID = $activityID
Details = $details
}
}
4769 {
# Kerberos Service Ticket Request
$userName = if ($message -match 'Account Name:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$userDomain = if ($message -match 'Account Domain:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$serviceName = if ($message -match 'Service Name:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$sourceIP = if ($message -match 'Client Address:\s+::ffff:([^\r\n]+)') { $matches[1].Trim() }
elseif ($message -match 'Client Address:\s+([^\r\n]+)') { $matches[1].Trim() }
else { 'N/A' }
$statusCode = if ($message -match 'Failure Code:\s+([^\r\n]+)') { $matches[1].Trim() } else { '0x0' }
$eventType = if ($statusCode -eq '0x0') { 'Kerberos Service Ticket Success' } else { 'Kerberos Service Ticket Failed' }
$details = "Service: $serviceName | Result: $statusCode"
[PSCustomObject]@{
TimeCreated = $event.TimeCreated
EventID = $event.Id
EventType = $eventType
User = $userName
Domain = $userDomain
SourceIP = $sourceIP
SessionID = $null
LogonID = $null
ActivityID = $activityID
Details = $details
}
}
4770 {
# Kerberos Service Ticket Renewal
$userName = if ($message -match 'Account Name:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$userDomain = if ($message -match 'Account Domain:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$serviceName = if ($message -match 'Service Name:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$sourceIP = if ($message -match 'Client Address:\s+::ffff:([^\r\n]+)') { $matches[1].Trim() }
elseif ($message -match 'Client Address:\s+([^\r\n]+)') { $matches[1].Trim() }
else { 'N/A' }
$eventType = 'Kerberos Ticket Renewed'
$details = "Service: $serviceName"
[PSCustomObject]@{
TimeCreated = $event.TimeCreated
EventID = $event.Id
EventType = $eventType
User = $userName
Domain = $userDomain
SourceIP = $sourceIP
SessionID = $null
LogonID = $null
ActivityID = $activityID
Details = $details
}
}
4771 {
# Kerberos Pre-authentication Failed (KEY EVENT - shows why Kerberos failed)
$userName = if ($message -match 'Account Name:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$userDomain = if ($message -match 'Service Name:\s+krbtgt/([^\r\n]+)') { $matches[1].Trim() }
elseif ($message -match 'Account Domain:\s+([^\r\n]+)') { $matches[1].Trim() }
else { 'N/A' }
$sourceIP = if ($message -match 'Client Address:\s+::ffff:([^\r\n]+)') { $matches[1].Trim() }
elseif ($message -match 'Client Address:\s+([^\r\n]+)') { $matches[1].Trim() }
else { 'N/A' }
$errorCode = if ($message -match 'Failure Code:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
# Common Kerberos error codes
$errorDesc = switch ($errorCode) {
'0x6' { 'Client not found' }
'0x7' { 'Server not found' }
'0xC' { 'Workstation restriction' }
'0x12' { 'Client revoked/disabled' }
'0x17' { 'Password expired' }
'0x18' { 'Wrong password' }
'0x25' { 'Clock skew too large' }
default { "Code $errorCode" }
}
$eventType = 'Kerberos Pre-auth Failed'
$details = "Error: $errorDesc | Source: $sourceIP"
[PSCustomObject]@{
TimeCreated = $event.TimeCreated
EventID = $event.Id
EventType = $eventType
User = $userName
Domain = $userDomain
SourceIP = $sourceIP
SessionID = $null
LogonID = $null
ActivityID = $activityID
Details = $details
}
}
4772 {
# Kerberos Authentication Ticket Request Failed
$userName = if ($message -match 'Account Name:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$userDomain = if ($message -match 'Account Domain:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$sourceIP = if ($message -match 'Client Address:\s+::ffff:([^\r\n]+)') { $matches[1].Trim() }
elseif ($message -match 'Client Address:\s+([^\r\n]+)') { $matches[1].Trim() }
else { 'N/A' }
$errorCode = if ($message -match 'Failure Code:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$eventType = 'Kerberos Ticket Request Failed'
$details = "Error Code: $errorCode"
[PSCustomObject]@{
TimeCreated = $event.TimeCreated
EventID = $event.Id
EventType = $eventType
User = $userName
Domain = $userDomain
SourceIP = $sourceIP
SessionID = $null
LogonID = $null
ActivityID = $activityID
Details = $details
}
}
4776 {
# NTLM Credential Validation
# 4776 has format "Logon Account: DOMAIN\Username"
$logonAccount = if ($message -match 'Logon Account:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
# Extract just the username if domain\username format
$userName = if ($logonAccount -match '\\(.+)$') { $matches[1] }
elseif ($logonAccount -ne 'N/A') { $logonAccount }
else { 'N/A' }
$userDomain = if ($message -match 'Source Workstation:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$errorCode = if ($message -match 'Error Code:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$authPackage = if ($message -match 'Authentication Package:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'NTLM' }
$eventType = if ($errorCode -eq '0x0') { 'NTLM Validation Success' } else { 'NTLM Validation Failed' }
$details = "$authPackage | Error Code: $errorCode | Source: $userDomain"
[PSCustomObject]@{
TimeCreated = $event.TimeCreated
EventID = $event.Id
EventType = $eventType
User = $userName
Domain = 'N/A'
SourceIP = 'N/A'
SessionID = $null
LogonID = $null
ActivityID = $activityID
Details = $details
}
}
4648 {
# Explicit Credential Usage (credential submission before logon)
# Shows WHO submitted credentials, FOR WHICH account, FROM WHERE
$subjectUserName = if ($message -match 'Subject:[\s\S]*?Account Name:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$subjectDomain = if ($message -match 'Subject:[\s\S]*?Account Domain:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$subjectLogonID = if ($message -match 'Subject:[\s\S]*?Logon ID:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$targetUserName = if ($message -match 'Account Whose Credentials Were Used:[\s\S]*?Account Name:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$targetDomain = if ($message -match 'Account Whose Credentials Were Used:[\s\S]*?Account Domain:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$targetServerName = if ($message -match 'Target Server:[\s\S]*?Target Server Name:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$sourceIP = if ($message -match 'Network Information:[\s\S]*?Network Address:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$processName = if ($message -match 'Process Information:[\s\S]*?Process Name:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
# Construct usernames
if ($subjectDomain -ne 'N/A' -and $subjectDomain -ne '-' -and $subjectUserName -ne 'N/A') {
$subjectFullName = "$subjectDomain\$subjectUserName"
}
else {
$subjectFullName = $subjectUserName
}
if ($targetDomain -ne 'N/A' -and $targetDomain -ne '-' -and $targetUserName -ne 'N/A') {
$targetFullName = "$targetDomain\$targetUserName"
}
else {
$targetFullName = $targetUserName
}
# Use target user as primary User field (the account being authenticated)
$userName = $targetFullName
$userDomain = $targetDomain
$eventType = 'Credential Submission'
$details = "Subject: $subjectFullName -> Target: $targetFullName | Server: $targetServerName | Process: $(Split-Path $processName -Leaf)"
[PSCustomObject]@{
TimeCreated = $event.TimeCreated
EventID = $event.Id
EventType = $eventType
User = $userName
Domain = $userDomain
SourceIP = $sourceIP
SessionID = $null
LogonID = $subjectLogonID
ActivityID = $activityID
Details = $details
}
}
default {
# Logon/Failed Logon (4624/4625)
# Match fields from "New Logon" section (not "Subject" section)
$accountName = if ($message -match 'New Logon:[\s\S]*?Account Name:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$userDomain = if ($message -match 'New Logon:[\s\S]*?Account Domain:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
# Construct full username as DOMAIN\User to match TerminalServices event format
if ($userDomain -ne 'N/A' -and $userDomain -ne '-' -and $accountName -ne 'N/A') {
$userName = "$userDomain\$accountName"
}
else {
$userName = $accountName
}
$sourceIP = if ($message -match 'Source Network Address:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$logonType = if ($message -match 'Logon Type:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$logonID = if ($message -match 'New Logon:[\s\S]*?Logon ID:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$workstation = if ($message -match 'Workstation Name:\s+([^\r\n]+)') { $matches[1].Trim() } else { 'N/A' }
$logonTypeDesc = switch ($logonType) {
'2' { 'Interactive (Local)' }
'3' { 'Network' }
'4' { 'Batch' }
'5' { 'Service/Console' }
'7' { 'Unlock/Reconnect' }
'8' { 'NetworkCleartext' }
'9' { 'NewCredentials' }
'10' { 'RemoteInteractive (RDP)' }
'11' { 'CachedInteractive' }
default { "Unknown ($logonType)" }
}
$eventType = if ($event.Id -eq 4624) { 'Successful Logon' } else { 'Failed Logon' }
[PSCustomObject]@{
TimeCreated = $event.TimeCreated
EventID = $event.Id
EventType = $eventType
User = $userName
Domain = $userDomain
SourceIP = $sourceIP
SessionID = $null
LogonID = $logonID
ActivityID = $activityID
Details = "$logonTypeDesc | Workstation: $workstation"
}
}
}
}
Write-Host " $(Get-Emoji 'check') Found " -ForegroundColor Green -NoNewline
Write-Host "$($results.Count)" -ForegroundColor White -NoNewline
Write-Host " authentication events" -ForegroundColor Green
return $results
}
else {
Write-Host " $(Get-Emoji 'cross') No authentication events found" -ForegroundColor DarkGray
return @()
}
}
catch {
Write-Warning "Error collecting authentication events: $_"
return @()
}
}
# Function to parse Session Logon/Logoff Events
function Get-RDPSessionEvents {
param([DateTime]$Start, [DateTime]$End)
Write-Host "$(Get-Emoji 'computer') [3/6] Collecting RDP Session Events (EventID 21-25, 39, 40)..." -ForegroundColor Yellow
try {
$events = Get-WinEvent -FilterHashtable @{
LogName = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
Id = 21, 22, 23, 24, 25, 39, 40
StartTime = $Start
EndTime = $End
} -ErrorAction SilentlyContinue
if ($events) {
[xml[]]$xml = $events | ForEach-Object { $_.ToXml() }
$results = foreach ($event in $xml.Event) {
$eventID = $event.System.EventID
$timeCreated = [DateTime]::Parse($event.System.TimeCreated.SystemTime)
# Extract ActivityID from Correlation element
$activityID = if ($event.System.Correlation.ActivityID) {
$event.System.Correlation.ActivityID
}
else {
$null
}
# Parse UserData
$user = if ($event.UserData.EventXML.User) { $event.UserData.EventXML.User } else { 'N/A' }
$sessionID = if ($event.UserData.EventXML.SessionID) { $event.UserData.EventXML.SessionID } else { 'N/A' }
$address = if ($event.UserData.EventXML.Address) { $event.UserData.EventXML.Address } else { 'N/A' }
$eventType = switch ($eventID) {
21 { 'Session Logon Succeeded' }
22 { 'Shell Start Notification' }
23 { 'Session Logoff Succeeded' }
24 { 'Session Disconnected' }
25 { 'Session Reconnected' }
39 { 'Session Disconnected by Another Session' }
40 { 'Session Disconnected (With Reason Code)' }
default { "Event $eventID" }
}
$details = if ($eventID -eq 40) {
$reasonCode = $event.UserData.EventXML.Reason
$reasonText = switch ($reasonCode) {
0 { 'No additional information' }
5 { 'Client connection replaced by another' }
11 { 'User activity initiated disconnect' }
default { "Reason code: $reasonCode" }
}
$reasonText
}
elseif ($eventID -eq 39) {
$sessionA = $event.UserData.EventXML.SessionID
$sessionB = $event.UserData.EventXML.Param2
"Session $sessionA disconnected by session $sessionB"
}
else {
"Session ID: $sessionID"
}
[PSCustomObject]@{
TimeCreated = $timeCreated
EventID = [int]$eventID
EventType = $eventType
User = $user
Domain = 'N/A'
SourceIP = $address
SessionID = $sessionID
LogonID = $null
ActivityID = $activityID
Details = $details
}
}
Write-Host " $(Get-Emoji 'check') Found " -ForegroundColor Green -NoNewline
Write-Host "$($results.Count)" -ForegroundColor White -NoNewline
Write-Host " session events" -ForegroundColor Green
return $results
}
else {
Write-Host " $(Get-Emoji 'cross') No session events found" -ForegroundColor DarkGray
return @()
}
}
catch {
Write-Warning "Error collecting session events: $_"
return @()
}
}
# Function to parse Session Lock/Unlock Events
function Get-RDPLockUnlockEvents {
param([DateTime]$Start, [DateTime]$End)
Write-Host "$(Get-Emoji 'lock') [4/7] Collecting Session Lock/Unlock Events (EventID 4800, 4801)..." -ForegroundColor Yellow
try {
$events = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
Id = 4800, 4801
StartTime = $Start
EndTime = $End
} -ErrorAction SilentlyContinue
if ($events) {
$results = foreach ($event in $events) {
$message = $event.Message
# Extract ActivityID from XML
[xml]$eventXml = $event.ToXml()
$activityID = if ($eventXml.Event.System.Correlation.ActivityID) {
$eventXml.Event.System.Correlation.ActivityID
}
else {
$null