-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathGet-InjectedThreadEx.ps1
3153 lines (2520 loc) · 114 KB
/
Get-InjectedThreadEx.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
function Get-InjectedThreadEx
{
<#
.SYNOPSIS
Looks for threads that were created as a result of code injection.
.DESCRIPTION
Memory resident malware (fileless malware) often uses a form of memory injection to get code execution. Get-InjectedThread looks at each running thread to determine if it is the result of memory injection.
Common memory injection techniques that *can* be caught using this method include:
- Classic Injection (OpenProcess, VirtualAllocEx, WriteProcessMemory, CreateRemoteThread)
- Reflective DLL Injection
- Memory Module
NOTE: Nothing in security is a silver bullet. An attacker could modify their tactics to avoid detection using this methodology.
KNOWN LIMITATIONS:
- PowerShell 2 is not supported - no bitwise arithemtic shift operators.
- 32-bit Windows support not implemented.
- Limited WoW64 support.
- Slow - uses a single thread.
.PARAMETER Aggressive
Enables additional scans that have higher false positive rates.
.PARAMETER ProcessId
Only scans the specified pid.
.PARAMETER Brief
Limits output to process name, pid, tid, Win32StartAddress module and detections only.
.NOTES
Authors - Jared Atkinson (@jaredcatkinson)
- Joe Desimone (@dez_)
- John Uhlmann (@jdu2600)
.EXAMPLE
PS > Get-InjectedThreadEx
ProcessName : ThreadStart.exe
ProcessId : 7784
Wow64 : False
Path : C:\Users\tester\Desktop\ThreadStart.exe
KernelPath : C:\Users\tester\Desktop\ThreadStart.exe
CommandLine : "C:\Users\tester\Desktop\ThreadStart.exe"
PathMismatch : False
ProcessIntegrity : MEDIUM_MANDATORY_LEVEL
ProcessPrivilege : SeChangeNotifyPrivilege
ProcessLogonId : 999
ProcessSecurityIdentifier : S-1-5-21-386661145-2656271985-3844047388-1001
ProcessUserName : DESKTOP-HMTGQ0R\SYSTEM
ProcessLogonSessionStartTime : 3/15/2017 5:45:38 PM
ProcessLogonType : System
ProcessAuthenticationPackage : NTLM
ThreadId : 14512
BasePriority : 8
IsUniqueThreadToken : False
ThreadIntegrity :
ThreadPrivilege :
AdditionalThreadPrivilege :
ThreadLogonId :
ThreadSecurityIdentifier :
ThreadUserName : \
ThreadLogonSessionStartTime :
ThreadLogonType :
ThreadAuthenticationPackage :
AllocatedMemoryProtection : PAGE_EXECUTE_READWRITE
MemoryProtection : PAGE_EXECUTE_READWRITE
MemoryState : MEM_COMMIT
MemoryType : MEM_PRIVATE
Win32StartAddress : 430000
Win32StartAddressModule :
Win32StartAddressModuleSigned : False
Win32StartAddressPrivate : True
Size : 4096
TailBytes : 90909090909090909090909090909090
StartBytes : 558bec5356578b7d086a008b5f1083671000ff15c4c9595a8bf085f6780f8bcfe82f85f5ff8bf0ff15c8c9595a5653ff
Detections : {MEM_PRIVATE}
#>
[CmdletBinding()]
param
(
[Parameter()]
[Switch]$Aggressive,
[Parameter()]
[Switch]$Brief,
[Parameter()]
[UInt32]$ProcessId
)
if(![Environment]::Is64BitProcess)
{
Write-Warning "32-bit not currently supported."
}
$WindowsVersion = [Int]((Get-WmiObject Win32_OperatingSystem).version -split '\.')[0]
# Cache for signature checks
$AuthenticodeSignatures = @{}
$CfgBitMapAddress = GetCfgBitMapAddress
# Construct a list of ntdll thread entry points
$NtdllRegex = '^[A-Z]:\\Windows\\Sys(tem32|WOW64)\\ntdll\.dll$'
$NtdllThreads64 = @()
# [1] ntdll!RtlpQueryProcessDebugInformationRemote is exported - look it up.
$NtdllThreads64 += GetProcAddress -ModuleName "ntdll.dll" -ProcName "RtlpQueryProcessDebugInformationRemote"
# [2] ntdll!DbgUiRemoteBreakin is exported - look it up.
$NtdllThreads64 += GetProcAddress -ModuleName "ntdll.dll" -ProcName "DbgUiRemoteBreakin"
# For the non-exported entry points, we check the Win32StartAddress of threads we trust.
# [3] ntdll!TppWorkerThread is already used by PowerShell :-)
# [4] ntdll!EtwpLogger is not exported, but is spawned in processes that use a Private ETW Logging Session
# https://docs.microsoft.com/en-us/windows/win32/etw/configuring-and-starting-a-private-logger-session
# Note - the PowerShell ETW CmdLets don't fully support private sessions.
# This means that we need to need start it asynchronously (-AsJob) or wait for a timeout.
# We also we can't stop it.
try
{
$EVENT_TRACE_PRIVATE_LOGGER_MODE = 0x800
$Random = [System.IO.Path]::GetRandomFileName()
$Job = New-EtwTraceSession -Name "GetInjectedThreadEx_$($Random)" -LogFileMode $EVENT_TRACE_PRIVATE_LOGGER_MODE -LocalFilePath "$($ENV:Temp)\GetInjectedThreadEx-$($Random).etl" -AsJob
Start-Sleep -Milliseconds 500
}
catch
{
Write-Warning "New-EtwTraceSession not found. Can't find ntdll!EtwpLogger."
}
# Loop over our process's threads to find the valid ntdll threat start adddresses
$hProcess = OpenProcess -ProcessId $PID -DesiredAccess PROCESS_ALL_ACCESS -InheritHandle $false
foreach ($Thread in (Get-Process -Id $PID).Threads)
{
$hThread = OpenThread -ThreadId $Thread.Id -DesiredAccess THREAD_ALL_ACCESS
$Win32StartAddress = NtQueryInformationThread_Win32StartAddress -ThreadHandle $hThread
$StartAddressModule = GetMappedFileName -ProcessHandle $hProcess -Address $Win32StartAddress
if($StartAddressModule -match $NtdllRegex -and $NtdllThreads64 -notcontains $Win32StartAddress)
{
$NtdllThreads64 += $Win32StartAddress
}
}
if($NtdllThreads64.Length -ne 4)
{
Write-Warning "Failed to enumerate all valid ntdll thread start addresses."
}
$LoadLibrary = @()
$LoadLibrary += GetProcAddress -ModuleName "kernel32.dll" -ProcName "LoadLibraryA"
$LoadLibrary += GetProcAddress -ModuleName "kernel32.dll" -ProcName "LoadLibraryW"
# Now enumerate all threads for all processes and check for injection characteristics
$Processes = if($ProcessId) { Get-Process -Id $ProcessId } else {Get-Process}
foreach($Process in $Processes)
{
if($Process.Id -eq 0 -or $Process.Id -eq 4)
{
continue # skip Idle and System
}
$hProcess = OpenProcess -ProcessId $Process.Id -DesiredAccess PROCESS_ALL_ACCESS -InheritHandle $false
if($hProcess -eq 0)
{
continue # skip process - Access is Denied
}
Write-Verbose -Message "Checking $($Process.Name) [$($Process.Id)] for injection"
# Collect per-process information
$IsWow64Process = IsWow64Process -ProcessHandle $hProcess
$WmiProcess = Get-WmiObject Win32_Process -Filter "ProcessId = '$($Process.Id)'"
$ProcessKernelPath = QueryFullProcessImageName -ProcessHandle $hProcess
if(-not $ProcessKernelPath)
{
continue # process has stopped
}
$PathMismatch = $Process.Path.ToLower() -ne $ProcessKernelPath.ToLower()
if(-not $AuthenticodeSignatures.ContainsKey($ProcessKernelPath))
{
$AuthenticodeSignatures[$ProcessKernelPath] = Get-AuthenticodeSignature -FilePath $ProcessKernelPath
}
$ProcessModuleSigned = $AuthenticodeSignatures[$ProcessKernelPath].Status -eq 'Valid'
$hProcessToken = OpenProcessToken -ProcessHandle $hProcess -DesiredAccess TOKEN_QUERY
if($hProcessToken -ne 0)
{
$ProcessSID = GetTokenInformation -TokenHandle $hProcessToken -TokenInformationClass 1
$ProcessPrivs = GetTokenInformation -TokenHandle $hProcessToken -TokenInformationClass 3
$ProcessLogonSession = GetTokenInformation -TokenHandle $hProcessToken -TokenInformationClass 17
$ProcessIntegrity = GetTokenInformation -TokenHandle $hProcessToken -TokenInformationClass 25
}
# Now loop over this process's threads
foreach ($thread in $Process.Threads)
{
$hThread = OpenThread -ThreadId $Thread.Id -DesiredAccess THREAD_ALL_ACCESS
if ($hThread -eq 0)
{
continue # skip thread - Access is Denied
}
# Win32StartAddress memory information
$Win32StartAddress = NtQueryInformationThread_Win32StartAddress -ThreadHandle $hThread
$MemoryBasicInfo = VirtualQueryEx -ProcessHandle $hProcess -BaseAddress $Win32StartAddress
$AllocatedMemoryProtection = $MemoryBasicInfo.AllocationProtect -as $MemProtection
$MemoryProtection = $MemoryBasicInfo.Protect -as $MemProtection
$MemoryState = $MemoryBasicInfo.State -as $MemState
$MemoryType = $MemoryBasicInfo.Type -as $MemType
# Win32StartAddress module information
$StartAddressModuleSigned = $false
if($MemoryType -eq $MemType::MEM_IMAGE)
{
$StartAddressModule = GetMappedFileName -ProcessHandle $hProcess -Address $Win32StartAddress
if(-not $AuthenticodeSignatures.ContainsKey($StartAddressModule))
{
$AuthenticodeSignatures[$StartAddressModule] = Get-AuthenticodeSignature -FilePath $StartAddressModule
}
$AuthenticodeSignature = $AuthenticodeSignatures[$StartAddressModule]
$StartAddressModuleSigned = $AuthenticodeSignature.Status -eq 'Valid'
Write-Verbose -Message " * Thread Id: [$($Thread.Id)] $($StartAddressModule) signed:$($StartAddressModuleSigned)"
}
else
{
Write-Verbose -Message " * Thread Id: [$($Thread.Id)] $($MemoryType)"
}
# check if thread has unique token
$IsUniqueThreadToken = $false
$ThreadSID = ""
$ThreadPrivs = ""
$ThreadLogonSession = ""
$ThreadIntegrity = ""
$NewPrivileges = ""
try
{
$hThreadToken = OpenThreadToken -ThreadHandle $hThread -DesiredAccess TOKEN_QUERY
if ($hThreadToken -ne 0)
{
$ThreadSID = GetTokenInformation -TokenHandle $hThreadToken -TokenInformationClass 1
$ThreadPrivs = GetTokenInformation -TokenHandle $hThreadToken -TokenInformationClass 3
$ThreadLogonSession = GetTokenInformation -TokenHandle $hThreadToken -TokenInformationClass 17
$ThreadIntegrity = GetTokenInformation -TokenHandle $hThreadToken -TokenInformationClass 25
$IsUniqueThreadToken = $true
}
}
catch {}
$Detections = @()
#################################################################################################
# Suspicious thread heuristics
#################################################################################################
# original
# - not MEM_IMAGE
# new
# - MEM_IMAGE and x64 and Win32StartAddress is unexpected prolog
# - MEM_IMAGE and Win32StartAddress is on a private (modified) page
# - MEM_IMAGE and dll and Win32StartAddress entry in CFG BitMap is on a private (modified) page
# - MEM_IMAGE and dll and Win32StartAddress is CFG violation or suppressed export
# - MEM_IMAGE and Win32StartAddress is in a suspicious module
# - MEM_IMAGE and x64 and Win32StartAddress wraps non-MEM_IMAGE start address
# - MEM_IMAGE and Win32StartAddress is preceded by unexpected byte (-Aggressive only)
# - MEM_IMAGE and x64 and Win32StartAddress is missing from call stack (-Aggressive only)
# - MEM_IMAGE and x64 and Win32StartAddress is not 16-byte aligned (-Aggressive only)
# - Thread is impersonating SYSTEM
# - Thread is sleeping (enrichment only)
#################################################################################################
if ($MemoryState -eq $MemState::MEM_COMMIT)
{
$StartBytesLength = [math]::Min([Int64]48, $MemoryBasicInfo.BaseAddress.ToUInt64() + $MemoryBasicInfo.RegionSize.ToUInt64() - $Win32StartAddress.ToInt64())
$Buffer = ReadProcessMemory -ProcessHandle $hProcess -BaseAddress $Win32StartAddress -Size $StartBytesLength
$StartBytes = New-Object -TypeName System.Text.StringBuilder
$StartBytes.Capacity = $StartBytesLength
ForEach ($Byte in $Buffer) { $StartBytes.AppendFormat("{0:x2}", $Byte) | Out-Null }
$StartBytes = $StartBytes.ToString()
$TailBytesLength = [math]::Min([Int64]16, $Win32StartAddress.ToInt64() - $MemoryBasicInfo.BaseAddress.ToUInt64())
$Buffer = ReadProcessMemory -ProcessHandle $hProcess -BaseAddress ($Win32StartAddress.ToInt64() - $TailBytesLength) -Size $TailBytesLength
$TailBytes = New-Object -TypeName System.Text.StringBuilder
$TailBytes.Capacity = $TailBytesLength
ForEach ($Byte in $Buffer) { $TailBytes.AppendFormat("{0:x2}", $Byte) | Out-Null }
$TailBytes = $TailBytes.ToString()
# All threads not starting in a MEM_IMAGE region are suspicious
if ($MemoryType -ne $MemType::MEM_IMAGE)
{
$Detections += $MemoryType
}
# Any x64 threads not starting with a valid Windows x64 prolog are suspicious
# In lieu of a dissassembler in PowerShell we approximate with a regex :-(
$x64PrologRegex = '^(' +
'(488d0[5d]........)?' + # lea rax,[rip+nnnn]
'(eb0.(90){3,14})?' + # hot patch space
'(488bc4|4c8bdc)?' + # stack pointer - rax|r11
'(4[8-9c]89(....|[3-7][4c]24..))*' + # save registers in shadow space
'((5|fff|4(0|1)5)[0-7])*' + # push registers
'(488bec|4889e5)?' + # stack pointer - rbp
'(488d6c24..)?' + # lea rbp,[rsp+n]
'(488dac24........)?' + # lea rbp,[rsp+nnnn]
'(488d68..)?' + # lea rbp,[rax+n]
'(488da8........)?' + # lea rbp,[rax+nnnn]
'(498d6b..)?' + # lea rbp,[r11+n]
'(498dab........)?' + # lea rbp,[r11+nnnn]
'(488(1|3)ec' + # sub rsp,n
'|b8........e8........482be0)' + # mov rax; call; sub rsp, rax
'|4885c90f8[4-5]........(e9........cc|b8........c3)' + # test rcx,rcx; j[n]e nnnn; [jmp nnnn | mov eax, ret]
'|(488d0[5d]........)?(488b..(..)?)*(48)?(e9|ff25)' + # (mov ... ) jmp
'|4d5a90000300000004000000ffff0000b8000000000000004000000000000000' + # PE Header -> CLR Assembly with AddressOfEntryPoint=0
')'
# TODO(jdu) - update with more variants? Or is the approach simply too unreliable?
if ((-not $IsWow64Process) -and
($StartBytes -notmatch $x64PrologRegex))
{
$Detections += 'prolog'
}
$x86PrologRegex = '^(' +
'(8bff)?(6690)?' + # 2-byte nop
'55(8bec|89e5)' + # stack pointer
'|(..)+8[13]ec' + # sub esp,nnnn
'|(6a..|(68|b8)........)*e8' + # call
'|e9|ff25' + # jmp
'|4d5a90000300000004000000ffff0000b8000000000000004000000000000000' + # CLR Assembly
')'
if ($IsWow64Process -and
($StartBytes -notmatch $x86PrologRegex))
{
$Detections += 'prolog'
}
# Has our MEM_IMAGE Win32StartAddress been (naively) hooked?
# https://blog.redbluepurple.io/offensive-research/bypassing-injection-detection#creating-the-thread
# Note - checking against bytes on disk after the fact won't help with false positives
# as the hook can easily be removed after thread start.
# Detection gap - the hook could easily be deeper, potentially even in a subsequent call. :-(
# Microsoft-Windows-Threat-Intelligence ETW events should detect this more robustly.
$PrivatePage = IsWorkingSetPage -ProcessHandle $hProcess -Address $Win32StartAddress
if (($MemoryType -eq $MemType::MEM_IMAGE) -and
$PrivatePage)
{
$Detections += 'hooked'
}
# Check for suspcious CFG BitMap states
if ((-not $IsWow64Process) -and # TODO(jdu) Wow64 support not implemented
([IntPtr]::Zero -ne $CfgBitMapAddress) -and
($MemoryType -eq $MemType::MEM_IMAGE))
{
$Detections += (CfgDetections -pCfgBitMap $CfgBitMapAddress -ProcessHandle $hProcess -Address $Win32StartAddress)
}
### Suspicious start modules
# unsigned module in signed process - e.g. dll sideloading
if (($WindowsVersion -ge 10) -and $ProcessModuleSigned -and -not $StartAddressModuleSigned)
{
$Detections += 'unsigned'
}
# There are no valid thread entry points (that I know of) in many Win32 modules.
$ModulesWithoutThreadEntries = @(
('^[A-Z]:\\Windows\\Sys(tem32|WOW64)\\kernel32\.dll$', 'kernel32'),
('^[A-Z]:\\Windows\\Sys(tem32|WOW64)\\kernelbase\.dll$', 'kernelbase'),
('^[A-Z]:\\Windows\\Sys(tem32|WOW64)\\user32\.dll$', 'user32'),
('^[A-Z]:\\Windows\\Sys(tem32|WOW64)\\advapi32\.dll$', 'advapi32')
# ... and many more
);
foreach ($Module in $ModulesWithoutThreadEntries)
{
if ($StartAddressModule -match $Module[0])
{
$Detections += $Module[1]
break
}
}
# kernel32!LoadLibrary
# And, even if there are, LoadLibrary is always a suspicious start address.
if ($LoadLibrary -contains $Win32StartAddress)
{
$Detections += 'LoadLibrary'
}
# ntdll.dll but not -
# * ntdll!TppWorkerThread
# * ntdll!EtwpLogger
# * ntdll!DbgUiRemoteBreakin
# * ntdll!RtlpQueryProcessDebugInformationRemote
# These are the only valid thread entry points in ntdll that I know of.
if ((-not $IsWow64Process) -and
($NtdllThreads64.Length -eq 4) -and
($StartAddressModule -match $NtdllRegex) -and
($NtdllThreads64 -notcontains $Win32StartAddress))
{
$Detections += 'ntdll'
}
# Is SYSTEM being impersonated?
if (($ProcessSID -ne "S-1-5-18") -and ($ThreadSID -eq "S-1-5-18"))
{
$Detections += 'SYSTEM impersonation'
}
# Check for suspicious call stacks
# https://www.trustedsec.com/blog/avoiding-get-injectedthread-for-internal-thread-creation/
$WrapperRegex = '^[A-Z]:\\Windows\\Sys(tem32|WOW64)\\((msvcr[t0-9]+|ucrtbase)d?|SHCore|Shlwapi)\.dll$'
if ((-not $IsWow64Process) -and # TODO(jdu) Wow64 support not implemented
($StartAddressModule -match $WrapperRegex) -or # Always perform if a known wrapper module.
($StartAddressModule -match $NtdllRegex) -or # Always perform if ntdll.
$Aggressive -or
($Detections.Length -ne 0))
{
$Detections += (CallStackDetections -ProcessHandle $hProcess -ThreadHandle $hThread -StartAddressModule $StartAddressModule -Aggressive $Aggressive)
}
# The byte preceding a function prolog is typically a return, or filler byte.
# False positives can occur if data was included in a code section. This was
# common in older compilers.
# In practice, this has a medium FP rate - so don't check by default.
$x64EpilogFillerRegex = '(00|90|c3|cc|(e8|e9|ff25)........|eb..|^)$'
if (($Aggressive -or ($Detections.Length -ne 0)) -and
($TailBytes -notmatch $x64EpilogFillerRegex))
{
$Detections += 'tail'
}
# Modern CPUs load instructions in 16-byte lines. So, for performance, compilers may want to
# ensure that the maximum number of useful bytes will be loaded. This is either 16 or the
# number of bytes modulo 16 until the end of the first call (or absolute jmp) instruction.
#
# Any start address not aligned as such is a potential MEM_IMAGE trampoline gadget such
# as 'jmp rcx'
# https://blog.xpnsec.com/undersanding-and-evading-get-injectedthread/
#
# In practice, this has a high FP rate - so don't check by default.
$EarlyCallRegex = '^(..)*?(e8|ff15)'
$ImmediateJumpRegex = '^(e9|(48)?ff25)'
if (($Aggressive -or ($Detections.Length -ne 0)) -and
(($Win32StartAddress.ToInt64() -band 0xF) -ne 0) -and
# If < Windows 10 then also allow 4-byte alignments
(($WindowsVersion -ge 10) -or (($Win32StartAddress.ToInt64() -band 3) -ne 0)))
{
if ($StartBytes -match $EarlyCallRegex)
{
# Calulate the distance to the end of the call modulo 16
# This calculation isn't perfect - we did a rough regex match, not an exact decompilation...
$BytesNeeded = (($matches[0].Length / 2) -band 0xF) + 4
$BytesLoaded = 16 - ($Win32StartAddress.ToInt64() -band 0xF)
if ($BytesLoaded -lt $BytesNeeded)
{
$Detections += 'alignment'
}
}
elseif ($StartBytes -notmatch $ImmediateJumpRegex)
{
$Detections += 'alignment'
}
}
# Definitely not a smoking gun on its own, but obfuscate-and-sleep approaches are becoming popular.
if (($Detections.Length -ne 0) -and
($null -ne $Thread.WaitReason) -and
($Thread.WaitReason.ToString() -eq 'ExecutionDelay'))
{
$Detections += "sleep"
}
if ($Detections.Length -ne 0)
{
$ThreadDetail = New-Object PSObject
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ProcessName -Value $WmiProcess.Name
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ProcessId -Value $WmiProcess.ProcessId
if (-not $Brief)
{
$ThreadDetail | Add-Member -MemberType Noteproperty -Name Wow64 -Value $IsWow64Process
$ThreadDetail | Add-Member -MemberType Noteproperty -Name Path -Value $WmiProcess.Path
$ThreadDetail | Add-Member -MemberType Noteproperty -Name KernelPath -Value $ProcessKernelPath
$ThreadDetail | Add-Member -MemberType Noteproperty -Name CommandLine -Value $WmiProcess.CommandLine
$ThreadDetail | Add-Member -MemberType Noteproperty -Name PathMismatch -Value $PathMismatch
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ProcessIntegrity -Value $ProcessIntegrity
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ProcessPrivilege -Value $ProcessPrivs
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ProcessLogonId -Value $ProcessLogonSession.LogonId
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ProcessSecurityIdentifier -Value $ProcessSID
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ProcessUserName -Value "$($ProcessLogonSession.Domain)\$($ProcessLogonSession.UserName)"
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ProcessLogonSessionStartTime -Value $ProcessLogonSession.StartTime
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ProcessLogonType -Value $ProcessLogonSession.LogonType
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ProcessAuthenticationPackage -Value $ProcessLogonSession.AuthenticationPackage
}
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ThreadId -Value $Thread.Id
if (-not $Brief)
{
$ThreadDetail | Add-Member -MemberType NoteProperty -Name ThreadStartTime -Value $Thread.StartTime
$ThreadDetail | Add-Member -MemberType Noteproperty -Name BasePriority -Value $Thread.BasePriority
$ThreadDetail | Add-Member -MemberType Noteproperty -Name WaitReason -Value $Thread.WaitReason
$ThreadDetail | Add-Member -MemberType Noteproperty -Name IsUniqueThreadToken -Value $IsUniqueThreadToken
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ThreadIntegrity -Value $ThreadIntegrity
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ThreadPrivilege -Value $ThreadPrivs
$ThreadDetail | Add-Member -MemberType Noteproperty -Name AdditionalThreadPrivilege -Value $NewPrivileges
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ThreadLogonId -Value $ThreadLogonSession.LogonId
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ThreadSecurityIdentifier -Value $ThreadSID
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ThreadUserName -Value "$($ThreadLogonSession.Domain)\$($ThreadLogonSession.UserName)"
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ThreadLogonSessionStartTime -Value $ThreadLogonSession.StartTime
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ThreadLogonType -Value $ThreadLogonSession.LogonType
$ThreadDetail | Add-Member -MemberType Noteproperty -Name ThreadAuthenticationPackage -Value $ThreadLogonSession.AuthenticationPackage
$ThreadDetail | Add-Member -MemberType Noteproperty -Name AllocatedMemoryProtection -Value $AllocatedMemoryProtection
$ThreadDetail | Add-Member -MemberType Noteproperty -Name MemoryProtection -Value $MemoryProtection
$ThreadDetail | Add-Member -MemberType Noteproperty -Name MemoryState -Value $MemoryState
$ThreadDetail | Add-Member -MemberType Noteproperty -Name MemoryType -Value $MemoryType
$ThreadDetail | Add-Member -MemberType Noteproperty -Name Win32StartAddress -Value $Win32StartAddress.ToString('x')
}
$ThreadDetail | Add-Member -MemberType Noteproperty -Name Win32StartAddressModule -Value $StartAddressModule
if (-not $Brief)
{
$ThreadDetail | Add-Member -MemberType Noteproperty -Name Win32StartAddressModuleSigned -Value $StartAddressModuleSigned
$ThreadDetail | Add-Member -MemberType Noteproperty -Name Win32StartAddressPrivate -Value $PrivatePage
$ThreadDetail | Add-Member -MemberType Noteproperty -Name Size -Value $MemoryBasicInfo.RegionSize
$ThreadDetail | Add-Member -MemberType Noteproperty -Name TailBytes -Value $TailBytes
$ThreadDetail | Add-Member -MemberType Noteproperty -Name StartBytes -Value $StartBytes
}
$ThreadDetail | Add-Member -MemberType Noteproperty -Name Detections -Value $Detections
Write-Output $ThreadDetail
}
}
CloseHandle($hThread)
}
CloseHandle($hProcess)
}
}
function GetCfgBitMapAddress
{
<#
.SYNOPSIS
Returns the address of ntdll!LdrSystemDllInitBlock.CfgBitMap, or Zero if CFG is not supported.
.DESCRIPTION
.NOTES
Author - John Uhlmann (@jdu2600)
.LINK
.EXAMPLE
#>
# Find non-exported ntdll!LdrSystemDllInitBlock.CfgBitMap
# 180033520 ntdll!LdrControlFlowGuardEnforced
# 180033520 48833d80be140000 CMP qword ptr[LdrSystemDllInitBlock.CfgBitMap], 0x0
$LdrControlFlowGuardEnforced = GetProcAddress -ModuleName "ntdll.dll" -ProcName "LdrControlFlowGuardEnforced"
if ($LdrControlFlowGuardEnforced -eq 0)
{
return [IntPtr]::Zero # CFG not supported on this platform
}
$Offset = [System.Runtime.InteropServices.Marshal]::ReadInt32($LdrControlFlowGuardEnforced.ToInt64() + 3)
$pCfgBitMap = $LdrControlFlowGuardEnforced.ToInt64() + 8 + $Offset
# Read the value of the CFG BitMap address in our CFG-Enabled PowerShell process
$CfgBitMap = [System.Runtime.InteropServices.Marshal]::ReadIntPtr($pCfgBitMap)
if ($CfgBitMap -eq [IntPtr]::Zero)
{
Write-Warning "CFG BitMap address not found at 0x$($CfgBitmap.ToString('x'))"
return [IntPtr]::Zero
}
# Validate the CFG BitMap address
$CurrentProcess = [IntPtr](-1)
$MemoryBasicInfo = VirtualQueryEx -ProcessHandle $CurrentProcess -BaseAddress $CfgBitMap
if ($MemoryBasicInfo.AllocationBase -ne [UIntPtr]([UInt64]$CfgBitMap.ToInt64()))
{
Write-Warning "CFG BitMap address not valid at 0x$($CfgBitmap.ToString('x'))"
return [IntPtr]::Zero
}
return [IntPtr]$pCfgBitmap
}
function CfgDetections
{
<#
.SYNOPSIS
Checks the CFG BitMap for anomalies related to the given Address.
.DESCRIPTION
.PARAMETER pCfgBitMap
The address of ntdll!LdrSystemDllInitBlock.CfgBitMap
.PARAMETER ProcessHandle
A read handle to the target process.
.PARAMETER Address
The address to check.
.NOTES
Author - John Uhlmann (@jdu2600)
.LINK
.EXAMPLE
#>
param
(
[Parameter(Mandatory = $true)]
[IntPtr]
$pCfgBitMap,
[Parameter(Mandatory = $true)]
[IntPtr]
$ProcessHandle,
[Parameter(Mandatory = $true)]
[IntPtr]
$Address
)
$Detections = @()
# Read the location of the CFG BitMap address in our process
$Buffer = ReadProcessMemory -ProcessHandle $ProcessHandle -BaseAddress $pCfgBitmap -Size $([IntPtr]::Size)
$CfgBitmap = if ([IntPtr]::Size -eq 8) {[System.BitConverter]::ToInt64($Buffer, 0)} else {[System.BitConverter]::ToInt32($Buffer, 0)}
if($CfgBitmap -eq 0)
{
return # CFG is not enabled
}
# Validate the CFG BitMap
$MemoryBasicInfo = VirtualQueryEx -ProcessHandle $ProcessHandle -BaseAddress $CfgBitmap
if($MemoryBasicInfo.AllocationBase -ne [UIntPtr]([UInt64]$CfgBitmap))
{
Write-Warning "CFG BitMap address not found at 0x$($CfgBitmap.ToString('x'))"
return
}
# TODO(jdu) - implement bitwise shift operations to support PowerShell 2.
# Perhaps https://github.com/vrimkus/PoSh2.0-BitShifting
# Find the CFG entry for target address
$CfgIndexShift = if ([IntPtr]::Size -eq 8) { 9 } else { 8 }
$pCfgEntry = $CfgBitmap + ($Address.ToInt64() -shr $CfgIndexShift) * [IntPtr]::Size
$MemoryBasicInfo = VirtualQueryEx -ProcessHandle $ProcessHandle -BaseAddress $pCfgEntry
if (($MemoryBasicInfo.State -ne $MemState::MEM_COMMIT) -or
($MemoryBasicInfo.Type -ne $MemType::MEM_MAPPED) -or
($MemoryBasicInfo.Protect -eq $MemProtect::PAGE_NOACCESS))
{
Write-Warning "Invalid CFG Entry for 0x$($Address.ToString('x'))"
return
}
if (IsWorkingSetPage -ProcessHandle $ProcessHandle -Address $pCfgEntry)
{
$AddressModule = GetMappedFileName -ProcessHandle $ProcessHandle -Address $Address
$ProcessExecutable = QueryFullProcessImageName -ProcessHandle $hProcess
# executable CFG bitmaps are not shared - only library (dll) ones.
# https://www.trendmicro.com/en_us/research/16/j/control-flow-guard-improvements-windows-10-anniversary-update.html
# The original Microsoft Edge modifies its CFG bitmap
if(($AddressModule -notmatch '\.exe$') -and
($ProcessExecutable -notmatch '^[A-Z]:\\Windows\\.*\\MicrosoftEdge(CP|SH)?\.exe$'))
{
$Detections += "cfg_modified"
}
}
$Buffer = ReadProcessMemory -ProcessHandle $ProcessHandle -BaseAddress $pCfgEntry -Size $([IntPtr]::Size)
$CfgEntry = if ([IntPtr]::Size -eq 8) { [System.BitConverter]::ToInt64($Buffer, 0) } else { [System.BitConverter]::ToInt32($Buffer, 0) }
# Check the relevant bits for address in this entry
$CfgOffsetMask = (([IntPtr]::Size -shl 3) - 2)
$BitPairOffset = ($Address.ToInt64() -shr 3) -band $CfgOffsetMask
$BitPair = ($CfgEntry -shr $BitPairOffset) -band 3
# 00 - no address in this range is a valid target
# 01 - the only valid target is 16-byte aligned
# 10 - this range contains an export-suppressed target
# 11 - all addresses in this range are valid.
# export suppressed CFG addresses are suspicious thread start addresses
if ($BitPair -eq 2)
{
$Detections += 'cfg_export_suppressed'
}
# Was CFG bypassed?
elseif (($Address.ToInt64() -band 0xF) -eq 0)
{
# 16-byte aligned check
if (($BitPair -band 1) -eq 0)
{
$Detections += 'cfg'
}
}
elseif ($BitPair -ne 3)
{
$Detections += 'cfg'
}
Write-Output $Detections
}
function CallStackDetections
{
<#
.SYNOPSIS
Checks the bottom of the thread's stack for suspicious return addresses.
.DESCRIPTION
.PARAMETER ProcessHandle
.PARAMETER ThreadHandle
.PARAMETER StartAddressModule
.PARAMETER Aggressive
.NOTES
Author - John Uhlmann (@jdu2600)
.LINK
.EXAMPLE
#>
param
(
[Parameter(Mandatory = $true)]
[IntPtr]
$ProcessHandle,
[Parameter(Mandatory = $true)]
[IntPtr]
$ThreadHandle,
[Parameter(Mandatory = $true)]
[String]
$StartAddressModule,
[Parameter(Mandatory = $true)]
[Boolean]
$Aggressive
)
<#
(func ntdll NtQueryInformationThread ([UInt32]) @(
[IntPtr], #_In_ HANDLE ThreadHandle,
[Int32], #_In_ THREADINFOCLASS ThreadInformationClass,
[THREAD_BASIC_INFORMATION].MakeByRefType(), #_Inout_ PVOID ThreadInformation,
[Int32], #_In_ ULONG ThreadInformationLength,
[IntPtr] #_Out_opt_ PULONG ReturnLength
))
#>
$WrapperRegex = '^[A-Z]:\\Windows\\Sys(tem32|WOW64)\\((msvcr[t0-9]+|ucrtbase)d?|SHCore|Shlwapi)\.dll$'
# TODO(jdu) Handle 32-bit thread stacks...
# 1. Query the THREAD_BASIC_INFORMATION to determine the location of the Thread Environment Block (TEB)
$ThreadBasicInfo = [Activator]::CreateInstance($THREAD_BASIC_INFORMATION)
$NtStatus = $Ntdll::NtQueryInformationThread($ThreadHandle, 0, [Ref]$ThreadBasicInfo, $THREAD_BASIC_INFORMATION::GetSize(), [IntPtr]::Zero)
if ($NtStatus -ne 0)
{
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
throw "NtQueryInformationThread Error: $(([ComponentModel.Win32Exception] $LastError).Message)"
}
if($ThreadBasicInfo.TebBaseAddress -eq 0)
{
return
}
# 2. The TIB is the first elemenet of the TEB. Read the TIB to determine the stack limits.
$Buffer = ReadProcessMemory -ProcessHandle $ProcessHandle -BaseAddress $ThreadBasicInfo.TebBaseAddress -Size $TIB64::GetSize()
$TibPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TIB64::GetSize())
[System.Runtime.InteropServices.Marshal]::Copy($Buffer, 0, $TibPtr, $TIB64::GetSize())
$Tib = $TibPtr -as $TIB64
# 3. Read the (partial) stack contents
$StackReadLength = [math]::Min([Int64]0x1000, $Tib.StackBase.ToInt64() - $Tib.StackLimit.ToInt64())
$StackBuffer = ReadProcessMemory -ProcessHandle $ProcessHandle -BaseAddress ($Tib.StackBase.ToInt64() - $StackReadLength) -Size $StackReadLength
# 4. Search the stack bottom up for the (probable) initial return addresses of the first 5 frames.
# [expected] ntdll!RtlUserThreadStart -> kernel32!BaseThreadInitThunk -> Win32StartAddress
# Note - at this stack depth it is unlikely, but not impossible, that we encounter a false positive return address on the stack.
$RspBuffer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal([IntPtr]::Size)
$Detections = @()
$Unbacked = $false
$ReturnModules = @()
# Our return addresses are only probable as we're not stack walking. Collect up to 5 in case of false positives.
$MaxFrameCount = 5
# x64 stack frames are 16-byte aligned, and return addresses are 8-byte aligned.
for ($i = 8; ($ReturnModules.Count -lt $MaxFrameCount) -and ($i -lt $StackReadLength); $i += 16)
{
[System.Runtime.InteropServices.Marshal]::Copy($StackBuffer, ($StackReadLength - $i), $RspBuffer, [IntPtr]::Size)
$CandidateRsp = [System.Runtime.InteropServices.Marshal]::ReadInt64($RspBuffer)
if ($CandidateRsp -ne 0)
{
$MemoryBasicInfo = VirtualQueryEx -ProcessHandle $ProcessHandle -BaseAddress $CandidateRsp
if ($MemoryBasicInfo.State -eq $MemState::MEM_COMMIT -and
($MemoryBasicInfo.Protect -eq $MemProtection::PAGE_EXECUTE -or
$MemoryBasicInfo.Protect -eq $MemProtection::PAGE_EXECUTE_READ -or
$MemoryBasicInfo.Protect -eq $MemProtection::PAGE_EXECUTE_READWRITE -or
$MemoryBasicInfo.Protect -eq $MemProtection::PAGE_EXECUTE_WRITECOPY))
{
if ($MemoryBasicInfo.Type -eq $MemType::MEM_IMAGE)
{
$CandidateRspModule = GetMappedFileName -ProcessHandle $hProcess -Address $CandidateRsp
if($CandidateRspModule -eq $StartAddressModule)
{
# StartAddressModule found - stop searching (or after next frame)
$MaxFrameCount = if($Aggressive -or ($StartAddressModule -match $WrapperRegex)) {[math]::Min($MaxFrameCount, $ReturnModules.Count + 2)} else {$ReturnModules.Count}
}
elseif(IsWorkingSetPage -ProcessHandle $hProcess -Address $CandidateRsp)
{
$Detections += "hooked(" + [System.IO.Path]::GetFileNameWithoutExtension($CandidateRspModule) + ")"
}
}
else
{
$CandidateRspModule = $MemoryBasicInfo.Type -as $MemType
$Unbacked = $true
# Unbacked found - stop searching after next frame
$MaxFrameCount = [math]::Min($MaxFrameCount, $ReturnModules.Count + 2)
}
Write-Verbose -Message " * Stack [0x$($CandidateRsp.ToString('x'))] +0x$($i.ToString('x')): $($CandidateRspModule) "
if (($ReturnModules.Count -eq 0) -or ($ReturnModules[$ReturnModules.Count-1] -ne $CandidateRspModule))
{
$ReturnModules += $CandidateRspModule;
if (($ReturnModules.Count -le 2) -and ($CandidateRspModule -match "^[A-Z]:\\Windows\\System32\\(ntdll|kernel32)\.dll$"))
{
$i += 32 # skip parameter shadow space - this helps with FPs
}
}
}
}
}
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($TibPtr)
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($RspBuffer)
if($ReturnModules.Count -eq 0)
{
return
}
# 5. Validate the initial inferred call stack frames
$StackSummary = (($ReturnModules | ForEach-Object { [System.IO.Path]::GetFileNameWithoutExtension($_) }) -join ';').Replace("ntdll;kernel32;", "")
# Has the thread been hijacked before Win32StartAddress was called?
if ($Aggressive -and
# Our "call stack" is a rough approximation - and could cause false positives.
# Also, the Win32StartAddress function could be a Tail Call Optimized (TCO).
($ReturnModules -notcontains $StartAddressModule) -and
# .NET executables always intially jump to the CLR runtime startup shim mscoree!_CorExeMain.
($ReturnModules[2] -notmatch "^[A-Z]:\\Windows\\Sys(tem32|WOW64)\\mscoree\.dll$") -and
# WindowsApps executables sometimes just jump to a dll of the same name!
($ReturnModules[2] -notcontains $StartAddressModule.Replace(".exe", ".dll")) -and
# WoW64 thread
$StackSummary -notmatch "^ntdll;wow64;wow64cpu;")
{
$Detections += "hijacked($($StackSummary))"
}
# Is the stack base normal?
# Note - MSYS2 will false positive here.
elseif (($ReturnModules[0] -notmatch "^[A-Z]:\\Windows\\Sys(tem32|WOW64)\\ntdll\.dll$") -or
($ReturnModules[1] -and ($ReturnModules[1] -notmatch "^[A-Z]:\\Windows\\Sys(tem32|WOW64)\\(wow64|kernel32)\.dll$")))
{
$Detections += "hijacked($($StackSummary))"
}
# Has a private start address been called indirectly via a wrapper function?
elseif ($Unbacked -and ($ReturnModules -contains $StartAddressModule))
{
$Detections += "wrapper($($StackSummary))"
}
# Is there a private start address near the bottom of the stack?
elseif ($Unbacked)
{
$Detections += "early_unbacked($($StackSummary))"
}
Write-Output $Detections
}
function Get-LogonSession
{
<#
.NOTES
Author: Lee Christensen (@tifkin_)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
#>
param
(
[Parameter(Mandatory = $true)]
[UInt32]
$LogonId
)
$LogonMap = @{}
Get-WmiObject Win32_LoggedOnUser | %{
$Identity = $_.Antecedent | Select-String 'Domain="(.*)",Name="(.*)"'
$LogonSession = $_.Dependent | Select-String 'LogonId="(\d+)"'
$LogonMap[$LogonSession.Matches[0].Groups[1].Value] = New-Object PSObject -Property @{
Domain = $Identity.Matches[0].Groups[1].Value
UserName = $Identity.Matches[0].Groups[2].Value
}
}
Get-WmiObject Win32_LogonSession -Filter "LogonId = `"$($LogonId)`"" | %{
$LogonType = $Null
switch($_.LogonType) {
$null {$LogonType = 'None'}
0 { $LogonType = 'System' }
2 { $LogonType = 'Interactive' }
3 { $LogonType = 'Network' }
4 { $LogonType = 'Batch' }
5 { $LogonType = 'Service' }
6 { $LogonType = 'Proxy' }
7 { $LogonType = 'Unlock' }
8 { $LogonType = 'NetworkCleartext' }
9 { $LogonType = 'NewCredentials' }
10 { $LogonType = 'RemoteInteractive' }
11 { $LogonType = 'CachedInteractive' }
12 { $LogonType = 'CachedRemoteInteractive' }
13 { $LogonType = 'CachedUnlock' }
default { $LogonType = $_.LogonType}
}
New-Object PSObject -Property @{
UserName = $LogonMap[$_.LogonId].UserName
Domain = $LogonMap[$_.LogonId].Domain
LogonId = $_.LogonId
LogonType = $LogonType
AuthenticationPackage = $_.AuthenticationPackage
Caption = $_.Caption
Description = $_.Description
InstallDate = $_.InstallDate
Name = $_.Name
StartTime = $_.ConvertToDateTime($_.StartTime)
}
}
}
#region PSReflect
function New-InMemoryModule
{
<#
.SYNOPSIS
Creates an in-memory assembly and module
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
When defining custom enums, structs, and unmanaged functions, it is
necessary to associate to an assembly module. This helper function
creates an in-memory module that can be passed to the 'enum',
'struct', and Add-Win32Type functions.
.PARAMETER ModuleName
Specifies the desired name for the in-memory assembly and module. If
ModuleName is not provided, it will default to a GUID.