他人の空似自作物置場

ArbitraryCodeGuard.zip/4/Attacker/Attacker.cpp


#include <iostream>

#include <Windows.h>
#include <memoryapi.h>
#include <Tlhelp32.h>

DWORD findProcess(const std::string filename) {
   HANDLE snapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
   PROCESSENTRY32 entry;
   entry.dwSize = sizeof(entry);
   ::Process32First(snapshot, &entry);
   do {
      if (filename == entry.szExeFile) {
         ::CloseHandle(snapshot);
         return entry.th32ProcessID;
      }
   } while (::Process32Next(snapshot, &entry));
   ::CloseHandle(snapshot);
   return 0;
}

void write(HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesWritten) {
   ::WriteProcessMemory(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesWritten);
}

void* alloc(HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) {
   return ::VirtualAllocEx(hProcess, lpAddress, dwSize, flAllocationType, flProtect);
}

bool run(const DWORD processId) {
   if (processId == 0) {
      return false;
   }

   unsigned char code[] = {
      0x68, 0x00, 0x00, 0x00, 0x00, // PUSH 0x00000000(PUSH &"dll.dll")
      0x68, 0x00, 0x00, 0x00, 0x00, // PUSH 0x00000000(PUSH &::LoadLibraryA)
      0x58, // POP EAX
      0xFF, 0xD0, // JMP EAX
      0xC3, // RETN
   };
   const char dllName[] = "dll.dll";
   *reinterpret_cast<void**>(&code[6]) = &::LoadLibraryA;
   const HANDLE process = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
   void* dllNameAddress = ::VirtualAllocEx(process, nullptr, sizeof(dllName), MEM_COMMIT, PAGE_READWRITE);
   if (dllNameAddress == nullptr) {
      return false;
   }
   *reinterpret_cast<void**>(&code[1]) = dllNameAddress;
   write(process, dllNameAddress, dllName, sizeof(dllName), nullptr);
   void* codeAddress = ::VirtualAllocEx(process, nullptr, sizeof(code), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
   if (codeAddress == nullptr) {
      return false;
   }
   write(process, codeAddress, code, sizeof(code), nullptr);
   ::CreateRemoteThread(process, nullptr, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(codeAddress), nullptr, 0, nullptr);
   return true;
}

void enableACG() {
   PROCESS_MITIGATION_DYNAMIC_CODE_POLICY policy;
   policy.Flags = 0;
   policy.ProhibitDynamicCode = 0x01;
   policy.ReservedFlags = 0;
   ::SetProcessMitigationPolicy(ProcessDynamicCodePolicy, &policy, sizeof(policy));
}

void disableACG() {
   PROCESS_MITIGATION_DYNAMIC_CODE_POLICY policy;
   policy.Flags = 0;
   policy.ProhibitDynamicCode = 0x00;
   policy.ReservedFlags = 0;
   ::SetProcessMitigationPolicy(ProcessDynamicCodePolicy, &policy, sizeof(policy));
}

int main() {
   enableACG();
   disableACG();
   if (!run(findProcess("Target.exe"))) {
      std::cout << "Failure\n";
   } else {
      std::cout << "Success\n";
   }
   std::cin.get();
   return 0;
}