Blink roll 18aa52da6706987b8d9242b1cba8fc929b74fcee:25b6bd3a7a131ffe68d809546ad1a2070...
[chromium-blink-merge.git] / chrome_elf / blacklist / blacklist.cc
blobf775b62d409d270dfd8d38aa44d2cc9aa463f9f4
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"datamngr.dll", // Unknown (suspected adware).
42 L"hk.dll", // Unknown (keystroke logger).
43 L"libapi2hook.dll", // V-Bates.
44 L"libinject.dll", // V-Bates.
45 L"libinject2.dll", // V-Bates.
46 L"libredir2.dll", // V-Bates.
47 L"libsvn_tsvn32.dll", // TortoiseSVN.
48 L"libwinhook.dll", // V-Bates.
49 L"lmrn.dll", // Unknown.
50 L"minisp.dll", // Unknown (suspected malware).
51 L"safetynut.dll", // Unknown (suspected adware).
52 L"systemk.dll", // Unknown (suspected adware).
53 L"wajam_goblin_64.dll", // Wajam Internet Technologies.
54 L"wajam_goblin.dll", // Wajam Internet Technologies.
55 L"windowsapihookdll32.dll", // Lenovo One Key Theater.
56 // See crbug.com/379218.
57 L"windowsapihookdll64.dll", // Lenovo One Key Theater.
58 // Keep this null pointer here to mark the end of the list.
59 NULL,
62 bool g_blocked_dlls[kTroublesomeDllsMaxCount] = {};
63 int g_num_blocked_dlls = 0;
65 } // namespace blacklist
67 // Allocate storage for thunks in a page of this module to save on doing
68 // an extra allocation at run time.
69 #pragma section(".crthunk",read,execute)
70 __declspec(allocate(".crthunk")) sandbox::ThunkData g_thunk_storage;
72 namespace {
74 // Record if the blacklist was successfully initialized so processes can easily
75 // determine if the blacklist is enabled for them.
76 bool g_blacklist_initialized = false;
78 // Helper to set DWORD registry values.
79 DWORD SetDWValue(HKEY* key, const wchar_t* property, DWORD value) {
80 return ::RegSetValueEx(*key,
81 property,
83 REG_DWORD,
84 reinterpret_cast<LPBYTE>(&value),
85 sizeof(value));
88 bool GenerateStateFromBeaconAndAttemptCount(HKEY* key, DWORD blacklist_state) {
89 LONG result = 0;
90 if (blacklist_state == blacklist::BLACKLIST_ENABLED) {
91 // If the blacklist succeeded on the previous run reset the failure
92 // counter.
93 return (SetDWValue(key,
94 blacklist::kBeaconAttemptCount,
95 static_cast<DWORD>(0)) == ERROR_SUCCESS);
96 } else {
97 // Some part of the blacklist setup failed last time. If this has occured
98 // blacklist::kBeaconMaxAttempts times in a row we switch the state to
99 // failed and skip setting up the blacklist.
100 DWORD attempt_count = 0;
101 DWORD attempt_count_size = sizeof(attempt_count);
102 result = ::RegQueryValueEx(*key,
103 blacklist::kBeaconAttemptCount,
105 NULL,
106 reinterpret_cast<LPBYTE>(&attempt_count),
107 &attempt_count_size);
109 if (result == ERROR_FILE_NOT_FOUND)
110 attempt_count = 0;
111 else if (result != ERROR_SUCCESS)
112 return false;
114 ++attempt_count;
115 SetDWValue(key, blacklist::kBeaconAttemptCount, attempt_count);
117 if (attempt_count >= blacklist::kBeaconMaxAttempts) {
118 blacklist_state = blacklist::BLACKLIST_SETUP_FAILED;
119 SetDWValue(key, blacklist::kBeaconState, blacklist_state);
122 return false;
126 } // namespace
128 namespace blacklist {
130 #if defined(_WIN64)
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;
135 #endif
137 bool LeaveSetupBeacon() {
138 HKEY key = NULL;
139 DWORD disposition = 0;
140 LONG result = ::RegCreateKeyEx(HKEY_CURRENT_USER,
141 kRegistryBeaconPath,
143 NULL,
144 REG_OPTION_NON_VOLATILE,
145 KEY_QUERY_VALUE | KEY_SET_VALUE,
146 NULL,
147 &key,
148 &disposition);
149 if (result != ERROR_SUCCESS)
150 return false;
152 // Retrieve the current blacklist state.
153 DWORD blacklist_state = BLACKLIST_STATE_MAX;
154 DWORD blacklist_state_size = sizeof(blacklist_state);
155 DWORD type = 0;
156 result = ::RegQueryValueEx(key,
157 kBeaconState,
159 &type,
160 reinterpret_cast<LPBYTE>(&blacklist_state),
161 &blacklist_state_size);
163 if (result != ERROR_SUCCESS || blacklist_state == BLACKLIST_DISABLED ||
164 type != REG_DWORD) {
165 ::RegCloseKey(key);
166 return false;
169 if (!GenerateStateFromBeaconAndAttemptCount(&key, blacklist_state)) {
170 ::RegCloseKey(key);
171 return false;
174 result = SetDWValue(&key, kBeaconState, BLACKLIST_SETUP_RUNNING);
175 ::RegCloseKey(key);
177 return (result == ERROR_SUCCESS);
180 bool ResetBeacon() {
181 HKEY key = NULL;
182 DWORD disposition = 0;
183 LONG result = ::RegCreateKeyEx(HKEY_CURRENT_USER,
184 kRegistryBeaconPath,
186 NULL,
187 REG_OPTION_NON_VOLATILE,
188 KEY_QUERY_VALUE | KEY_SET_VALUE,
189 NULL,
190 &key,
191 &disposition);
192 if (result != ERROR_SUCCESS)
193 return false;
195 DWORD blacklist_state = BLACKLIST_STATE_MAX;
196 DWORD blacklist_state_size = sizeof(blacklist_state);
197 DWORD type = 0;
198 result = ::RegQueryValueEx(key,
199 kBeaconState,
201 &type,
202 reinterpret_cast<LPBYTE>(&blacklist_state),
203 &blacklist_state_size);
205 if (result != ERROR_SUCCESS || type != REG_DWORD) {
206 ::RegCloseKey(key);
207 return false;
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);
216 ::RegCloseKey(key);
217 return (result == ERROR_SUCCESS);
220 int BlacklistSize() {
221 int size = -1;
222 while (blacklist::g_troublesome_dlls[++size] != NULL) {}
224 return size;
227 bool IsBlacklistInitialized() {
228 return g_blacklist_initialized;
231 int GetBlacklistIndex(const wchar_t* dll_name) {
232 for (int i = 0; i < kTroublesomeDllsMaxCount && g_troublesome_dlls[i]; ++i) {
233 if (_wcsicmp(dll_name, g_troublesome_dlls[i]) == 0)
234 return i;
236 return -1;
239 bool AddDllToBlacklist(const wchar_t* dll_name) {
240 int blacklist_size = BlacklistSize();
241 // We need to leave one space at the end for the null pointer.
242 if (blacklist_size + 1 >= kTroublesomeDllsMaxCount)
243 return false;
244 for (int i = 0; i < blacklist_size; ++i) {
245 if (!_wcsicmp(g_troublesome_dlls[i], dll_name))
246 return true;
249 // Copy string to blacklist.
250 wchar_t* str_buffer = new wchar_t[wcslen(dll_name) + 1];
251 wcscpy(str_buffer, dll_name);
253 g_troublesome_dlls[blacklist_size] = str_buffer;
254 g_blocked_dlls[blacklist_size] = false;
255 return true;
258 bool RemoveDllFromBlacklist(const wchar_t* dll_name) {
259 int blacklist_size = BlacklistSize();
260 for (int i = 0; i < blacklist_size; ++i) {
261 if (!_wcsicmp(g_troublesome_dlls[i], dll_name)) {
262 // Found the thing to remove. Delete it then replace it with the last
263 // element.
264 delete[] g_troublesome_dlls[i];
265 g_troublesome_dlls[i] = g_troublesome_dlls[blacklist_size - 1];
266 g_troublesome_dlls[blacklist_size - 1] = NULL;
268 // Also update the stats recording if we have blocked this dll or not.
269 if (g_blocked_dlls[i])
270 --g_num_blocked_dlls;
271 g_blocked_dlls[i] = g_blocked_dlls[blacklist_size - 1];
272 return true;
275 return false;
278 // TODO(csharp): Maybe store these values in the registry so we can
279 // still report them if Chrome crashes early.
280 void SuccessfullyBlocked(const wchar_t** blocked_dlls, int* size) {
281 if (size == NULL)
282 return;
284 // If the array isn't valid or big enough, just report the size it needs to
285 // be and return.
286 if (blocked_dlls == NULL && *size < g_num_blocked_dlls) {
287 *size = g_num_blocked_dlls;
288 return;
291 *size = g_num_blocked_dlls;
293 int strings_to_fill = 0;
294 for (int i = 0; strings_to_fill < g_num_blocked_dlls && g_troublesome_dlls[i];
295 ++i) {
296 if (g_blocked_dlls[i]) {
297 blocked_dlls[strings_to_fill] = g_troublesome_dlls[i];
298 ++strings_to_fill;
303 void BlockedDll(size_t blocked_index) {
304 assert(blocked_index < kTroublesomeDllsMaxCount);
306 if (!g_blocked_dlls[blocked_index] &&
307 blocked_index < kTroublesomeDllsMaxCount) {
308 ++g_num_blocked_dlls;
309 g_blocked_dlls[blocked_index] = true;
313 bool Initialize(bool force) {
314 // Check to see that we found the functions we need in ntdll.
315 if (!InitializeInterceptImports())
316 return false;
318 // Check to see if this is a non-browser process, abort if so.
319 if (IsNonBrowserProcess())
320 return false;
322 // Check to see if the blacklist beacon is still set to running (indicating a
323 // failure) or disabled, and abort if so.
324 if (!force && !LeaveSetupBeacon())
325 return false;
327 // It is possible for other dlls to have already patched code by now and
328 // attempting to patch their code might result in crashes.
329 const bool kRelaxed = false;
331 // Create a thunk via the appropriate ServiceResolver instance.
332 sandbox::ServiceResolverThunk* thunk = GetThunk(kRelaxed);
334 // Don't try blacklisting on unsupported OS versions.
335 if (!thunk)
336 return false;
338 BYTE* thunk_storage = reinterpret_cast<BYTE*>(&g_thunk_storage);
340 // Mark the thunk storage as readable and writeable, since we
341 // ready to write to it.
342 DWORD old_protect = 0;
343 if (!VirtualProtect(&g_thunk_storage,
344 sizeof(g_thunk_storage),
345 PAGE_EXECUTE_READWRITE,
346 &old_protect)) {
347 return false;
350 thunk->AllowLocalPatches();
352 // We declare this early so it can be used in the 64-bit block below and
353 // still work on 32-bit build when referenced at the end of the function.
354 BOOL page_executable = false;
356 // Replace the default NtMapViewOfSection with our patched version.
357 #if defined(_WIN64)
358 NTSTATUS ret = thunk->Setup(::GetModuleHandle(sandbox::kNtdllName),
359 reinterpret_cast<void*>(&__ImageBase),
360 "NtMapViewOfSection",
361 NULL,
362 &blacklist::BlNtMapViewOfSection64,
363 thunk_storage,
364 sizeof(sandbox::ThunkData),
365 NULL);
367 // Keep a pointer to the original code, we don't have enough space to
368 // add it directly to the call.
369 g_nt_map_view_of_section_func = reinterpret_cast<NtMapViewOfSectionFunction>(
370 thunk_storage);
372 // Ensure that the pointer to the old function can't be changed.
373 page_executable = VirtualProtect(&g_nt_map_view_of_section_func,
374 sizeof(g_nt_map_view_of_section_func),
375 PAGE_EXECUTE_READ,
376 &old_protect);
377 #else
378 NTSTATUS ret = thunk->Setup(::GetModuleHandle(sandbox::kNtdllName),
379 reinterpret_cast<void*>(&__ImageBase),
380 "NtMapViewOfSection",
381 NULL,
382 &blacklist::BlNtMapViewOfSection,
383 thunk_storage,
384 sizeof(sandbox::ThunkData),
385 NULL);
386 #endif
387 delete thunk;
389 // Record if we have initialized the blacklist.
390 g_blacklist_initialized = NT_SUCCESS(ret);
392 // Mark the thunk storage as executable and prevent any future writes to it.
393 page_executable = page_executable && VirtualProtect(&g_thunk_storage,
394 sizeof(g_thunk_storage),
395 PAGE_EXECUTE_READ,
396 &old_protect);
398 AddDllsFromRegistryToBlacklist();
400 return NT_SUCCESS(ret) && page_executable;
403 void AddDllsFromRegistryToBlacklist() {
404 HKEY key = NULL;
405 LONG result = ::RegOpenKeyEx(HKEY_CURRENT_USER,
406 kRegistryFinchListPath,
408 KEY_QUERY_VALUE | KEY_SET_VALUE,
409 &key);
411 if (result != ERROR_SUCCESS)
412 return;
414 // We add dlls from the registry to the blacklist.
415 DWORD value_len;
416 DWORD name_len = MAX_PATH;
417 std::vector<wchar_t> name_buffer(name_len);
418 for (int i = 0; result == ERROR_SUCCESS; ++i) {
419 name_len = MAX_PATH;
420 value_len = 0;
421 result = ::RegEnumValue(
422 key, i, &name_buffer[0], &name_len, NULL, NULL, NULL, &value_len);
423 if (result != ERROR_SUCCESS)
424 break;
426 name_len = name_len + 1;
427 value_len = value_len + 1;
428 std::vector<wchar_t> value_buffer(value_len);
429 result = ::RegEnumValue(key, i, &name_buffer[0], &name_len, NULL, NULL,
430 reinterpret_cast<BYTE*>(&value_buffer[0]),
431 &value_len);
432 if (result != ERROR_SUCCESS)
433 break;
434 value_buffer[value_len - 1] = L'\0';
435 AddDllToBlacklist(&value_buffer[0]);
438 ::RegCloseKey(key);
439 return;
442 } // namespace blacklist