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 |
Public Class Form1 'https://data.bls.gov/timeseries/CUURS49ASA0 'Example table in the LA, CA area Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim inflationRates As Dictionary(Of DateTime, Decimal) = New Dictionary(Of DateTime, Decimal) From { {New DateTime(2014, 1, 1), 242.434}, ' 2014 inflation rate {New DateTime(2015, 1, 1), 244.632}, ' 2015 inflation rate {New DateTime(2016, 1, 1), 249.246}, ' 2016 inflation rate {New DateTime(2016, 7, 1), 249.784}, ' 2016 inflation rate {New DateTime(2017, 1, 1), 256.21}, ' 2017 inflation rate {New DateTime(2018, 1, 1), 265.962}, ' 2018 inflation rate {New DateTime(2019, 1, 1), 274.114}, ' 2019 inflation rate {New DateTime(2020, 1, 1), 278.567}, ' 2020 inflation rate {New DateTime(2021, 1, 1), 289.244}, ' 2021 inflation rate {New DateTime(2022, 1, 1), 310.782}, ' 2022 inflation rate {New DateTime(2023, 1, 1), 321.583}, ' 2023 inflation rate {New DateTime(2024, 1, 1), 326.64}, ' 2024 inflation rate {New DateTime(2024, 6, 1), 332.357} } Dim startDate As DateTime = New DateTime(2016, 7, 1) Dim endDate As DateTime = New DateTime(2024, 6, 1) Dim realWage As Decimal = CalculateRealWage(30.0D, inflationRates, startDate, endDate, True) Dim realWageBackwards As Decimal = CalculateRealWage(50.0D, inflationRates, startDate, endDate, False) 'Console.WriteLine("Real Wage: " & realWage.ToString("C")) End Sub Function CalculateRealWage(ByVal initialWage As Decimal, ByVal inflationRates As Dictionary(Of DateTime, Decimal), ByVal startDate As DateTime, ByVal endDate As DateTime, ByVal ForwardOrBackwards As Boolean) As Decimal Dim startCPI As Decimal = inflationRates(startDate) Dim endCPI As Decimal = inflationRates(endDate) Dim RealWage As Decimal If ForwardOrBackwards Then RealWage = initialWage * (endCPI / startCPI) Debug.WriteLine("Ratio value: Using the startCPI of " & startCPI & " and " & endCPI & " creates a ratio of " & (1 / (startCPI / endCPI))) Debug.WriteLine("The amount of $" & initialWage & " in 2016 is worth " & RealWage.ToString("C") & " in todays money") Else 'Dim ReverseRealWage As Decimal = initialWage * (1 / (startCPI / endCPI)) RealWage = initialWage * (startCPI / endCPI) Debug.WriteLine("The amount of $" & initialWage & " dollars in todays money is was worth " & RealWage.ToString("C") & " back in " & startDate) End If Return RealWage End Function End Class |
Updating Chivalry 2 Nitrado Map settings using Powershell and OAuth2.0 Lifetime Token
Support at this time does not allow setting the server password for access (Must be done through the Web interface using Username and Password auth), nor adding users to ban list / kicking players (must be done inside the Chivalry console itself during gameplay).
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 |
#https://doc.nitrado.net/ #https://server.nitrado.net/en-GB/guides/chivalry-2-map-rotation-server-guide # Define the necessary variables $LifeLongToken = "Put your Lifelong Token here" $ServiceID = "Put your serviceId here (7-8 digits)" $ServerDetails = "https://api.nitrado.net/services/$ServiceID/gameservers" $SettingsURL = "https://api.nitrado.net/services/$ServiceID/gameservers/settings" $RestartURL = "https://api.nitrado.net/services/$ServiceID/gameservers/restart" $ListPlayers = "https://api.nitrado.net/services/$ServiceID/gameservers/games/players" $headers = @{ 'Authorization' = 'Bearer ' + $LifeLongToken 'User-Agent' = 'PostmanRuntime/7.40.0' 'Accept' = '*/*' 'Host' = 'api.nitrado.net' } $token_response = Invoke-RestMethod -Method GET -Uri ($ServerDetails) -Headers $headers $token_response.data.gameserver $token_response = Invoke-RestMethod -Method GET -Uri ($ListPlayers) -Headers $headers write-host "Total players current in server: " $token_response.data.players.Count write-host $token_response.data.players $token_response = Invoke-RestMethod -Method GET -Uri ($SettingsURL+"/sets") -Headers $headers $token_response #$token_response.data.sets.data.settings.config."map-rotation" $token_response = Invoke-RestMethod -Method POST -Uri ($SettingsURL+"?category=settings&key=admin-list&value={PutPlayerAdminIDHere}`r`n{PutPlayerAdminIDHere}`r`n{PutPlayerAdminIDHere}") -Headers $headers $token_response $token_response = Invoke-RestMethod -Method POST -Uri ($SettingsURL+"?category=settings&key=map-rotation&value= TO_Raid FFA_Duelyard TO_DarkForest TO_RudhelmSiege TO_Citadel TO_Galencourt TO_Stronghold TO_Lionspire TO_Falmire") -Headers $headers $token_response $token_response = Invoke-RestMethod -Method POST -Uri ($SettingsURL+"?category=settings&key=map-rotation&value= FFA_Duelyard ") -Headers $headers $token_response $token_response = Invoke-RestMethod -Method POST -Uri ($RestartURL+"?message=Restarting Via Powershell&restart_message=Server Restarting...") -Headers $headers $token_response #Server will take 180 seconds to reestablish write-host "Restarting server, please wait 180 seconds" sleep 180 write-host "Server is expected to be up and running..." |
C++ Memory Manager
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 |
// DeleteMe.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <sstream> #include <map> #include <string> #include <string_view> #include <unordered_map> #include <vector> #include <Windows.h> #include <TlHelp32.h> #include <cstddef> #include <bitset> #include <iomanip> #include <psapi.h> #include <stdio.h> #include <tchar.h> #pragma comment(lib, "advapi32.lib") int decimalValue = 0; int main() { std::string input; while (true) { std::cout << "Enter a decimal string: "; std::cin >> input; decimalValue = std::stoi(input); } } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file |
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 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 |
// Memory.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <sstream> #include <map> #include <string> #include <string_view> #include <unordered_map> #include <vector> #include <Windows.h> #include <TlHelp32.h> #include <cstddef> #include <bitset> #include <iomanip> #include <psapi.h> #include <stdio.h> #include <tchar.h> #include <thread> #include <chrono> #pragma comment(lib, "advapi32.lib") //const wchar_t* ProcName = L"notepad.exe"; const wchar_t* ProcName = L"deleteme.exe"; DWORD processId = 0; // GetProcId(ProcName); HANDLE hProcess = 0; // OpenProcess(PROCESS_ALL_ACCESS, NULL, processId); class MemoryModule { public: std::string ModuleName; DWORD Address; MemoryModule(DWORD Addr, std::string val) : ModuleName(val), Address(Addr) { //std::cout << "MemoryEntry Addr (" << Addr << ") = " << "0x" << std::hex << val << std::endl; } }; class MemoryEntry { public: int value = 0; //Used for Single byte checks //byte ByteArray[4]; VOID * Address = NULL; VOID * Bytevalue = NULL; //Used for Arrays of values MemoryEntry(VOID * Addr, int val) : value(val), Address(Addr) { //std::cout << "MemoryEntry Addr (" << Addr << ") = " << "0x" << std::hex << val << std::endl; } MemoryEntry(VOID* Addr, byte val[], int length){ Address = Addr; value = length; for (int i = 0; i < length; i++) { } Bytevalue = malloc(length); memcpy(Bytevalue, val, length); } /* * ~MemoryEntry() { if (Bytevalue) { free(&Bytevalue); } } */ }; //std::unordered_map<std::string, std::vector<MemoryEntry>> GMemoryMap; //std::unordered_map<MemoryModule, std::vector<MemoryEntry>> GMemoryMap; std::unordered_map<VOID *, std::vector<MemoryEntry>> GMemoryMap; DWORD GetProcId(const wchar_t* procName); uintptr_t GetModuleBaseAddress(DWORD procID, const wchar_t* modName); uintptr_t FindDMAAddy(HANDLE hProc, uintptr_t ptr, std::vector<unsigned int> offsets); BOOL SetPrivilege(HANDLE hToken, // access token handle LPCTSTR lpszPrivilege, // name of privilege to enable/disable BOOL bEnablePrivilege // to enable or disable privilege ) { TOKEN_PRIVILEGES tp; LUID luid; if (!LookupPrivilegeValue( NULL, // lookup privilege on local system lpszPrivilege, // privilege to lookup &luid)) // receives LUID of privilege { printf("LookupPrivilegeValue error: %u\n", GetLastError()); return FALSE; } tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; if (bEnablePrivilege) tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; else tp.Privileges[0].Attributes = 0; // Enable the privilege or disable all privileges. if (!AdjustTokenPrivileges( hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL)) { printf("AdjustTokenPrivileges error: %u\n", GetLastError()); return FALSE; } if (GetLastError() == ERROR_NOT_ALL_ASSIGNED) { printf("The token does not have the specified privilege. \n"); return FALSE; } return TRUE; } std::vector<std::pair<HMODULE, DWORD>> GetModules(HANDLE hProcess) { std::vector<std::pair<HMODULE, DWORD>> modules; if (hProcess != NULL) { HMODULE hMods[1024]; DWORD cbNeeded = 0; if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) { for (int i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) { MODULEINFO mi; GetModuleInformation(hProcess, hMods[i], &mi, sizeof(mi)); modules.push_back(std::make_pair(hMods[i], mi.SizeOfImage)); } } else { std::cerr << "EnumProcessModules failed. Error code: " << GetLastError() << std::endl; } } return modules; } long TotalSizeOfMemory = 0; long TotalADDRFound = 0; int ReadAllProcModules(DWORD processId, HANDLE hProcess, byte BytePattern[], int Bytelength) { if (hProcess == NULL) { std::cerr << "Failed to open process. Error code: " << GetLastError() << std::endl; return 1; } // Get all modules in the target process std::vector<std::pair<HMODULE, DWORD>> modules = GetModules(hProcess); // Loop through each module and read memory for (const auto& module : modules) { // Allocate buffer to store module's memory std::vector<BYTE> buffer(module.second); // Read memory from the module's base address HANDLE ModuleAddress = module.first; if (ReadProcessMemory(hProcess, module.first, buffer.data(), buffer.size(), nullptr)) { TotalSizeOfMemory += buffer.size(); // Process the read data here (e.g., print or manipulate) // For demonstration, let's print the first few bytes of each module std::cout << "Module Base Address: " << module.first << " Module Size: " << buffer.size() << std::endl; /* std::cout << "First 16 bytes of module:" << std::endl; for (size_t i = 0; i < std::min<size_t>(16, buffer.size()); i++) { std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(buffer[i]) << " "; } */ for (size_t i = 0; i < buffer.size(); i++) { if (Bytelength == 1) //This will not work with a pointer { if (BytePattern[0] == buffer[i]) { //MemoryModule MemoryRegionKey = MemoryModule(DWORD(module.first), "Module"); VOID* test = module.first; VOID* test2 = module.first + 1; VOID* test3 = ((char*)module.first) + i; MemoryEntry MemoryEntryToAdd = MemoryEntry(((char*)module.first) + i, BytePattern[0]); GMemoryMap[module.first].push_back(MemoryEntryToAdd); TotalADDRFound += 1; } } else { int lenth = sizeof(BytePattern); bool match = true; for (size_t ii = 0; ii < Bytelength; ii++) { if (BytePattern[ii] != buffer[i + ii]) { match = false; break; } } if (match) { MemoryEntry MemoryEntryToAdd = MemoryEntry(((char*)module.first) + i, BytePattern, Bytelength); GMemoryMap[module.first].push_back(MemoryEntryToAdd); TotalADDRFound += 1; } } } } else { std::cerr << "Failed to read memory from module." << std::endl; } //std::cout << "Total Memorysize: " << std::dec << (TotalSizeOfMemory / 1024 / 1024) << "(MBs)" << std::endl; } std::cout << "Total TotalADDRFound: " << std::dec << TotalADDRFound << std::endl; } void ReadSpecificAddress(DWORD processId, HANDLE hProcess) { //Getmodulebaseaddress uintptr_t moduleBase = GetModuleBaseAddress(processId, ProcName); //Resolve base address of the pointer chain uintptr_t dynamicPtrBaseAddr = moduleBase + 0x10f4f4; std::cout << "DynamicPtrBaseAddr = " << "0x" << std::hex << dynamicPtrBaseAddr << std::endl; //Resolve our ammo pointer chain std::vector<unsigned int> ammoOffsets = { 0x374, 0x14, 0x0 }; uintptr_t ammoAddr = FindDMAAddy(hProcess, dynamicPtrBaseAddr, ammoOffsets); std::cout << "ammoAddr = " << "0x" << std::hex << ammoAddr << std::endl; //Read Ammo value int ammoValue = 0; ReadProcessMemory(hProcess, (BYTE*)ammoAddr, &ammoValue, sizeof(ammoValue), nullptr); //std::cout << "Current ammo = " << std::dec << ammoValue << std::endl; //Write to it int newAmmo = 1338; WriteProcessMemory(hProcess, (BYTE*)ammoAddr, &newAmmo, sizeof(newAmmo), nullptr); //Read out again ReadProcessMemory(hProcess, (BYTE*)ammoAddr, &ammoValue, sizeof(ammoValue), nullptr); //std::cout << "New ammo = " << std::dec << ammoValue << std::endl; } void CheckChanged(DWORD processId, HANDLE hProcess, std::unordered_map<VOID*, std::vector<MemoryEntry>>& LMemoryMap, bool RemoveIfChangedInsteadOfKeep) { char Buffer[1] = { 0 }; for (auto& pair : LMemoryMap) { VOID* key = pair.first; std::vector<MemoryEntry>& Tempobj = pair.second; for (int i = pair.second.size() - 1; i >= 0; i--) { MemoryEntry Obj = pair.second.at(i); VOID* ObjAddr = Obj.Address; if (ReadProcessMemory(hProcess, ObjAddr, &Buffer, 1, nullptr)) { char a = Buffer[0]; char b = Obj.value; if (!RemoveIfChangedInsteadOfKeep) { if (a != b) { //std::cout << "ModuleAddress: 0x" << std::hex << key << " Address: " << ObjAddr << " - Value: 0x" << std::hex << Obj.value << " Compared to: 0x" << (int)(Buffer[0]) << "\n"; if (TotalADDRFound % 10000 == 0) { std::cout << "Change Detected ModuleAddress: 0x" << std::hex << key << " Address: " << ObjAddr << " - BeforeValue: 0x" << std::hex << Obj.value << " NowValue: 0x" << std::hex << (int)(Buffer[0]) << "\n"; } TotalADDRFound -= 1; Obj.value = Buffer[0]; } else { Tempobj.erase(Tempobj.begin() + i); //Remove if same //std::cout << "Keeping ModuleAddress: 0x" << std::hex << key << " Address: " << ObjAddr << " - BeforeValue: 0x" << std::hex << Obj.value << " NowValue: 0x" << std::hex << (int)(Buffer[0]) << " Compared to: 0x" << int(Pattern[0]) << "\n"; } } else { if (a == b) { //std::cout << "ModuleAddress: 0x" << std::hex << key << " Address: " << ObjAddr << " - Value: 0x" << std::hex << Obj.value << " Compared to: 0x" << (int)(Buffer[0]) << "\n"; } else { if (TotalADDRFound % 10000 == 0) { std::cout << "Change Detected ModuleAddress: 0x" << std::hex << key << " Address: " << ObjAddr << " - BeforeValue: 0x" << std::hex << Obj.value << " NowValue: 0x" << std::hex << (int)(Buffer[0]) << "\n"; } TotalADDRFound -= 1; Tempobj.erase(Tempobj.begin() + i); //Remove if same } } } else { std::cout << "Unable to read from: " << Obj.Address << "\n"; } } } } void CheckAllRegisters(DWORD processId, HANDLE hProcess, std::unordered_map<VOID*, std::vector<MemoryEntry>>& LMemoryMap, byte Pattern[]) { char Buffer[1] = { 0 }; for (auto& pair : LMemoryMap) { VOID* key = pair.first; std::vector<MemoryEntry>& Tempobj = pair.second; for (int i = pair.second.size() - 1; i >= 0; i--) { MemoryEntry Obj = pair.second.at(i); VOID* ObjAddr = Obj.Address; if (ReadProcessMemory(hProcess, ObjAddr, &Buffer, 1, nullptr)) { char a = Buffer[0]; char b = Pattern[0]; if (a != b) { //std::cout << "ModuleAddress: 0x" << std::hex << key << " Address: " << ObjAddr << " - Value: 0x" << std::hex << Obj.value << " Compared to: 0x" << (int)(Buffer[0]) << "\n"; Tempobj.erase(Tempobj.begin() + i); if (TotalADDRFound % 10000 == 0) { std::cout << "Removing ModuleAddress: 0x" << std::hex << key << " Address: " << ObjAddr << " - BeforeValue: 0x" << std::hex << Obj.value << " NowValue: 0x" << std::hex << (int)(Buffer[0]) << " Compared to: 0x" << int(Pattern[0]) << "\n"; std::cout << "LMemoryMap - Remaining: " << std::dec << (Tempobj.size() - i) << "/" << Tempobj.size() << " Address left to check:" << TotalADDRFound << std::endl; } TotalADDRFound -= 1; } else { //std::cout << "Keeping ModuleAddress: 0x" << std::hex << key << " Address: " << ObjAddr << " - BeforeValue: 0x" << std::hex << Obj.value << " NowValue: 0x" << std::hex << (int)(Buffer[0]) << " Compared to: 0x" << int(Pattern[0]) << "\n"; } } else { std::cout << "Unable to read from: " << Obj.Address << "\n"; } } } } void DumpMemory() { std::cout << "\r\nElements in GMemoryMap:\n"; long ItemCount = 0; long PageCount = 0; for (const auto& pair : GMemoryMap) { PageCount++; //MemoryModule key = pair.first; VOID* key = pair.first; std::vector<MemoryEntry> obj = pair.second; /* for (const auto& obj : GMemoryMap["key1"]) { std::cout << obj.value << "\n"; } */ for (const auto& myobj : obj) { //MemoryEntry Obj = pair.second.at(i); VOID* ObjAddr = myobj.Address; if (myobj.Bytevalue == NULL) { char buffer[1] = { 0 }; if (!ReadProcessMemory(hProcess, ObjAddr, &buffer, 1, nullptr)) { //Unable to get mem } std::cout << "ModuleAddress: 0x" << std::hex << key << " Address: " << myobj.Address << " - InCache:" << std::dec << myobj.value << " InMem: " << int(buffer[0]) << "\n"; } else { unsigned char * buffer = (unsigned char *)(malloc(myobj.value)); if (!ReadProcessMemory(hProcess, ObjAddr, buffer, myobj.value, nullptr)) { //Unable to get mem } std::cout << "ModuleAddress: 0x" << std::hex << key << " Address: " << myobj.Address << " - ByteLen:" << std::dec << myobj.value << "\n"; unsigned char * bytePtr = static_cast<unsigned char*>(myobj.Bytevalue); std::cout << "InCache: "; for (size_t i = 0; i < std::min<size_t>(16, myobj.value); i++) { std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(bytePtr[i]) << " "; } std::cout << std::endl; std::cout << "InMem : "; for (size_t i = 0; i < std::min<size_t>(16, myobj.value); i++) { std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(buffer[i]) << " "; } std::cout << std::endl; if (!WriteProcessMemory(hProcess, myobj.Bytevalue, (void *)buffer, 1, nullptr)) { std::cerr << "Failed to write memory at address: " << myobj.Bytevalue << std::endl; } else { std::cout << "Successfully updated " << myobj.value << " bytes from address " << ObjAddr << " to " << myobj.Bytevalue << std::endl; } free(buffer); } ItemCount++; } } //std::vector<MemoryEntry> Memory = GMemoryMap[1]; std::cout << std::endl << "LMemoryMap - PageCount:" << std::dec << PageCount << " ItemCount" << ItemCount << std::endl; } DWORD GetProcId(const wchar_t* procName) { DWORD procId = 0; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnap != INVALID_HANDLE_VALUE) { PROCESSENTRY32 procEntry; procEntry.dwSize = sizeof(procEntry); if (Process32First(hSnap, &procEntry)) { do { if (!_wcsicmp(procEntry.szExeFile, procName)) { procId = procEntry.th32ProcessID; break; } } while (Process32Next(hSnap, &procEntry)); } } CloseHandle(hSnap); return procId; } uintptr_t GetModuleBaseAddress(DWORD procID, const wchar_t* modName) { uintptr_t modBaseAddr = 0; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, procID); if (hSnap != INVALID_HANDLE_VALUE) { MODULEENTRY32 modEntry; modEntry.dwSize = sizeof(modEntry); if (Module32First(hSnap, &modEntry)) { do { if (!_wcsicmp(modEntry.szModule, modName)) { modBaseAddr = (uintptr_t)modEntry.modBaseAddr; break; } } while (Module32Next(hSnap, &modEntry)); } } CloseHandle(hSnap); return modBaseAddr; } uintptr_t FindDMAAddy(HANDLE hProc, uintptr_t ptr, std::vector<unsigned int> offsets) { uintptr_t addr = ptr; for (unsigned int i = 0; i < offsets.size(); ++i) { ReadProcessMemory(hProc, (BYTE*)addr, &addr, sizeof(addr), 0); addr += offsets[i]; } return addr; } int PrintModules(DWORD processID, HANDLE hProcess) { HMODULE hMods[1024]; DWORD cbNeeded; unsigned int i; // Print the process identifier. printf("\nProcess ID: %u\n", processID); // Get a list of all the modules in this process. if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) { for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) { TCHAR szModName[MAX_PATH]; // Get the full path to the module's file. if (GetModuleFileNameEx(hProcess, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR))) { // Print the module name and handle value. _tprintf(TEXT("\t%s (0x%08X)\n"), szModName, hMods[i]); } } } return 0; } void ResumeProcess(DWORD processId) { HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hSnapshot != INVALID_HANDLE_VALUE) { THREADENTRY32 te32; te32.dwSize = sizeof(THREADENTRY32); if (Thread32First(hSnapshot, &te32)) { do { if (te32.th32OwnerProcessID == processId) { HANDLE hThread = OpenThread(THREAD_SUSPEND_RESUME, FALSE, te32.th32ThreadID); if (hThread != NULL) { ResumeThread(hThread); CloseHandle(hThread); } } } while (Thread32Next(hSnapshot, &te32)); } CloseHandle(hSnapshot); } } void SuspendProcess(DWORD processId) { HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hSnapshot != INVALID_HANDLE_VALUE) { THREADENTRY32 te32; te32.dwSize = sizeof(THREADENTRY32); if (Thread32First(hSnapshot, &te32)) { do { if (te32.th32OwnerProcessID == processId) { HANDLE hThread = OpenThread(THREAD_SUSPEND_RESUME, FALSE, te32.th32ThreadID); if (hThread != NULL) { SuspendThread(hThread); CloseHandle(hThread); } } } while (Thread32Next(hSnapshot, &te32)); } CloseHandle(hSnapshot); } } /* std::ostream& operator<<(std::ostream& os, int b) { return os << std::bitset<8>(int(b)); } */ void DisplayHelp() { std::cout << R"( Available commands: - ProcessName: Set the process image name for memory scanning. - scanstring: Scan for a specified string in memory. - scan8: Scan for a specified int8 value in memory. - same: Check for unchanged memory regions since last scan. - changed: Check for changed memory regions since last scan. - watch: Start monitoring memory for changes. - dump: Print information about loaded modules and dump memory. - recentlyremoved: Display recently removed memory addresses. - clear: Clear the memory list. - suspend: Suspend the target process. - resume: Resume the target process. - writeunistring: Overwrite a Unicode string in memory. - writestring: Overwrite an ASCII string in memory. - wint: Write an integer value to memory. - scanandoverwrite: Scan for a pattern and overwrite it in memory. - help: Display available commands. - version: Display version information. - exit/quit: Exit the program. )" << std::endl; } void DisplayVersion() { std::cout << R"(1.0)" << std::endl; } bool stopFlag = false; void threadFunction() { while (true) { if (stopFlag) { break; } byte Buffer[1] = { 0 }; for (auto& pair : GMemoryMap) { if (stopFlag) { break; } VOID* key = pair.first; std::vector<MemoryEntry>& Tempobj = pair.second; for (int i = pair.second.size() - 1; i >= 0; i--) { if (stopFlag) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(50)); MemoryEntry & Obj = pair.second.at(i); VOID* ObjAddr = Obj.Address; if (ReadProcessMemory(hProcess, ObjAddr, &Buffer, 1, nullptr)) { char a = Buffer[0]; char b = Obj.value; if (a != b) { //std::cout << "ModuleAddress: 0x" << std::hex << key << " Address: " << ObjAddr << " - Value: 0x" << std::hex << Obj.value << " Compared to: 0x" << (int)(Buffer[0]) << "\n"; //Tempobj.erase(Tempobj.begin() + i); std::cout << "Watch found a value change @ ModuleAddress: 0x" << std::hex << key << " Address: " << ObjAddr << " - BeforeValue: 0x" << std::hex << Obj.value << " NowValue: 0x" << std::hex << (int)(Buffer[0]) << "\n"; Obj.value = Buffer[0]; //TotalADDRFound -= 1; } else { //std::cout << "Keeping ModuleAddress: 0x" << std::hex << key << " Address: " << ObjAddr << " - BeforeValue: 0x" << std::hex << Obj.value << " NowValue: 0x" << std::hex << (int)(Buffer[0]) << " Compared to: 0x" << int(Pattern[0]) << "\n"; } } else { std::cout << "Unable to read from: " << Obj.Address << "\n"; } } } if (stopFlag) { break; } } } std::thread t; void menu(const std::string& userInput) { /* std::vector<std::pair<std::intptr_t, std::vector<byte[]>>> MyArrayListOfAddresses; std::map<std::intptr_t, std::vector<byte[]>> MyDictionaryOfAddresses; std::map < std::intptr_t, std::pair < std::vector < byte[] >, std::vector<byte[] >> > MyArrayListOfAddressesRecentlyRemoved; */ std::intptr_t MyProcessId = 0; // Initialize with an appropriate value std::string ValueToSearchFor; std::string IntValue; int Scans = 1; if (userInput == "ProcessName") { std::string ProcessName; std::cout << "Process Image Name (ex. notepad.exe): "; std::getline(std::cin, ProcessName); //processId = GetProcId((const * wchar_t)ProcessName); hProcess = OpenProcess(PROCESS_ALL_ACCESS, NULL, processId); //MyArrayListOfAddresses.clear(); } else if (userInput == "scanstring") { std::cout << "string: "; std::getline(std::cin >> std::ws, ValueToSearchFor); //cin.getline(input, sizeof(input)); //std::cin >> ValueToSearchFor; try { std::vector<char> bytes(ValueToSearchFor.begin(), ValueToSearchFor.end()); bytes.push_back('\0'); char* c = &bytes[0]; int size = bytes.size(); ReadAllProcModules(processId, hProcess, (byte*)c, bytes.size() - 1); } catch (const std::invalid_argument& ex) { std::cerr << "Invalid input: " << ex.what() << std::endl; } catch (const std::out_of_range& ex) { std::cerr << "Out of range error: " << ex.what() << std::endl; } } else if (userInput == "scan8") { std::string param; std::cout << "int8: "; std::cin >> param; if (GMemoryMap.size() == 0) { try { int decimalValue = std::stoi(param); ReadAllProcModules(processId, hProcess, new byte[]{ (unsigned char)decimalValue }, 1); } catch (const std::invalid_argument& ex) { std::cerr << "Invalid input: " << ex.what() << std::endl; } catch (const std::out_of_range& ex) { std::cerr << "Out of range error: " << ex.what() << std::endl; } } else { try { int decimalValue = std::stoi(param); CheckAllRegisters(processId, hProcess, GMemoryMap, new byte[]{ (unsigned char)decimalValue }); } catch (const std::invalid_argument& ex) { std::cerr << "Invalid input: " << ex.what() << std::endl; } catch (const std::out_of_range& ex) { std::cerr << "Out of range error: " << ex.what() << std::endl; } } } else if (userInput == "same") { CheckChanged(processId, hProcess, GMemoryMap, true); } else if (userInput == "changed") { CheckChanged(processId, hProcess, GMemoryMap, false); } else if (userInput == "watch") { stopFlag = false; t = std::thread(threadFunction); } else if (userInput == "stopwatch") { stopFlag = true; } else if (userInput == "dump") { PrintModules(processId, hProcess); DumpMemory(); } else if (userInput == "recentlyremoved") { /* for (const auto& entry : MyArrayListOfAddressesRecentlyRemoved) { //std::cout << std::hex << entry.first << std::endl; std::cout << "BEFORE: "; for (const auto& byteValue : entry.second.first) { //std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(byteValue) << " "; } std::cout << std::endl; std::cout << "AFTER: "; for (const auto& byteValue : entry.second.second) { //std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(byteValue) << " "; } std::cout << std::endl << std::endl; } */ } else if (userInput == "clear") { std::cout << "Memory list cleared" << std::endl; GMemoryMap.clear(); } else if (userInput == "suspend") { SuspendProcess(processId); } else if (userInput == "resume") { ResumeProcess(processId); } else if (userInput == "writeunistring") { // DotNetMemoryScan find_aob; std::string param; std::cout << "Overwrite unistring: "; //std::getline(std::cin, param); //int decimalValue = std::stoi(param); //std::cin >> param; /* for (const auto& MyAddress : MyArrayListOfAddresses) { if (MyAddress.first > 0) { //std::cout << "[scan_all 1] result 0x" << std::hex << std::setw(16) << std::setfill('0') << MyAddress.first << std::endl; // std::cout << "Bytes written: " << find_aob.write_mem(MyProcess, MyAddress.first, ValueToWrite) << std::endl; } } */ } else if (userInput == "writestring") { // DotNetMemoryScan find_aob; std::string ValueToWrite; std::cout << "Overwrite Asciistring: "; std::getline(std::cin >> std::ws, ValueToSearchFor); try { int Lengthofbuffer = ValueToSearchFor.length(); void * buffer = malloc(ValueToSearchFor.length()); for (const auto& pair : GMemoryMap) { //MemoryModule key = pair.first; VOID* key = pair.first; std::vector<MemoryEntry> obj = pair.second; for (const auto& myobj : obj) { VOID* ObjAddr = myobj.Address; if (!ReadProcessMemory(hProcess, ObjAddr, buffer, Lengthofbuffer, nullptr)) { } SIZE_T bytesWritten = 0; if (!WriteProcessMemory(hProcess, ObjAddr, ValueToWrite.c_str(), ValueToWrite.size(), &bytesWritten)) { std::cerr << "Failed to write memory at address: " << ObjAddr << std::endl; } else { std::cout << "Successfully wrote " << bytesWritten << " bytes to address: " << ObjAddr << std::endl; } std::cout << "Written ModuleAddress: 0x" << std::hex << key << " Address: " << myobj.Address << " - InCache:" << std::dec << myobj.value << " beforeInMem: " << (char *)buffer << " nowInMem: " << ValueToSearchFor << "\n"; for (size_t i = 0; i < Lengthofbuffer; ++i) { //std::cout << static_cast<int>(buffer[i]) << " "; } } } free(buffer); } catch (const std::invalid_argument& ex) { std::cerr << "Invalid input: " << ex.what() << std::endl; } catch (const std::out_of_range& ex) { std::cerr << "Out of range error: " << ex.what() << std::endl; } catch (const std::exception& ex) { std::cerr << "Error: " << ex.what() << std::endl; } } else if (userInput == "wint") { std::string param; std::cout << "value to write: "; std::cin >> param; //std::getline(std::cin, param); int decimalValue = std::stoi(param); char buffer[1] = { 0 }; char bufferToWrite[1] = { decimalValue }; for (const auto& pair : GMemoryMap) { //MemoryModule key = pair.first; VOID* key = pair.first; std::vector<MemoryEntry> obj = pair.second; for (const auto& myobj : obj) { VOID* ObjAddr = myobj.Address; if (!ReadProcessMemory(hProcess, ObjAddr, &buffer, 1, nullptr)) { } if (!WriteProcessMemory(hProcess, ObjAddr, &bufferToWrite, 1, nullptr)) { //Unable to get mem } std::cout << "Written ModuleAddress: 0x" << std::hex << key << " Address: " << myobj.Address << " - InCache:" << std::dec << myobj.value << " beforeInMem: " << int(buffer[0]) << " nowInMem: " << decimalValue << "\n"; } } } else if (userInput == "scanandoverwrite") { std::string OverwriteString; std::cout << "Overwrite string: "; std::getline(std::cin, OverwriteString); // OverwriteAllBytePattens(MyProcess.ProcessName, ConvertStringToUniByteString(OverwriteString), ConvertStringToUniByteString(ValueToSearchFor)); } else if (userInput == "help") { DisplayHelp(); } else if (userInput == "version") { DisplayVersion(); } else if (userInput == "exit" || userInput == "quit") { exit(0); } else { std::cout << "Unrecognized command. Type 'help' for available commands." << std::endl; } } int main() { std::cout << "Starting!\nEnter 'help' for commands\r\n"; HANDLE currentToken; OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, ¤tToken); if (!SetPrivilege(currentToken, SE_DEBUG_NAME, TRUE)) { std::cout << "Unable to adjust privileges" << std::endl; } //HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId); processId = GetProcId(ProcName); hProcess = OpenProcess(PROCESS_ALL_ACCESS, NULL, processId); std::string input; while (true) { std::cout << ">"; std::cin >> input; menu(input); } /* std::cout << "Press Any Key to continue:\n"; getchar(); */ // Close the process handle CloseHandle(hProcess); return 0; } |
Modifying a VB dictionary by ref
When the requirement of modifying data passed to a function, setting the type of the object to a Class will always pass ByRef in visual basic, however, swapping to a “structure” will make such values read-only after setting and the values will be unassignable.
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 |
Module Module1 Public Class Myclass 'Change to structure and review the debug output for the difference. Public Test As Boolean Public Sub Disabled() Test = False End Sub End Class Public MyDictionary As New Dictionary(Of Int16, Myclass) Sub Main() Dim MyTempClass As New Myclass MyTempClass.Test = True For i = 0 To 10 MyDictionary.Add(i, MyTempClass) Next MyFunc(MyDictionary) For Each MyTest In MyDictionary MyTest.Value.Disabled() Next For i = 0 To MyDictionary.Count - 1 MyDictionary(i).Disabled() Next Dim MyNewClass = New Myclass MyNewClass.Test = True MyDictionary(2) = MyNewClass For Each MyTest In MyDictionary Debug.WriteLine(MyTest.Value.Test) Next End Sub Private Sub MyFunc(ByRef MyDic As Dictionary(Of Int16, Myclass)) For Each MyTest In MyDic MyTest.Value.Disabled() Next For Each MyTest In MyDic Debug.WriteLine(MyTest.Value.Test) Next End Sub End Module |
VB.NET Memory Management Example
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); } } |