calling Win API from memory completely fileless
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://exploitmonday.blogspot.com/2012/05/accessing-native-windows-api-in.html | |
function getDelegateType { | |
Param ( | |
[Parameter(Position = 0, Mandatory = $True)] [Type[]] $func, | |
[Parameter(Position = 1)] [Type] $functionDelegateTypeType = [Void] | |
) | |
$type = [AppDomain]::CurrentDomain. | |
DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('ReflectedDelegate')), | |
[System.Reflection.Emit.AssemblyBuilderAccess]::Run). | |
DefineDynamicModule('InMemoryModule', $false). | |
DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', | |
[System.MulticastDelegate]) | |
$type.DefineConstructor('RTSpecialName, HideBySig, Public', | |
[System.Reflection.CallingConventions]::Standard, $func). | |
SetImplementationFlags('Runtime, Managed') | |
$type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $functionDelegateTypeType, $func). | |
SetImplementationFlags('Runtime, Managed') | |
return $type.CreateType() | |
} | |
function Get-ProcAddress { | |
Param ( | |
[Parameter(Position = 0, Mandatory = $True)] [String] $Module, | |
[Parameter(Position = 1, Mandatory = $True)] [String] $Procedure | |
) | |
# Get a reference to System.dll in the GAC | |
$SystemAssembly = ([AppDomain]::CurrentDomain.GetAssemblies() | | |
Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }) | |
$UnsafeNativeMethods = $SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods') | |
# Get a reference to the GetModuleHandle and GetProcAddress methods | |
$GetModuleHandle = $UnsafeNativeMethods.GetMethod('GetModuleHandle') | |
$UnsafeNativeMethods.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$GetProcAddress=$_}} | |
# Get a handle to the module specified | |
$Kern32Handle = $GetModuleHandle.Invoke($null, @($Module)) | |
$tmpPtr = New-Object IntPtr | |
$HandleRef = New-Object System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle) | |
# Return the address of the function | |
return $GetProcAddress.Invoke($null, @([System.Runtime.InteropServices.HandleRef]$HandleRef, $Procedure)) | |
} | |
$functionDelegateType = getDelegateType @([IntPtr], [String], [String], [int]) ([int]) #change types as per API function paramters | |
$msgBoxAddr = Get-ProcAddress user32.dll MessageBoxA | |
$MyFunction = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($msgBoxAddr, $functionDelegateType) | |
$MyFunction.Invoke([IntPtr]::Zero,"1337","twitter: @xxByte",0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment