Roll src/third_party/WebKit f36d5e0:68b67cd (svn 193299:193303)
[chromium-blink-merge.git] / chrome_elf / blacklist / blacklist.cc
blob31219cc9c6aa80b35bb96823fc7c26c5a42aa0bf
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"
7 #include <assert.h>
8 #include <string.h>
10 #include <vector>
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;
24 namespace blacklist{
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
30 // of it, see:
31 // https://sites.google.com/a/chromium.org/dev/Home/third-party-developers
32 // NOTE: Please remember to update the DllHash enum in histograms.xml when
33 // adding a new value to the blacklist.
34 const wchar_t* g_troublesome_dlls[kTroublesomeDllsMaxCount] = {
35 L"activedetect32.dll", // Lenovo One Key Theater.
36 // See crbug.com/379218.
37 L"activedetect64.dll", // Lenovo One Key Theater.
38 L"bitguard.dll", // Unknown (suspected malware).
39 L"chrmxtn.dll", // Unknown (keystroke logger).
40 L"cplushook.dll", // Unknown (suspected malware).
41 L"crdli.dll", // Linkury Inc.
42 L"crdli64.dll", // Linkury Inc.
43 L"datamngr.dll", // Unknown (suspected adware).
44 L"hk.dll", // Unknown (keystroke logger).
45 L"libapi2hook.dll", // V-Bates.
46 L"libinject.dll", // V-Bates.
47 L"libinject2.dll", // V-Bates.
48 L"libredir2.dll", // V-Bates.
49 L"libsvn_tsvn32.dll", // TortoiseSVN.
50 L"libwinhook.dll", // V-Bates.
51 L"lmrn.dll", // Unknown.
52 L"minisp.dll", // Unknown (suspected malware).
53 L"safetynut.dll", // Unknown (suspected adware).
54 L"smdmf.dll", // Unknown (suspected adware).
55 L"systemk.dll", // Unknown (suspected adware).
56 L"vntsrv.dll", // Virtual New Tab by APN LLC.
57 L"wajam_goblin_64.dll", // Wajam Internet Technologies.
58 L"wajam_goblin.dll", // Wajam Internet Technologies.
59 L"windowsapihookdll32.dll", // Lenovo One Key Theater.
60 // See crbug.com/379218.
61 L"windowsapihookdll64.dll", // Lenovo One Key Theater.
62 L"virtualcamera.ax", // %PROGRAMFILES%\ASUS\VirtualCamera.
63 // See crbug.com/422522.
64 L"ycwebcamerasource.ax", // CyberLink Youcam, crbug.com/424159
65 // Keep this null pointer here to mark the end of the list.
66 NULL,
69 bool g_blocked_dlls[kTroublesomeDllsMaxCount] = {};
70 int g_num_blocked_dlls = 0;
72 } // namespace blacklist
74 // Allocate storage for thunks in a page of this module to save on doing
75 // an extra allocation at run time.
76 #pragma section(".crthunk",read,execute)
77 __declspec(allocate(".crthunk")) sandbox::ThunkData g_thunk_storage;
79 namespace {
81 // Record if the blacklist was successfully initialized so processes can easily
82 // determine if the blacklist is enabled for them.
83 bool g_blacklist_initialized = false;
85 // Helper to set DWORD registry values.
86 DWORD SetDWValue(HKEY* key, const wchar_t* property, DWORD value) {
87 return ::RegSetValueEx(*key,
88 property,
90 REG_DWORD,
91 reinterpret_cast<LPBYTE>(&value),
92 sizeof(value));
95 bool GenerateStateFromBeaconAndAttemptCount(HKEY* key, DWORD blacklist_state) {
96 LONG result = 0;
97 if (blacklist_state == blacklist::BLACKLIST_ENABLED) {
98 // If the blacklist succeeded on the previous run reset the failure
99 // counter.
100 return (SetDWValue(key,
101 blacklist::kBeaconAttemptCount,
102 static_cast<DWORD>(0)) == ERROR_SUCCESS);
103 } else {
104 // Some part of the blacklist setup failed last time. If this has occured
105 // blacklist::kBeaconMaxAttempts times in a row we switch the state to
106 // failed and skip setting up the blacklist.
107 DWORD attempt_count = 0;
108 DWORD attempt_count_size = sizeof(attempt_count);
109 result = ::RegQueryValueEx(*key,
110 blacklist::kBeaconAttemptCount,
112 NULL,
113 reinterpret_cast<LPBYTE>(&attempt_count),
114 &attempt_count_size);
116 if (result == ERROR_FILE_NOT_FOUND)
117 attempt_count = 0;
118 else if (result != ERROR_SUCCESS)
119 return false;
121 ++attempt_count;
122 SetDWValue(key, blacklist::kBeaconAttemptCount, attempt_count);
124 if (attempt_count >= blacklist::kBeaconMaxAttempts) {
125 blacklist_state = blacklist::BLACKLIST_SETUP_FAILED;
126 SetDWValue(key, blacklist::kBeaconState, blacklist_state);
129 return false;
133 } // namespace
135 namespace blacklist {
137 #if defined(_WIN64)
138 // Allocate storage for the pointer to the old NtMapViewOfSectionFunction.
139 #pragma section(".oldntmap",write,read)
140 __declspec(allocate(".oldntmap"))
141 NtMapViewOfSectionFunction g_nt_map_view_of_section_func = NULL;
142 #endif
144 bool LeaveSetupBeacon() {
145 HKEY key = NULL;
146 DWORD disposition = 0;
147 LONG result = ::RegCreateKeyEx(HKEY_CURRENT_USER,
148 kRegistryBeaconPath,
150 NULL,
151 REG_OPTION_NON_VOLATILE,
152 KEY_QUERY_VALUE | KEY_SET_VALUE,
153 NULL,
154 &key,
155 &disposition);
156 if (result != ERROR_SUCCESS)
157 return false;
159 // Retrieve the current blacklist state.
160 DWORD blacklist_state = BLACKLIST_STATE_MAX;
161 DWORD blacklist_state_size = sizeof(blacklist_state);
162 DWORD type = 0;
163 result = ::RegQueryValueEx(key,
164 kBeaconState,
166 &type,
167 reinterpret_cast<LPBYTE>(&blacklist_state),
168 &blacklist_state_size);
170 if (result != ERROR_SUCCESS || blacklist_state == BLACKLIST_DISABLED ||
171 type != REG_DWORD) {
172 ::RegCloseKey(key);
173 return false;
176 if (!GenerateStateFromBeaconAndAttemptCount(&key, blacklist_state)) {
177 ::RegCloseKey(key);
178 return false;
181 result = SetDWValue(&key, kBeaconState, BLACKLIST_SETUP_RUNNING);
182 ::RegCloseKey(key);
184 return (result == ERROR_SUCCESS);
187 bool ResetBeacon() {
188 HKEY key = NULL;
189 DWORD disposition = 0;
190 LONG result = ::RegCreateKeyEx(HKEY_CURRENT_USER,
191 kRegistryBeaconPath,
193 NULL,
194 REG_OPTION_NON_VOLATILE,
195 KEY_QUERY_VALUE | KEY_SET_VALUE,
196 NULL,
197 &key,
198 &disposition);
199 if (result != ERROR_SUCCESS)
200 return false;
202 DWORD blacklist_state = BLACKLIST_STATE_MAX;
203 DWORD blacklist_state_size = sizeof(blacklist_state);
204 DWORD type = 0;
205 result = ::RegQueryValueEx(key,
206 kBeaconState,
208 &type,
209 reinterpret_cast<LPBYTE>(&blacklist_state),
210 &blacklist_state_size);
212 if (result != ERROR_SUCCESS || type != REG_DWORD) {
213 ::RegCloseKey(key);
214 return false;
217 // Reaching this point with the setup running state means the setup did not
218 // crash, so we reset to enabled. Any other state indicates that setup was
219 // skipped; in that case we leave the state alone for later recording.
220 if (blacklist_state == BLACKLIST_SETUP_RUNNING)
221 result = SetDWValue(&key, kBeaconState, BLACKLIST_ENABLED);
223 ::RegCloseKey(key);
224 return (result == ERROR_SUCCESS);
227 int BlacklistSize() {
228 int size = -1;
229 while (blacklist::g_troublesome_dlls[++size] != NULL) {}
231 return size;
234 bool IsBlacklistInitialized() {
235 return g_blacklist_initialized;
238 int GetBlacklistIndex(const wchar_t* dll_name) {
239 for (int i = 0; i < kTroublesomeDllsMaxCount && g_troublesome_dlls[i]; ++i) {
240 if (_wcsicmp(dll_name, g_troublesome_dlls[i]) == 0)
241 return i;
243 return -1;
246 bool AddDllToBlacklist(const wchar_t* dll_name) {
247 int blacklist_size = BlacklistSize();
248 // We need to leave one space at the end for the null pointer.
249 if (blacklist_size + 1 >= kTroublesomeDllsMaxCount)
250 return false;
251 for (int i = 0; i < blacklist_size; ++i) {
252 if (!_wcsicmp(g_troublesome_dlls[i], dll_name))
253 return true;
256 // Copy string to blacklist.
257 wchar_t* str_buffer = new wchar_t[wcslen(dll_name) + 1];
258 wcscpy(str_buffer, dll_name);
260 g_troublesome_dlls[blacklist_size] = str_buffer;
261 g_blocked_dlls[blacklist_size] = false;
262 return true;
265 bool RemoveDllFromBlacklist(const wchar_t* dll_name) {
266 int blacklist_size = BlacklistSize();
267 for (int i = 0; i < blacklist_size; ++i) {
268 if (!_wcsicmp(g_troublesome_dlls[i], dll_name)) {
269 // Found the thing to remove. Delete it then replace it with the last
270 // element.
271 delete[] g_troublesome_dlls[i];
272 g_troublesome_dlls[i] = g_troublesome_dlls[blacklist_size - 1];
273 g_troublesome_dlls[blacklist_size - 1] = NULL;
275 // Also update the stats recording if we have blocked this dll or not.
276 if (g_blocked_dlls[i])
277 --g_num_blocked_dlls;
278 g_blocked_dlls[i] = g_blocked_dlls[blacklist_size - 1];
279 return true;
282 return false;
285 // TODO(csharp): Maybe store these values in the registry so we can
286 // still report them if Chrome crashes early.
287 void SuccessfullyBlocked(const wchar_t** blocked_dlls, int* size) {
288 if (size == NULL)
289 return;
291 // If the array isn't valid or big enough, just report the size it needs to
292 // be and return.
293 if (blocked_dlls == NULL && *size < g_num_blocked_dlls) {
294 *size = g_num_blocked_dlls;
295 return;
298 *size = g_num_blocked_dlls;
300 int strings_to_fill = 0;
301 for (int i = 0; strings_to_fill < g_num_blocked_dlls && g_troublesome_dlls[i];
302 ++i) {
303 if (g_blocked_dlls[i]) {
304 blocked_dlls[strings_to_fill] = g_troublesome_dlls[i];
305 ++strings_to_fill;
310 void BlockedDll(size_t blocked_index) {
311 assert(blocked_index < kTroublesomeDllsMaxCount);
313 if (!g_blocked_dlls[blocked_index] &&
314 blocked_index < kTroublesomeDllsMaxCount) {
315 ++g_num_blocked_dlls;
316 g_blocked_dlls[blocked_index] = true;
320 bool Initialize(bool force) {
321 // Check to see that we found the functions we need in ntdll.
322 if (!InitializeInterceptImports())
323 return false;
325 // Check to see if this is a non-browser process, abort if so.
326 if (IsNonBrowserProcess())
327 return false;
329 // Check to see if the blacklist beacon is still set to running (indicating a
330 // failure) or disabled, and abort if so.
331 if (!force && !LeaveSetupBeacon())
332 return false;
334 // It is possible for other dlls to have already patched code by now and
335 // attempting to patch their code might result in crashes.
336 const bool kRelaxed = false;
338 // Create a thunk via the appropriate ServiceResolver instance.
339 sandbox::ServiceResolverThunk* thunk = GetThunk(kRelaxed);
341 // Don't try blacklisting on unsupported OS versions.
342 if (!thunk)
343 return false;
345 BYTE* thunk_storage = reinterpret_cast<BYTE*>(&g_thunk_storage);
347 // Mark the thunk storage as readable and writeable, since we
348 // ready to write to it.
349 DWORD old_protect = 0;
350 if (!VirtualProtect(&g_thunk_storage,
351 sizeof(g_thunk_storage),
352 PAGE_EXECUTE_READWRITE,
353 &old_protect)) {
354 return false;
357 thunk->AllowLocalPatches();
359 // We declare this early so it can be used in the 64-bit block below and
360 // still work on 32-bit build when referenced at the end of the function.
361 BOOL page_executable = false;
363 // Replace the default NtMapViewOfSection with our patched version.
364 #if defined(_WIN64)
365 NTSTATUS ret = thunk->Setup(::GetModuleHandle(sandbox::kNtdllName),
366 reinterpret_cast<void*>(&__ImageBase),
367 "NtMapViewOfSection",
368 NULL,
369 &blacklist::BlNtMapViewOfSection64,
370 thunk_storage,
371 sizeof(sandbox::ThunkData),
372 NULL);
374 // Keep a pointer to the original code, we don't have enough space to
375 // add it directly to the call.
376 g_nt_map_view_of_section_func = reinterpret_cast<NtMapViewOfSectionFunction>(
377 thunk_storage);
379 // Ensure that the pointer to the old function can't be changed.
380 page_executable = VirtualProtect(&g_nt_map_view_of_section_func,
381 sizeof(g_nt_map_view_of_section_func),
382 PAGE_EXECUTE_READ,
383 &old_protect);
384 #else
385 NTSTATUS ret = thunk->Setup(::GetModuleHandle(sandbox::kNtdllName),
386 reinterpret_cast<void*>(&__ImageBase),
387 "NtMapViewOfSection",
388 NULL,
389 &blacklist::BlNtMapViewOfSection,
390 thunk_storage,
391 sizeof(sandbox::ThunkData),
392 NULL);
393 #endif
394 delete thunk;
396 // Record if we have initialized the blacklist.
397 g_blacklist_initialized = NT_SUCCESS(ret);
399 // Mark the thunk storage as executable and prevent any future writes to it.
400 page_executable = page_executable && VirtualProtect(&g_thunk_storage,
401 sizeof(g_thunk_storage),
402 PAGE_EXECUTE_READ,
403 &old_protect);
405 AddDllsFromRegistryToBlacklist();
407 return NT_SUCCESS(ret) && page_executable;
410 void AddDllsFromRegistryToBlacklist() {
411 HKEY key = NULL;
412 LONG result = ::RegOpenKeyEx(HKEY_CURRENT_USER,
413 kRegistryFinchListPath,
415 KEY_QUERY_VALUE | KEY_SET_VALUE,
416 &key);
418 if (result != ERROR_SUCCESS)
419 return;
421 // We add dlls from the registry to the blacklist.
422 DWORD value_len;
423 DWORD name_len = MAX_PATH;
424 std::vector<wchar_t> name_buffer(name_len);
425 for (int i = 0; result == ERROR_SUCCESS; ++i) {
426 name_len = MAX_PATH;
427 value_len = 0;
428 result = ::RegEnumValue(
429 key, i, &name_buffer[0], &name_len, NULL, NULL, NULL, &value_len);
430 if (result != ERROR_SUCCESS)
431 break;
433 name_len = name_len + 1;
434 value_len = value_len + 1;
435 std::vector<wchar_t> value_buffer(value_len);
436 result = ::RegEnumValue(key, i, &name_buffer[0], &name_len, NULL, NULL,
437 reinterpret_cast<BYTE*>(&value_buffer[0]),
438 &value_len);
439 if (result != ERROR_SUCCESS)
440 break;
441 value_buffer[value_len - 1] = L'\0';
442 AddDllToBlacklist(&value_buffer[0]);
445 ::RegCloseKey(key);
446 return;
449 } // namespace blacklist