1 // Copyright 2013 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.
5 #include "chrome_elf/blacklist/blacklist.h"
12 #include "base/basictypes.h"
13 #include "chrome_elf/blacklist/blacklist_interceptions.h"
14 #include "chrome_elf/chrome_elf_constants.h"
15 #include "chrome_elf/chrome_elf_util.h"
16 #include "chrome_elf/thunk_getter.h"
17 #include "sandbox/win/src/interception_internal.h"
18 #include "sandbox/win/src/internal_types.h"
19 #include "sandbox/win/src/service_resolver.h"
21 // http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx
22 extern "C" IMAGE_DOS_HEADER __ImageBase;
26 // The DLLs listed here are known (or under strong suspicion) of causing crashes
27 // when they are loaded in the browser. DLLs should only be added to this list
28 // if there is nothing else Chrome can do to prevent those crashes.
29 // For more information about how this list is generated, and how to get off
31 // https://sites.google.com/a/chromium.org/dev/Home/third-party-developers
32 const wchar_t* g_troublesome_dlls[kTroublesomeDllsMaxCount] = {
33 L"activedetect32.dll", // Lenovo One Key Theater.
34 // See crbug.com/379218.
35 L"activedetect64.dll", // Lenovo One Key Theater.
36 L"bitguard.dll", // Unknown (suspected malware).
37 L"cespy.dll", // CovenantEyes.
38 L"chrmxtn.dll", // Unknown (keystroke logger).
39 L"cplushook.dll", // Unknown (suspected malware).
40 L"datamngr.dll", // Unknown (suspected adware).
41 L"hk.dll", // Unknown (keystroke logger).
42 L"libapi2hook.dll", // V-Bates.
43 L"libinject.dll", // V-Bates.
44 L"libinject2.dll", // V-Bates.
45 L"libredir2.dll", // V-Bates.
46 L"libsvn_tsvn32.dll", // TortoiseSVN.
47 L"libwinhook.dll", // V-Bates.
48 L"lmrn.dll", // Unknown.
49 L"minisp.dll", // Unknown (suspected malware).
50 L"scdetour.dll", // Quick Heal Antivirus.
51 // See crbug.com/382561.
52 L"systemk.dll", // Unknown (suspected adware).
53 L"windowsapihookdll32.dll", // Lenovo One Key Theater.
54 // See crbug.com/379218.
55 L"windowsapihookdll64.dll", // Lenovo One Key Theater.
56 // Keep this null pointer here to mark the end of the list.
60 bool g_blocked_dlls[kTroublesomeDllsMaxCount] = {};
61 int g_num_blocked_dlls = 0;
63 } // namespace blacklist
65 // Allocate storage for thunks in a page of this module to save on doing
66 // an extra allocation at run time.
67 #pragma section(".crthunk",read,execute)
68 __declspec(allocate(".crthunk")) sandbox::ThunkData g_thunk_storage;
72 // Record if the blacklist was successfully initialized so processes can easily
73 // determine if the blacklist is enabled for them.
74 bool g_blacklist_initialized = false;
76 // Helper to set DWORD registry values.
77 DWORD SetDWValue(HKEY* key, const wchar_t* property, DWORD value) {
78 return ::RegSetValueEx(*key,
82 reinterpret_cast<LPBYTE>(&value),
86 bool GenerateStateFromBeaconAndAttemptCount(HKEY* key, DWORD blacklist_state) {
88 if (blacklist_state == blacklist::BLACKLIST_SETUP_RUNNING) {
89 // Some part of the blacklist setup failed last time. If this has occured
90 // blacklist::kBeaconMaxAttempts times in a row we switch the state to
91 // failed and skip setting up the blacklist.
92 DWORD attempt_count = 0;
93 DWORD attempt_count_size = sizeof(attempt_count);
94 result = ::RegQueryValueEx(*key,
95 blacklist::kBeaconAttemptCount,
98 reinterpret_cast<LPBYTE>(&attempt_count),
101 if (result == ERROR_FILE_NOT_FOUND)
103 else if (result != ERROR_SUCCESS)
107 SetDWValue(key, blacklist::kBeaconAttemptCount, attempt_count);
109 if (attempt_count >= blacklist::kBeaconMaxAttempts) {
110 blacklist_state = blacklist::BLACKLIST_SETUP_FAILED;
111 SetDWValue(key, blacklist::kBeaconState, blacklist_state);
114 } else if (blacklist_state == blacklist::BLACKLIST_ENABLED) {
115 // If the blacklist succeeded on the previous run reset the failure
118 SetDWValue(key, blacklist::kBeaconAttemptCount, static_cast<DWORD>(0));
119 if (result != ERROR_SUCCESS) {
128 namespace blacklist {
131 // Allocate storage for the pointer to the old NtMapViewOfSectionFunction.
132 #pragma section(".oldntmap",write,read)
133 __declspec(allocate(".oldntmap"))
134 NtMapViewOfSectionFunction g_nt_map_view_of_section_func = NULL;
137 bool LeaveSetupBeacon() {
139 DWORD disposition = 0;
140 LONG result = ::RegCreateKeyEx(HKEY_CURRENT_USER,
144 REG_OPTION_NON_VOLATILE,
145 KEY_QUERY_VALUE | KEY_SET_VALUE,
149 if (result != ERROR_SUCCESS)
152 // Retrieve the current blacklist state.
153 DWORD blacklist_state = BLACKLIST_STATE_MAX;
154 DWORD blacklist_state_size = sizeof(blacklist_state);
156 result = ::RegQueryValueEx(key,
160 reinterpret_cast<LPBYTE>(&blacklist_state),
161 &blacklist_state_size);
163 if (blacklist_state == BLACKLIST_DISABLED || result != ERROR_SUCCESS ||
169 if (!GenerateStateFromBeaconAndAttemptCount(&key, blacklist_state)) {
174 result = SetDWValue(&key, kBeaconState, BLACKLIST_SETUP_RUNNING);
177 return (result == ERROR_SUCCESS);
182 DWORD disposition = 0;
183 LONG result = ::RegCreateKeyEx(HKEY_CURRENT_USER,
187 REG_OPTION_NON_VOLATILE,
188 KEY_QUERY_VALUE | KEY_SET_VALUE,
192 if (result != ERROR_SUCCESS)
195 DWORD blacklist_state = BLACKLIST_STATE_MAX;
196 DWORD blacklist_state_size = sizeof(blacklist_state);
198 result = ::RegQueryValueEx(key,
202 reinterpret_cast<LPBYTE>(&blacklist_state),
203 &blacklist_state_size);
205 if (result != ERROR_SUCCESS || type != REG_DWORD) {
210 // Reaching this point with the setup running state means the setup did not
211 // crash, so we reset to enabled. Any other state indicates that setup was
212 // skipped; in that case we leave the state alone for later recording.
213 if (blacklist_state == BLACKLIST_SETUP_RUNNING)
214 result = SetDWValue(&key, kBeaconState, BLACKLIST_ENABLED);
217 return (result == ERROR_SUCCESS);
220 int BlacklistSize() {
222 while (blacklist::g_troublesome_dlls[++size] != NULL) {}
227 bool IsBlacklistInitialized() {
228 return g_blacklist_initialized;
231 bool AddDllToBlacklist(const wchar_t* dll_name) {
232 int blacklist_size = BlacklistSize();
233 // We need to leave one space at the end for the null pointer.
234 if (blacklist_size + 1 >= kTroublesomeDllsMaxCount)
236 for (int i = 0; i < blacklist_size; ++i) {
237 if (!_wcsicmp(g_troublesome_dlls[i], dll_name))
241 // Copy string to blacklist.
242 wchar_t* str_buffer = new wchar_t[wcslen(dll_name) + 1];
243 wcscpy(str_buffer, dll_name);
245 g_troublesome_dlls[blacklist_size] = str_buffer;
246 g_blocked_dlls[blacklist_size] = false;
250 bool RemoveDllFromBlacklist(const wchar_t* dll_name) {
251 int blacklist_size = BlacklistSize();
252 for (int i = 0; i < blacklist_size; ++i) {
253 if (!_wcsicmp(g_troublesome_dlls[i], dll_name)) {
254 // Found the thing to remove. Delete it then replace it with the last
256 delete[] g_troublesome_dlls[i];
257 g_troublesome_dlls[i] = g_troublesome_dlls[blacklist_size - 1];
258 g_troublesome_dlls[blacklist_size - 1] = NULL;
260 // Also update the stats recording if we have blocked this dll or not.
261 if (g_blocked_dlls[i])
262 --g_num_blocked_dlls;
263 g_blocked_dlls[i] = g_blocked_dlls[blacklist_size - 1];
270 // TODO(csharp): Maybe store these values in the registry so we can
271 // still report them if Chrome crashes early.
272 void SuccessfullyBlocked(const wchar_t** blocked_dlls, int* size) {
276 // If the array isn't valid or big enough, just report the size it needs to
278 if (blocked_dlls == NULL && *size < g_num_blocked_dlls) {
279 *size = g_num_blocked_dlls;
283 *size = g_num_blocked_dlls;
285 int strings_to_fill = 0;
286 for (int i = 0; strings_to_fill < g_num_blocked_dlls && g_troublesome_dlls[i];
288 if (g_blocked_dlls[i]) {
289 blocked_dlls[strings_to_fill] = g_troublesome_dlls[i];
295 void BlockedDll(size_t blocked_index) {
296 assert(blocked_index < kTroublesomeDllsMaxCount);
298 if (!g_blocked_dlls[blocked_index] &&
299 blocked_index < kTroublesomeDllsMaxCount) {
300 ++g_num_blocked_dlls;
301 g_blocked_dlls[blocked_index] = true;
305 bool Initialize(bool force) {
306 // Check to see that we found the functions we need in ntdll.
307 if (!InitializeInterceptImports())
310 // Check to see if this is a non-browser process, abort if so.
311 if (IsNonBrowserProcess())
314 // Check to see if the blacklist beacon is still set to running (indicating a
315 // failure) or disabled, and abort if so.
316 if (!force && !LeaveSetupBeacon())
319 // It is possible for other dlls to have already patched code by now and
320 // attempting to patch their code might result in crashes.
321 const bool kRelaxed = false;
323 // Create a thunk via the appropriate ServiceResolver instance.
324 sandbox::ServiceResolverThunk* thunk = GetThunk(kRelaxed);
326 // Don't try blacklisting on unsupported OS versions.
330 BYTE* thunk_storage = reinterpret_cast<BYTE*>(&g_thunk_storage);
332 // Mark the thunk storage as readable and writeable, since we
333 // ready to write to it.
334 DWORD old_protect = 0;
335 if (!VirtualProtect(&g_thunk_storage,
336 sizeof(g_thunk_storage),
337 PAGE_EXECUTE_READWRITE,
342 thunk->AllowLocalPatches();
344 // We declare this early so it can be used in the 64-bit block below and
345 // still work on 32-bit build when referenced at the end of the function.
346 BOOL page_executable = false;
348 // Replace the default NtMapViewOfSection with our patched version.
350 NTSTATUS ret = thunk->Setup(::GetModuleHandle(sandbox::kNtdllName),
351 reinterpret_cast<void*>(&__ImageBase),
352 "NtMapViewOfSection",
354 &blacklist::BlNtMapViewOfSection64,
356 sizeof(sandbox::ThunkData),
359 // Keep a pointer to the original code, we don't have enough space to
360 // add it directly to the call.
361 g_nt_map_view_of_section_func = reinterpret_cast<NtMapViewOfSectionFunction>(
364 // Ensure that the pointer to the old function can't be changed.
365 page_executable = VirtualProtect(&g_nt_map_view_of_section_func,
366 sizeof(g_nt_map_view_of_section_func),
370 NTSTATUS ret = thunk->Setup(::GetModuleHandle(sandbox::kNtdllName),
371 reinterpret_cast<void*>(&__ImageBase),
372 "NtMapViewOfSection",
374 &blacklist::BlNtMapViewOfSection,
376 sizeof(sandbox::ThunkData),
381 // Record if we have initialized the blacklist.
382 g_blacklist_initialized = NT_SUCCESS(ret);
384 // Mark the thunk storage as executable and prevent any future writes to it.
385 page_executable = page_executable && VirtualProtect(&g_thunk_storage,
386 sizeof(g_thunk_storage),
390 AddDllsFromRegistryToBlacklist();
392 return NT_SUCCESS(ret) && page_executable;
395 bool AddDllsFromRegistryToBlacklist() {
397 LONG result = ::RegOpenKeyEx(HKEY_CURRENT_USER,
398 kRegistryFinchListPath,
400 KEY_QUERY_VALUE | KEY_SET_VALUE,
403 if (result != ERROR_SUCCESS)
406 // We add dlls from the registry to the blacklist, and then clear registry.
408 DWORD name_len = MAX_PATH;
409 std::vector<wchar_t> name_buffer(name_len);
410 for (int i = 0; result == ERROR_SUCCESS; ++i) {
413 result = ::RegEnumValue(
414 key, i, &name_buffer[0], &name_len, NULL, NULL, NULL, &value_len);
415 name_len = name_len + 1;
416 value_len = value_len + 1;
417 std::vector<wchar_t> value_buffer(value_len);
418 result = ::RegEnumValue(key, i, &name_buffer[0], &name_len, NULL, NULL,
419 reinterpret_cast<BYTE*>(&value_buffer[0]),
421 value_buffer[value_len - 1] = L'\0';
423 if (result == ERROR_SUCCESS) {
424 AddDllToBlacklist(&value_buffer[0]);
428 // Delete the finch registry key to clear the values.
429 result = ::RegDeleteKey(key, L"");
432 return result == ERROR_SUCCESS;
435 } // namespace blacklist