PowerShell Reflection
Reflection in PowerShell enabled three main techniques
Type introspection: used if we want to determine all .NET assemblies that reference
System.Management.Automation.dll
, determine what classes and methods exist in an assembly or during .NET malware analysisOverwriting member visibility: useful to borrow .NET code that isn't publicly accessible and editing internal properties or fields - with access to the reflection API, we have access to any field / property / method within a given class in PowerShell
Dynamic code invocation & generation (metaprogramming): used in .NET assembly in-memory loading & execution, dynamic .NET malware analysis and .NET malware re-purposing
We can use reflection for the following:
type retrieval
# type retrieval standard method
[System.Diagnostics.ProcessStartInfo]
# type retrieval reflection method
# referencing a known public class from the same assembly
# the full class name must be specified
[System.Diagnostics.Process].Assembly.GetType('System.Diagnostics .ProcessStartInfo')
object instantiation
# standard method
$ProcStartInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo -ArgumentList 'cmd.exe'
# reflection method #1
$ProcStartInfo = [Activator]::CreateInstance([System.Diagnostics.ProcessStartInfo], [Object[]] @('cmd.exe'))
# reflection method #2
$ProcessStartInfoStringConstructor = [System.Diagnostics.ProcessStartInfo].GetConstructor([Type[]] @([String]))
$ProcStartInfo = $ProcessStartInfoStringConstructor.Invoke([Object[]] @('cmd.exe'))
method invocation
# converting an Int32 to a hex string using the standard method
(1094795585).ToString('X8')
# reflection method
$IntToConvert = 1094795585
$ToStringMethod = [Int32].GetMethod('ToString', [Reflection.BindingFlags] 'Public, Instance', $null, [Type[]] @([String]), $null) $ToStringMethod.Invoke($IntToConvert, [Object[]] @('X8'))
Find out how to use if offensively with PowerShell reflection offensive use-case.
Last updated