process_mitigations_extensionpoints_unittest.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. // Copyright 2017 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 "sandbox/win/src/process_mitigations.h"
  5. #include <windows.h>
  6. #include <psapi.h>
  7. #include "base/scoped_native_library.h"
  8. #include "base/win/registry.h"
  9. #include "base/win/startup_information.h"
  10. #include "base/win/win_util.h"
  11. #include "base/win/windows_version.h"
  12. #include "sandbox/win/tests/common/controller.h"
  13. #include "sandbox/win/tests/integration_tests/hooking_dll.h"
  14. #include "sandbox/win/tests/integration_tests/hooking_win_proc.h"
  15. #include "sandbox/win/tests/integration_tests/integration_tests_common.h"
  16. #include "testing/gtest/include/gtest/gtest.h"
  17. namespace {
  18. //------------------------------------------------------------------------------
  19. // Internal Defines & Functions
  20. //------------------------------------------------------------------------------
  21. // hooking_dll defines
  22. using WasHookCalledFunction = decltype(&hooking_dll::WasHookCalled);
  23. using SetHookFunction = decltype(&hooking_dll::SetHook);
  24. constexpr char g_hook_handler_func[] = "HookProc";
  25. constexpr char g_was_hook_called_func[] = "WasHookCalled";
  26. constexpr char g_set_hook_func[] = "SetHook";
  27. // System mutex to prevent conflicting tests from running at the same time.
  28. const wchar_t g_extension_point_test_mutex[] = L"ChromeExtensionTestMutex";
  29. //------------------------------------------------------------------------------
  30. // ExtensionPoint test helper function.
  31. //
  32. // Spawn Windows process (with or without mitigation enabled).
  33. //------------------------------------------------------------------------------
  34. bool SpawnWinProc(PROCESS_INFORMATION* pi, bool success_test, HANDLE* event) {
  35. base::win::StartupInformation startup_info;
  36. DWORD creation_flags = 0;
  37. if (!success_test) {
  38. DWORD64 flags =
  39. PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_ON;
  40. // This test only runs on >= Win8, so don't have to handle
  41. // illegal 64-bit flags on 32-bit <= Win7.
  42. size_t flags_size = sizeof(flags);
  43. if (!startup_info.InitializeProcThreadAttributeList(1) ||
  44. !startup_info.UpdateProcThreadAttribute(
  45. PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY, &flags, flags_size)) {
  46. ADD_FAILURE();
  47. return false;
  48. }
  49. creation_flags = EXTENDED_STARTUPINFO_PRESENT;
  50. }
  51. // Command line must be writable.
  52. std::wstring cmd_writeable(hooking_win_proc::g_winproc_file);
  53. if (!::CreateProcessW(nullptr, &cmd_writeable[0], nullptr, nullptr, false,
  54. creation_flags, nullptr, nullptr,
  55. startup_info.startup_info(), pi)) {
  56. ADD_FAILURE();
  57. return false;
  58. }
  59. EXPECT_EQ(WAIT_OBJECT_0,
  60. ::WaitForSingleObject(*event, sandbox::SboxTestEventTimeout()));
  61. return true;
  62. }
  63. //------------------------------------------------------------------------------
  64. // ExtensionPoint test helper function.
  65. //
  66. // 1. Spawn a Windows process (with or without mitigation enabled).
  67. // 2. Load the hook Dll locally.
  68. // 3. Create a global named event for the hook to trigger.
  69. // 4. Start the hook (for the specific WinProc or globally).
  70. // 5. Send a keystroke event.
  71. // 6. Ask the hook Dll if it received a hook callback.
  72. // 7. Cleanup the hooking.
  73. // 8. Signal the Windows process to shutdown.
  74. //
  75. // Do NOT use any ASSERTs in this function. Cleanup required.
  76. //------------------------------------------------------------------------------
  77. void TestWin8ExtensionPointHookWrapper(bool is_success_test, bool global_hook) {
  78. // Set up a couple global events that this test will use.
  79. HANDLE winproc_event =
  80. ::CreateEventW(nullptr, false, false, hooking_win_proc::g_winproc_event);
  81. if (!winproc_event) {
  82. ADD_FAILURE();
  83. return;
  84. }
  85. base::win::ScopedHandle scoped_winproc_event(winproc_event);
  86. HANDLE hook_event =
  87. ::CreateEventW(nullptr, false, false, hooking_dll::g_hook_event);
  88. if (!hook_event) {
  89. ADD_FAILURE();
  90. return;
  91. }
  92. base::win::ScopedHandle scoped_hook_event(hook_event);
  93. // 1. Spawn WinProc.
  94. PROCESS_INFORMATION proc_info = {};
  95. if (!SpawnWinProc(&proc_info, is_success_test, &winproc_event))
  96. return;
  97. // From this point on, no return on failure. Cleanup required.
  98. bool all_good = true;
  99. // 2. Load the hook DLL.
  100. base::FilePath hook_dll_path(hooking_dll::g_hook_dll_file);
  101. base::ScopedNativeLibrary dll(hook_dll_path);
  102. EXPECT_TRUE(dll.is_valid());
  103. HOOKPROC hook_proc =
  104. reinterpret_cast<HOOKPROC>(dll.GetFunctionPointer(g_hook_handler_func));
  105. WasHookCalledFunction was_hook_called =
  106. reinterpret_cast<WasHookCalledFunction>(
  107. dll.GetFunctionPointer(g_was_hook_called_func));
  108. SetHookFunction set_hook = reinterpret_cast<SetHookFunction>(
  109. dll.GetFunctionPointer(g_set_hook_func));
  110. if (!hook_proc || !was_hook_called || !set_hook) {
  111. ADD_FAILURE();
  112. all_good = false;
  113. }
  114. // 3. Try installing the hook (either on a remote target thread,
  115. // or globally).
  116. HHOOK hook = nullptr;
  117. if (all_good) {
  118. DWORD target = 0;
  119. if (!global_hook)
  120. target = proc_info.dwThreadId;
  121. hook = ::SetWindowsHookExW(WH_KEYBOARD, hook_proc, dll.get(), target);
  122. if (!hook) {
  123. ADD_FAILURE();
  124. all_good = false;
  125. } else
  126. // Pass the hook DLL the hook handle.
  127. set_hook(hook);
  128. }
  129. // 4. Inject a keyboard event.
  130. if (all_good) {
  131. // Note: that PostThreadMessage and SendMessage APIs will not deliver
  132. // a keystroke in such a way that triggers a "legitimate" hook.
  133. // Have to use targetless SendInput or keybd_event. The latter is
  134. // less code and easier to work with.
  135. keybd_event(VkKeyScan(L'A'), 0, 0, 0);
  136. keybd_event(VkKeyScan(L'A'), 0, KEYEVENTF_KEYUP, 0);
  137. // Give it a chance to hit the hook handler...
  138. ::WaitForSingleObject(hook_event, sandbox::SboxTestEventTimeout());
  139. // 5. Did the hook get hit? Was it expected to?
  140. if (global_hook)
  141. EXPECT_EQ((is_success_test ? true : false), was_hook_called());
  142. else
  143. // ***IMPORTANT: when targeting a specific thread id, the
  144. // PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE
  145. // mitigation does NOT disable the hook API. It ONLY
  146. // stops global hooks from running in a process. Hence,
  147. // the hook will hit (true) even in the "failure"
  148. // case for a non-global/targeted hook.
  149. EXPECT_EQ((is_success_test ? true : true), was_hook_called());
  150. }
  151. // 6. Disable hook.
  152. if (hook)
  153. EXPECT_TRUE(::UnhookWindowsHookEx(hook));
  154. // 7. Trigger shutdown of WinProc.
  155. if (proc_info.hProcess) {
  156. if (::PostThreadMessageW(proc_info.dwThreadId, WM_QUIT, 0, 0)) {
  157. // Note: The combination/perfect-storm of a Global Hook, in a
  158. // WinProc that has the EXTENSION_POINT_DISABLE mitigation ON, and the
  159. // use of the SendInput or keybd_event API to inject a keystroke,
  160. // results in the target becoming unresponsive. If any one of these
  161. // states are changed, the problem does not occur. This means the WM_QUIT
  162. // message is not handled and the call to WaitForSingleObject times out.
  163. // Therefore not checking the return val.
  164. ::WaitForSingleObject(winproc_event, sandbox::SboxTestEventTimeout());
  165. } else {
  166. // Ensure no strays.
  167. ::TerminateProcess(proc_info.hProcess, 0);
  168. ADD_FAILURE();
  169. }
  170. EXPECT_TRUE(::CloseHandle(proc_info.hThread));
  171. EXPECT_TRUE(::CloseHandle(proc_info.hProcess));
  172. }
  173. }
  174. //------------------------------------------------------------------------------
  175. // ExtensionPoint test helper function.
  176. //
  177. // 1. Set up the AppInit Dll in registry settings. (Enable)
  178. // 2. Spawn a Windows process (with or without mitigation enabled).
  179. // 3. Check if the AppInit Dll got loaded in the Windows process or not.
  180. // 4. Signal the Windows process to shutdown.
  181. // 5. Restore original reg settings.
  182. //
  183. // Do NOT use any ASSERTs in this function. Cleanup required.
  184. //------------------------------------------------------------------------------
  185. void TestWin8ExtensionPointAppInitWrapper(bool is_success_test) {
  186. // 0.5 Get path of current module. The appropriate build of the
  187. // AppInit DLL will be in the same directory (and the
  188. // full path is needed for reg).
  189. wchar_t path[MAX_PATH];
  190. if (!::GetModuleFileNameW(nullptr, path, MAX_PATH)) {
  191. ADD_FAILURE();
  192. return;
  193. }
  194. // Only want the directory. Switch file name for the AppInit DLL.
  195. base::FilePath full_dll_path(path);
  196. full_dll_path = full_dll_path.DirName();
  197. full_dll_path = full_dll_path.Append(hooking_dll::g_hook_dll_file);
  198. wchar_t* non_const = const_cast<wchar_t*>(full_dll_path.value().c_str());
  199. // Now make sure the path is in "short-name" form for registry.
  200. DWORD length = ::GetShortPathNameW(non_const, nullptr, 0);
  201. std::vector<wchar_t> short_name(length);
  202. if (!::GetShortPathNameW(non_const, &short_name[0], length)) {
  203. ADD_FAILURE();
  204. return;
  205. }
  206. // 1. Reg setup.
  207. const wchar_t* app_init_reg_path =
  208. L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows";
  209. const wchar_t* dlls_value_name = L"AppInit_DLLs";
  210. const wchar_t* enabled_value_name = L"LoadAppInit_DLLs";
  211. const wchar_t* signing_value_name = L"RequireSignedAppInit_DLLs";
  212. std::wstring orig_dlls;
  213. std::wstring new_dlls;
  214. DWORD orig_enabled_value = 0;
  215. DWORD orig_signing_value = 0;
  216. base::win::RegKey app_init_key(HKEY_LOCAL_MACHINE, app_init_reg_path,
  217. KEY_QUERY_VALUE | KEY_SET_VALUE);
  218. // Backup the existing settings.
  219. if (!app_init_key.Valid() || !app_init_key.HasValue(dlls_value_name) ||
  220. !app_init_key.HasValue(enabled_value_name) ||
  221. ERROR_SUCCESS != app_init_key.ReadValue(dlls_value_name, &orig_dlls) ||
  222. ERROR_SUCCESS !=
  223. app_init_key.ReadValueDW(enabled_value_name, &orig_enabled_value)) {
  224. ADD_FAILURE();
  225. return;
  226. }
  227. if (app_init_key.HasValue(signing_value_name)) {
  228. if (ERROR_SUCCESS !=
  229. app_init_key.ReadValueDW(signing_value_name, &orig_signing_value)) {
  230. ADD_FAILURE();
  231. return;
  232. }
  233. }
  234. // Set the new settings (obviously requires local admin privileges).
  235. new_dlls = orig_dlls;
  236. if (!orig_dlls.empty())
  237. new_dlls.append(L",");
  238. new_dlls.append(short_name.data());
  239. // From this point on, no return on failure. Cleanup required.
  240. bool all_good = true;
  241. if (app_init_key.HasValue(signing_value_name)) {
  242. if (ERROR_SUCCESS !=
  243. app_init_key.WriteValue(signing_value_name, static_cast<DWORD>(0))) {
  244. ADD_FAILURE();
  245. all_good = false;
  246. }
  247. }
  248. if (ERROR_SUCCESS !=
  249. app_init_key.WriteValue(dlls_value_name, new_dlls.c_str()) ||
  250. ERROR_SUCCESS !=
  251. app_init_key.WriteValue(enabled_value_name, static_cast<DWORD>(1))) {
  252. ADD_FAILURE();
  253. all_good = false;
  254. }
  255. // 2. Spawn WinProc.
  256. HANDLE winproc_event = nullptr;
  257. base::win::ScopedHandle scoped_event;
  258. PROCESS_INFORMATION proc_info = {};
  259. if (all_good) {
  260. winproc_event = ::CreateEventW(nullptr, false, false,
  261. hooking_win_proc::g_winproc_event);
  262. if (!winproc_event) {
  263. ADD_FAILURE();
  264. all_good = false;
  265. } else {
  266. scoped_event.Set(winproc_event);
  267. if (!SpawnWinProc(&proc_info, is_success_test, &winproc_event))
  268. all_good = false;
  269. }
  270. }
  271. // 3. Check loaded modules in WinProc to see if the AppInit dll is loaded.
  272. bool dll_loaded = false;
  273. if (all_good) {
  274. std::vector<HMODULE>(modules);
  275. if (!base::win::GetLoadedModulesSnapshot(proc_info.hProcess, &modules)) {
  276. ADD_FAILURE();
  277. all_good = false;
  278. } else {
  279. for (HMODULE module : modules) {
  280. wchar_t name[MAX_PATH] = {};
  281. if (::GetModuleFileNameExW(proc_info.hProcess, module, name,
  282. MAX_PATH) &&
  283. ::wcsstr(name, hooking_dll::g_hook_dll_file)) {
  284. // Found it.
  285. dll_loaded = true;
  286. break;
  287. }
  288. }
  289. }
  290. }
  291. // Was the test result as expected?
  292. if (all_good)
  293. EXPECT_EQ((is_success_test ? true : false), dll_loaded);
  294. // 4. Trigger shutdown of WinProc.
  295. if (proc_info.hProcess) {
  296. if (::PostThreadMessageW(proc_info.dwThreadId, WM_QUIT, 0, 0)) {
  297. ::WaitForSingleObject(winproc_event, sandbox::SboxTestEventTimeout());
  298. } else {
  299. // Ensure no strays.
  300. ::TerminateProcess(proc_info.hProcess, 0);
  301. ADD_FAILURE();
  302. }
  303. EXPECT_TRUE(::CloseHandle(proc_info.hThread));
  304. EXPECT_TRUE(::CloseHandle(proc_info.hProcess));
  305. }
  306. // 5. Reg Restore
  307. EXPECT_EQ(ERROR_SUCCESS,
  308. app_init_key.WriteValue(enabled_value_name, orig_enabled_value));
  309. if (app_init_key.HasValue(signing_value_name))
  310. EXPECT_EQ(ERROR_SUCCESS,
  311. app_init_key.WriteValue(signing_value_name, orig_signing_value));
  312. EXPECT_EQ(ERROR_SUCCESS,
  313. app_init_key.WriteValue(dlls_value_name, orig_dlls.c_str()));
  314. }
  315. } // namespace
  316. namespace sandbox {
  317. //------------------------------------------------------------------------------
  318. // Exported Extension Point Tests
  319. //------------------------------------------------------------------------------
  320. //------------------------------------------------------------------------------
  321. // Disable extension points (MITIGATION_EXTENSION_POINT_DISABLE).
  322. // >= Win8
  323. //------------------------------------------------------------------------------
  324. // This test validates that setting the MITIGATION_EXTENSION_POINT_DISABLE
  325. // mitigation enables the setting on a process.
  326. TEST(ProcessMitigationsTest, CheckWin8ExtensionPointPolicySuccess) {
  327. if (base::win::GetVersion() < base::win::Version::WIN8)
  328. return;
  329. std::wstring test_command = L"CheckPolicy ";
  330. test_command += std::to_wstring(sandbox::TESTPOLICY_EXTENSIONPOINT);
  331. //---------------------------------
  332. // 1) Test setting pre-startup.
  333. //---------------------------------
  334. TestRunner runner;
  335. sandbox::TargetPolicy* policy = runner.GetPolicy();
  336. EXPECT_EQ(policy->SetProcessMitigations(MITIGATION_EXTENSION_POINT_DISABLE),
  337. SBOX_ALL_OK);
  338. EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(test_command.c_str()));
  339. //---------------------------------
  340. // 2) Test setting post-startup.
  341. //---------------------------------
  342. TestRunner runner2;
  343. sandbox::TargetPolicy* policy2 = runner2.GetPolicy();
  344. EXPECT_EQ(
  345. policy2->SetDelayedProcessMitigations(MITIGATION_EXTENSION_POINT_DISABLE),
  346. SBOX_ALL_OK);
  347. EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner2.RunTest(test_command.c_str()));
  348. }
  349. // This test validates that a "legitimate" global hook CAN be set on the
  350. // sandboxed proc/thread if the MITIGATION_EXTENSION_POINT_DISABLE
  351. // mitigation is not set.
  352. //
  353. // MANUAL testing only.
  354. TEST(ProcessMitigationsTest,
  355. DISABLED_CheckWin8ExtensionPoint_GlobalHook_Success) {
  356. if (base::win::GetVersion() < base::win::Version::WIN8)
  357. return;
  358. ScopedTestMutex mutex(g_extension_point_test_mutex);
  359. TestWin8ExtensionPointHookWrapper(true /* is_success_test */,
  360. true /* global hook */);
  361. }
  362. // This test validates that setting the MITIGATION_EXTENSION_POINT_DISABLE
  363. // mitigation prevents a global hook on WinProc.
  364. //
  365. // MANUAL testing only.
  366. TEST(ProcessMitigationsTest,
  367. DISABLED_CheckWin8ExtensionPoint_GlobalHook_Failure) {
  368. if (base::win::GetVersion() < base::win::Version::WIN8)
  369. return;
  370. ScopedTestMutex mutex(g_extension_point_test_mutex);
  371. TestWin8ExtensionPointHookWrapper(false /* is_success_test */,
  372. true /* global hook */);
  373. }
  374. // This test validates that a "legitimate" hook CAN be set on the sandboxed
  375. // proc/thread if the MITIGATION_EXTENSION_POINT_DISABLE mitigation is not set.
  376. //
  377. // MANUAL testing only.
  378. TEST(ProcessMitigationsTest, DISABLED_CheckWin8ExtensionPoint_Hook_Success) {
  379. if (base::win::GetVersion() < base::win::Version::WIN8)
  380. return;
  381. ScopedTestMutex mutex(g_extension_point_test_mutex);
  382. TestWin8ExtensionPointHookWrapper(true /* is_success_test */,
  383. false /* global hook */);
  384. }
  385. // *** Important: MITIGATION_EXTENSION_POINT_DISABLE does NOT prevent
  386. // hooks targetted at a specific thread id. It only prevents
  387. // global hooks. So this test does NOT actually expect the hook
  388. // to fail (see TestWin8ExtensionPointHookWrapper function) even
  389. // with the mitigation on.
  390. //
  391. // MANUAL testing only.
  392. TEST(ProcessMitigationsTest, DISABLED_CheckWin8ExtensionPoint_Hook_Failure) {
  393. if (base::win::GetVersion() < base::win::Version::WIN8)
  394. return;
  395. ScopedTestMutex mutex(g_extension_point_test_mutex);
  396. TestWin8ExtensionPointHookWrapper(false /* is_success_test */,
  397. false /* global hook */);
  398. }
  399. // This test validates that an AppInit Dll CAN be added to a target
  400. // WinProc if the MITIGATION_EXTENSION_POINT_DISABLE mitigation is not set.
  401. //
  402. // MANUAL testing only.
  403. // Must run this test as admin/elevated.
  404. TEST(ProcessMitigationsTest, DISABLED_CheckWin8ExtensionPoint_AppInit_Success) {
  405. if (base::win::GetVersion() < base::win::Version::WIN8)
  406. return;
  407. ScopedTestMutex mutex(g_extension_point_test_mutex);
  408. TestWin8ExtensionPointAppInitWrapper(true /* is_success_test */);
  409. }
  410. // This test validates that setting the MITIGATION_EXTENSION_POINT_DISABLE
  411. // mitigation prevents the loading of any AppInit Dll into WinProc.
  412. //
  413. // MANUAL testing only.
  414. // Must run this test as admin/elevated.
  415. TEST(ProcessMitigationsTest, DISABLED_CheckWin8ExtensionPoint_AppInit_Failure) {
  416. if (base::win::GetVersion() < base::win::Version::WIN8)
  417. return;
  418. ScopedTestMutex mutex(g_extension_point_test_mutex);
  419. TestWin8ExtensionPointAppInitWrapper(false /* is_success_test */);
  420. }
  421. } // namespace sandbox