Revert of [webcrypto] Give more descriptive error messages on Linux for unsupported...
[chromium-blink-merge.git] / chrome_elf / blacklist / blacklist.cc
blobba544e253a5ea06f3951d7907dff7a4aa02688bd
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 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"chrmxtn.dll", // Unknown (keystroke logger).
38 L"datamngr.dll", // Unknown (suspected adware).
39 L"hk.dll", // Unknown (keystroke logger).
40 L"libsvn_tsvn32.dll", // TortoiseSVN.
41 L"lmrn.dll", // Unknown.
42 L"systemk.dll", // Unknown (suspected adware).
43 L"windowsapihookdll32.dll", // Lenovo One Key Theater.
44 // See crbug.com/379218.
45 L"windowsapihookdll64.dll", // Lenovo One Key Theater.
46 // Keep this null pointer here to mark the end of the list.
47 NULL,
50 bool g_blocked_dlls[kTroublesomeDllsMaxCount] = {};
51 int g_num_blocked_dlls = 0;
53 } // namespace blacklist
55 // Allocate storage for thunks in a page of this module to save on doing
56 // an extra allocation at run time.
57 #pragma section(".crthunk",read,execute)
58 __declspec(allocate(".crthunk")) sandbox::ThunkData g_thunk_storage;
60 namespace {
62 // Record if the blacklist was successfully initialized so processes can easily
63 // determine if the blacklist is enabled for them.
64 bool g_blacklist_initialized = false;
66 // Helper to set DWORD registry values.
67 DWORD SetDWValue(HKEY* key, const wchar_t* property, DWORD value) {
68 return ::RegSetValueEx(*key,
69 property,
71 REG_DWORD,
72 reinterpret_cast<LPBYTE>(&value),
73 sizeof(value));
76 bool GenerateStateFromBeaconAndAttemptCount(HKEY* key, DWORD blacklist_state) {
77 LONG result = 0;
78 if (blacklist_state == blacklist::BLACKLIST_SETUP_RUNNING) {
79 // Some part of the blacklist setup failed last time. If this has occured
80 // blacklist::kBeaconMaxAttempts times in a row we switch the state to
81 // failed and skip setting up the blacklist.
82 DWORD attempt_count = 0;
83 DWORD attempt_count_size = sizeof(attempt_count);
84 result = ::RegQueryValueEx(*key,
85 blacklist::kBeaconAttemptCount,
87 NULL,
88 reinterpret_cast<LPBYTE>(&attempt_count),
89 &attempt_count_size);
91 if (result == ERROR_FILE_NOT_FOUND)
92 attempt_count = 0;
93 else if (result != ERROR_SUCCESS)
94 return false;
96 ++attempt_count;
97 SetDWValue(key, blacklist::kBeaconAttemptCount, attempt_count);
99 if (attempt_count >= blacklist::kBeaconMaxAttempts) {
100 blacklist_state = blacklist::BLACKLIST_SETUP_FAILED;
101 SetDWValue(key, blacklist::kBeaconState, blacklist_state);
102 return false;
104 } else if (blacklist_state == blacklist::BLACKLIST_ENABLED) {
105 // If the blacklist succeeded on the previous run reset the failure
106 // counter.
107 result =
108 SetDWValue(key, blacklist::kBeaconAttemptCount, static_cast<DWORD>(0));
109 if (result != ERROR_SUCCESS) {
110 return false;
113 return true;
116 } // namespace
118 namespace blacklist {
120 #if defined(_WIN64)
121 // Allocate storage for the pointer to the old NtMapViewOfSectionFunction.
122 #pragma section(".oldntmap",write,read)
123 __declspec(allocate(".oldntmap"))
124 NtMapViewOfSectionFunction g_nt_map_view_of_section_func = NULL;
125 #endif
127 bool LeaveSetupBeacon() {
128 HKEY key = NULL;
129 DWORD disposition = 0;
130 LONG result = ::RegCreateKeyEx(HKEY_CURRENT_USER,
131 kRegistryBeaconPath,
133 NULL,
134 REG_OPTION_NON_VOLATILE,
135 KEY_QUERY_VALUE | KEY_SET_VALUE,
136 NULL,
137 &key,
138 &disposition);
139 if (result != ERROR_SUCCESS)
140 return false;
142 // Retrieve the current blacklist state.
143 DWORD blacklist_state = BLACKLIST_STATE_MAX;
144 DWORD blacklist_state_size = sizeof(blacklist_state);
145 DWORD type = 0;
146 result = ::RegQueryValueEx(key,
147 kBeaconState,
149 &type,
150 reinterpret_cast<LPBYTE>(&blacklist_state),
151 &blacklist_state_size);
153 if (blacklist_state == BLACKLIST_DISABLED || result != ERROR_SUCCESS ||
154 type != REG_DWORD) {
155 ::RegCloseKey(key);
156 return false;
159 if (!GenerateStateFromBeaconAndAttemptCount(&key, blacklist_state)) {
160 ::RegCloseKey(key);
161 return false;
164 result = SetDWValue(&key, kBeaconState, BLACKLIST_SETUP_RUNNING);
165 ::RegCloseKey(key);
167 return (result == ERROR_SUCCESS);
170 bool ResetBeacon() {
171 HKEY key = NULL;
172 DWORD disposition = 0;
173 LONG result = ::RegCreateKeyEx(HKEY_CURRENT_USER,
174 kRegistryBeaconPath,
176 NULL,
177 REG_OPTION_NON_VOLATILE,
178 KEY_QUERY_VALUE | KEY_SET_VALUE,
179 NULL,
180 &key,
181 &disposition);
182 if (result != ERROR_SUCCESS)
183 return false;
185 DWORD blacklist_state = BLACKLIST_STATE_MAX;
186 DWORD blacklist_state_size = sizeof(blacklist_state);
187 DWORD type = 0;
188 result = ::RegQueryValueEx(key,
189 kBeaconState,
191 &type,
192 reinterpret_cast<LPBYTE>(&blacklist_state),
193 &blacklist_state_size);
195 if (result != ERROR_SUCCESS || type != REG_DWORD) {
196 ::RegCloseKey(key);
197 return false;
200 // Reaching this point with the setup running state means the setup
201 // succeeded and so we reset to enabled. Any other state indicates that setup
202 // was skipped; in that case we leave the state alone for later recording.
203 if (blacklist_state == BLACKLIST_SETUP_RUNNING)
204 result = SetDWValue(&key, kBeaconState, BLACKLIST_ENABLED);
206 ::RegCloseKey(key);
207 return (result == ERROR_SUCCESS);
210 int BlacklistSize() {
211 int size = -1;
212 while (blacklist::g_troublesome_dlls[++size] != NULL) {}
214 return size;
217 bool IsBlacklistInitialized() {
218 return g_blacklist_initialized;
221 bool AddDllToBlacklist(const wchar_t* dll_name) {
222 int blacklist_size = BlacklistSize();
223 // We need to leave one space at the end for the null pointer.
224 if (blacklist_size + 1 >= kTroublesomeDllsMaxCount)
225 return false;
226 for (int i = 0; i < blacklist_size; ++i) {
227 if (!_wcsicmp(g_troublesome_dlls[i], dll_name))
228 return true;
231 // Copy string to blacklist.
232 wchar_t* str_buffer = new wchar_t[wcslen(dll_name) + 1];
233 wcscpy(str_buffer, dll_name);
235 g_troublesome_dlls[blacklist_size] = str_buffer;
236 g_blocked_dlls[blacklist_size] = false;
237 return true;
240 bool RemoveDllFromBlacklist(const wchar_t* dll_name) {
241 int blacklist_size = BlacklistSize();
242 for (int i = 0; i < blacklist_size; ++i) {
243 if (!_wcsicmp(g_troublesome_dlls[i], dll_name)) {
244 // Found the thing to remove. Delete it then replace it with the last
245 // element.
246 delete[] g_troublesome_dlls[i];
247 g_troublesome_dlls[i] = g_troublesome_dlls[blacklist_size - 1];
248 g_troublesome_dlls[blacklist_size - 1] = NULL;
250 // Also update the stats recording if we have blocked this dll or not.
251 if (g_blocked_dlls[i])
252 --g_num_blocked_dlls;
253 g_blocked_dlls[i] = g_blocked_dlls[blacklist_size - 1];
254 return true;
257 return false;
260 // TODO(csharp): Maybe store these values in the registry so we can
261 // still report them if Chrome crashes early.
262 void SuccessfullyBlocked(const wchar_t** blocked_dlls, int* size) {
263 if (size == NULL)
264 return;
266 // If the array isn't valid or big enough, just report the size it needs to
267 // be and return.
268 if (blocked_dlls == NULL && *size < g_num_blocked_dlls) {
269 *size = g_num_blocked_dlls;
270 return;
273 *size = g_num_blocked_dlls;
275 int strings_to_fill = 0;
276 for (int i = 0; strings_to_fill < g_num_blocked_dlls && g_troublesome_dlls[i];
277 ++i) {
278 if (g_blocked_dlls[i]) {
279 blocked_dlls[strings_to_fill] = g_troublesome_dlls[i];
280 ++strings_to_fill;
285 void BlockedDll(size_t blocked_index) {
286 assert(blocked_index < kTroublesomeDllsMaxCount);
288 if (!g_blocked_dlls[blocked_index] &&
289 blocked_index < kTroublesomeDllsMaxCount) {
290 ++g_num_blocked_dlls;
291 g_blocked_dlls[blocked_index] = true;
295 bool Initialize(bool force) {
296 // Check to see that we found the functions we need in ntdll.
297 if (!InitializeInterceptImports())
298 return false;
300 // Check to see if this is a non-browser process, abort if so.
301 if (IsNonBrowserProcess())
302 return false;
304 // Check to see if the blacklist beacon is still set to running (indicating a
305 // failure) or disabled, and abort if so.
306 if (!force && !LeaveSetupBeacon())
307 return false;
309 // It is possible for other dlls to have already patched code by now and
310 // attempting to patch their code might result in crashes.
311 const bool kRelaxed = false;
313 // Create a thunk via the appropriate ServiceResolver instance.
314 sandbox::ServiceResolverThunk* thunk = GetThunk(kRelaxed);
316 // Don't try blacklisting on unsupported OS versions.
317 if (!thunk)
318 return false;
320 BYTE* thunk_storage = reinterpret_cast<BYTE*>(&g_thunk_storage);
322 // Mark the thunk storage as readable and writeable, since we
323 // ready to write to it.
324 DWORD old_protect = 0;
325 if (!VirtualProtect(&g_thunk_storage,
326 sizeof(g_thunk_storage),
327 PAGE_EXECUTE_READWRITE,
328 &old_protect)) {
329 return false;
332 thunk->AllowLocalPatches();
334 // We declare this early so it can be used in the 64-bit block below and
335 // still work on 32-bit build when referenced at the end of the function.
336 BOOL page_executable = false;
338 // Replace the default NtMapViewOfSection with our patched version.
339 #if defined(_WIN64)
340 NTSTATUS ret = thunk->Setup(::GetModuleHandle(sandbox::kNtdllName),
341 reinterpret_cast<void*>(&__ImageBase),
342 "NtMapViewOfSection",
343 NULL,
344 &blacklist::BlNtMapViewOfSection64,
345 thunk_storage,
346 sizeof(sandbox::ThunkData),
347 NULL);
349 // Keep a pointer to the original code, we don't have enough space to
350 // add it directly to the call.
351 g_nt_map_view_of_section_func = reinterpret_cast<NtMapViewOfSectionFunction>(
352 thunk_storage);
354 // Ensure that the pointer to the old function can't be changed.
355 page_executable = VirtualProtect(&g_nt_map_view_of_section_func,
356 sizeof(g_nt_map_view_of_section_func),
357 PAGE_EXECUTE_READ,
358 &old_protect);
359 #else
360 NTSTATUS ret = thunk->Setup(::GetModuleHandle(sandbox::kNtdllName),
361 reinterpret_cast<void*>(&__ImageBase),
362 "NtMapViewOfSection",
363 NULL,
364 &blacklist::BlNtMapViewOfSection,
365 thunk_storage,
366 sizeof(sandbox::ThunkData),
367 NULL);
368 #endif
369 delete thunk;
371 // Record if we have initialized the blacklist.
372 g_blacklist_initialized = NT_SUCCESS(ret);
374 // Mark the thunk storage as executable and prevent any future writes to it.
375 page_executable = page_executable && VirtualProtect(&g_thunk_storage,
376 sizeof(g_thunk_storage),
377 PAGE_EXECUTE_READ,
378 &old_protect);
380 AddDllsFromRegistryToBlacklist();
382 return NT_SUCCESS(ret) && page_executable;
385 bool AddDllsFromRegistryToBlacklist() {
386 HKEY key = NULL;
387 LONG result = ::RegOpenKeyEx(HKEY_CURRENT_USER,
388 kRegistryFinchListPath,
390 KEY_QUERY_VALUE | KEY_SET_VALUE,
391 &key);
393 if (result != ERROR_SUCCESS)
394 return false;
396 // We add dlls from the registry to the blacklist, and then clear registry.
397 DWORD value_len;
398 DWORD name_len = MAX_PATH;
399 std::vector<wchar_t> name_buffer(name_len);
400 for (int i = 0; result == ERROR_SUCCESS; ++i) {
401 name_len = MAX_PATH;
402 value_len = 0;
403 result = ::RegEnumValue(
404 key, i, &name_buffer[0], &name_len, NULL, NULL, NULL, &value_len);
405 name_len = name_len + 1;
406 value_len = value_len + 1;
407 std::vector<wchar_t> value_buffer(value_len);
408 result = ::RegEnumValue(key, i, &name_buffer[0], &name_len, NULL, NULL,
409 reinterpret_cast<BYTE*>(&value_buffer[0]),
410 &value_len);
411 value_buffer[value_len - 1] = L'\0';
413 if (result == ERROR_SUCCESS) {
414 AddDllToBlacklist(&value_buffer[0]);
418 // Delete the finch registry key to clear the values.
419 result = ::RegDeleteKey(key, L"");
421 ::RegCloseKey(key);
422 return result == ERROR_SUCCESS;
425 } // namespace blacklist