forked from mattifestation/PowerShellArsenal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloadlib.ps1
287 lines (211 loc) · 9.32 KB
/
loadlib.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
function Invoke-LoadLibrary {
<#
.SYNOPSIS
Loads a DLL into the current PowerShell process.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Invoke-LoadLibrary is a simple wrapper for kernel32!LoadLibrary
designed primarily for malware analysis the output of which can be
consumed by New-DllExportFunction.
.PARAMETER FileName
Specifies the name of the module to load. If the string specifies a
relative path or a module name without a path, the function uses a
standard search strategy to find the module. See the MSDN
documentation on LoadLibrary for more information on DLL search
paths.
.EXAMPLE
Invoke-LoadLibrary -FileName C:\temp\evil.dll
.EXAMPLE
'kernel32', 'ntdll' | Invoke-LoadLibrary
.INPUTS
System.String
Invoke-LoadLibrary accepts one or more module names to load over the
pipeline.
.OUTPUTS
System.Diagnostics.ProcessModule
#>
[OutputType([Diagnostics.ProcessModule])]
[CmdletBinding()]
Param (
[Parameter(Position = 0, Mandatory = $True, ValueFromPipeline = $True)]
[ValidateNotNullOrEmpty()]
[String]
$FileName
)
BEGIN {
$SafeNativeMethods = $null
$LoadLibrary = $null
# System.Uri and Microsoft.Win32.SafeNativeMethods are both
# contained within System.dll. [Uri] is public though.
# Microsoft.Win32.SafeNativeMethods is a NonPublic class.
$UnmanagedClass = 'Microsoft.Win32.SafeNativeMethods'
$SafeNativeMethods = [Uri].Assembly.GetType($UnmanagedClass)
# Perform additional error handling since we're borrowing LoadLibrary
# from a NonPublic class. Technically, Microsoft could change this
# interface at any time.
if ($SafeNativeMethods -eq $null) {
throw 'Unable to get a reference to the ' +
'Microsoft.Win32.SafeNativeMethods within System.dll.'
}
$LoadLibrary = $SafeNativeMethods.GetMethod('LoadLibrary')
if ($LoadLibrary -eq $null) {
throw 'Unable to get a reference to LoadLibrary within' +
'Microsoft.Win32.SafeNativeMethods.'
}
}
PROCESS {
$LoadedModuleInfo = $null
$LibAddress = $LoadLibrary.Invoke($null, @($FileName))
$Exception = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($LibAddress -eq [IntPtr]::Zero) {
$Exception = New-Object ComponentModel.Win32Exception($Exception)
throw $Exception.Message
}
$IntPtrPrintWidth = "X$([IntPtr]::Size * 2)"
Write-Verbose "$FileName loaded at 0x$(($LibAddress).ToString($IntPtrPrintWidth))"
$CurrentProcess = Get-Process -Id $PID
$LoadedModuleInfo = $CurrentProcess.Modules |
Where-Object { $_.BaseAddress -eq $LibAddress }
if ($LoadedModuleInfo -eq $null) {
throw 'Unable to obtain loaded module information for ' +
"$FileName. The module was likely already unloaded."
}
return $LoadedModuleInfo
}
}
function New-DllExportFunction {
<#
.SYNOPSIS
Creates an executable wrapper delegate around an unmanaged, exported
function.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: Invoke-LoadLibrary
.DESCRIPTION
New-DllExportFunction accepts a module, exported procedure name, a
return type, and parameter types, and creates a managed delegate that
can be used to execute the unmanaged function.
.PARAMETER Module
Specifies the module that contains the desired exported procedure.
The Module parameter accepts a System.Diagnostics.ProcessModule
object which can be obtained by calling Get-Process and filtering out
the 'Modules' property or by calling Invoke-LoadLibrary.
.PARAMETER ProcedureName
Specifies the exported procedure name. Note, for functions that
accept wide or ascii strings, you must specify which variant you want
to call - e.g. CreateFileA vs. CreateFileW.
.PARAMETER Parameters
Specifies the managed parameter types of the function. pinvoke.net is
a good reference for mapping managed to unmanaged types. This
argument may be left empty if the function doesn't accept any
arguments.
.PARAMETER ReturnType
Specifies the managed return type of the function. pinvoke.net is
a good reference for mapping managed to unmanaged types. This
argument may be left empty if the function doesn't has a void return
type.
.EXAMPLE
C:\PS>$Kernel32 = Invoke-LoadLibrary -FileName kernel32
C:\PS>$MulDiv = New-DllExportFunction -Module $Kernel32 -ProcedureName MulDiv -Parameters ([Int], [Int], [Int]) -ReturnType ([Int])
C:\PS>$MulDiv.Invoke(2, 3, 1)
.EXAMPLE
C:\PS>$Kernel32 = Invoke-LoadLibrary -FileName kernel32
C:\PS>$IsWow64Process = New-DllExportFunction -Module $Kernel32 -ProcedureName IsWow64Process -Parameters ([IntPtr], [Bool].MakeByRefType()) -ReturnType ([Bool])
C:\PS>$bIsWow64Process = $False
C:\PS>$IsWow64Process.Invoke((Get-Process -Id $PID).Handle, [Ref] $bIsWow64Process)
.EXAMPLE
C:\PS>$Ntdll = Get-Process -Id $PID | Select-Object -ExpandProperty Modules | Where-Object { $_.ModuleName -eq 'ntdll.dll' }
C:\PS>$RtlGetCurrentPeb = New-DllExportFunction -Module $Ntdll -ProcedureName RtlGetCurrentPeb -ReturnType ([IntPtr])
C:\PS>$RtlGetCurrentPeb.Invoke()
.OUTPUTS
System.Delegate
#>
[OutputType([Delegate])]
Param (
[Parameter(Mandatory = $True)]
[Diagnostics.ProcessModule]
[ValidateNotNull()]
$Module,
[Parameter(Mandatory = $True)]
[String]
[ValidateNotNullOrEmpty()]
$ProcedureName,
[Type[]]
$Parameters = (New-Object Type[](0)),
[Type]
$ReturnType = [Void]
)
function Local:Get-DelegateType
{
[OutputType([Type])]
Param (
[Parameter( Position = 0)]
[Type[]]
$Parameters = (New-Object Type[](0)),
[Parameter( Position = 1 )]
[Type]
$ReturnType = [Void]
)
$Domain = [AppDomain]::CurrentDomain
$DynAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate')
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $False)
$TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
$ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters)
$ConstructorBuilder.SetImplementationFlags('Runtime, Managed')
$MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters)
$MethodBuilder.SetImplementationFlags('Runtime, Managed')
return $TypeBuilder.CreateType()
}
function Local:Get-ProcAddress
{
[OutputType([IntPtr])]
Param (
[Parameter( Position = 0, Mandatory = $True )]
[Diagnostics.ProcessModule]
$Module,
[Parameter( Position = 1, Mandatory = $True )]
[String]
$ProcedureName
)
$UnsafeNativeMethods = $null
$GetProcAddress = $null
# System.Uri and Microsoft.Win32.UnsafeNativeMethods are both
# contained within System.dll. [Uri] is public though.
# Microsoft.Win32.UnsafeNativeMethods is a NonPublic class.
$UnmanagedClass = 'Microsoft.Win32.UnsafeNativeMethods'
$UnsafeNativeMethods = [Uri].Assembly.GetType($UnmanagedClass)
# Perform additional error handling since we're borrowing GetProcAddress
# from a NonPublic class. Technically, Microsoft could change this
# interface at any time.
if ($UnsafeNativeMethods -eq $null) {
throw 'Unable to get a reference to the ' +
'Microsoft.Win32.UnsafeNativeMethods within System.dll.'
}
$GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress')
if ($GetProcAddress -eq $null) {
throw 'Unable to get a reference to GetProcAddress within' +
'Microsoft.Win32.UnsafeNativeMethods.'
}
$TempPtr = New-Object IntPtr
$HandleRef = New-Object System.Runtime.InteropServices.HandleRef($TempPtr, $Module.BaseAddress)
$ProcAddr = $GetProcAddress.Invoke($null, @([Runtime.InteropServices.HandleRef] $HandleRef, $ProcedureName))
if ($ProcAddr -eq [IntPtr]::Zero) {
Write-Error "Unable to obtain the address of $($Module.ModuleName)!$ProcedureName. $ProcedureName is likely not exported."
return [IntPtr]::Zero
}
return $ProcAddr
}
$ProcAddress = Get-ProcAddress -Module $Module -ProcedureName $ProcedureName
if ($ProcAddress -ne [IntPtr]::Zero) {
$IntPtrPrintWidth = "X$([IntPtr]::Size * 2)"
Write-Verbose "$($Module.ModuleName)!$ProcedureName address: 0x$(($ProcAddress).ToString($IntPtrPrintWidth))"
$DelegateType = Get-DelegateType -Parameters $Parameters -ReturnType $ReturnType
$ProcedureDelegate = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($ProcAddress, $DelegateType)
return $ProcedureDelegate
}
}