Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / chrome_elf / blacklist / blacklist.cc
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.
4
5 #include "chrome_elf/blacklist/blacklist.h"
6
7 #include <assert.h>
8 #include <string.h>
9
10 #include <vector>
11
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"
20
21 // http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx
22 extern "C" IMAGE_DOS_HEADER __ImageBase;
23
24 namespace blacklist{
25
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"cespy.dll",                         // CovenantEyes.
40   L"chrmxtn.dll",                       // Unknown (keystroke logger).
41   L"cplushook.dll",                     // Unknown (suspected malware).
42   L"datamngr.dll",                      // Unknown (suspected adware).
43   L"hk.dll",                            // Unknown (keystroke logger).
44   L"libapi2hook.dll",                   // V-Bates.
45   L"libinject.dll",                     // V-Bates.
46   L"libinject2.dll",                    // V-Bates.
47   L"libredir2.dll",                     // V-Bates.
48   L"libsvn_tsvn32.dll",                 // TortoiseSVN.
49   L"libwinhook.dll",                    // V-Bates.
50   L"lmrn.dll",                          // Unknown.
51   L"minisp.dll",                        // Unknown (suspected malware).
52   L"scdetour.dll",                      // Quick Heal Antivirus.
53                                         // See crbug.com/382561.
54   L"systemk.dll",                       // Unknown (suspected adware).
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,
60 };
61
62 bool g_blocked_dlls[kTroublesomeDllsMaxCount] = {};
63 int g_num_blocked_dlls = 0;
64
65 }  // namespace blacklist
66
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;
71
72 namespace {
73
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;
77
78 // Helper to set DWORD registry values.
79 DWORD SetDWValue(HKEY* key, const wchar_t* property, DWORD value) {
80   return ::RegSetValueEx(*key,
81                          property,
82                          0,
83                          REG_DWORD,
84                          reinterpret_cast<LPBYTE>(&value),
85                          sizeof(value));
86 }
87
88 bool GenerateStateFromBeaconAndAttemptCount(HKEY* key, DWORD blacklist_state) {
89   LONG result = 0;
90   if (blacklist_state == blacklist::BLACKLIST_SETUP_RUNNING) {
91     // Some part of the blacklist setup failed last time.  If this has occured
92     // blacklist::kBeaconMaxAttempts times in a row we switch the state to
93     // failed and skip setting up the blacklist.
94     DWORD attempt_count = 0;
95     DWORD attempt_count_size = sizeof(attempt_count);
96     result = ::RegQueryValueEx(*key,
97                                blacklist::kBeaconAttemptCount,
98                                0,
99                                NULL,
100                                reinterpret_cast<LPBYTE>(&attempt_count),
101                                &attempt_count_size);
102
103     if (result == ERROR_FILE_NOT_FOUND)
104       attempt_count = 0;
105     else if (result != ERROR_SUCCESS)
106       return false;
107
108     ++attempt_count;
109     SetDWValue(key, blacklist::kBeaconAttemptCount, attempt_count);
110
111     if (attempt_count >= blacklist::kBeaconMaxAttempts) {
112       blacklist_state = blacklist::BLACKLIST_SETUP_FAILED;
113       SetDWValue(key, blacklist::kBeaconState, blacklist_state);
114       return false;
115     }
116   } else if (blacklist_state == blacklist::BLACKLIST_ENABLED) {
117     // If the blacklist succeeded on the previous run reset the failure
118     // counter.
119     result =
120         SetDWValue(key, blacklist::kBeaconAttemptCount, static_cast<DWORD>(0));
121     if (result != ERROR_SUCCESS) {
122       return false;
123     }
124   }
125   return true;
126 }
127
128 }  // namespace
129
130 namespace blacklist {
131
132 #if defined(_WIN64)
133   // Allocate storage for the pointer to the old NtMapViewOfSectionFunction.
134 #pragma section(".oldntmap",write,read)
135   __declspec(allocate(".oldntmap"))
136     NtMapViewOfSectionFunction g_nt_map_view_of_section_func = NULL;
137 #endif
138
139 bool LeaveSetupBeacon() {
140   HKEY key = NULL;
141   DWORD disposition = 0;
142   LONG result = ::RegCreateKeyEx(HKEY_CURRENT_USER,
143                                  kRegistryBeaconPath,
144                                  0,
145                                  NULL,
146                                  REG_OPTION_NON_VOLATILE,
147                                  KEY_QUERY_VALUE | KEY_SET_VALUE,
148                                  NULL,
149                                  &key,
150                                  &disposition);
151   if (result != ERROR_SUCCESS)
152     return false;
153
154   // Retrieve the current blacklist state.
155   DWORD blacklist_state = BLACKLIST_STATE_MAX;
156   DWORD blacklist_state_size = sizeof(blacklist_state);
157   DWORD type = 0;
158   result = ::RegQueryValueEx(key,
159                              kBeaconState,
160                              0,
161                              &type,
162                              reinterpret_cast<LPBYTE>(&blacklist_state),
163                              &blacklist_state_size);
164
165   if (blacklist_state == BLACKLIST_DISABLED || result != ERROR_SUCCESS ||
166       type != REG_DWORD) {
167     ::RegCloseKey(key);
168     return false;
169   }
170
171   if (!GenerateStateFromBeaconAndAttemptCount(&key, blacklist_state)) {
172     ::RegCloseKey(key);
173     return false;
174   }
175
176   result = SetDWValue(&key, kBeaconState, BLACKLIST_SETUP_RUNNING);
177   ::RegCloseKey(key);
178
179   return (result == ERROR_SUCCESS);
180 }
181
182 bool ResetBeacon() {
183   HKEY key = NULL;
184   DWORD disposition = 0;
185   LONG result = ::RegCreateKeyEx(HKEY_CURRENT_USER,
186                                  kRegistryBeaconPath,
187                                  0,
188                                  NULL,
189                                  REG_OPTION_NON_VOLATILE,
190                                  KEY_QUERY_VALUE | KEY_SET_VALUE,
191                                  NULL,
192                                  &key,
193                                  &disposition);
194   if (result != ERROR_SUCCESS)
195     return false;
196
197   DWORD blacklist_state = BLACKLIST_STATE_MAX;
198   DWORD blacklist_state_size = sizeof(blacklist_state);
199   DWORD type = 0;
200   result = ::RegQueryValueEx(key,
201                              kBeaconState,
202                              0,
203                              &type,
204                              reinterpret_cast<LPBYTE>(&blacklist_state),
205                              &blacklist_state_size);
206
207   if (result != ERROR_SUCCESS || type != REG_DWORD) {
208     ::RegCloseKey(key);
209     return false;
210   }
211
212   // Reaching this point with the setup running state means the setup did not
213   // crash, so we reset to enabled.  Any other state indicates that setup was
214   // skipped; in that case we leave the state alone for later recording.
215   if (blacklist_state == BLACKLIST_SETUP_RUNNING)
216     result = SetDWValue(&key, kBeaconState, BLACKLIST_ENABLED);
217
218   ::RegCloseKey(key);
219   return (result == ERROR_SUCCESS);
220 }
221
222 int BlacklistSize() {
223   int size = -1;
224   while (blacklist::g_troublesome_dlls[++size] != NULL) {}
225
226   return size;
227 }
228
229 bool IsBlacklistInitialized() {
230   return g_blacklist_initialized;
231 }
232
233 int GetBlacklistIndex(const wchar_t* dll_name) {
234   for (int i = 0; i < kTroublesomeDllsMaxCount, g_troublesome_dlls[i]; ++i) {
235     if (_wcsicmp(dll_name, g_troublesome_dlls[i]) == 0)
236       return i;
237   }
238   return -1;
239 }
240
241 bool AddDllToBlacklist(const wchar_t* dll_name) {
242   int blacklist_size = BlacklistSize();
243   // We need to leave one space at the end for the null pointer.
244   if (blacklist_size + 1 >= kTroublesomeDllsMaxCount)
245     return false;
246   for (int i = 0; i < blacklist_size; ++i) {
247     if (!_wcsicmp(g_troublesome_dlls[i], dll_name))
248       return true;
249   }
250
251   // Copy string to blacklist.
252   wchar_t* str_buffer = new wchar_t[wcslen(dll_name) + 1];
253   wcscpy(str_buffer, dll_name);
254
255   g_troublesome_dlls[blacklist_size] = str_buffer;
256   g_blocked_dlls[blacklist_size] = false;
257   return true;
258 }
259
260 bool RemoveDllFromBlacklist(const wchar_t* dll_name) {
261   int blacklist_size = BlacklistSize();
262   for (int i = 0; i < blacklist_size; ++i) {
263     if (!_wcsicmp(g_troublesome_dlls[i], dll_name)) {
264       // Found the thing to remove. Delete it then replace it with the last
265       // element.
266       delete[] g_troublesome_dlls[i];
267       g_troublesome_dlls[i] = g_troublesome_dlls[blacklist_size - 1];
268       g_troublesome_dlls[blacklist_size - 1] = NULL;
269
270       // Also update the stats recording if we have blocked this dll or not.
271       if (g_blocked_dlls[i])
272         --g_num_blocked_dlls;
273       g_blocked_dlls[i] = g_blocked_dlls[blacklist_size - 1];
274       return true;
275     }
276   }
277   return false;
278 }
279
280 // TODO(csharp): Maybe store these values in the registry so we can
281 // still report them if Chrome crashes early.
282 void SuccessfullyBlocked(const wchar_t** blocked_dlls, int* size) {
283   if (size == NULL)
284     return;
285
286   // If the array isn't valid or big enough, just report the size it needs to
287   // be and return.
288   if (blocked_dlls == NULL && *size < g_num_blocked_dlls) {
289     *size = g_num_blocked_dlls;
290     return;
291   }
292
293   *size = g_num_blocked_dlls;
294
295   int strings_to_fill = 0;
296   for (int i = 0; strings_to_fill < g_num_blocked_dlls && g_troublesome_dlls[i];
297        ++i) {
298     if (g_blocked_dlls[i]) {
299       blocked_dlls[strings_to_fill] = g_troublesome_dlls[i];
300       ++strings_to_fill;
301     }
302   }
303 }
304
305 void BlockedDll(size_t blocked_index) {
306   assert(blocked_index < kTroublesomeDllsMaxCount);
307
308   if (!g_blocked_dlls[blocked_index] &&
309       blocked_index < kTroublesomeDllsMaxCount) {
310     ++g_num_blocked_dlls;
311     g_blocked_dlls[blocked_index] = true;
312   }
313 }
314
315 bool Initialize(bool force) {
316   // Check to see that we found the functions we need in ntdll.
317   if (!InitializeInterceptImports())
318     return false;
319
320   // Check to see if this is a non-browser process, abort if so.
321   if (IsNonBrowserProcess())
322     return false;
323
324   // Check to see if the blacklist beacon is still set to running (indicating a
325   // failure) or disabled, and abort if so.
326   if (!force && !LeaveSetupBeacon())
327     return false;
328
329   // It is possible for other dlls to have already patched code by now and
330   // attempting to patch their code might result in crashes.
331   const bool kRelaxed = false;
332
333   // Create a thunk via the appropriate ServiceResolver instance.
334   sandbox::ServiceResolverThunk* thunk = GetThunk(kRelaxed);
335
336   // Don't try blacklisting on unsupported OS versions.
337   if (!thunk)
338     return false;
339
340   BYTE* thunk_storage = reinterpret_cast<BYTE*>(&g_thunk_storage);
341
342   // Mark the thunk storage as readable and writeable, since we
343   // ready to write to it.
344   DWORD old_protect = 0;
345   if (!VirtualProtect(&g_thunk_storage,
346                       sizeof(g_thunk_storage),
347                       PAGE_EXECUTE_READWRITE,
348                       &old_protect)) {
349     return false;
350   }
351
352   thunk->AllowLocalPatches();
353
354   // We declare this early so it can be used in the 64-bit block below and
355   // still work on 32-bit build when referenced at the end of the function.
356   BOOL page_executable = false;
357
358   // Replace the default NtMapViewOfSection with our patched version.
359 #if defined(_WIN64)
360   NTSTATUS ret = thunk->Setup(::GetModuleHandle(sandbox::kNtdllName),
361                               reinterpret_cast<void*>(&__ImageBase),
362                               "NtMapViewOfSection",
363                               NULL,
364                               &blacklist::BlNtMapViewOfSection64,
365                               thunk_storage,
366                               sizeof(sandbox::ThunkData),
367                               NULL);
368
369   // Keep a pointer to the original code, we don't have enough space to
370   // add it directly to the call.
371   g_nt_map_view_of_section_func = reinterpret_cast<NtMapViewOfSectionFunction>(
372       thunk_storage);
373
374   // Ensure that the pointer to the old function can't be changed.
375  page_executable = VirtualProtect(&g_nt_map_view_of_section_func,
376                                   sizeof(g_nt_map_view_of_section_func),
377                                   PAGE_EXECUTE_READ,
378                                   &old_protect);
379 #else
380   NTSTATUS ret = thunk->Setup(::GetModuleHandle(sandbox::kNtdllName),
381                               reinterpret_cast<void*>(&__ImageBase),
382                               "NtMapViewOfSection",
383                               NULL,
384                               &blacklist::BlNtMapViewOfSection,
385                               thunk_storage,
386                               sizeof(sandbox::ThunkData),
387                               NULL);
388 #endif
389   delete thunk;
390
391   // Record if we have initialized the blacklist.
392   g_blacklist_initialized = NT_SUCCESS(ret);
393
394   // Mark the thunk storage as executable and prevent any future writes to it.
395   page_executable = page_executable && VirtualProtect(&g_thunk_storage,
396                                                       sizeof(g_thunk_storage),
397                                                       PAGE_EXECUTE_READ,
398                                                       &old_protect);
399
400   AddDllsFromRegistryToBlacklist();
401
402   return NT_SUCCESS(ret) && page_executable;
403 }
404
405 void AddDllsFromRegistryToBlacklist() {
406   HKEY key = NULL;
407   LONG result = ::RegOpenKeyEx(HKEY_CURRENT_USER,
408                                kRegistryFinchListPath,
409                                0,
410                                KEY_QUERY_VALUE | KEY_SET_VALUE,
411                                &key);
412
413   if (result != ERROR_SUCCESS)
414     return;
415
416   // We add dlls from the registry to the blacklist.
417   DWORD value_len;
418   DWORD name_len = MAX_PATH;
419   std::vector<wchar_t> name_buffer(name_len);
420   for (int i = 0; result == ERROR_SUCCESS; ++i) {
421     name_len = MAX_PATH;
422     value_len = 0;
423     result = ::RegEnumValue(
424         key, i, &name_buffer[0], &name_len, NULL, NULL, NULL, &value_len);
425     if (result != ERROR_SUCCESS)
426       break;
427
428     name_len = name_len + 1;
429     value_len = value_len + 1;
430     std::vector<wchar_t> value_buffer(value_len);
431     result = ::RegEnumValue(key, i, &name_buffer[0], &name_len, NULL, NULL,
432                             reinterpret_cast<BYTE*>(&value_buffer[0]),
433                             &value_len);
434     if (result != ERROR_SUCCESS)
435       break;
436     value_buffer[value_len - 1] = L'\0';
437     AddDllToBlacklist(&value_buffer[0]);
438   }
439
440   ::RegCloseKey(key);
441   return;
442 }
443
444 }  // namespace blacklist