Advertisement
Guest User

Untitled

a guest
Jul 15th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 6.40 KB | None | 0 0
  1. /*
  2.     g++ main.cpp -o main.exe --std=c++11
  3. */
  4. #include <windows.h>
  5. #include <tlhelp32.h>
  6. #include <iostream>
  7. #include <vector>
  8. #include <fstream>
  9.  
  10. using namespace std;
  11.  
  12. typedef vector<char> Memory;
  13. typedef vector<Memory> Memories;
  14.  
  15. /*
  16.     OpenProcessToken:
  17.         BOOL WINAPI OpenProcessToken(
  18.           _In_  HANDLE  ProcessHandle,
  19.           _In_  DWORD   DesiredAccess,
  20.           _Out_ PHANDLE TokenHandle
  21.         );
  22.        
  23.         DesiredAccess:
  24.             Options:
  25.                 TOKEN_ADJUST_DEFAULT
  26.                 TOKEN_ADJUST_GROUPS
  27.                 TOKEN_ADJUST_PRIVILEGES
  28.                 TOKEN_ADJUST_SESSIONID
  29.                 TOKEN_ASSIGN_PRIMARY
  30.                 TOKEN_DUPLICATE
  31.                 TOKEN_EXECUTE
  32.                 TOKEN_IMPERSONATE
  33.                 TOKEN_QUERY
  34.                 TOKEN_QUERY_SOURCE
  35.                 TOKEN_READ
  36.                 TOKEN_WRITE
  37.                 TOKEN_ALL_ACCESS
  38.            
  39.             Reference:
  40.                 https://docs.microsoft.com/en-us/windows/desktop/SecAuthZ/access-rights-for-access-token-objects
  41.        
  42.         Reference:
  43.             https://msdn.microsoft.com/en-us/library/Aa379295(v=VS.85).aspx
  44.    
  45.     LookupPrivilegeValue:
  46.         BOOL LookupPrivilegeValueA(
  47.             LPCSTR lpSystemName,
  48.             LPCSTR lpName,
  49.             PLUID  lpLuid
  50.         );
  51.        
  52.         Reference:
  53.             https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-lookupprivilegevaluea
  54.    
  55.     AdjustTokenPrivileges:
  56.         BOOL WINAPI AdjustTokenPrivileges(
  57.           _In_      HANDLE            TokenHandle,
  58.           _In_      BOOL              DisableAllPrivileges,
  59.           _In_opt_  PTOKEN_PRIVILEGES NewState,
  60.           _In_      DWORD             BufferLength,
  61.           _Out_opt_ PTOKEN_PRIVILEGES PreviousState,
  62.           _Out_opt_ PDWORD            ReturnLength
  63.         );
  64.        
  65.         Reference:
  66.             https://msdn.microsoft.com/en-us/library/windows/desktop/aa375202(v=vs.85).aspx
  67.    
  68.     TOKEN_PRIVILEGES:
  69.         PrivilegeCount:
  70.             This must be set to the number of entries in the Privileges array.
  71.        
  72.         Privileges:
  73.             Options:
  74.                 SE_PRIVILEGE_ENABLED
  75.                 SE_PRIVILEGE_ENABLED_BY_DEFAULT
  76.                 SE_PRIVILEGE_REMOVED
  77.                 SE_PRIVILEGE_USED_FOR_ACCESS
  78.        
  79.         Reference:
  80.             https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_token_privileges
  81.    
  82.     MEMORY_BASIC_INFORMATION:
  83.         BaseAddress
  84.        
  85.         AllocationBase
  86.        
  87.         AllocationProtect:
  88.             The memory protection option when the region was initially allocated.
  89.             This member can be one of the memory protection constants or 0 if the caller does not have access.
  90.        
  91.         RegionSize:
  92.        
  93.         State:
  94.             Options:
  95.                 MEM_COMMIT
  96.                 MEM_FREE
  97.                 MEM_RESERVE
  98.            
  99.         Protect:
  100.             The access protection of the pages in the region. This member is one of the values listed for the AllocationProtect member.
  101.            
  102.         Type:
  103.             Options:
  104.                 MEM_IMAGE
  105.                 MEM_MAPPED
  106.                 MEM_PRIVATE
  107.        
  108.         Reference:
  109.             https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_memory_basic_information
  110. */
  111.  
  112. string getLastErrorAsString() {
  113.     //Get the error message, if any.
  114.     DWORD errorMessageID = ::GetLastError();
  115.    
  116.     if(errorMessageID == 0)
  117.         return std::string(); //No error message has been recorded
  118.  
  119.     LPSTR messageBuffer = nullptr;
  120.     size_t size = FormatMessageA(
  121.         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  122.         NULL,
  123.         errorMessageID,
  124.         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  125.         (LPSTR)&messageBuffer,
  126.         0,
  127.         NULL
  128.     );
  129.  
  130.     string message(messageBuffer, size);
  131.  
  132.     //Free the buffer.
  133.     LocalFree(messageBuffer);
  134.  
  135.     return message;
  136. }
  137.  
  138. /*
  139.     Enables Debug Privilages to the current process
  140. */
  141. bool enableDebugPriv() {
  142.     HANDLE hToken;
  143.     LUID luid;
  144.     TOKEN_PRIVILEGES tkp;
  145.    
  146.     if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
  147.         if(LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid)) {
  148.             tkp.PrivilegeCount = 1;
  149.             tkp.Privileges[0].Luid = luid;
  150.             tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  151.  
  152.             if(AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL) == 0)
  153.                 return false;
  154.         }
  155.         else
  156.             return false;
  157.            
  158.         CloseHandle(hToken);
  159.     }
  160.     else
  161.         return false;
  162.    
  163.     return true;
  164. }
  165.  
  166. /*
  167.     Collect all memory areas
  168. */
  169. Memories getAllMemories(HANDLE process) {
  170.     unsigned char *p;
  171.     MEMORY_BASIC_INFORMATION info;
  172.     Memory memory;
  173.     Memories memories;
  174.    
  175.     #if defined(_M_X64) || defined(__amd64__)
  176.         size_t bytes_read;
  177.     #else
  178.         DWORD bytes_read;
  179.     #endif
  180.    
  181.     for(p = NULL; VirtualQueryEx(process, p, &info, sizeof(info)) == sizeof(info); p += info.RegionSize) {
  182.         if(info.AllocationProtect >= PAGE_READONLY) {
  183.             memory.resize(info.RegionSize);
  184.  
  185.             if(ReadProcessMemory(process, p, &memory[0], info.RegionSize, &bytes_read)) {
  186.                 memory.resize(bytes_read);
  187.  
  188.                 memories.push_back(memory);
  189.             }
  190.         }
  191.     }
  192.  
  193.     return memories;
  194. }
  195.  
  196. /*
  197.     Get Process by name
  198. */
  199. HANDLE getProcessByName(string name) {
  200.     HANDLE snapshot, process;
  201.     PROCESSENTRY32 entry;
  202.    
  203.     // Patch entry size
  204.     entry.dwSize = sizeof(PROCESSENTRY32);
  205.    
  206.     // Enable debug mode
  207.     if(!enableDebugPriv())
  208.         return NULL;
  209.    
  210.     // Create snapshot
  211.     snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  212.     if(snapshot == INVALID_HANDLE_VALUE)
  213.         return NULL;
  214.    
  215.     if(Process32First(snapshot, &entry) == TRUE) {
  216.         // Loop Processes
  217.         while(Process32Next(snapshot, &entry) == TRUE) {
  218.             // Check executable name
  219.             if(strcmp(entry.szExeFile, name.c_str()) == 0) {  
  220.                 // Open process
  221.                 return OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
  222.             }
  223.         }
  224.     }
  225.    
  226.     CloseHandle(snapshot);
  227.    
  228.     return NULL;
  229. }
  230.  
  231. void saveMemories(string process_name, Memories &m) {
  232.     int i;
  233.     string folder, file_path;
  234.     ofstream outfile;
  235.    
  236.     //Init
  237.     folder = "memories/" + process_name;
  238.    
  239.     // Create folder
  240.     CreateDirectory(folder.c_str(), NULL);
  241.    
  242.     // Loop through memories
  243.     for(i = 0; i < m.size(); i++) {
  244.         // Generate file path
  245.         file_path = folder + "/" + to_string(i) + ".data";
  246.        
  247.         // Open file
  248.         outfile.open(file_path.c_str(), std::ofstream::binary);
  249.        
  250.         if(!outfile.fail()) {
  251.             // Save data
  252.             outfile.write((char*)&m[i][0], m[i].size());
  253.            
  254.             // Close file
  255.             outfile.close();
  256.         }
  257.     }
  258. }
  259.  
  260. int main() {
  261.     string process_name;
  262.     Memories m;
  263.     HANDLE p;
  264.    
  265.     // Init
  266.     //process_name = "main.exe";
  267.     process_name = "explorer.exe";
  268.    
  269.     // Get process
  270.     p = getProcessByName(process_name);
  271.     if(p) {
  272.         // Collect memories
  273.         m = getAllMemories(p);
  274.        
  275.         // Save memories
  276.         saveMemories(process_name, m);
  277.        
  278.         // Show total memory pages collected
  279.         cout << "Saved " << m.size() << " memories" << endl;
  280.        
  281.         // Close process
  282.         CloseHandle(p);
  283.     }
  284.     else
  285.         cout << getLastErrorAsString() << endl;
  286.    
  287.     return 0;
  288. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement