Implementation of the NetworkingConfigService
[chromium-blink-merge.git] / chrome_elf / blacklist / blacklist.cc
blob44629fb433104e13bd83588b2536f83002cab9a9
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"systemk.dll", // Unknown (suspected adware).
55 L"vntsrv.dll", // Virtual New Tab by APN LLC.
56 L"wajam_goblin_64.dll", // Wajam Internet Technologies.
57 L"wajam_goblin.dll", // Wajam Internet Technologies.
58 L"windowsapihookdll32.dll", // Lenovo One Key Theater.
59 // See crbug.com/379218.
60 L"windowsapihookdll64.dll", // Lenovo One Key Theater.
61 L"virtualCamera.ax", // %PROGRAMFILES%\ASUS\VirtualCamera.
62 // See crbug.com/422522.
63 L"YCWebCameraSource.ax", // CyberLink Youcam, crbug.com/424159
64 // Keep this null pointer here to mark the end of the list.
65 NULL,
68 bool g_blocked_dlls[kTroublesomeDllsMaxCount] = {};
69 int g_num_blocked_dlls = 0;
71 } // namespace blacklist
73 // Allocate storage for thunks in a page of this module to save on doing
74 // an extra allocation at run time.
75 #pragma section(".crthunk",read,execute)
76 __declspec(allocate(".crthunk")) sandbox::ThunkData g_thunk_storage;
78 namespace {
80 // Record if the blacklist was successfully initialized so processes can easily
81 // determine if the blacklist is enabled for them.
82 bool g_blacklist_initialized = false;
84 // Helper to set DWORD registry values.
85 DWORD SetDWValue(HKEY* key, const wchar_t* property, DWORD value) {
86 return ::RegSetValueEx(*key,
87 property,
89 REG_DWORD,
90 reinterpret_cast<LPBYTE>(&value),
91 sizeof(value));
94 bool GenerateStateFromBeaconAndAttemptCount(HKEY* key, DWORD blacklist_state) {
95 LONG result = 0;
96 if (blacklist_state == blacklist::BLACKLIST_ENABLED) {
97 // If the blacklist succeeded on the previous run reset the failure
98 // counter.
99 return (SetDWValue(key,
100 blacklist::kBeaconAttemptCount,
101 static_cast<DWORD>(0)) == ERROR_SUCCESS);
102 } else {
103 // Some part of the blacklist setup failed last time. If this has occured
104 // blacklist::kBeaconMaxAttempts times in a row we switch the state to
105 // failed and skip setting up the blacklist.
106 DWORD attempt_count = 0;
107 DWORD attempt_count_size = sizeof(attempt_count);
108 result = ::RegQueryValueEx(*key,
109 blacklist::kBeaconAttemptCount,
111 NULL,
112 reinterpret_cast<LPBYTE>(&attempt_count),
113 &attempt_count_size);
115 if (result == ERROR_FILE_NOT_FOUND)
116 attempt_count = 0;
117 else if (result != ERROR_SUCCESS)
118 return false;
120 ++attempt_count;
121 SetDWValue(key, blacklist::kBeaconAttemptCount, attempt_count);
123 if (attempt_count >= blacklist::kBeaconMaxAttempts) {
124 blacklist_state = blacklist::BLACKLIST_SETUP_FAILED;
125 SetDWValue(key, blacklist::kBeaconState, blacklist_state);
128 return false;
132 } // namespace
134 namespace blacklist {
136 #if defined(_WIN64)
137 // Allocate storage for the pointer to the old NtMapViewOfSectionFunction.
138 #pragma section(".oldntmap",write,read)
139 __declspec(allocate(".oldntmap"))
140 NtMapViewOfSectionFunction g_nt_map_view_of_section_func = NULL;
141 #endif
143 bool LeaveSetupBeacon() {
144 HKEY key = NULL;
145 DWORD disposition = 0;
146 LONG result = ::RegCreateKeyEx(HKEY_CURRENT_USER,
147 kRegistryBeaconPath,
149 NULL,
150 REG_OPTION_NON_VOLATILE,
151 KEY_QUERY_VALUE | KEY_SET_VALUE,
152 NULL,
153 &key,
154 &disposition);
155 if (result != ERROR_SUCCESS)
156 return false;
158 // Retrieve the current blacklist state.
159 DWORD blacklist_state = BLACKLIST_STATE_MAX;
160 DWORD blacklist_state_size = sizeof(blacklist_state);
161 DWORD type = 0;
162 result = ::RegQueryValueEx(key,
163 kBeaconState,
165 &type,
166 reinterpret_cast<LPBYTE>(&blacklist_state),
167 &blacklist_state_size);
169 if (result != ERROR_SUCCESS || blacklist_state == BLACKLIST_DISABLED ||
170 type != REG_DWORD) {
171 ::RegCloseKey(key);
172 return false;
175 if (!GenerateStateFromBeaconAndAttemptCount(&key, blacklist_state)) {
176 ::RegCloseKey(key);
177 return false;
180 result = SetDWValue(&key, kBeaconState, BLACKLIST_SETUP_RUNNING);
181 ::RegCloseKey(key);
183 return (result == ERROR_SUCCESS);
186 bool ResetBeacon() {
187 HKEY key = NULL;
188 DWORD disposition = 0;
189 LONG result = ::RegCreateKeyEx(HKEY_CURRENT_USER,
190 kRegistryBeaconPath,
192 NULL,
193 REG_OPTION_NON_VOLATILE,
194 KEY_QUERY_VALUE | KEY_SET_VALUE,
195 NULL,
196 &key,
197 &disposition);
198 if (result != ERROR_SUCCESS)
199 return false;
201 DWORD blacklist_state = BLACKLIST_STATE_MAX;
202 DWORD blacklist_state_size = sizeof(blacklist_state);
203 DWORD type = 0;
204 result = ::RegQueryValueEx(key,
205 kBeaconState,
207 &type,
208 reinterpret_cast<LPBYTE>(&blacklist_state),
209 &blacklist_state_size);
211 if (result != ERROR_SUCCESS || type != REG_DWORD) {
212 ::RegCloseKey(key);
213 return false;
216 // Reaching this point with the setup running state means the setup did not
217 // crash, so we reset to enabled. Any other state indicates that setup was
218 // skipped; in that case we leave the state alone for later recording.
219 if (blacklist_state == BLACKLIST_SETUP_RUNNING)
220 result = SetDWValue(&key, kBeaconState, BLACKLIST_ENABLED);
222 ::RegCloseKey(key);
223 return (result == ERROR_SUCCESS);
226 int BlacklistSize() {
227 int size = -1;
228 while (blacklist::g_troublesome_dlls[++size] != NULL) {}
230 return size;
233 bool IsBlacklistInitialized() {
234 return g_blacklist_initialized;
237 int GetBlacklistIndex(const wchar_t* dll_name) {
238 for (int i = 0; i < kTroublesomeDllsMaxCount && g_troublesome_dlls[i]; ++i) {
239 if (_wcsicmp(dll_name, g_troublesome_dlls[i]) == 0)
240 return i;
242 return -1;
245 bool AddDllToBlacklist(const wchar_t* dll_name) {
246 int blacklist_size = BlacklistSize();
247 // We need to leave one space at the end for the null pointer.
248 if (blacklist_size + 1 >= kTroublesomeDllsMaxCount)
249 return false;
250 for (int i = 0; i < blacklist_size; ++i) {
251 if (!_wcsicmp(g_troublesome_dlls[i], dll_name))
252 return true;
255 // Copy string to blacklist.
256 wchar_t* str_buffer = new wchar_t[wcslen(dll_name) + 1];
257 wcscpy(str_buffer, dll_name);
259 g_troublesome_dlls[blacklist_size] = str_buffer;
260 g_blocked_dlls[blacklist_size] = false;
261 return true;
264 bool RemoveDllFromBlacklist(const wchar_t* dll_name) {
265 int blacklist_size = BlacklistSize();
266 for (int i = 0; i < blacklist_size; ++i) {
267 if (!_wcsicmp(g_troublesome_dlls[i], dll_name)) {
268 // Found the thing to remove. Delete it then replace it with the last
269 // element.
270 delete[] g_troublesome_dlls[i];
271 g_troublesome_dlls[i] = g_troublesome_dlls[blacklist_size - 1];
272 g_troublesome_dlls[blacklist_size - 1] = NULL;
274 // Also update the stats recording if we have blocked this dll or not.
275 if (g_blocked_dlls[i])
276 --g_num_blocked_dlls;
277 g_blocked_dlls[i] = g_blocked_dlls[blacklist_size - 1];
278 return true;
281 return false;
284 // TODO(csharp): Maybe store these values in the registry so we can
285 // still report them if Chrome crashes early.
286 void SuccessfullyBlocked(const wchar_t** blocked_dlls, int* size) {
287 if (size == NULL)
288 return;
290 // If the array isn't valid or big enough, just report the size it needs to
291 // be and return.
292 if (blocked_dlls == NULL && *size < g_num_blocked_dlls) {
293 *size = g_num_blocked_dlls;
294 return;
297 *size = g_num_blocked_dlls;
299 int strings_to_fill = 0;
300 for (int i = 0; strings_to_fill < g_num_blocked_dlls && g_troublesome_dlls[i];
301 ++i) {
302 if (g_blocked_dlls[i]) {
303 blocked_dlls[strings_to_fill] = g_troublesome_dlls[i];
304 ++strings_to_fill;
309 void BlockedDll(size_t blocked_index) {
310 assert(blocked_index < kTroublesomeDllsMaxCount);
312 if (!g_blocked_dlls[blocked_index] &&
313 blocked_index < kTroublesomeDllsMaxCount) {
314 ++g_num_blocked_dlls;
315 g_blocked_dlls[blocked_index] = true;
319 bool Initialize(bool force) {
320 // Check to see that we found the functions we need in ntdll.
321 if (!InitializeInterceptImports())
322 return false;
324 // Check to see if this is a non-browser process, abort if so.
325 if (IsNonBrowserProcess())
326 return false;
328 // Check to see if the blacklist beacon is still set to running (indicating a
329 // failure) or disabled, and abort if so.
330 if (!force && !LeaveSetupBeacon())
331 return false;
333 // It is possible for other dlls to have already patched code by now and
334 // attempting to patch their code might result in crashes.
335 const bool kRelaxed = false;
337 // Create a thunk via the appropriate ServiceResolver instance.
338 sandbox::ServiceResolverThunk* thunk = GetThunk(kRelaxed);
340 // Don't try blacklisting on unsupported OS versions.
341 if (!thunk)
342 return false;
344 BYTE* thunk_storage = reinterpret_cast<BYTE*>(&g_thunk_storage);
346 // Mark the thunk storage as readable and writeable, since we
347 // ready to write to it.
348 DWORD old_protect = 0;
349 if (!VirtualProtect(&g_thunk_storage,
350 sizeof(g_thunk_storage),
351 PAGE_EXECUTE_READWRITE,
352 &old_protect)) {
353 return false;
356 thunk->AllowLocalPatches();
358 // We declare this early so it can be used in the 64-bit block below and
359 // still work on 32-bit build when referenced at the end of the function.
360 BOOL page_executable = false;
362 // Replace the default NtMapViewOfSection with our patched version.
363 #if defined(_WIN64)
364 NTSTATUS ret = thunk->Setup(::GetModuleHandle(sandbox::kNtdllName),
365 reinterpret_cast<void*>(&__ImageBase),
366 "NtMapViewOfSection",
367 NULL,
368 &blacklist::BlNtMapViewOfSection64,
369 thunk_storage,
370 sizeof(sandbox::ThunkData),
371 NULL);
373 // Keep a pointer to the original code, we don't have enough space to
374 // add it directly to the call.
375 g_nt_map_view_of_section_func = reinterpret_cast<NtMapViewOfSectionFunction>(
376 thunk_storage);
378 // Ensure that the pointer to the old function can't be changed.
379 page_executable = VirtualProtect(&g_nt_map_view_of_section_func,
380 sizeof(g_nt_map_view_of_section_func),
381 PAGE_EXECUTE_READ,
382 &old_protect);
383 #else
384 NTSTATUS ret = thunk->Setup(::GetModuleHandle(sandbox::kNtdllName),
385 reinterpret_cast<void*>(&__ImageBase),
386 "NtMapViewOfSection",
387 NULL,
388 &blacklist::BlNtMapViewOfSection,
389 thunk_storage,
390 sizeof(sandbox::ThunkData),
391 NULL);
392 #endif
393 delete thunk;
395 // Record if we have initialized the blacklist.
396 g_blacklist_initialized = NT_SUCCESS(ret);
398 // Mark the thunk storage as executable and prevent any future writes to it.
399 page_executable = page_executable && VirtualProtect(&g_thunk_storage,
400 sizeof(g_thunk_storage),
401 PAGE_EXECUTE_READ,
402 &old_protect);
404 AddDllsFromRegistryToBlacklist();
406 return NT_SUCCESS(ret) && page_executable;
409 void AddDllsFromRegistryToBlacklist() {
410 HKEY key = NULL;
411 LONG result = ::RegOpenKeyEx(HKEY_CURRENT_USER,
412 kRegistryFinchListPath,
414 KEY_QUERY_VALUE | KEY_SET_VALUE,
415 &key);
417 if (result != ERROR_SUCCESS)
418 return;
420 // We add dlls from the registry to the blacklist.
421 DWORD value_len;
422 DWORD name_len = MAX_PATH;
423 std::vector<wchar_t> name_buffer(name_len);
424 for (int i = 0; result == ERROR_SUCCESS; ++i) {
425 name_len = MAX_PATH;
426 value_len = 0;
427 result = ::RegEnumValue(
428 key, i, &name_buffer[0], &name_len, NULL, NULL, NULL, &value_len);
429 if (result != ERROR_SUCCESS)
430 break;
432 name_len = name_len + 1;
433 value_len = value_len + 1;
434 std::vector<wchar_t> value_buffer(value_len);
435 result = ::RegEnumValue(key, i, &name_buffer[0], &name_len, NULL, NULL,
436 reinterpret_cast<BYTE*>(&value_buffer[0]),
437 &value_len);
438 if (result != ERROR_SUCCESS)
439 break;
440 value_buffer[value_len - 1] = L'\0';
441 AddDllToBlacklist(&value_buffer[0]);
444 ::RegCloseKey(key);
445 return;
448 } // namespace blacklist