Win32 API Execution

Powershell

Add-Type

Add-Type calls the csc compiler, which writes to disk.
1
$User32 = @"
2
using System;
3
using System.Runtime.InteropServices;
4
public class User32 {
5
[DllImport("user32.dll", CharSet=CharSet.Auto)]
6
public static extern int MessageBox(IntPtr hWnd, String text, String caption, int
7
options);
8
}
9
"@
10
Add-Type $User32
11
[User32]::MessageBox(0, "This is an alert", "MyBox", 0)
Copied!

Dynamic Invocation - UnsafeNativeMethods

This snippet's purpose is to demonstrate the concept of Dynamic Invocation,
For actual operational usage I recommend using this amazing project by TheWover
1
function LookupFunc {
2
Param ($moduleName, $functionName)
3
$assem = ([AppDomain]::CurrentDomain.GetAssemblies() |
4
Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].
5
Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods')
7
$assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
8
return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null,
9
@($moduleName)), $functionName))
10
}
11
12
function getDelegateType {
13
Param (
14
[Parameter(Position = 0, Mandatory = $True)] [Type[]] $func,
15
[Parameter(Position = 1)] [Type] $delType = [Void]
16
)
17
18
$type = [AppDomain]::CurrentDomain.
19
DefineDynamicAssembly((New-Object
20
System.Reflection.AssemblyName('ReflectedDelegate')),
21
[System.Reflection.Emit.AssemblyBuilderAccess]::Run).
22
DefineDynamicModule('InMemoryModule', $false).
23
DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass',
24
[System.MulticastDelegate])
25
26
$type.
27
DefineConstructor('RTSpecialName, HideBySig, Public',
28
[System.Reflection.CallingConventions]::Standard, $func).
29
SetImplementationFlags('Runtime, Managed')
30
31
$type.
32
DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $delType, $func).
33
SetImplementationFlags('Runtime, Managed')
34
35
return $type.CreateType()
36
}
37
38
$VirtualAllocAddr = LookupFunc kernel32.dll VirtualAlloc
39
$VirtualAllocDelegateType = getDelegateType @([IntPtr], [UInt32], [UInt32], [UInt32])
Copied!