Advertisement
Guest User

Untitled

a guest
Dec 28th, 2018
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.99 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8.  
  9. namespace NachoEngine.ScanMethods
  10. {
  11. public enum ProcessorArchitecture
  12. {
  13. X86 = 0,
  14. X64 = 9,
  15. Arm = -1,
  16. Itanium = 6,
  17. Unknown = 0xFFFF
  18. }
  19.  
  20. [StructLayout(LayoutKind.Sequential)]
  21. public struct SystemInfo
  22. {
  23. public ProcessorArchitecture ProcessorArchitecture;
  24. public uint PageSize;
  25. public IntPtr MinimumApplicationAddress;
  26. public IntPtr MaximumApplicationAddress;
  27. public IntPtr ActiveProcessorMask;
  28. public uint NumberOfProcessors;
  29. public uint ProcessorType;
  30. public uint AllocationGranularity;
  31. public ushort ProcessorLevel;
  32. public ushort ProcessorRevision;
  33. }
  34.  
  35. [StructLayout(LayoutKind.Sequential)]
  36. public struct MEMORY_BASIC_INFORMATION
  37. {
  38. public IntPtr BaseAddress;
  39. public IntPtr AllocationBase;
  40. public uint AllocationProtect;
  41. public IntPtr RegionSize;
  42. public uint State;
  43. public uint Protect;
  44. public uint Type;
  45. }
  46.  
  47. public class SearchResult
  48. {
  49. public SearchResult(IntPtr add, byte[] value)
  50. {
  51. Address = add;
  52. Buffer = value;
  53. }
  54.  
  55. public IntPtr Address { get; set; }
  56.  
  57. public Byte[] Buffer { get; set; }
  58. }
  59.  
  60. public class MemorySearch
  61. {
  62. private IntPtr _handle;
  63. private int _processId;
  64. private uint _maxAddress;
  65.  
  66. private Dictionary<IntPtr, byte[]> _regions;
  67. private List<SearchResult> _results;
  68.  
  69. public event ProgressChanged ProgressChangedEvent;
  70. public delegate void ProgressChanged(int value);
  71.  
  72. [DllImport("NM_BPY.dll")]
  73. public static extern IntPtr _handleGet(IntPtr handle_h);
  74.  
  75. [DllImport("kernel32.dll")]
  76. public static extern void GetSystemInfo(out SystemInfo Info);
  77.  
  78. [DllImport("kernel32.dll")]
  79. public static extern IntPtr OpenProcess(uint access, bool inherit, int process);
  80.  
  81. [DllImport("kernel32.dll")]
  82. public static extern bool CloseHandle(IntPtr handle);
  83.  
  84. [DllImport("kernel32.dll")]
  85. public static extern int VirtualQueryEx(IntPtr handle, IntPtr baseAddress, out MEMORY_BASIC_INFORMATION lpBuffer, int length);
  86.  
  87. [DllImport("kernel32.dll", SetLastError = true)]
  88. public static extern bool ReadProcessMemory(IntPtr handle, IntPtr baseAddress, byte[] buffer, uint size, out int length);
  89.  
  90. [DllImport("kernel32.dll", SetLastError = true)]
  91. public static extern bool WriteProcessMemory(IntPtr handle, IntPtr baseAddress, byte[] buffer, int size, out int length);
  92.  
  93. public MemorySearch()
  94. {
  95. SystemInfo info;
  96. GetSystemInfo(out info);
  97.  
  98. _maxAddress = (uint)info.MaximumApplicationAddress;
  99. resetFields();
  100. }
  101.  
  102. private void resetFields()
  103. {
  104. _handle = IntPtr.Zero;
  105. _regions = new Dictionary<IntPtr, byte[]>();
  106. _results = new List<SearchResult>();
  107. }
  108.  
  109. public void setProgressEvent(ProgressChanged p)
  110. {
  111. ProgressChangedEvent = p;
  112. }
  113.  
  114. public void openProcess(int processId)
  115. {
  116. if (_handle != IntPtr.Zero)
  117. {
  118. closeProcess();
  119. resetFields();
  120. }
  121.  
  122. _processId = processId;
  123. _handle = OpenProcess(1080, false, processId);
  124.  
  125. if (_handle == IntPtr.Zero)
  126. throw new Exception("Failed to open process " + processId.ToString() + ". Error code: " + Marshal.GetLastWin32Error().ToString());
  127. }
  128.  
  129. public void closeProcess()
  130. {
  131. CloseHandle(_handle);
  132. }
  133.  
  134. private void dumpRegions()
  135. {
  136. if (_handle == IntPtr.Zero)
  137. throw new InvalidOperationException("Cannot dump process memory regions. No process loaded.");
  138.  
  139. _regions.Clear();
  140.  
  141. IntPtr current = IntPtr.Zero;
  142. MEMORY_BASIC_INFORMATION memInfo = new MEMORY_BASIC_INFORMATION();
  143.  
  144. while ((uint)current < _maxAddress && VirtualQueryEx(_handle, current, out memInfo, Marshal.SizeOf(memInfo)) != 0)
  145. {
  146. if (memInfo.State == 4096 && memInfo.Protect == 4 && (uint)memInfo.RegionSize != 0)
  147. {
  148. byte[] regionData = new byte[(int)memInfo.RegionSize];
  149. int bytesRead = 0;
  150.  
  151. if (!ReadProcessMemory(_handle, memInfo.BaseAddress, regionData, (uint)memInfo.RegionSize, out bytesRead))
  152. throw new Exception("Failed to read process memory at " + memInfo.BaseAddress.ToString() + ". Error code: " + Marshal.GetLastWin32Error().ToString());
  153.  
  154. _regions.Add(memInfo.BaseAddress, regionData);
  155. }
  156.  
  157. current = IntPtr.Add(memInfo.BaseAddress, memInfo.RegionSize.ToInt32());
  158. }
  159. }
  160.  
  161. private void updateProgress(int amount)
  162. {
  163. if (ProgressChangedEvent != null)
  164. ProgressChangedEvent(amount);
  165. }
  166.  
  167. public void firstScan(byte[] buffer, Action callback = null)
  168. {
  169. _handle = _handleGet(_handle);
  170. if (_handle == IntPtr.Zero)
  171. throw new InvalidOperationException("Cannot scan process memory regions. No process loaded.");
  172.  
  173. if (buffer.Length == 0)
  174. throw new ArgumentOutOfRangeException("Buffer cannot be of length 0.");
  175.  
  176. _results.Clear();
  177.  
  178. dumpRegions();
  179. updateProgress(0);
  180.  
  181. int count = 0;
  182.  
  183. foreach (IntPtr address in _regions.Keys)
  184. {
  185. foreach (int i in ByteSearch.allIndexOf(_regions[address], buffer))
  186. _results.Add(new SearchResult(IntPtr.Add(address, i), buffer));
  187.  
  188. count++;
  189. updateProgress((int)(count / _regions.Count * 100));
  190. }
  191.  
  192. updateProgress(100);
  193.  
  194. if (callback != null)
  195. callback();
  196. }
  197.  
  198. public void nextScan(byte[] buffer, Action callback = null)
  199. {
  200. if (_handle == IntPtr.Zero)
  201. throw new InvalidOperationException("Cannot scan process memory regions. No process loaded.");
  202.  
  203. if (buffer.Length == 0)
  204. throw new ArgumentOutOfRangeException("Buffer cannot be of length 0.");
  205.  
  206. dumpRegions();
  207. updateProgress(0);
  208.  
  209. int count = 0;
  210.  
  211. foreach (SearchResult sr in _results.ToArray())
  212. {
  213. if (_regions.ContainsKey(sr.Address))
  214. {
  215. if (!ByteSearch.matchAtOffset(_regions[sr.Address], buffer, 0))
  216. _results.Remove(sr);
  217. else
  218. sr.Buffer = buffer;
  219. }
  220. else
  221. {
  222. foreach (IntPtr regionAddress in _regions.Keys)
  223. {
  224. int lowerBound = (int)regionAddress;
  225. int upperBound = lowerBound + _regions[regionAddress].Length;
  226. int cAddress = (int)sr.Address;
  227.  
  228. if (cAddress >= lowerBound && cAddress <= upperBound)
  229. {
  230. if (!ByteSearch.matchAtOffset(_regions[regionAddress], buffer, cAddress - lowerBound))
  231. _results.Remove(sr);
  232. else
  233. sr.Buffer = buffer;
  234.  
  235. break;
  236. }
  237. }
  238. }
  239.  
  240. count++;
  241. updateProgress((int)(count / _regions.Count * 100));
  242. }
  243.  
  244. updateProgress(100);
  245.  
  246. if (callback != null)
  247. callback();
  248. }
  249.  
  250. public byte[] readMemory(IntPtr address, int length)
  251. {
  252. if (_handle == IntPtr.Zero)
  253. throw new InvalidOperationException("Cannot read process memory at " + address.ToString() + ". No process loaded.");
  254.  
  255. if (address == IntPtr.Zero)
  256. throw new ArgumentOutOfRangeException("Cannot read process memory. Invalid memory address.");
  257.  
  258. if (length < 1)
  259. throw new ArgumentOutOfRangeException("Cannot read process memory of size " + length + ".");
  260.  
  261. int bytesRead;
  262. byte[] data = new byte[length];
  263.  
  264. if (!ReadProcessMemory(_handle, address, data, (uint)data.Length, out bytesRead))
  265. throw new Exception("Failed to read process memory at " + address.ToString() + ". Error code: " + Marshal.GetLastWin32Error().ToString());
  266.  
  267. return data;
  268. }
  269.  
  270. public void writeMemory(IntPtr address, byte[] data)
  271. {
  272. if (_handle == IntPtr.Zero)
  273. throw new InvalidOperationException("Cannot write process memory at " + address.ToString() + ". No process loaded.");
  274.  
  275. if (address == IntPtr.Zero)
  276. throw new ArgumentOutOfRangeException("Cannot write process memory. Invalid memory address.");
  277.  
  278. if (data.Length < 1)
  279. throw new ArgumentOutOfRangeException("Cannot write process memory of size " + data.Length + ".");
  280.  
  281. int bytesWritten;
  282.  
  283. if (!WriteProcessMemory(_handle, address, data, data.Length, out bytesWritten))
  284. throw new Exception("Failed to write process memory at " + address.ToString() + ". Error code: " + Marshal.GetLastWin32Error().ToString());
  285. }
  286.  
  287. public IntPtr Handle { get { return _handle; } }
  288.  
  289. public SearchResult[] Results { get { return _results.ToArray(); } }
  290. }
  291. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement