1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 |
Module Module1 '83 05 ?? ?? ?? ?? 0A A1 '\x83\x05\x00\x00\x00\x00\x0A\xA1 'xx????xx '0045B072 Function ConvertStringToUniByteString(inputString As String) As String Dim unicodeBytes As New List(Of String)() For Each c As Char In inputString Dim bytes As Byte() = Text.Encoding.Unicode.GetBytes(c) For Each b As Byte In bytes unicodeBytes.Add(b.ToString("X2")) ' Convert byte to hexadecimal string Next Next ' Join the hexadecimal byte strings with spaces Return String.Join(" ", unicodeBytes) End Function Function ConvertStringToByteString(inputString As String) As String Dim byteString As New Text.StringBuilder() ' Convert each character to its corresponding byte and append to the byteString For Each ch As Char In inputString Dim byteValue As Byte = Convert.ToByte(ch) byteString.Append(byteValue.ToString("X2")) ' X2 format to ensure each byte is represented by 2 hex digits byteString.Append(" ") ' Append space after each byte Next ' Remove the last space If byteString.Length > 0 Then byteString.Length -= 1 End If Return byteString.ToString() End Function Function CompareByteArrays(arr1 As Byte(), arr2 As Byte()) As Boolean ' Check if the arrays are the same length If arr1.Length <> arr2.Length Then Return False End If ' Compare each byte in the arrays For i As Integer = 0 To arr1.Length - 1 If arr1(i) <> arr2(i) Then Return False End If Next ' If all bytes match, return true Return True End Function Private Function OverwriteBytePatten(ByVal Process As String, ByVal Pattern As String, replace As String) Dim ArrayListToReturn As New ArrayList Dim find_aob As New dotNetMemoryScan() ' scan_all: will scan all process memory, from Static And dynamic. Dim Address As New IntPtr(1) Do Until Address.ToInt64 = 0 Address = find_aob.scan_all(Process, Pattern, True) If Address.ToInt64 > IntPtr.Zero.ToInt64 Then ArrayListToReturn.Add(Address) Console.WriteLine("[scan_all 1] result 0x{0:X16}", Address.ToInt64()) Console.WriteLine("Bytes written: " & find_aob.write_mem("notepad.exe", Address, replace)) Else Console.WriteLine("[scan_all Finished]") Return ArrayListToReturn End If Loop End Function Private Function ScanAddress(ByVal Process As String, ByVal Pattern As String) As ArrayList Dim ArrayListToReturn As New ArrayList Dim find_aob As New dotNetMemoryScan() ' scan_all: will scan all process memory, from Static And dynamic. Dim Address As New IntPtr(1) Do Until Address.ToInt64 = 0 Address = find_aob.scan_all(Process, Pattern, True) If Address.ToInt64 > IntPtr.Zero.ToInt64 Then ArrayListToReturn.Add(Address) Console.WriteLine("[scan_all 1] result 0x{0:X16}", Address.ToInt64()) 'Console.WriteLine("Bytes written: " & find_aob.write_mem("notepad.exe", test2, ConvertStringToUniByteString("ZZZZZZ"))) Else Console.WriteLine("[scan_all Finished]") Return ArrayListToReturn End If Loop Return Nothing End Function Private Function MonitorAddress(ByVal MyArrayList As ArrayList, ByVal Value As Byte()) As ArrayList Dim ArrayListToReturn = MyArrayList.Clone Dim find_aob As New dotNetMemoryScan() Dim ReturnedBytes As Byte() For Each MyItem As IntPtr In MyArrayList ReturnedBytes = find_aob.address_space("notepad.exe", MyItem, Value.Length) If (CompareByteArrays(ReturnedBytes, Value) = False) Then Console.WriteLine("Change detected: " & MyItem.ToInt64.ToString("X2") & " - " & BitConverter.ToString(ReturnedBytes)) ArrayListToReturn.Remove(MyItem) End If Next Return ArrayListToReturn End Function Sub use_example() Dim find_aob As New dotNetMemoryScan() ' scan_all: will scan all process memory, from Static And dynamic. Dim test1 = IntPtr.Zero Dim test2 = IntPtr.Zero Dim MyString As String = "dsghgshs3" ' scan_module: scans only the Static part Of the Module Console.WriteLine("Looking for bytes: " & ConvertStringToUniByteString(MyString)) test1 = find_aob.scan_module("notepad.exe", "notepad.exe", ConvertStringToUniByteString(MyString)) Console.WriteLine("[module 1] result 0x{0:X16}", test1.ToInt64()) Dim MyArrayList = ScanAddress("notepad.exe", ConvertStringToUniByteString("ABCDE")) Do While True MyArrayList = MonitorAddress(MyArrayList, System.Text.Encoding.Unicode.GetBytes("ABCDE")) Threading.Thread.Sleep(10000) Loop 'OverwriteBytePatten("notepad.exe", ConvertStringToUniByteString("ZZZZZ"), ConvertStringToUniByteString("ABCDE")) Return ' with simple array 'test2 = find_aob.scan_all("notepad.exe", "83 05 ?? ?? ?? ?? 0A A1") test2 = find_aob.scan_all("notepad.exe", ConvertStringToByteString("Total1"), True) ' with pattern And mask test1 = find_aob.scan_all("notepad.exe", "\x83\x05\x00\x00\x00\x00\x0A\xA1", "xx????xx", True) Console.WriteLine("result 0x{0:X16}, 0x{0:X16}", test1.ToInt64(), test2.ToInt64()) Dim p = Process.GetProcessesByName("test") If Not IsNothing(p) And p.Count() > 0 Then ' can be used by passing the process handle directly. test1 = find_aob.scan_all(p(0).Handle, "83 05 ?? ?? ?? ?? 0A A1", True) Console.WriteLine("[handle] result 0x{0:X16}", test1.ToInt64()) ' can be used by passing the process. test1 = find_aob.scan_all(p(0), "83 05 ?? ?? ?? ?? 0A A1", True) Console.WriteLine("[process] result 0x{0:X16}", test1.ToInt64()) ' can be used by passing the process id. test1 = find_aob.scan_all(p(0).Id, "83 05 ?? ?? ?? ?? 0A A1", True) Console.WriteLine("[pid] result 0x{0:X16}", test1.ToInt64()) End If ' scan_module: scans only the Static part Of the Module test2 = find_aob.scan_module("test.exe", "test.exe", "83 05 ?? ?? ?? ?? 0A A1") Console.WriteLine("[module 1] result 0x{0:X16}", test1.ToInt64()) ' with pattern And mask test1 = find_aob.scan_module("test.exe", "name.dll", "\x83\x05\x00\x00\x00\x00\x0A\xA1", "xx????xx") Console.WriteLine("[module 2] result 0x{0:X16}", test1.ToInt64()) ' Writing in memory. find_aob.write_mem("test.exe", test1, "90 90 90 90 90 90 90") ' or find_aob.write_mem("test.exe", test1, "\x90\x90\x90\x90\x90\x90\x90") End Sub Sub Main() use_example() Console.WriteLine("Done") Console.ReadKey() End Sub End Module |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; using System.Diagnostics; using System.IO; using Microsoft.Win32.SafeHandles; using System.Windows.Forms; using System.Text.RegularExpressions; using System.Runtime.ConstrainedExecution; using System.Security; using System.Security.Principal; public class dotNetMemoryScan { [DllImport("kernel32.dll")] public static extern uint GetLastError(); [DllImport("kernel32.dll", SetLastError = true)] static extern void SetLastError(uint dwErrorCode); [DllImport("kernel32.dll")] public static extern int OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int dwProcessId); [DllImport("kernel32.dll")] protected static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] buffer, uint size, out uint lpNumberOfBytesRead); [DllImport("kernel32.dll")] public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] buffer, uint size, uint lpNumberOfBytesWritten); [DllImport("kernel32.dll", SetLastError = true)] protected static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, uint dwLength); [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWow64Process([In] IntPtr processHandle, [Out, MarshalAs(UnmanagedType.Bool)] out bool wow64Process); [DllImport("kernel32.dll", EntryPoint = "GetProcessId", CharSet = CharSet.Auto)] static extern int GetProcessId(IntPtr handle); [DllImport("kernel32.dll")] static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); public dotNetMemoryScan() { EnablePrivileges.GoDebugPriv(); } public static string GetSystemMessage(uint errorCode) { var exception = new System.ComponentModel.Win32Exception((int)errorCode); return exception.Message; } [StructLayout(LayoutKind.Sequential)] protected struct MEMORY_BASIC_INFORMATION { public IntPtr BaseAddress; public IntPtr AllocationBase; public uint AllocationProtect; public UIntPtr RegionSize; public uint State; public uint Protect; public uint Type; } //uint PROCESS_ALL_ACCESS = 0x1F0FF; //Memory Protect //https://msdn.microsoft.com/en-us/library/windows/hardware/dn957515(v=vs.85).aspx private enum AllocationProtectEnum : uint { PAGE_EXECUTE = 0x00000010, PAGE_EXECUTE_READ = 0x00000020, PAGE_EXECUTE_READWRITE = 0x00000040, PAGE_EXECUTE_WRITECOPY = 0x00000080, PAGE_NOACCESS = 0x00000001, PAGE_READONLY = 0x00000002, PAGE_READWRITE = 0x00000004, PAGE_WRITECOPY = 0x00000008, PAGE_GUARD = 0x00000100, PAGE_NOCACHE = 0x00000200, PAGE_WRITECOMBINE = 0x00000400 } //Memory State //https://msdn.microsoft.com/en-us/library/windows/desktop/aa366775(v=vs.85).aspx private enum StateEnum : uint { MEM_COMMIT = 0x1000, MEM_FREE = 0x10000, MEM_RESERVE = 0x2000 } private enum TypeEnum : uint { MEM_IMAGE = 0x1000000, MEM_MAPPED = 0x40000, MEM_PRIVATE = 0x20000 } byte[] current_aob = null; string mask = ""; IntPtr handle = IntPtr.Zero; int pid = 0; bool is_valid_hex_array(string text) { var regex = new Regex(@"^([a-fA-F0-9]{2}?(.*\?)?\s?)+$"); var match = regex.Match(text); return (match.Success); } bool is_valid_pattern_mask(string text) { var regex = new Regex(@"^([\\*][x][a-fA-F0-9]{2})+$"); var match = regex.Match(text); return (match.Success); } bool is_valid_mask(string text) { var regex = new Regex(@"^([xX]?(.*\?)?)+$"); var match = regex.Match(text); return (match.Success); } int str_array_to_aob(string inputed_str) { var trated_str = inputed_str.Replace(" ", ""); trated_str = (trated_str[0] == ' ') ? trated_str.Substring(1, trated_str.Length - 1) : trated_str; trated_str = (trated_str.Substring(trated_str.Length - 1, 1) == " ") ? trated_str.Substring(0, trated_str.Length - 1) : trated_str; if (!is_valid_hex_array(trated_str)) { MessageBox.Show("not valid hex array {x1F0}", "by dotNetMemoryScan"); return 0; } mask = ""; var part_hex = inputed_str.Split(' '); current_aob = new byte[part_hex.Count()]; for (var i = 0; i < part_hex.Count(); ++i) { if (part_hex[i].Contains("?")) { current_aob[i] = 0xCC; mask += "?"; } else { current_aob[i] = Convert.ToByte(part_hex[i], 16); mask += "x"; } } return part_hex.Count(); } int pattern_to_aob(string inputed_str, string i_mask) { if (!is_valid_mask(i_mask)) return 0; var trated_str = inputed_str.Replace(" ", ""); if (!is_valid_pattern_mask(trated_str)) { MessageBox.Show("not valid pattern {x1F0}", "by dotNetMemoryScan"); return 0; } var part_hex = inputed_str.Split(new[] { @"\x" }, StringSplitOptions.None); if ((part_hex.Count() - 1) != i_mask.Length) return 0; mask = i_mask; current_aob = new byte[part_hex.Count()-1]; for (var i = 1; i < part_hex.Count(); ++i) { var l = i - 1; if (i_mask[l] == '?') current_aob[l] = 0xCC; else current_aob[l] = Convert.ToByte(part_hex[i], 16); } return part_hex.Count(); } int pattern_to_aob(string inputed_str) { var trated_str = inputed_str.Replace(" ", ""); if (!is_valid_pattern_mask(trated_str)) { MessageBox.Show("not valid pattern {x1F1}", "by dotNetMemoryScan"); return 0; } var part_hex = inputed_str.Split(new[] { @"\x" }, StringSplitOptions.None); current_aob = new byte[part_hex.Count() - 1]; for (var i = 1; i < part_hex.Count(); ++i) current_aob[i - 1] = Convert.ToByte(part_hex[i], 16); return part_hex.Count(); } public static bool IsAdministrator() { return (new WindowsPrincipal(WindowsIdentity.GetCurrent())) .IsInRole(WindowsBuiltInRole.Administrator); } IntPtr get_handle(Process p) { if (p == null) return IntPtr.Zero; try { return p.Handle; } catch(Exception ex) { if (!IsAdministrator()) MessageBox.Show("Run the program as an administrator.", "by dotNetMemoryScan"); else MessageBox.Show("error: " + ex.Message); } return IntPtr.Zero; } //=================================================================================================================================== //=================================================================================================================================== //=================================================================================================================================== public IntPtr scan_all(IntPtr handle, string pattern, bool bContinue) { if (str_array_to_aob(pattern) == 0) return IntPtr.Zero; this.handle = handle; this.pid = GetProcessId(this.handle); return scan_all_regions(bContinue); } public IntPtr scan_all(Process p, string pattern, bool bContinue) { var by_handle = get_handle(p); if (by_handle != IntPtr.Zero) return scan_all(by_handle, pattern, bContinue); return IntPtr.Zero; } public IntPtr scan_all(string p_name, string pattern, bool bContinue) { var by_handle = get_handle(GetPID(p_name.Replace(".exe", ""))); if (by_handle != IntPtr.Zero) return scan_all(by_handle, pattern, bContinue); return IntPtr.Zero; } public IntPtr scan_all(int pid, string pattern, bool bContinue) { var by_handle = get_handle(Process.GetProcessById(pid)); if (by_handle != IntPtr.Zero) return scan_all(by_handle, pattern, bContinue); return IntPtr.Zero; } //=================================================================================================================================== //=================================================================================================================================== //=================================================================================================================================== public IntPtr scan_all(IntPtr handle, string pattern, string mask, bool bContinue) { if (pattern_to_aob(pattern, mask) == 0) return IntPtr.Zero; this.handle = handle; return scan_all_regions(bContinue); } public IntPtr scan_all(Process p, string pattern, string mask, bool bContinue) { var by_handle = get_handle(p); if (by_handle != IntPtr.Zero) return scan_all(by_handle, pattern, mask, bContinue); return IntPtr.Zero; } public IntPtr scan_all(string p_name, string pattern, string mask, bool bContinue) { var by_handle = get_handle(GetPID(p_name.Replace(".exe", ""))); if (by_handle != IntPtr.Zero) return scan_all(by_handle, pattern, mask, bContinue); return IntPtr.Zero; } public IntPtr scan_all(int pid, string pattern, string mask, bool bContinue) { var by_handle = get_handle(Process.GetProcessById(pid)); if (by_handle != IntPtr.Zero) return scan_all(by_handle, pattern, mask, bContinue); return IntPtr.Zero; } //=================================================================================================================================== //=================================================================================================================================== //=================================================================================================================================== public IntPtr scan_module(Process p, string module_name, string pattern) { this.handle = get_handle(p); if (this.handle == IntPtr.Zero) return IntPtr.Zero; if (str_array_to_aob(pattern) == 0) return IntPtr.Zero; return module_region(p, module_name); } public IntPtr scan_module(int pid, string module_name, string pattern) { var p = Process.GetProcessById(pid); if (p != null) return scan_module(p, module_name, pattern); return IntPtr.Zero; } public IntPtr scan_module(string p_name, string module_name, string pattern) { var p = GetPID(p_name.Replace(".exe", "")); if (p != null) return scan_module(p, module_name, pattern); return IntPtr.Zero; } public IntPtr scan_module(IntPtr handle, string module_name, string pattern) { int pid = GetProcessId(handle); if (pid == 0) return IntPtr.Zero; return scan_module(pid, module_name, pattern); } //=================================================================================================================================== //=================================================================================================================================== //=================================================================================================================================== public IntPtr scan_module(Process p, string module_name, string pattern, string mask) { this.handle = get_handle(p); if (this.handle == IntPtr.Zero) return IntPtr.Zero; if (pattern_to_aob(pattern, mask) == 0) return IntPtr.Zero; return module_region(p, module_name); } public IntPtr scan_module(int pid, string module_name, string pattern, string mask) { var p = Process.GetProcessById(pid); if (p != null) return scan_module(p, module_name, pattern, mask); return IntPtr.Zero; } public IntPtr scan_module(string p_name, string module_name, string pattern, string mask) { var p = GetPID(p_name.Replace(".exe", "")); if (p != null) return scan_module(p, module_name, pattern, mask); return IntPtr.Zero; } public IntPtr scan_module(IntPtr handle, string module_name, string pattern, string mask) { int pid = GetProcessId(handle); if (pid == 0) return IntPtr.Zero; return scan_module(pid, module_name, pattern, mask); } //=================================================================================================================================== //=================================================================================================================================== //=================================================================================================================================== protected bool map_process_memory(IntPtr pHandle, List<MEMORY_BASIC_INFORMATION> mapped_memory) { IntPtr address = new IntPtr(); MEMORY_BASIC_INFORMATION MBI = new MEMORY_BASIC_INFORMATION(); var found = VirtualQueryEx(pHandle, address, out MBI, (uint)Marshal.SizeOf(MBI)); while ( found != 0) { if ((MBI.State & (uint)StateEnum.MEM_COMMIT) != 0 && (MBI.Protect & (uint)AllocationProtectEnum.PAGE_GUARD) != (uint)AllocationProtectEnum.PAGE_GUARD) mapped_memory.Add(MBI); address = new IntPtr(MBI.BaseAddress.ToInt64() + (long)MBI.RegionSize); found = VirtualQueryEx(pHandle, address, out MBI, (uint)Marshal.SizeOf(MBI)); } return (mapped_memory.Count() > 0); } int is_x64_process(IntPtr by_handle) { var is_64 = false; if (!IsWow64Process(by_handle, out is_64)) return -1; return Convert.ToInt32(!is_64); } int search_pattern(byte[] buffer, int init_index) { for (var i = init_index; i < buffer.Count(); ++i) { for (var x = 0; x < current_aob.Count(); x++) { if (i + x >= buffer.Length) // Check if the index is within buffer bounds goto end; if (current_aob[x] != buffer[i + x] && mask[x] != '?') goto end; } return i; end:; } return 0; } IntPtr module_region(Process p, string module_str) { if (is_x64_process(Process.GetCurrentProcess().Handle) != is_x64_process(this.handle)) { MessageBox.Show("Problems with retaining information or architectural incompatibility with the target process.", "by dotNetMemoryScan"); return IntPtr.Zero; } var mod = find_module(p, module_str); if (mod == null) return IntPtr.Zero; byte[] buffer = new byte[mod.ModuleMemorySize]; uint NumberOfBytesRead; if (ReadProcessMemory(handle, mod.BaseAddress, buffer, (uint)mod.ModuleMemorySize, out NumberOfBytesRead) && NumberOfBytesRead > 0) { var ret = search_pattern(buffer, 0); if (ret != 0) return (IntPtr)(mod.BaseAddress.ToInt64() + ret); } return IntPtr.Zero; } public byte[] address_space(string p_name, IntPtr address, uint length) { var p = GetPID(p_name.Replace(".exe", "")); if (p != null) { handle = p.Handle; } if (is_x64_process(Process.GetCurrentProcess().Handle) != is_x64_process(this.handle)) { MessageBox.Show("Problems with retaining information or architectural incompatibility with the target process.", "by dotNetMemoryScan"); return null; } byte[] buffer = new byte[length]; uint NumberOfBytesRead; if (ReadProcessMemory(handle, address, buffer, (uint)length, out NumberOfBytesRead) && NumberOfBytesRead > 0) { return buffer; } return null; } //IntPtr mappedMemoryCount = new IntPtr(0); int mappedMemoryCount = 0; int IndexLeftOffMemory = 0; IntPtr BaseAddressMemory = new IntPtr(0); IntPtr scan_all_regions(bool bContinue) { if (is_x64_process(Process.GetCurrentProcess().Handle) != is_x64_process(this.handle)) { MessageBox.Show("Problems with retaining information or architectural incompatibility with the target process.", "by dotNetMemoryScan"); return IntPtr.Zero; } var mapped_memory = new List<MEMORY_BASIC_INFORMATION>(); if (!map_process_memory(handle, mapped_memory)) return IntPtr.Zero; if (!bContinue) { mappedMemoryCount = 0; BaseAddressMemory = IntPtr.Zero; IndexLeftOffMemory = 0; } for (int i = mappedMemoryCount; i < mapped_memory.Count(); i++) { byte[] buffer = new byte[(uint)mapped_memory[i].RegionSize]; uint NumberOfBytesRead; if (ReadProcessMemory(handle, mapped_memory[i].BaseAddress, buffer, (uint)mapped_memory[i].RegionSize, out NumberOfBytesRead) && NumberOfBytesRead > 0) { if (mappedMemoryCount != 0 && i != mappedMemoryCount && IndexLeftOffMemory > 0) { IndexLeftOffMemory = 0; } var ret = search_pattern(buffer, IndexLeftOffMemory + 1); if (ret != 0) { mappedMemoryCount = i; IndexLeftOffMemory = ret; BaseAddressMemory = mapped_memory[i].BaseAddress + ret; return (IntPtr)(mapped_memory[i].BaseAddress.ToInt64() + ret); } } var error_code = GetLastError(); if (error_code == 6)//sometimes .net closes the handle. { var p = Process.GetProcessById(pid); if (p != null) this.handle = p.Handle; } } return IntPtr.Zero; } public Process GetPID(string ProcessName) { try { return Process.GetProcessesByName(ProcessName)[0]; } catch { } return null; } bool write_mem(IntPtr address, string pattern) { var size = 0; if (pattern.Contains(@"\x")) size = pattern_to_aob(pattern); else size = str_array_to_aob(pattern); if (size == 0) return false; uint old_p = 0; if (!VirtualProtectEx(handle, address, (UIntPtr)size, (uint)AllocationProtectEnum.PAGE_EXECUTE_READWRITE, out old_p)) return false; var ret = WriteProcessMemory(handle, address, current_aob, (uint)size, 0); VirtualProtectEx(handle, address, (UIntPtr)size, old_p, out old_p); return ret; } public bool write_mem(IntPtr handle, IntPtr address, string pattern) { if (address == null) return false; this.handle = handle; return write_mem(address, pattern); } public bool write_mem(Process p, IntPtr address, string pattern) { var by_handle = get_handle(p); if (by_handle == IntPtr.Zero) return false; return write_mem(by_handle, address, pattern); } public bool write_mem(string p_name, IntPtr address, string pattern) { var by_handle = get_handle(GetPID(p_name.Replace(".exe", ""))); if (by_handle == IntPtr.Zero) return false; return write_mem(by_handle, address, pattern); } public bool write_mem(int pid, IntPtr address, string pattern) { var by_handle = get_handle(Process.GetProcessById(pid)); if (by_handle == IntPtr.Zero) return false; return write_mem(by_handle, address, pattern); } public ProcessModule find_module(Process p, string module_str) { foreach (ProcessModule modu in p.Modules) { if (modu.FileName.ToLower().Contains(module_str.ToLower())) return modu; } return null; } public Process get_chrome_flashplayer_process() { foreach (Process proc in Process.GetProcessesByName("chrome")) { if (find_module(proc, "pepflashplayer.dll") != null) return proc; } return null; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Runtime.InteropServices; public class EnablePrivileges { [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle); private static uint STANDARD_RIGHTS_REQUIRED = 0x000F0000; private static uint STANDARD_RIGHTS_READ = 0x00020000; private static uint TOKEN_ASSIGN_PRIMARY = 0x0001; private static uint TOKEN_DUPLICATE = 0x0002; private static uint TOKEN_IMPERSONATE = 0x0004; private static uint TOKEN_QUERY = 0x0008; private static uint TOKEN_QUERY_SOURCE = 0x0010; private static uint TOKEN_ADJUST_PRIVILEGES = 0x0020; private static uint TOKEN_ADJUST_GROUPS = 0x0040; private static uint TOKEN_ADJUST_DEFAULT = 0x0080; private static uint TOKEN_ADJUST_SESSIONID = 0x0100; private static uint TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY); private static uint TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID); [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr GetCurrentProcess(); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid); public const string SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege"; public const string SE_AUDIT_NAME = "SeAuditPrivilege"; public const string SE_BACKUP_NAME = "SeBackupPrivilege"; public const string SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege"; public const string SE_CREATE_GLOBAL_NAME = "SeCreateGlobalPrivilege"; public const string SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege"; public const string SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege"; public const string SE_CREATE_SYMBOLIC_LINK_NAME = "SeCreateSymbolicLinkPrivilege"; public const string SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege"; public const string SE_DEBUG_NAME = "SeDebugPrivilege"; public const string SE_ENABLE_DELEGATION_NAME = "SeEnableDelegationPrivilege"; public const string SE_IMPERSONATE_NAME = "SeImpersonatePrivilege"; public const string SE_INC_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege"; public const string SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege"; public const string SE_INC_WORKING_SET_NAME = "SeIncreaseWorkingSetPrivilege"; public const string SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege"; public const string SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege"; public const string SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege"; public const string SE_MANAGE_VOLUME_NAME = "SeManageVolumePrivilege"; public const string SE_PROF_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege"; public const string SE_RELABEL_NAME = "SeRelabelPrivilege"; public const string SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege"; public const string SE_RESTORE_NAME = "SeRestorePrivilege"; public const string SE_SECURITY_NAME = "SeSecurityPrivilege"; public const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege"; public const string SE_SYNC_AGENT_NAME = "SeSyncAgentPrivilege"; public const string SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege"; public const string SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege"; public const string SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege"; public const string SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege"; public const string SE_TCB_NAME = "SeTcbPrivilege"; public const string SE_TIME_ZONE_NAME = "SeTimeZonePrivilege"; public const string SE_TRUSTED_CREDMAN_ACCESS_NAME = "SeTrustedCredManAccessPrivilege"; public const string SE_UNDOCK_NAME = "SeUndockPrivilege"; public const string SE_UNSOLICITED_INPUT_NAME = "SeUnsolicitedInputPrivilege"; [StructLayout(LayoutKind.Sequential)] public struct LUID { public UInt32 LowPart; public Int32 HighPart; } [DllImport("kernel32.dll", SetLastError = true)] static extern bool CloseHandle(IntPtr hHandle); public const UInt32 SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001; public const UInt32 SE_PRIVILEGE_ENABLED = 0x00000002; public const UInt32 SE_PRIVILEGE_REMOVED = 0x00000004; public const UInt32 SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000; [StructLayout(LayoutKind.Sequential)] public struct TOKEN_PRIVILEGES { public UInt32 PrivilegeCount; public LUID Luid; public UInt32 Attributes; } [StructLayout(LayoutKind.Sequential)] public struct LUID_AND_ATTRIBUTES { public LUID Luid; public UInt32 Attributes; } // Use this signature if you do not want the previous state [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, UInt32 Zero, IntPtr Null1, IntPtr Null2); public static void GoDebugPriv() { IntPtr hToken; LUID luidSEDebugNameValue; TOKEN_PRIVILEGES tkpPrivileges; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out hToken)) { return; } if (!LookupPrivilegeValue(null, SE_DEBUG_NAME, out luidSEDebugNameValue)) { CloseHandle(hToken); return; } tkpPrivileges.PrivilegeCount = 1; tkpPrivileges.Luid = luidSEDebugNameValue; tkpPrivileges.Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken, false, ref tkpPrivileges, 0, IntPtr.Zero, IntPtr.Zero); CloseHandle(hToken); } } |