handle_hooks_win.cc 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. // Copyright 2015 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/debug/handle_hooks_win.h"
  5. #include <windows.h>
  6. #include <psapi.h>
  7. #include <stddef.h>
  8. #include "base/logging.h"
  9. #include "base/memory/raw_ptr.h"
  10. #include "base/numerics/safe_conversions.h"
  11. #include "base/win/iat_patch_function.h"
  12. #include "base/win/pe_image.h"
  13. #include "base/win/scoped_handle.h"
  14. #include "build/build_config.h"
  15. namespace {
  16. using CloseHandleType = decltype(&::CloseHandle);
  17. using DuplicateHandleType = decltype(&::DuplicateHandle);
  18. CloseHandleType g_close_function = nullptr;
  19. DuplicateHandleType g_duplicate_function = nullptr;
  20. // The entry point for CloseHandle interception. This function notifies the
  21. // verifier about the handle that is being closed, and calls the original
  22. // function.
  23. BOOL WINAPI CloseHandleHook(HANDLE handle) {
  24. base::win::OnHandleBeingClosed(handle,
  25. base::win::HandleOperation::kCloseHandleHook);
  26. return g_close_function(handle);
  27. }
  28. BOOL WINAPI DuplicateHandleHook(HANDLE source_process,
  29. HANDLE source_handle,
  30. HANDLE target_process,
  31. HANDLE* target_handle,
  32. DWORD desired_access,
  33. BOOL inherit_handle,
  34. DWORD options) {
  35. if ((options & DUPLICATE_CLOSE_SOURCE) &&
  36. (GetProcessId(source_process) == ::GetCurrentProcessId())) {
  37. base::win::OnHandleBeingClosed(
  38. source_handle, base::win::HandleOperation::kDuplicateHandleHook);
  39. }
  40. return g_duplicate_function(source_process, source_handle, target_process,
  41. target_handle, desired_access, inherit_handle,
  42. options);
  43. }
  44. } // namespace
  45. namespace base {
  46. namespace debug {
  47. namespace {
  48. // Provides a simple way to temporarily change the protection of a memory page.
  49. class AutoProtectMemory {
  50. public:
  51. AutoProtectMemory()
  52. : changed_(false), address_(nullptr), bytes_(0), old_protect_(0) {}
  53. AutoProtectMemory(const AutoProtectMemory&) = delete;
  54. AutoProtectMemory& operator=(const AutoProtectMemory&) = delete;
  55. ~AutoProtectMemory() { RevertProtection(); }
  56. // Grants write access to a given memory range.
  57. bool ChangeProtection(void* address, size_t bytes);
  58. // Restores the original page protection.
  59. void RevertProtection();
  60. private:
  61. bool changed_;
  62. raw_ptr<void> address_;
  63. size_t bytes_;
  64. DWORD old_protect_;
  65. };
  66. bool AutoProtectMemory::ChangeProtection(void* address, size_t bytes) {
  67. DCHECK(!changed_);
  68. DCHECK(address);
  69. // Change the page protection so that we can write.
  70. MEMORY_BASIC_INFORMATION memory_info;
  71. if (!VirtualQuery(address, &memory_info, sizeof(memory_info)))
  72. return false;
  73. DWORD is_executable = (PAGE_EXECUTE | PAGE_EXECUTE_READ |
  74. PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY) &
  75. memory_info.Protect;
  76. DWORD protect = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
  77. if (!VirtualProtect(address, bytes, protect, &old_protect_))
  78. return false;
  79. changed_ = true;
  80. address_ = address;
  81. bytes_ = bytes;
  82. return true;
  83. }
  84. void AutoProtectMemory::RevertProtection() {
  85. if (!changed_)
  86. return;
  87. DCHECK(address_);
  88. DCHECK(bytes_);
  89. VirtualProtect(address_, bytes_, old_protect_, &old_protect_);
  90. changed_ = false;
  91. address_ = nullptr;
  92. bytes_ = 0;
  93. old_protect_ = 0;
  94. }
  95. #if defined(ARCH_CPU_32_BITS)
  96. // Performs an EAT interception. Only supported on 32-bit.
  97. void EATPatch(HMODULE module,
  98. const char* function_name,
  99. void* new_function,
  100. void** old_function) {
  101. if (!module)
  102. return;
  103. base::win::PEImage pe(module);
  104. if (!pe.VerifyMagic())
  105. return;
  106. DWORD* eat_entry = pe.GetExportEntry(function_name);
  107. if (!eat_entry)
  108. return;
  109. if (!(*old_function))
  110. *old_function = pe.RVAToAddr(*eat_entry);
  111. AutoProtectMemory memory;
  112. if (!memory.ChangeProtection(eat_entry, sizeof(DWORD)))
  113. return;
  114. // Perform the patch.
  115. *eat_entry =
  116. base::checked_cast<DWORD>(reinterpret_cast<uintptr_t>(new_function) -
  117. reinterpret_cast<uintptr_t>(module));
  118. }
  119. #endif // defined(ARCH_CPU_32_BITS)
  120. // Performs an IAT interception.
  121. std::unique_ptr<base::win::IATPatchFunction> IATPatch(HMODULE module,
  122. const char* function_name,
  123. void* new_function,
  124. void** old_function) {
  125. if (!module)
  126. return nullptr;
  127. auto patch = std::make_unique<base::win::IATPatchFunction>();
  128. __try {
  129. // There is no guarantee that |module| is still loaded at this point.
  130. if (patch->PatchFromModule(module, "kernel32.dll", function_name,
  131. new_function)) {
  132. return nullptr;
  133. }
  134. } __except ((GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ||
  135. GetExceptionCode() == EXCEPTION_GUARD_PAGE ||
  136. GetExceptionCode() == EXCEPTION_IN_PAGE_ERROR)
  137. ? EXCEPTION_EXECUTE_HANDLER
  138. : EXCEPTION_CONTINUE_SEARCH) {
  139. // Leak the patch.
  140. std::ignore = patch.release();
  141. return nullptr;
  142. }
  143. if (!(*old_function)) {
  144. // Things are probably messed up if each intercepted function points to
  145. // a different place, but we need only one function to call.
  146. *old_function = patch->original_function();
  147. }
  148. return patch;
  149. }
  150. } // namespace
  151. // static
  152. void HandleHooks::AddIATPatch(HMODULE module) {
  153. if (!module)
  154. return;
  155. auto close_handle_patch =
  156. IATPatch(module, "CloseHandle", reinterpret_cast<void*>(&CloseHandleHook),
  157. reinterpret_cast<void**>(&g_close_function));
  158. if (!close_handle_patch)
  159. return;
  160. // This is intentionally leaked.
  161. std::ignore = close_handle_patch.release();
  162. auto duplicate_handle_patch = IATPatch(
  163. module, "DuplicateHandle", reinterpret_cast<void*>(&DuplicateHandleHook),
  164. reinterpret_cast<void**>(&g_duplicate_function));
  165. if (!duplicate_handle_patch)
  166. return;
  167. // This is intentionally leaked.
  168. std::ignore = duplicate_handle_patch.release();
  169. }
  170. #if defined(ARCH_CPU_32_BITS)
  171. // static
  172. void HandleHooks::AddEATPatch() {
  173. // An attempt to restore the entry on the table at destruction is not safe.
  174. EATPatch(GetModuleHandleA("kernel32.dll"), "CloseHandle",
  175. reinterpret_cast<void*>(&CloseHandleHook),
  176. reinterpret_cast<void**>(&g_close_function));
  177. EATPatch(GetModuleHandleA("kernel32.dll"), "DuplicateHandle",
  178. reinterpret_cast<void*>(&DuplicateHandleHook),
  179. reinterpret_cast<void**>(&g_duplicate_function));
  180. }
  181. #endif // defined(ARCH_CPU_32_BITS)
  182. // static
  183. void HandleHooks::PatchLoadedModules() {
  184. const DWORD kSize = 256;
  185. DWORD returned;
  186. auto modules = std::make_unique<HMODULE[]>(kSize);
  187. if (!::EnumProcessModules(GetCurrentProcess(), modules.get(),
  188. kSize * sizeof(HMODULE), &returned)) {
  189. return;
  190. }
  191. returned /= sizeof(HMODULE);
  192. returned = std::min(kSize, returned);
  193. for (DWORD current = 0; current < returned; current++) {
  194. AddIATPatch(modules[current]);
  195. }
  196. }
  197. } // namespace debug
  198. } // namespace base