Allows data to be copied from a managed array to an unmanaged memory pointer
WaitSingleObject
Artifacts
CSC: C# Command Line Compiler
List loaded assemblies
Add-Type
[appdomain]::currentdomain.getassemblies()
In this case, could be flagged by antivirus
Dynamic Lookup
Add-Type
System.dll
Microsoft.Win32.UnsafeNativeMethods class
GetModuleHandle
GetProcAddress
Create the .NET assembly in memory instead of writing code to disk and compiling it. These methods are only meant to be used internally by the .NET code. Therefore it's impossible to call them directly from Powershell or C#. - Check UnsafeNativeMethods branch -
Create New Assemblies
GetAssemblies
ForEach-Object
GetTypes
Get-Member
Static Flag
Where-Object
Unsafe Keyword in TypeName
Search for preloaded assemblies that could match our criteria
UnsafeNativeMethods
Assembly filtering
GlobalAssemblyCache
Location
List of all native and registered assemblies on Windows: this is what we want
GetMethod function to obtain a reference to the internal GetModuleHandle method
Use the internal Invoke method to call GetModuleHandle and obtain the base address of an unmanaged DLL
.NET Reflection
GetMethods vs GetMethod
GetProcAddress
Locate GetProcAddress to resolve arbitrary APIs
Delegate Type Reflection
(C#) delegate
Creation using Reflection
Create New Assembly
AssemblyName Class
Access mode
DefineDynamicAssembly
System.Reflection.Emit.AssemblyBuilderAccess namespace - Value set to RUN
Access mode configuration: no disk access and executable
Creating Content
DefineDynamicModule
DefineType
Custom Name
Attributes
Class
Public
Sealed
AnsiClass
AutoClass
Check MS Doc
MulticastDelegate class
Inside an assembly the main building bloc is a Module
DefineType takes 3 args
Construct our Custom Delegate Type
DefineConstructor
MethodAttributes Enum
[System.Reflection.CallingConventions]::Standard
Types of the Constructor
Constructor Call
SetImplementationFlags
Runtime
Managed
Invoke
DefineMethod
Method Name
Method Attributes
Return Type
Array of Arg Types
Takes 4 args
MethodImplAttributes Enum
Delegate Type Instantiation
CreateType
2004 Blog post
Generate Shellcode
ps1 format
32bit architecture (cf. MS Office arch)
Use of msfvenom (shortcut)
Copy it with .NET Copy method
Use System Proxy (optional)
Natively not accessible in Powershell. Thank you .NET -> C#
Invoke functions in unmanaged
dynamic link libraries
Once translation done: use of the .NET framework to compile and create objects containing the structures, values, functions, or code inside the Add-Type statement
Avoid Powershell termination before Shell fully executed.
Be aware, closing MSOffice will kill the Shellcode - Check advanced attack with Powershell
Client Side Code Execution With Windows Script Host