Remove no longer needed toolbar layer method.
[chromium-blink-merge.git] / chrome / browser / enumerate_modules_model_win.cc
blobc5d394358cf80f8d7b34a67aa70774c548aa5ef3
1 // Copyright (c) 2012 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/browser/enumerate_modules_model_win.h"
7 #include <Tlhelp32.h>
8 #include <wintrust.h>
9 #include <algorithm>
11 #include "base/bind.h"
12 #include "base/command_line.h"
13 #include "base/environment.h"
14 #include "base/file_version_info_win.h"
15 #include "base/files/file_path.h"
16 #include "base/i18n/case_conversion.h"
17 #include "base/metrics/histogram.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/time/time.h"
22 #include "base/values.h"
23 #include "base/version.h"
24 #include "base/win/registry.h"
25 #include "base/win/scoped_handle.h"
26 #include "base/win/windows_version.h"
27 #include "chrome/browser/chrome_notification_types.h"
28 #include "chrome/browser/net/service_providers_win.h"
29 #include "chrome/common/chrome_constants.h"
30 #include "chrome/grit/generated_resources.h"
31 #include "content/public/browser/notification_service.h"
32 #include "crypto/sha2.h"
33 #include "ui/base/l10n/l10n_util.h"
35 using content::BrowserThread;
37 // The period of time (in milliseconds) to wait until checking to see if any
38 // incompatible modules exist.
39 static const int kModuleCheckDelayMs = 45 * 1000;
41 // The path to the Shell Extension key in the Windows registry.
42 static const wchar_t kRegPath[] =
43 L"Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved";
45 // Short-hand for things on the blacklist you should simply get rid of.
46 static const ModuleEnumerator::RecommendedAction kUninstallLink =
47 static_cast<ModuleEnumerator::RecommendedAction>(
48 ModuleEnumerator::UNINSTALL | ModuleEnumerator::SEE_LINK);
50 // Short-hand for things on the blacklist we are investigating and have info.
51 static const ModuleEnumerator::RecommendedAction kInvestigatingLink =
52 static_cast<ModuleEnumerator::RecommendedAction>(
53 ModuleEnumerator::INVESTIGATING | ModuleEnumerator::SEE_LINK);
55 // A sort method that sorts by bad modules first, then by full name (including
56 // path).
57 static bool ModuleSort(const ModuleEnumerator::Module& a,
58 const ModuleEnumerator::Module& b) {
59 if (a.status != b.status)
60 return a.status > b.status;
62 if (a.location == b.location)
63 return a.name < b.name;
65 return a.location < b.location;
68 namespace {
70 // Used to protect the LoadedModuleVector which is accessed
71 // from both the UI thread and the FILE thread.
72 base::Lock* lock = NULL;
74 // A struct to help de-duping modules before adding them to the enumerated
75 // modules vector.
76 struct FindModule {
77 public:
78 explicit FindModule(const ModuleEnumerator::Module& x)
79 : module(x) {}
80 bool operator()(const ModuleEnumerator::Module& module_in) const {
81 return (module.location == module_in.location) &&
82 (module.name == module_in.name);
85 const ModuleEnumerator::Module& module;
88 // Returns the long path name given a short path name. A short path name is a
89 // path that follows the 8.3 convention and has ~x in it. If the path is already
90 // a long path name, the function returns the current path without modification.
91 bool ConvertToLongPath(const base::string16& short_path,
92 base::string16* long_path) {
93 wchar_t long_path_buf[MAX_PATH];
94 DWORD return_value = GetLongPathName(short_path.c_str(), long_path_buf,
95 MAX_PATH);
96 if (return_value != 0 && return_value < MAX_PATH) {
97 *long_path = long_path_buf;
98 return true;
101 return false;
104 } // namespace
106 // The browser process module blacklist. This lists modules that are known
107 // to cause compatibility issues within the browser process. When adding to this
108 // list, make sure that all paths are lower-case, in long pathname form, end
109 // with a slash and use environments variables (or just look at one of the
110 // comments below and keep it consistent with that). When adding an entry with
111 // an environment variable not currently used in the list below, make sure to
112 // update the list in PreparePathMappings. Filename, Description/Signer, and
113 // Location must be entered as hashes (see GenerateHash). Filename is mandatory.
114 // Entries without any Description, Signer info, or Location will never be
115 // marked as confirmed bad (only as suspicious).
116 const ModuleEnumerator::BlacklistEntry ModuleEnumerator::kModuleBlacklist[] = {
117 // NOTE: Please keep this list sorted by dll name, then location.
119 // Version 3.2.1.6 seems to be implicated in most cases (and 3.2.2.2 in some).
120 // There is a more recent version available for download.
121 // accelerator.dll, "%programfiles%\\speedbit video accelerator\\".
122 { "7ba9402f", "c9132d48", "", "", "", ALL, kInvestigatingLink },
124 // apiqq0.dll, "%temp%\\".
125 { "26134911", "59145acf", "", "", "", ALL, kUninstallLink },
127 // arking0.dll, "%systemroot%\\system32\\".
128 { "f5d8f549", "23d01d5b", "", "", "", ALL, kUninstallLink },
130 // arking1.dll, "%systemroot%\\system32\\".
131 { "c60ca062", "23d01d5b", "", "", "", ALL, kUninstallLink },
133 // aswjsflt.dll, "%ProgramFiles%\\avast software\\avast\\", "AVAST Software".
134 // NOTE: The digital signature of the DLL is double null terminated.
135 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
136 // when blocked from running.
137 { "2ea5422a", "6b3a1b00", "a7db0e0c", "", "8.0", XP,
138 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
140 // aswjsflt.dll, "%ProgramFiles%\\alwil software\\avast5\\", "AVAST Software".
141 // NOTE: The digital signature of the DLL is double null terminated.
142 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
143 // when blocked from running.
144 { "2ea5422a", "d8686924", "a7db0e0c", "", "8.0", XP,
145 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
147 // Said to belong to Killer NIC from BigFoot Networks (not verified). Versions
148 // 6.0.0.7 and 6.0.0.10 implicated.
149 // bfllr.dll, "%systemroot%\\system32\\".
150 { "6bb57633", "23d01d5b", "", "", "", ALL, kInvestigatingLink },
152 // clickpotatolitesahook.dll, "". Different version each report.
153 { "0396e037.dll", "", "", "", "", ALL, kUninstallLink },
155 // cvasds0.dll, "%temp%\\".
156 { "5ce0037c", "59145acf", "", "", "", ALL, kUninstallLink },
158 // cwalsp.dll, "%systemroot%\\system32\\".
159 { "e579a039", "23d01d5b", "", "", "", ALL, kUninstallLink },
161 // datamngr.dll (1), "%programfiles%\\searchqu toolbar\\datamngr\\".
162 { "7add320b", "470a3da3", "", "", "", ALL, kUninstallLink },
164 // datamngr.dll (2), "%programfiles%\\windows searchqu toolbar\\".
165 { "7add320b", "7a3c8be3", "", "", "", ALL, kUninstallLink },
167 // dsoqq0.dll, "%temp%\\".
168 { "1c4df325", "59145acf", "", "", "", ALL, kUninstallLink },
170 // flt.dll, "%programfiles%\\tueagles\\".
171 { "6d01f4a1", "7935e9c2", "", "", "", ALL, kUninstallLink },
173 // This looks like a malware edition of a Brazilian Bank plugin, sometimes
174 // referred to as Malware.Banc.A.
175 // gbieh.dll, "%programfiles%\\gbplugin\\".
176 { "4cb4f2e3", "88e4a3b1", "", "", "", ALL, kUninstallLink },
178 // hblitesahook.dll. Each report has different version number in location.
179 { "5d10b363", "", "", "", "", ALL, kUninstallLink },
181 // icf.dll, "%systemroot%\\system32\\".
182 { "303825ed", "23d01d5b", "", "", "", ALL, INVESTIGATING },
184 // idmmbc.dll (IDM), "%systemroot%\\system32\\". See: http://crbug.com/26892/.
185 { "b8dce5c3", "23d01d5b", "", "", "6.03", ALL,
186 static_cast<RecommendedAction>(UPDATE | DISABLE) },
188 // imon.dll (NOD32), "%systemroot%\\system32\\". See: http://crbug.com/21715.
189 { "8f42f22e", "23d01d5b", "", "", "4.0", ALL,
190 static_cast<RecommendedAction>(UPDATE | DISABLE) },
192 // is3lsp.dll, "%commonprogramfiles%\\is3\\anti-spyware\\".
193 { "7ffbdce9", "bc5673f2", "", "", "", ALL,
194 static_cast<RecommendedAction>(UPDATE | DISABLE | SEE_LINK) },
196 // jsi.dll, "%programfiles%\\profilecraze\\".
197 { "f9555eea", "e3548061", "", "", "", ALL, kUninstallLink },
199 // kernel.dll, "%programfiles%\\contentwatch\\internet protection\\modules\\".
200 { "ead2768e", "4e61ce60", "", "", "", ALL, INVESTIGATING },
202 // mgking0.dll, "%systemroot%\\system32\\".
203 { "d0893e38", "23d01d5b", "", "", "", ALL, kUninstallLink },
205 // mgking0.dll, "%temp%\\".
206 { "d0893e38", "59145acf", "", "", "", ALL, kUninstallLink },
208 // mgking1.dll, "%systemroot%\\system32\\".
209 { "3e837222", "23d01d5b", "", "", "", ALL, kUninstallLink },
211 // mgking1.dll, "%temp%\\".
212 { "3e837222", "59145acf", "", "", "", ALL, kUninstallLink },
214 // mstcipha.ime, "%systemroot%\\system32\\".
215 { "5523579e", "23d01d5b", "", "", "", ALL, INVESTIGATING },
217 // mwtsp.dll, "%systemroot%\\system32\\".
218 { "9830bff6", "23d01d5b", "", "", "", ALL, kUninstallLink },
220 // nodqq0.dll, "%temp%\\".
221 { "b86ce04d", "59145acf", "", "", "", ALL, kUninstallLink },
223 // nProtect GameGuard Anti-cheat system. Every report has a different
224 // location, since it is installed into and run from a game folder. Various
225 // versions implicated.
226 // npggnt.des, no fixed location.
227 { "f2c8790d", "", "", "", "", ALL, kInvestigatingLink },
229 // nvlsp.dll,
230 // "%programfiles%\\nvidia corporation\\networkaccessmanager\\bin32\\".
231 { "37f907e2", "3ad0ff23", "", "", "", ALL, INVESTIGATING },
233 // post0.dll, "%systemroot%\\system32\\".
234 { "7405c0c8", "23d01d5b", "", "", "", ALL, kUninstallLink },
236 // questbrwsearch.dll, "%programfiles%\\questbrwsearch\\".
237 { "0953ed09", "f0d5eeda", "", "", "", ALL, kUninstallLink },
239 // questscan.dll, "%programfiles%\\questscan\\".
240 { "f4f3391e", "119d20f7", "", "", "", ALL, kUninstallLink },
242 // radhslib.dll (Naomi web filter), "%programfiles%\\rnamfler\\".
243 // See http://crbug.com/12517.
244 { "7edcd250", "0733dc3e", "", "", "", ALL, INVESTIGATING },
246 // rlls.dll, "%programfiles%\\relevantknowledge\\".
247 { "a1ed94a7", "ea9d6b36", "", "", "", ALL, kUninstallLink },
249 // rooksdol.dll, "%programfiles%\\trusteer\\rapport\\bin\\".
250 { "802aefef", "06120e13", "", "", "3.5.1008.40", ALL, UPDATE },
252 // scanquery.dll, "%programfiles%\\scanquery\\".
253 { "0b52d2ae", "a4cc88b1", "", "", "", ALL, kUninstallLink },
255 // sdata.dll, "%programdata%\\srtserv\\".
256 { "1936d5cc", "223c44be", "", "", "", ALL, kUninstallLink },
258 // searchtree.dll,
259 // "%programfiles%\\contentwatch\\internet protection\\modules\\".
260 { "f6915a31", "4e61ce60", "", "", "", ALL, INVESTIGATING },
262 // sgprxy.dll, "%commonprogramfiles%\\is3\\anti-spyware\\".
263 { "005965ea", "bc5673f2", "", "", "", ALL, INVESTIGATING },
265 // snxhk.dll, "%ProgramFiles%\\avast software\\avast\\", "AVAST Software".
266 // NOTE: The digital signature of the DLL is double null terminated.
267 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
268 // when blocked from running.
269 { "46c16aa8", "6b3a1b00", "a7db0e0c", "", "8.0", XP,
270 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
272 // snxhk.dll, "%ProgramFiles%\\alwil software\\avast5\\", "AVAST Software".
273 // NOTE: The digital signature of the DLL is double null terminated.
274 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
275 // when blocked from running.
276 { "46c16aa8", "d8686924", "a7db0e0c", "", "8.0", XP,
277 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
279 // sprotector.dll, "". Different location each report.
280 { "24555d74", "", "", "", "", ALL, kUninstallLink },
282 // swi_filter_0001.dll (Sophos Web Intelligence),
283 // "%programfiles%\\sophos\\sophos anti-virus\\web intelligence\\".
284 // A small random sample all showed version 1.0.5.0.
285 { "61112d7b", "25fb120f", "", "", "", ALL, kInvestigatingLink },
287 // twking0.dll, "%systemroot%\\system32\\".
288 { "0355549b", "23d01d5b", "", "", "", ALL, kUninstallLink },
290 // twking1.dll, "%systemroot%\\system32\\".
291 { "02e44508", "23d01d5b", "", "", "", ALL, kUninstallLink },
293 // vksaver.dll, "%systemroot%\\system32\\".
294 { "c4a784d5", "23d01d5b", "", "", "", ALL, kUninstallLink },
296 // vlsp.dll (Venturi Firewall?), "%systemroot%\\system32\\".
297 { "2e4eb93d", "23d01d5b", "", "", "", ALL, INVESTIGATING },
299 // vmn3_1dn.dll, "%appdata%\\roaming\\vmndtxtb\\".
300 { "bba2037d", "9ab68585", "", "", "", ALL, kUninstallLink },
302 // webanalyzer.dll,
303 // "%programfiles%\\contentwatch\\internet protection\\modules\\".
304 { "c70b697d", "4e61ce60", "", "", "", ALL, INVESTIGATING },
306 // wowst0.dll, "%systemroot%\\system32\\".
307 { "38ad9963", "23d01d5b", "", "", "", ALL, kUninstallLink },
309 // wxbase28u_vc_cw.dll, "%systemroot%\\system32\\".
310 { "e967210d", "23d01d5b", "", "", "", ALL, kUninstallLink },
313 // Generates an 8 digit hash from the input given.
314 static void GenerateHash(const std::string& input, std::string* output) {
315 if (input.empty()) {
316 *output = "";
317 return;
320 uint8 hash[4];
321 crypto::SHA256HashString(input, hash, sizeof(hash));
322 *output = base::StringToLowerASCII(base::HexEncode(hash, sizeof(hash)));
325 // -----------------------------------------------------------------------------
327 // static
328 void ModuleEnumerator::NormalizeModule(Module* module) {
329 base::string16 path = module->location;
330 if (!ConvertToLongPath(path, &module->location))
331 module->location = path;
333 module->location = base::i18n::ToLower(module->location);
335 // Location contains the filename, so the last slash is where the path
336 // ends.
337 size_t last_slash = module->location.find_last_of(L"\\");
338 if (last_slash != base::string16::npos) {
339 module->name = module->location.substr(last_slash + 1);
340 module->location = module->location.substr(0, last_slash + 1);
341 } else {
342 module->name = module->location;
343 module->location.clear();
346 // Some version strings have things like (win7_rtm.090713-1255) appended
347 // to them. Remove that.
348 size_t first_space = module->version.find_first_of(L" ");
349 if (first_space != base::string16::npos)
350 module->version = module->version.substr(0, first_space);
352 module->normalized = true;
355 // static
356 ModuleEnumerator::ModuleStatus ModuleEnumerator::Match(
357 const ModuleEnumerator::Module& module,
358 const ModuleEnumerator::BlacklistEntry& blacklisted) {
359 // All modules must be normalized before matching against blacklist.
360 DCHECK(module.normalized);
361 // Filename is mandatory and version should not contain spaces.
362 DCHECK(strlen(blacklisted.filename) > 0);
363 DCHECK(!strstr(blacklisted.version_from, " "));
364 DCHECK(!strstr(blacklisted.version_to, " "));
366 base::win::Version version = base::win::GetVersion();
367 switch (version) {
368 case base::win::VERSION_XP:
369 if (!(blacklisted.os & XP)) return NOT_MATCHED;
370 break;
371 default:
372 break;
375 std::string filename_hash, location_hash;
376 GenerateHash(base::WideToUTF8(module.name), &filename_hash);
377 GenerateHash(base::WideToUTF8(module.location), &location_hash);
379 // Filenames are mandatory. Location is mandatory if given.
380 if (filename_hash == blacklisted.filename &&
381 (std::string(blacklisted.location).empty() ||
382 location_hash == blacklisted.location)) {
383 // We have a name match against the blacklist (and possibly location match
384 // also), so check version.
385 Version module_version(base::UTF16ToASCII(module.version));
386 Version version_min(blacklisted.version_from);
387 Version version_max(blacklisted.version_to);
388 bool version_ok = !version_min.IsValid() && !version_max.IsValid();
389 if (!version_ok) {
390 bool too_low = version_min.IsValid() &&
391 (!module_version.IsValid() ||
392 module_version.CompareTo(version_min) < 0);
393 bool too_high = version_max.IsValid() &&
394 (!module_version.IsValid() ||
395 module_version.CompareTo(version_max) >= 0);
396 version_ok = !too_low && !too_high;
399 if (version_ok) {
400 // At this point, the names match and there is no version specified
401 // or the versions also match.
403 std::string desc_or_signer(blacklisted.desc_or_signer);
404 std::string signer_hash, description_hash;
405 GenerateHash(base::WideToUTF8(module.digital_signer), &signer_hash);
406 GenerateHash(base::WideToUTF8(module.description), &description_hash);
408 // If signatures match (or both are empty), then we have a winner.
409 if (signer_hash == desc_or_signer)
410 return CONFIRMED_BAD;
412 // If descriptions match (or both are empty) and the locations match, then
413 // we also have a confirmed match.
414 if (description_hash == desc_or_signer &&
415 !location_hash.empty() && location_hash == blacklisted.location)
416 return CONFIRMED_BAD;
418 // We are not sure, but it is likely bad.
419 return SUSPECTED_BAD;
423 return NOT_MATCHED;
426 ModuleEnumerator::ModuleEnumerator(EnumerateModulesModel* observer)
427 : enumerated_modules_(NULL),
428 observer_(observer),
429 limited_mode_(false),
430 callback_thread_id_(BrowserThread::ID_COUNT) {
433 ModuleEnumerator::~ModuleEnumerator() {
436 void ModuleEnumerator::ScanNow(ModulesVector* list, bool limited_mode) {
437 enumerated_modules_ = list;
439 limited_mode_ = limited_mode;
441 if (!limited_mode_) {
442 CHECK(BrowserThread::GetCurrentThreadIdentifier(&callback_thread_id_));
443 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
444 base::Bind(&ModuleEnumerator::ScanImpl, this));
445 } else {
446 // Run it synchronously.
447 ScanImpl();
451 void ModuleEnumerator::ScanImpl() {
452 base::TimeTicks start_time = base::TimeTicks::Now();
454 enumerated_modules_->clear();
456 // Make sure the path mapping vector is setup so we can collapse paths.
457 PreparePathMappings();
459 // Enumerating loaded modules must happen first since the other types of
460 // modules check for duplication against the loaded modules.
461 base::TimeTicks checkpoint = base::TimeTicks::Now();
462 EnumerateLoadedModules();
463 base::TimeTicks checkpoint2 = base::TimeTicks::Now();
464 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateLoadedModules",
465 checkpoint2 - checkpoint);
467 checkpoint = checkpoint2;
468 EnumerateShellExtensions();
469 checkpoint2 = base::TimeTicks::Now();
470 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateShellExtensions",
471 checkpoint2 - checkpoint);
473 checkpoint = checkpoint2;
474 EnumerateWinsockModules();
475 checkpoint2 = base::TimeTicks::Now();
476 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateWinsockModules",
477 checkpoint2 - checkpoint);
479 MatchAgainstBlacklist();
481 std::sort(enumerated_modules_->begin(),
482 enumerated_modules_->end(), ModuleSort);
484 if (!limited_mode_) {
485 // Send a reply back on the UI thread.
486 BrowserThread::PostTask(callback_thread_id_, FROM_HERE,
487 base::Bind(&ModuleEnumerator::ReportBack, this));
488 } else {
489 // We are on the main thread already.
490 ReportBack();
493 UMA_HISTOGRAM_TIMES("Conflicts.EnumerationTotalTime",
494 base::TimeTicks::Now() - start_time);
497 void ModuleEnumerator::EnumerateLoadedModules() {
498 // Get all modules in the current process.
499 base::win::ScopedHandle snap(::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,
500 ::GetCurrentProcessId()));
501 if (!snap.Get())
502 return;
504 // Walk the module list.
505 MODULEENTRY32 module = { sizeof(module) };
506 if (!::Module32First(snap.Get(), &module))
507 return;
509 do {
510 // It would be weird to present chrome.exe as a loaded module.
511 if (_wcsicmp(chrome::kBrowserProcessExecutableName, module.szModule) == 0)
512 continue;
514 Module entry;
515 entry.type = LOADED_MODULE;
516 entry.location = module.szExePath;
517 PopulateModuleInformation(&entry);
519 NormalizeModule(&entry);
520 CollapsePath(&entry);
521 enumerated_modules_->push_back(entry);
522 } while (::Module32Next(snap.Get(), &module));
525 void ModuleEnumerator::EnumerateShellExtensions() {
526 ReadShellExtensions(HKEY_LOCAL_MACHINE);
527 ReadShellExtensions(HKEY_CURRENT_USER);
530 void ModuleEnumerator::ReadShellExtensions(HKEY parent) {
531 base::win::RegistryValueIterator registration(parent, kRegPath);
532 while (registration.Valid()) {
533 std::wstring key(std::wstring(L"CLSID\\") + registration.Name() +
534 L"\\InProcServer32");
535 base::win::RegKey clsid;
536 if (clsid.Open(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ) != ERROR_SUCCESS) {
537 ++registration;
538 continue;
540 base::string16 dll;
541 if (clsid.ReadValue(L"", &dll) != ERROR_SUCCESS) {
542 ++registration;
543 continue;
545 clsid.Close();
547 Module entry;
548 entry.type = SHELL_EXTENSION;
549 entry.location = dll;
550 PopulateModuleInformation(&entry);
552 NormalizeModule(&entry);
553 CollapsePath(&entry);
554 AddToListWithoutDuplicating(entry);
556 ++registration;
560 void ModuleEnumerator::EnumerateWinsockModules() {
561 // Add to this list the Winsock LSP DLLs.
562 WinsockLayeredServiceProviderList layered_providers;
563 GetWinsockLayeredServiceProviders(&layered_providers);
564 for (size_t i = 0; i < layered_providers.size(); ++i) {
565 Module entry;
566 entry.type = WINSOCK_MODULE_REGISTRATION;
567 entry.status = NOT_MATCHED;
568 entry.normalized = false;
569 entry.location = layered_providers[i].path;
570 entry.description = layered_providers[i].name;
571 entry.recommended_action = NONE;
572 entry.duplicate_count = 0;
574 wchar_t expanded[MAX_PATH];
575 DWORD size = ExpandEnvironmentStrings(
576 entry.location.c_str(), expanded, MAX_PATH);
577 if (size != 0 && size <= MAX_PATH) {
578 entry.digital_signer =
579 GetSubjectNameFromDigitalSignature(base::FilePath(expanded));
581 entry.version = base::IntToString16(layered_providers[i].version);
583 // Paths have already been collapsed.
584 NormalizeModule(&entry);
585 AddToListWithoutDuplicating(entry);
589 void ModuleEnumerator::PopulateModuleInformation(Module* module) {
590 module->status = NOT_MATCHED;
591 module->duplicate_count = 0;
592 module->normalized = false;
593 module->digital_signer =
594 GetSubjectNameFromDigitalSignature(base::FilePath(module->location));
595 module->recommended_action = NONE;
596 scoped_ptr<FileVersionInfo> version_info(
597 FileVersionInfo::CreateFileVersionInfo(base::FilePath(module->location)));
598 if (version_info.get()) {
599 FileVersionInfoWin* version_info_win =
600 static_cast<FileVersionInfoWin*>(version_info.get());
602 VS_FIXEDFILEINFO* fixed_file_info = version_info_win->fixed_file_info();
603 if (fixed_file_info) {
604 module->description = version_info_win->file_description();
605 module->version = version_info_win->file_version();
606 module->product_name = version_info_win->product_name();
611 void ModuleEnumerator::AddToListWithoutDuplicating(const Module& module) {
612 DCHECK(module.normalized);
613 // These are registered modules, not loaded modules so the same module
614 // can be registered multiple times, often dozens of times. There is no need
615 // to list each registration, so we just increment the count for each module
616 // that is counted multiple times.
617 ModulesVector::iterator iter;
618 iter = std::find_if(enumerated_modules_->begin(),
619 enumerated_modules_->end(),
620 FindModule(module));
621 if (iter != enumerated_modules_->end()) {
622 iter->duplicate_count++;
623 iter->type = static_cast<ModuleType>(iter->type | module.type);
624 } else {
625 enumerated_modules_->push_back(module);
629 void ModuleEnumerator::PreparePathMappings() {
630 path_mapping_.clear();
632 scoped_ptr<base::Environment> environment(base::Environment::Create());
633 std::vector<base::string16> env_vars;
634 env_vars.push_back(L"LOCALAPPDATA");
635 env_vars.push_back(L"ProgramFiles");
636 env_vars.push_back(L"ProgramData");
637 env_vars.push_back(L"USERPROFILE");
638 env_vars.push_back(L"SystemRoot");
639 env_vars.push_back(L"TEMP");
640 env_vars.push_back(L"TMP");
641 env_vars.push_back(L"CommonProgramFiles");
642 for (std::vector<base::string16>::const_iterator variable = env_vars.begin();
643 variable != env_vars.end(); ++variable) {
644 std::string path;
645 if (environment->GetVar(base::UTF16ToASCII(*variable).c_str(), &path)) {
646 path_mapping_.push_back(
647 std::make_pair(base::i18n::ToLower(base::UTF8ToUTF16(path)) + L"\\",
648 L"%" + base::i18n::ToLower(*variable) + L"%"));
653 void ModuleEnumerator::CollapsePath(Module* entry) {
654 // Take the path and see if we can use any of the substitution values
655 // from the vector constructed above to replace c:\windows with, for
656 // example, %systemroot%. The most collapsed path (the one with the
657 // minimum length) wins.
658 size_t min_length = MAXINT;
659 base::string16 location = entry->location;
660 for (PathMapping::const_iterator mapping = path_mapping_.begin();
661 mapping != path_mapping_.end(); ++mapping) {
662 base::string16 prefix = mapping->first;
663 if (StartsWith(location, prefix, false)) {
664 base::string16 new_location = mapping->second +
665 location.substr(prefix.length() - 1);
666 size_t length = new_location.length() - mapping->second.length();
667 if (length < min_length) {
668 entry->location = new_location;
669 min_length = length;
675 void ModuleEnumerator::MatchAgainstBlacklist() {
676 for (size_t m = 0; m < enumerated_modules_->size(); ++m) {
677 // Match this module against the blacklist.
678 Module* module = &(*enumerated_modules_)[m];
679 module->status = GOOD; // We change this below potentially.
680 for (size_t i = 0; i < arraysize(kModuleBlacklist); ++i) {
681 #if !defined(NDEBUG)
682 // This saves time when constructing the blacklist.
683 std::string hashes(kModuleBlacklist[i].filename);
684 std::string hash1, hash2, hash3;
685 GenerateHash(kModuleBlacklist[i].filename, &hash1);
686 hashes += " - " + hash1;
687 GenerateHash(kModuleBlacklist[i].location, &hash2);
688 hashes += " - " + hash2;
689 GenerateHash(kModuleBlacklist[i].desc_or_signer, &hash3);
690 hashes += " - " + hash3;
691 #endif
693 ModuleStatus status = Match(*module, kModuleBlacklist[i]);
694 if (status != NOT_MATCHED) {
695 // We have a match against the blacklist. Mark it as such.
696 module->status = status;
697 module->recommended_action = kModuleBlacklist[i].help_tip;
698 break;
702 // Modules loaded from these locations are frequently malicious
703 // and notorious for changing frequently so they are not good candidates
704 // for blacklisting individually. Mark them as suspicious if we haven't
705 // classified them as bad yet.
706 if (module->status == NOT_MATCHED || module->status == GOOD) {
707 if (StartsWith(module->location, L"%temp%", false) ||
708 StartsWith(module->location, L"%tmp%", false)) {
709 module->status = SUSPECTED_BAD;
715 void ModuleEnumerator::ReportBack() {
716 if (!limited_mode_)
717 DCHECK(BrowserThread::CurrentlyOn(callback_thread_id_));
718 observer_->DoneScanning();
721 base::string16 ModuleEnumerator::GetSubjectNameFromDigitalSignature(
722 const base::FilePath& filename) {
723 HCERTSTORE store = NULL;
724 HCRYPTMSG message = NULL;
726 // Find the crypto message for this filename.
727 bool result = !!CryptQueryObject(CERT_QUERY_OBJECT_FILE,
728 filename.value().c_str(),
729 CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
730 CERT_QUERY_FORMAT_FLAG_BINARY,
732 NULL,
733 NULL,
734 NULL,
735 &store,
736 &message,
737 NULL);
738 if (!result)
739 return base::string16();
741 // Determine the size of the signer info data.
742 DWORD signer_info_size = 0;
743 result = !!CryptMsgGetParam(message,
744 CMSG_SIGNER_INFO_PARAM,
746 NULL,
747 &signer_info_size);
748 if (!result)
749 return base::string16();
751 // Allocate enough space to hold the signer info.
752 scoped_ptr<BYTE[]> signer_info_buffer(new BYTE[signer_info_size]);
753 CMSG_SIGNER_INFO* signer_info =
754 reinterpret_cast<CMSG_SIGNER_INFO*>(signer_info_buffer.get());
756 // Obtain the signer info.
757 result = !!CryptMsgGetParam(message,
758 CMSG_SIGNER_INFO_PARAM,
760 signer_info,
761 &signer_info_size);
762 if (!result)
763 return base::string16();
765 // Search for the signer certificate.
766 CERT_INFO CertInfo = {0};
767 PCCERT_CONTEXT cert_context = NULL;
768 CertInfo.Issuer = signer_info->Issuer;
769 CertInfo.SerialNumber = signer_info->SerialNumber;
771 cert_context = CertFindCertificateInStore(
772 store,
773 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
775 CERT_FIND_SUBJECT_CERT,
776 &CertInfo,
777 NULL);
778 if (!cert_context)
779 return base::string16();
781 // Determine the size of the Subject name.
782 DWORD subject_name_size = CertGetNameString(
783 cert_context, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, NULL, 0);
784 if (!subject_name_size)
785 return base::string16();
787 base::string16 subject_name;
788 subject_name.resize(subject_name_size);
790 // Get subject name.
791 if (!(CertGetNameString(cert_context,
792 CERT_NAME_SIMPLE_DISPLAY_TYPE,
794 NULL,
795 const_cast<LPWSTR>(subject_name.c_str()),
796 subject_name_size))) {
797 return base::string16();
800 return subject_name;
803 // ----------------------------------------------------------------------------
805 // static
806 EnumerateModulesModel* EnumerateModulesModel::GetInstance() {
807 return Singleton<EnumerateModulesModel>::get();
810 bool EnumerateModulesModel::ShouldShowConflictWarning() const {
811 // If the user has acknowledged the conflict notification, then we don't need
812 // to show it again (because the scanning only happens once per the lifetime
813 // of the process). If we were to run the scanning more than once, then we'd
814 // need to clear the flag somewhere when we are ready to show it again.
815 if (conflict_notification_acknowledged_)
816 return false;
818 return confirmed_bad_modules_detected_ > 0;
821 void EnumerateModulesModel::AcknowledgeConflictNotification() {
822 if (!conflict_notification_acknowledged_) {
823 conflict_notification_acknowledged_ = true;
824 content::NotificationService::current()->Notify(
825 chrome::NOTIFICATION_MODULE_INCOMPATIBILITY_BADGE_CHANGE,
826 content::Source<EnumerateModulesModel>(this),
827 content::NotificationService::NoDetails());
831 void EnumerateModulesModel::ScanNow() {
832 if (scanning_)
833 return; // A scan is already in progress.
835 lock->Acquire(); // Balanced in DoneScanning();
837 scanning_ = true;
839 // Instruct the ModuleEnumerator class to load this on the File thread.
840 // ScanNow does not block.
841 if (!module_enumerator_.get())
842 module_enumerator_ = new ModuleEnumerator(this);
843 module_enumerator_->ScanNow(&enumerated_modules_, limited_mode_);
846 base::ListValue* EnumerateModulesModel::GetModuleList() const {
847 if (scanning_)
848 return NULL;
850 lock->Acquire();
852 if (enumerated_modules_.empty()) {
853 lock->Release();
854 return NULL;
857 base::ListValue* list = new base::ListValue();
859 for (ModuleEnumerator::ModulesVector::const_iterator module =
860 enumerated_modules_.begin();
861 module != enumerated_modules_.end(); ++module) {
862 base::DictionaryValue* data = new base::DictionaryValue();
863 data->SetInteger("type", module->type);
864 base::string16 type_string;
865 if ((module->type & ModuleEnumerator::LOADED_MODULE) == 0) {
866 // Module is not loaded, denote type of module.
867 if (module->type & ModuleEnumerator::SHELL_EXTENSION)
868 type_string = L"Shell Extension";
869 if (module->type & ModuleEnumerator::WINSOCK_MODULE_REGISTRATION) {
870 if (!type_string.empty())
871 type_string += L", ";
872 type_string += L"Winsock";
874 // Must be one of the above type.
875 DCHECK(!type_string.empty());
876 if (!limited_mode_) {
877 type_string += L" -- ";
878 type_string += l10n_util::GetStringUTF16(IDS_CONFLICTS_NOT_LOADED_YET);
881 data->SetString("type_description", type_string);
882 data->SetInteger("status", module->status);
883 data->SetString("location", module->location);
884 data->SetString("name", module->name);
885 data->SetString("product_name", module->product_name);
886 data->SetString("description", module->description);
887 data->SetString("version", module->version);
888 data->SetString("digital_signer", module->digital_signer);
890 if (!limited_mode_) {
891 // Figure out the possible resolution help string.
892 base::string16 actions;
893 base::string16 separator = L" " +
894 l10n_util::GetStringUTF16(
895 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_SEPARATOR) +
896 L" ";
898 if (module->recommended_action & ModuleEnumerator::INVESTIGATING) {
899 actions = l10n_util::GetStringUTF16(
900 IDS_CONFLICTS_CHECK_INVESTIGATING);
901 } else {
902 if (module->recommended_action & ModuleEnumerator::UNINSTALL) {
903 if (!actions.empty())
904 actions += separator;
905 actions = l10n_util::GetStringUTF16(
906 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_UNINSTALL);
908 if (module->recommended_action & ModuleEnumerator::UPDATE) {
909 if (!actions.empty())
910 actions += separator;
911 actions += l10n_util::GetStringUTF16(
912 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_UPDATE);
914 if (module->recommended_action & ModuleEnumerator::DISABLE) {
915 if (!actions.empty())
916 actions += separator;
917 actions += l10n_util::GetStringUTF16(
918 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_DISABLE);
921 base::string16 possible_resolution;
922 if (!actions.empty()) {
923 possible_resolution =
924 l10n_util::GetStringUTF16(IDS_CONFLICTS_CHECK_POSSIBLE_ACTIONS) +
925 L" " + actions;
927 data->SetString("possibleResolution", possible_resolution);
928 data->SetString("help_url",
929 ConstructHelpCenterUrl(*module).spec().c_str());
932 list->Append(data);
935 lock->Release();
936 return list;
939 GURL EnumerateModulesModel::GetFirstNotableConflict() {
940 lock->Acquire();
941 GURL url;
943 if (enumerated_modules_.empty()) {
944 lock->Release();
945 return GURL();
948 for (ModuleEnumerator::ModulesVector::const_iterator module =
949 enumerated_modules_.begin();
950 module != enumerated_modules_.end(); ++module) {
951 if (!(module->recommended_action & ModuleEnumerator::NOTIFY_USER))
952 continue;
954 url = ConstructHelpCenterUrl(*module);
955 DCHECK(url.is_valid());
956 break;
959 lock->Release();
960 return url;
964 EnumerateModulesModel::EnumerateModulesModel()
965 : limited_mode_(false),
966 scanning_(false),
967 conflict_notification_acknowledged_(false),
968 confirmed_bad_modules_detected_(0),
969 suspected_bad_modules_detected_(0),
970 modules_to_notify_about_(0) {
971 lock = new base::Lock();
974 EnumerateModulesModel::~EnumerateModulesModel() {
975 delete lock;
978 void EnumerateModulesModel::MaybePostScanningTask() {
979 static bool done = false;
980 if (!done) {
981 done = true;
982 if (base::win::GetVersion() == base::win::VERSION_XP) {
983 check_modules_timer_.Start(FROM_HERE,
984 base::TimeDelta::FromMilliseconds(kModuleCheckDelayMs),
985 this, &EnumerateModulesModel::ScanNow);
990 void EnumerateModulesModel::DoneScanning() {
991 confirmed_bad_modules_detected_ = 0;
992 suspected_bad_modules_detected_ = 0;
993 modules_to_notify_about_ = 0;
994 for (ModuleEnumerator::ModulesVector::const_iterator module =
995 enumerated_modules_.begin();
996 module != enumerated_modules_.end(); ++module) {
997 if (module->status == ModuleEnumerator::CONFIRMED_BAD) {
998 ++confirmed_bad_modules_detected_;
999 if (module->recommended_action & ModuleEnumerator::NOTIFY_USER)
1000 ++modules_to_notify_about_;
1001 } else if (module->status == ModuleEnumerator::SUSPECTED_BAD) {
1002 ++suspected_bad_modules_detected_;
1003 if (module->recommended_action & ModuleEnumerator::NOTIFY_USER)
1004 ++modules_to_notify_about_;
1008 scanning_ = false;
1009 lock->Release();
1011 UMA_HISTOGRAM_COUNTS_100("Conflicts.SuspectedBadModules",
1012 suspected_bad_modules_detected_);
1013 UMA_HISTOGRAM_COUNTS_100("Conflicts.ConfirmedBadModules",
1014 confirmed_bad_modules_detected_);
1016 // Notifications are not available in limited mode.
1017 if (limited_mode_)
1018 return;
1020 content::NotificationService::current()->Notify(
1021 chrome::NOTIFICATION_MODULE_LIST_ENUMERATED,
1022 content::Source<EnumerateModulesModel>(this),
1023 content::NotificationService::NoDetails());
1026 GURL EnumerateModulesModel::ConstructHelpCenterUrl(
1027 const ModuleEnumerator::Module& module) const {
1028 if (!(module.recommended_action & ModuleEnumerator::SEE_LINK) &&
1029 !(module.recommended_action & ModuleEnumerator::NOTIFY_USER))
1030 return GURL();
1032 // Construct the needed hashes.
1033 std::string filename, location, description, signer;
1034 GenerateHash(base::WideToUTF8(module.name), &filename);
1035 GenerateHash(base::WideToUTF8(module.location), &location);
1036 GenerateHash(base::WideToUTF8(module.description), &description);
1037 GenerateHash(base::WideToUTF8(module.digital_signer), &signer);
1039 base::string16 url =
1040 l10n_util::GetStringFUTF16(IDS_HELP_CENTER_VIEW_CONFLICTS,
1041 base::ASCIIToUTF16(filename), base::ASCIIToUTF16(location),
1042 base::ASCIIToUTF16(description), base::ASCIIToUTF16(signer));
1043 return GURL(base::UTF16ToUTF8(url));