Componentize ShortcutsBackend
[chromium-blink-merge.git] / chrome / browser / enumerate_modules_model_win.cc
blob4a23e1ddf37a4f7bcb0721a4dd221cf97e8bb83f
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 ModuleEnumerator::Module::Module() {
109 ModuleEnumerator::Module::Module(const Module& rhs) = default;
111 ModuleEnumerator::Module::Module(ModuleType type,
112 ModuleStatus status,
113 const base::string16& location,
114 const base::string16& name,
115 const base::string16& product_name,
116 const base::string16& description,
117 const base::string16& version,
118 const base::string16& digital_signer,
119 RecommendedAction recommended_action)
120 : type(type),
121 status(status),
122 location(location),
123 name(name),
124 product_name(product_name),
125 description(description),
126 version(version),
127 digital_signer(digital_signer),
128 recommended_action(recommended_action),
129 duplicate_count(0),
130 normalized(false) {
133 ModuleEnumerator::Module::~Module() {
136 // The browser process module blacklist. This lists modules that are known
137 // to cause compatibility issues within the browser process. When adding to this
138 // list, make sure that all paths are lower-case, in long pathname form, end
139 // with a slash and use environments variables (or just look at one of the
140 // comments below and keep it consistent with that). When adding an entry with
141 // an environment variable not currently used in the list below, make sure to
142 // update the list in PreparePathMappings. Filename, Description/Signer, and
143 // Location must be entered as hashes (see GenerateHash). Filename is mandatory.
144 // Entries without any Description, Signer info, or Location will never be
145 // marked as confirmed bad (only as suspicious).
146 const ModuleEnumerator::BlacklistEntry ModuleEnumerator::kModuleBlacklist[] = {
147 // NOTE: Please keep this list sorted by dll name, then location.
149 // Version 3.2.1.6 seems to be implicated in most cases (and 3.2.2.2 in some).
150 // There is a more recent version available for download.
151 // accelerator.dll, "%programfiles%\\speedbit video accelerator\\".
152 { "7ba9402f", "c9132d48", "", "", "", ALL, kInvestigatingLink },
154 // apiqq0.dll, "%temp%\\".
155 { "26134911", "59145acf", "", "", "", ALL, kUninstallLink },
157 // arking0.dll, "%systemroot%\\system32\\".
158 { "f5d8f549", "23d01d5b", "", "", "", ALL, kUninstallLink },
160 // arking1.dll, "%systemroot%\\system32\\".
161 { "c60ca062", "23d01d5b", "", "", "", ALL, kUninstallLink },
163 // aswjsflt.dll, "%ProgramFiles%\\avast software\\avast\\", "AVAST Software".
164 // NOTE: The digital signature of the DLL is double null terminated.
165 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
166 // when blocked from running.
167 { "2ea5422a", "6b3a1b00", "a7db0e0c", "", "8.0", XP,
168 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
170 // aswjsflt.dll, "%ProgramFiles%\\alwil software\\avast5\\", "AVAST Software".
171 // NOTE: The digital signature of the DLL is double null terminated.
172 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
173 // when blocked from running.
174 { "2ea5422a", "d8686924", "a7db0e0c", "", "8.0", XP,
175 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
177 // Said to belong to Killer NIC from BigFoot Networks (not verified). Versions
178 // 6.0.0.7 and 6.0.0.10 implicated.
179 // bfllr.dll, "%systemroot%\\system32\\".
180 { "6bb57633", "23d01d5b", "", "", "", ALL, kInvestigatingLink },
182 // clickpotatolitesahook.dll, "". Different version each report.
183 { "0396e037.dll", "", "", "", "", ALL, kUninstallLink },
185 // cvasds0.dll, "%temp%\\".
186 { "5ce0037c", "59145acf", "", "", "", ALL, kUninstallLink },
188 // cwalsp.dll, "%systemroot%\\system32\\".
189 { "e579a039", "23d01d5b", "", "", "", ALL, kUninstallLink },
191 // datamngr.dll (1), "%programfiles%\\searchqu toolbar\\datamngr\\".
192 { "7add320b", "470a3da3", "", "", "", ALL, kUninstallLink },
194 // datamngr.dll (2), "%programfiles%\\windows searchqu toolbar\\".
195 { "7add320b", "7a3c8be3", "", "", "", ALL, kUninstallLink },
197 // dsoqq0.dll, "%temp%\\".
198 { "1c4df325", "59145acf", "", "", "", ALL, kUninstallLink },
200 // flt.dll, "%programfiles%\\tueagles\\".
201 { "6d01f4a1", "7935e9c2", "", "", "", ALL, kUninstallLink },
203 // This looks like a malware edition of a Brazilian Bank plugin, sometimes
204 // referred to as Malware.Banc.A.
205 // gbieh.dll, "%programfiles%\\gbplugin\\".
206 { "4cb4f2e3", "88e4a3b1", "", "", "", ALL, kUninstallLink },
208 // hblitesahook.dll. Each report has different version number in location.
209 { "5d10b363", "", "", "", "", ALL, kUninstallLink },
211 // icf.dll, "%systemroot%\\system32\\".
212 { "303825ed", "23d01d5b", "", "", "", ALL, INVESTIGATING },
214 // idmmbc.dll (IDM), "%systemroot%\\system32\\". See: http://crbug.com/26892/.
215 { "b8dce5c3", "23d01d5b", "", "", "6.03", ALL,
216 static_cast<RecommendedAction>(UPDATE | DISABLE) },
218 // imon.dll (NOD32), "%systemroot%\\system32\\". See: http://crbug.com/21715.
219 { "8f42f22e", "23d01d5b", "", "", "4.0", ALL,
220 static_cast<RecommendedAction>(UPDATE | DISABLE) },
222 // is3lsp.dll, "%commonprogramfiles%\\is3\\anti-spyware\\".
223 { "7ffbdce9", "bc5673f2", "", "", "", ALL,
224 static_cast<RecommendedAction>(UPDATE | DISABLE | SEE_LINK) },
226 // jsi.dll, "%programfiles%\\profilecraze\\".
227 { "f9555eea", "e3548061", "", "", "", ALL, kUninstallLink },
229 // kernel.dll, "%programfiles%\\contentwatch\\internet protection\\modules\\".
230 { "ead2768e", "4e61ce60", "", "", "", ALL, INVESTIGATING },
232 // mgking0.dll, "%systemroot%\\system32\\".
233 { "d0893e38", "23d01d5b", "", "", "", ALL, kUninstallLink },
235 // mgking0.dll, "%temp%\\".
236 { "d0893e38", "59145acf", "", "", "", ALL, kUninstallLink },
238 // mgking1.dll, "%systemroot%\\system32\\".
239 { "3e837222", "23d01d5b", "", "", "", ALL, kUninstallLink },
241 // mgking1.dll, "%temp%\\".
242 { "3e837222", "59145acf", "", "", "", ALL, kUninstallLink },
244 // mstcipha.ime, "%systemroot%\\system32\\".
245 { "5523579e", "23d01d5b", "", "", "", ALL, INVESTIGATING },
247 // mwtsp.dll, "%systemroot%\\system32\\".
248 { "9830bff6", "23d01d5b", "", "", "", ALL, kUninstallLink },
250 // nodqq0.dll, "%temp%\\".
251 { "b86ce04d", "59145acf", "", "", "", ALL, kUninstallLink },
253 // nProtect GameGuard Anti-cheat system. Every report has a different
254 // location, since it is installed into and run from a game folder. Various
255 // versions implicated.
256 // npggnt.des, no fixed location.
257 { "f2c8790d", "", "", "", "", ALL, kInvestigatingLink },
259 // nvlsp.dll,
260 // "%programfiles%\\nvidia corporation\\networkaccessmanager\\bin32\\".
261 { "37f907e2", "3ad0ff23", "", "", "", ALL, INVESTIGATING },
263 // post0.dll, "%systemroot%\\system32\\".
264 { "7405c0c8", "23d01d5b", "", "", "", ALL, kUninstallLink },
266 // questbrwsearch.dll, "%programfiles%\\questbrwsearch\\".
267 { "0953ed09", "f0d5eeda", "", "", "", ALL, kUninstallLink },
269 // questscan.dll, "%programfiles%\\questscan\\".
270 { "f4f3391e", "119d20f7", "", "", "", ALL, kUninstallLink },
272 // radhslib.dll (Naomi web filter), "%programfiles%\\rnamfler\\".
273 // See http://crbug.com/12517.
274 { "7edcd250", "0733dc3e", "", "", "", ALL, INVESTIGATING },
276 // rlls.dll, "%programfiles%\\relevantknowledge\\".
277 { "a1ed94a7", "ea9d6b36", "", "", "", ALL, kUninstallLink },
279 // rooksdol.dll, "%programfiles%\\trusteer\\rapport\\bin\\".
280 { "802aefef", "06120e13", "", "", "3.5.1008.40", ALL, UPDATE },
282 // scanquery.dll, "%programfiles%\\scanquery\\".
283 { "0b52d2ae", "a4cc88b1", "", "", "", ALL, kUninstallLink },
285 // sdata.dll, "%programdata%\\srtserv\\".
286 { "1936d5cc", "223c44be", "", "", "", ALL, kUninstallLink },
288 // searchtree.dll,
289 // "%programfiles%\\contentwatch\\internet protection\\modules\\".
290 { "f6915a31", "4e61ce60", "", "", "", ALL, INVESTIGATING },
292 // sgprxy.dll, "%commonprogramfiles%\\is3\\anti-spyware\\".
293 { "005965ea", "bc5673f2", "", "", "", ALL, INVESTIGATING },
295 // snxhk.dll, "%ProgramFiles%\\avast software\\avast\\", "AVAST Software".
296 // NOTE: The digital signature of the DLL is double null terminated.
297 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
298 // when blocked from running.
299 { "46c16aa8", "6b3a1b00", "a7db0e0c", "", "8.0", XP,
300 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
302 // snxhk.dll, "%ProgramFiles%\\alwil software\\avast5\\", "AVAST Software".
303 // NOTE: The digital signature of the DLL is double null terminated.
304 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
305 // when blocked from running.
306 { "46c16aa8", "d8686924", "a7db0e0c", "", "8.0", XP,
307 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
309 // sprotector.dll, "". Different location each report.
310 { "24555d74", "", "", "", "", ALL, kUninstallLink },
312 // swi_filter_0001.dll (Sophos Web Intelligence),
313 // "%programfiles%\\sophos\\sophos anti-virus\\web intelligence\\".
314 // A small random sample all showed version 1.0.5.0.
315 { "61112d7b", "25fb120f", "", "", "", ALL, kInvestigatingLink },
317 // twking0.dll, "%systemroot%\\system32\\".
318 { "0355549b", "23d01d5b", "", "", "", ALL, kUninstallLink },
320 // twking1.dll, "%systemroot%\\system32\\".
321 { "02e44508", "23d01d5b", "", "", "", ALL, kUninstallLink },
323 // vksaver.dll, "%systemroot%\\system32\\".
324 { "c4a784d5", "23d01d5b", "", "", "", ALL, kUninstallLink },
326 // vlsp.dll (Venturi Firewall?), "%systemroot%\\system32\\".
327 { "2e4eb93d", "23d01d5b", "", "", "", ALL, INVESTIGATING },
329 // vmn3_1dn.dll, "%appdata%\\roaming\\vmndtxtb\\".
330 { "bba2037d", "9ab68585", "", "", "", ALL, kUninstallLink },
332 // webanalyzer.dll,
333 // "%programfiles%\\contentwatch\\internet protection\\modules\\".
334 { "c70b697d", "4e61ce60", "", "", "", ALL, INVESTIGATING },
336 // wowst0.dll, "%systemroot%\\system32\\".
337 { "38ad9963", "23d01d5b", "", "", "", ALL, kUninstallLink },
339 // wxbase28u_vc_cw.dll, "%systemroot%\\system32\\".
340 { "e967210d", "23d01d5b", "", "", "", ALL, kUninstallLink },
343 // Generates an 8 digit hash from the input given.
344 static void GenerateHash(const std::string& input, std::string* output) {
345 if (input.empty()) {
346 *output = "";
347 return;
350 uint8 hash[4];
351 crypto::SHA256HashString(input, hash, sizeof(hash));
352 *output = base::StringToLowerASCII(base::HexEncode(hash, sizeof(hash)));
355 // -----------------------------------------------------------------------------
357 // static
358 void ModuleEnumerator::NormalizeModule(Module* module) {
359 base::string16 path = module->location;
360 if (!ConvertToLongPath(path, &module->location))
361 module->location = path;
363 module->location = base::i18n::ToLower(module->location);
365 // Location contains the filename, so the last slash is where the path
366 // ends.
367 size_t last_slash = module->location.find_last_of(L"\\");
368 if (last_slash != base::string16::npos) {
369 module->name = module->location.substr(last_slash + 1);
370 module->location = module->location.substr(0, last_slash + 1);
371 } else {
372 module->name = module->location;
373 module->location.clear();
376 // Some version strings have things like (win7_rtm.090713-1255) appended
377 // to them. Remove that.
378 size_t first_space = module->version.find_first_of(L" ");
379 if (first_space != base::string16::npos)
380 module->version = module->version.substr(0, first_space);
382 module->normalized = true;
385 // static
386 ModuleEnumerator::ModuleStatus ModuleEnumerator::Match(
387 const ModuleEnumerator::Module& module,
388 const ModuleEnumerator::BlacklistEntry& blacklisted) {
389 // All modules must be normalized before matching against blacklist.
390 DCHECK(module.normalized);
391 // Filename is mandatory and version should not contain spaces.
392 DCHECK(strlen(blacklisted.filename) > 0);
393 DCHECK(!strstr(blacklisted.version_from, " "));
394 DCHECK(!strstr(blacklisted.version_to, " "));
396 base::win::Version version = base::win::GetVersion();
397 switch (version) {
398 case base::win::VERSION_XP:
399 if (!(blacklisted.os & XP)) return NOT_MATCHED;
400 break;
401 default:
402 break;
405 std::string filename_hash, location_hash;
406 GenerateHash(base::WideToUTF8(module.name), &filename_hash);
407 GenerateHash(base::WideToUTF8(module.location), &location_hash);
409 // Filenames are mandatory. Location is mandatory if given.
410 if (filename_hash == blacklisted.filename &&
411 (std::string(blacklisted.location).empty() ||
412 location_hash == blacklisted.location)) {
413 // We have a name match against the blacklist (and possibly location match
414 // also), so check version.
415 Version module_version(base::UTF16ToASCII(module.version));
416 Version version_min(blacklisted.version_from);
417 Version version_max(blacklisted.version_to);
418 bool version_ok = !version_min.IsValid() && !version_max.IsValid();
419 if (!version_ok) {
420 bool too_low = version_min.IsValid() &&
421 (!module_version.IsValid() ||
422 module_version.CompareTo(version_min) < 0);
423 bool too_high = version_max.IsValid() &&
424 (!module_version.IsValid() ||
425 module_version.CompareTo(version_max) >= 0);
426 version_ok = !too_low && !too_high;
429 if (version_ok) {
430 // At this point, the names match and there is no version specified
431 // or the versions also match.
433 std::string desc_or_signer(blacklisted.desc_or_signer);
434 std::string signer_hash, description_hash;
435 GenerateHash(base::WideToUTF8(module.digital_signer), &signer_hash);
436 GenerateHash(base::WideToUTF8(module.description), &description_hash);
438 // If signatures match (or both are empty), then we have a winner.
439 if (signer_hash == desc_or_signer)
440 return CONFIRMED_BAD;
442 // If descriptions match (or both are empty) and the locations match, then
443 // we also have a confirmed match.
444 if (description_hash == desc_or_signer &&
445 !location_hash.empty() && location_hash == blacklisted.location)
446 return CONFIRMED_BAD;
448 // We are not sure, but it is likely bad.
449 return SUSPECTED_BAD;
453 return NOT_MATCHED;
456 ModuleEnumerator::ModuleEnumerator(EnumerateModulesModel* observer)
457 : enumerated_modules_(NULL),
458 observer_(observer),
459 limited_mode_(false),
460 callback_thread_id_(BrowserThread::ID_COUNT) {
463 void ModuleEnumerator::ScanNow(ModulesVector* list, bool limited_mode) {
464 enumerated_modules_ = list;
466 limited_mode_ = limited_mode;
468 if (!limited_mode_) {
469 CHECK(BrowserThread::GetCurrentThreadIdentifier(&callback_thread_id_));
470 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
471 base::Bind(&ModuleEnumerator::ScanImpl, this));
472 } else {
473 // Run it synchronously.
474 ScanImpl();
478 ModuleEnumerator::~ModuleEnumerator() {
481 void ModuleEnumerator::ScanImpl() {
482 base::TimeTicks start_time = base::TimeTicks::Now();
484 enumerated_modules_->clear();
486 // Make sure the path mapping vector is setup so we can collapse paths.
487 PreparePathMappings();
489 // Enumerating loaded modules must happen first since the other types of
490 // modules check for duplication against the loaded modules.
491 base::TimeTicks checkpoint = base::TimeTicks::Now();
492 EnumerateLoadedModules();
493 base::TimeTicks checkpoint2 = base::TimeTicks::Now();
494 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateLoadedModules",
495 checkpoint2 - checkpoint);
497 checkpoint = checkpoint2;
498 EnumerateShellExtensions();
499 checkpoint2 = base::TimeTicks::Now();
500 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateShellExtensions",
501 checkpoint2 - checkpoint);
503 checkpoint = checkpoint2;
504 EnumerateWinsockModules();
505 checkpoint2 = base::TimeTicks::Now();
506 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateWinsockModules",
507 checkpoint2 - checkpoint);
509 MatchAgainstBlacklist();
511 std::sort(enumerated_modules_->begin(),
512 enumerated_modules_->end(), ModuleSort);
514 if (!limited_mode_) {
515 // Send a reply back on the UI thread.
516 BrowserThread::PostTask(callback_thread_id_, FROM_HERE,
517 base::Bind(&ModuleEnumerator::ReportBack, this));
518 } else {
519 // We are on the main thread already.
520 ReportBack();
523 UMA_HISTOGRAM_TIMES("Conflicts.EnumerationTotalTime",
524 base::TimeTicks::Now() - start_time);
527 void ModuleEnumerator::EnumerateLoadedModules() {
528 // Get all modules in the current process.
529 base::win::ScopedHandle snap(::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,
530 ::GetCurrentProcessId()));
531 if (!snap.Get())
532 return;
534 // Walk the module list.
535 MODULEENTRY32 module = { sizeof(module) };
536 if (!::Module32First(snap.Get(), &module))
537 return;
539 do {
540 // It would be weird to present chrome.exe as a loaded module.
541 if (_wcsicmp(chrome::kBrowserProcessExecutableName, module.szModule) == 0)
542 continue;
544 Module entry;
545 entry.type = LOADED_MODULE;
546 entry.location = module.szExePath;
547 PopulateModuleInformation(&entry);
549 NormalizeModule(&entry);
550 CollapsePath(&entry);
551 enumerated_modules_->push_back(entry);
552 } while (::Module32Next(snap.Get(), &module));
555 void ModuleEnumerator::EnumerateShellExtensions() {
556 ReadShellExtensions(HKEY_LOCAL_MACHINE);
557 ReadShellExtensions(HKEY_CURRENT_USER);
560 void ModuleEnumerator::ReadShellExtensions(HKEY parent) {
561 base::win::RegistryValueIterator registration(parent, kRegPath);
562 while (registration.Valid()) {
563 std::wstring key(std::wstring(L"CLSID\\") + registration.Name() +
564 L"\\InProcServer32");
565 base::win::RegKey clsid;
566 if (clsid.Open(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ) != ERROR_SUCCESS) {
567 ++registration;
568 continue;
570 base::string16 dll;
571 if (clsid.ReadValue(L"", &dll) != ERROR_SUCCESS) {
572 ++registration;
573 continue;
575 clsid.Close();
577 Module entry;
578 entry.type = SHELL_EXTENSION;
579 entry.location = dll;
580 PopulateModuleInformation(&entry);
582 NormalizeModule(&entry);
583 CollapsePath(&entry);
584 AddToListWithoutDuplicating(entry);
586 ++registration;
590 void ModuleEnumerator::EnumerateWinsockModules() {
591 // Add to this list the Winsock LSP DLLs.
592 WinsockLayeredServiceProviderList layered_providers;
593 GetWinsockLayeredServiceProviders(&layered_providers);
594 for (size_t i = 0; i < layered_providers.size(); ++i) {
595 Module entry;
596 entry.type = WINSOCK_MODULE_REGISTRATION;
597 entry.status = NOT_MATCHED;
598 entry.normalized = false;
599 entry.location = layered_providers[i].path;
600 entry.description = layered_providers[i].name;
601 entry.recommended_action = NONE;
602 entry.duplicate_count = 0;
604 wchar_t expanded[MAX_PATH];
605 DWORD size = ExpandEnvironmentStrings(
606 entry.location.c_str(), expanded, MAX_PATH);
607 if (size != 0 && size <= MAX_PATH) {
608 entry.digital_signer =
609 GetSubjectNameFromDigitalSignature(base::FilePath(expanded));
611 entry.version = base::IntToString16(layered_providers[i].version);
613 // Paths have already been collapsed.
614 NormalizeModule(&entry);
615 AddToListWithoutDuplicating(entry);
619 void ModuleEnumerator::PopulateModuleInformation(Module* module) {
620 module->status = NOT_MATCHED;
621 module->duplicate_count = 0;
622 module->normalized = false;
623 module->digital_signer =
624 GetSubjectNameFromDigitalSignature(base::FilePath(module->location));
625 module->recommended_action = NONE;
626 scoped_ptr<FileVersionInfo> version_info(
627 FileVersionInfo::CreateFileVersionInfo(base::FilePath(module->location)));
628 if (version_info.get()) {
629 FileVersionInfoWin* version_info_win =
630 static_cast<FileVersionInfoWin*>(version_info.get());
632 VS_FIXEDFILEINFO* fixed_file_info = version_info_win->fixed_file_info();
633 if (fixed_file_info) {
634 module->description = version_info_win->file_description();
635 module->version = version_info_win->file_version();
636 module->product_name = version_info_win->product_name();
641 void ModuleEnumerator::AddToListWithoutDuplicating(const Module& module) {
642 DCHECK(module.normalized);
643 // These are registered modules, not loaded modules so the same module
644 // can be registered multiple times, often dozens of times. There is no need
645 // to list each registration, so we just increment the count for each module
646 // that is counted multiple times.
647 ModulesVector::iterator iter;
648 iter = std::find_if(enumerated_modules_->begin(),
649 enumerated_modules_->end(),
650 FindModule(module));
651 if (iter != enumerated_modules_->end()) {
652 iter->duplicate_count++;
653 iter->type = static_cast<ModuleType>(iter->type | module.type);
654 } else {
655 enumerated_modules_->push_back(module);
659 void ModuleEnumerator::PreparePathMappings() {
660 path_mapping_.clear();
662 scoped_ptr<base::Environment> environment(base::Environment::Create());
663 std::vector<base::string16> env_vars;
664 env_vars.push_back(L"LOCALAPPDATA");
665 env_vars.push_back(L"ProgramFiles");
666 env_vars.push_back(L"ProgramData");
667 env_vars.push_back(L"USERPROFILE");
668 env_vars.push_back(L"SystemRoot");
669 env_vars.push_back(L"TEMP");
670 env_vars.push_back(L"TMP");
671 env_vars.push_back(L"CommonProgramFiles");
672 for (std::vector<base::string16>::const_iterator variable = env_vars.begin();
673 variable != env_vars.end(); ++variable) {
674 std::string path;
675 if (environment->GetVar(base::UTF16ToASCII(*variable).c_str(), &path)) {
676 path_mapping_.push_back(
677 std::make_pair(base::i18n::ToLower(base::UTF8ToUTF16(path)) + L"\\",
678 L"%" + base::i18n::ToLower(*variable) + L"%"));
683 void ModuleEnumerator::CollapsePath(Module* entry) {
684 // Take the path and see if we can use any of the substitution values
685 // from the vector constructed above to replace c:\windows with, for
686 // example, %systemroot%. The most collapsed path (the one with the
687 // minimum length) wins.
688 size_t min_length = MAXINT;
689 base::string16 location = entry->location;
690 for (PathMapping::const_iterator mapping = path_mapping_.begin();
691 mapping != path_mapping_.end(); ++mapping) {
692 base::string16 prefix = mapping->first;
693 if (base::StartsWith(location, prefix, false)) {
694 base::string16 new_location = mapping->second +
695 location.substr(prefix.length() - 1);
696 size_t length = new_location.length() - mapping->second.length();
697 if (length < min_length) {
698 entry->location = new_location;
699 min_length = length;
705 void ModuleEnumerator::MatchAgainstBlacklist() {
706 for (size_t m = 0; m < enumerated_modules_->size(); ++m) {
707 // Match this module against the blacklist.
708 Module* module = &(*enumerated_modules_)[m];
709 module->status = GOOD; // We change this below potentially.
710 for (size_t i = 0; i < arraysize(kModuleBlacklist); ++i) {
711 #if !defined(NDEBUG)
712 // This saves time when constructing the blacklist.
713 std::string hashes(kModuleBlacklist[i].filename);
714 std::string hash1, hash2, hash3;
715 GenerateHash(kModuleBlacklist[i].filename, &hash1);
716 hashes += " - " + hash1;
717 GenerateHash(kModuleBlacklist[i].location, &hash2);
718 hashes += " - " + hash2;
719 GenerateHash(kModuleBlacklist[i].desc_or_signer, &hash3);
720 hashes += " - " + hash3;
721 #endif
723 ModuleStatus status = Match(*module, kModuleBlacklist[i]);
724 if (status != NOT_MATCHED) {
725 // We have a match against the blacklist. Mark it as such.
726 module->status = status;
727 module->recommended_action = kModuleBlacklist[i].help_tip;
728 break;
732 // Modules loaded from these locations are frequently malicious
733 // and notorious for changing frequently so they are not good candidates
734 // for blacklisting individually. Mark them as suspicious if we haven't
735 // classified them as bad yet.
736 if (module->status == NOT_MATCHED || module->status == GOOD) {
737 if (base::StartsWith(module->location, L"%temp%", false) ||
738 base::StartsWith(module->location, L"%tmp%", false)) {
739 module->status = SUSPECTED_BAD;
745 void ModuleEnumerator::ReportBack() {
746 if (!limited_mode_)
747 DCHECK(BrowserThread::CurrentlyOn(callback_thread_id_));
748 observer_->DoneScanning();
751 base::string16 ModuleEnumerator::GetSubjectNameFromDigitalSignature(
752 const base::FilePath& filename) {
753 HCERTSTORE store = NULL;
754 HCRYPTMSG message = NULL;
756 // Find the crypto message for this filename.
757 bool result = !!CryptQueryObject(CERT_QUERY_OBJECT_FILE,
758 filename.value().c_str(),
759 CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
760 CERT_QUERY_FORMAT_FLAG_BINARY,
762 NULL,
763 NULL,
764 NULL,
765 &store,
766 &message,
767 NULL);
768 if (!result)
769 return base::string16();
771 // Determine the size of the signer info data.
772 DWORD signer_info_size = 0;
773 result = !!CryptMsgGetParam(message,
774 CMSG_SIGNER_INFO_PARAM,
776 NULL,
777 &signer_info_size);
778 if (!result)
779 return base::string16();
781 // Allocate enough space to hold the signer info.
782 scoped_ptr<BYTE[]> signer_info_buffer(new BYTE[signer_info_size]);
783 CMSG_SIGNER_INFO* signer_info =
784 reinterpret_cast<CMSG_SIGNER_INFO*>(signer_info_buffer.get());
786 // Obtain the signer info.
787 result = !!CryptMsgGetParam(message,
788 CMSG_SIGNER_INFO_PARAM,
790 signer_info,
791 &signer_info_size);
792 if (!result)
793 return base::string16();
795 // Search for the signer certificate.
796 CERT_INFO CertInfo = {0};
797 PCCERT_CONTEXT cert_context = NULL;
798 CertInfo.Issuer = signer_info->Issuer;
799 CertInfo.SerialNumber = signer_info->SerialNumber;
801 cert_context = CertFindCertificateInStore(
802 store,
803 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
805 CERT_FIND_SUBJECT_CERT,
806 &CertInfo,
807 NULL);
808 if (!cert_context)
809 return base::string16();
811 // Determine the size of the Subject name.
812 DWORD subject_name_size = CertGetNameString(
813 cert_context, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, NULL, 0);
814 if (!subject_name_size)
815 return base::string16();
817 base::string16 subject_name;
818 subject_name.resize(subject_name_size);
820 // Get subject name.
821 if (!(CertGetNameString(cert_context,
822 CERT_NAME_SIMPLE_DISPLAY_TYPE,
824 NULL,
825 const_cast<LPWSTR>(subject_name.c_str()),
826 subject_name_size))) {
827 return base::string16();
830 return subject_name;
833 // ----------------------------------------------------------------------------
835 // static
836 EnumerateModulesModel* EnumerateModulesModel::GetInstance() {
837 return Singleton<EnumerateModulesModel>::get();
840 bool EnumerateModulesModel::ShouldShowConflictWarning() const {
841 // If the user has acknowledged the conflict notification, then we don't need
842 // to show it again (because the scanning only happens once per the lifetime
843 // of the process). If we were to run the scanning more than once, then we'd
844 // need to clear the flag somewhere when we are ready to show it again.
845 if (conflict_notification_acknowledged_)
846 return false;
848 return confirmed_bad_modules_detected_ > 0;
851 void EnumerateModulesModel::AcknowledgeConflictNotification() {
852 if (!conflict_notification_acknowledged_) {
853 conflict_notification_acknowledged_ = true;
854 content::NotificationService::current()->Notify(
855 chrome::NOTIFICATION_MODULE_INCOMPATIBILITY_BADGE_CHANGE,
856 content::Source<EnumerateModulesModel>(this),
857 content::NotificationService::NoDetails());
861 void EnumerateModulesModel::ScanNow() {
862 if (scanning_)
863 return; // A scan is already in progress.
865 lock->Acquire(); // Balanced in DoneScanning();
867 scanning_ = true;
869 // Instruct the ModuleEnumerator class to load this on the File thread.
870 // ScanNow does not block.
871 if (!module_enumerator_.get())
872 module_enumerator_ = new ModuleEnumerator(this);
873 module_enumerator_->ScanNow(&enumerated_modules_, limited_mode_);
876 base::ListValue* EnumerateModulesModel::GetModuleList() const {
877 if (scanning_)
878 return NULL;
880 lock->Acquire();
882 if (enumerated_modules_.empty()) {
883 lock->Release();
884 return NULL;
887 base::ListValue* list = new base::ListValue();
889 for (ModuleEnumerator::ModulesVector::const_iterator module =
890 enumerated_modules_.begin();
891 module != enumerated_modules_.end(); ++module) {
892 base::DictionaryValue* data = new base::DictionaryValue();
893 data->SetInteger("type", module->type);
894 base::string16 type_string;
895 if ((module->type & ModuleEnumerator::LOADED_MODULE) == 0) {
896 // Module is not loaded, denote type of module.
897 if (module->type & ModuleEnumerator::SHELL_EXTENSION)
898 type_string = L"Shell Extension";
899 if (module->type & ModuleEnumerator::WINSOCK_MODULE_REGISTRATION) {
900 if (!type_string.empty())
901 type_string += L", ";
902 type_string += L"Winsock";
904 // Must be one of the above type.
905 DCHECK(!type_string.empty());
906 if (!limited_mode_) {
907 type_string += L" -- ";
908 type_string += l10n_util::GetStringUTF16(IDS_CONFLICTS_NOT_LOADED_YET);
911 data->SetString("type_description", type_string);
912 data->SetInteger("status", module->status);
913 data->SetString("location", module->location);
914 data->SetString("name", module->name);
915 data->SetString("product_name", module->product_name);
916 data->SetString("description", module->description);
917 data->SetString("version", module->version);
918 data->SetString("digital_signer", module->digital_signer);
920 if (!limited_mode_) {
921 // Figure out the possible resolution help string.
922 base::string16 actions;
923 base::string16 separator = L" " +
924 l10n_util::GetStringUTF16(
925 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_SEPARATOR) +
926 L" ";
928 if (module->recommended_action & ModuleEnumerator::INVESTIGATING) {
929 actions = l10n_util::GetStringUTF16(
930 IDS_CONFLICTS_CHECK_INVESTIGATING);
931 } else {
932 if (module->recommended_action & ModuleEnumerator::UNINSTALL) {
933 if (!actions.empty())
934 actions += separator;
935 actions = l10n_util::GetStringUTF16(
936 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_UNINSTALL);
938 if (module->recommended_action & ModuleEnumerator::UPDATE) {
939 if (!actions.empty())
940 actions += separator;
941 actions += l10n_util::GetStringUTF16(
942 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_UPDATE);
944 if (module->recommended_action & ModuleEnumerator::DISABLE) {
945 if (!actions.empty())
946 actions += separator;
947 actions += l10n_util::GetStringUTF16(
948 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_DISABLE);
951 base::string16 possible_resolution;
952 if (!actions.empty()) {
953 possible_resolution =
954 l10n_util::GetStringUTF16(IDS_CONFLICTS_CHECK_POSSIBLE_ACTIONS) +
955 L" " + actions;
957 data->SetString("possibleResolution", possible_resolution);
958 data->SetString("help_url",
959 ConstructHelpCenterUrl(*module).spec().c_str());
962 list->Append(data);
965 lock->Release();
966 return list;
969 GURL EnumerateModulesModel::GetFirstNotableConflict() {
970 lock->Acquire();
971 GURL url;
973 if (enumerated_modules_.empty()) {
974 lock->Release();
975 return GURL();
978 for (ModuleEnumerator::ModulesVector::const_iterator module =
979 enumerated_modules_.begin();
980 module != enumerated_modules_.end(); ++module) {
981 if (!(module->recommended_action & ModuleEnumerator::NOTIFY_USER))
982 continue;
984 url = ConstructHelpCenterUrl(*module);
985 DCHECK(url.is_valid());
986 break;
989 lock->Release();
990 return url;
994 EnumerateModulesModel::EnumerateModulesModel()
995 : limited_mode_(false),
996 scanning_(false),
997 conflict_notification_acknowledged_(false),
998 confirmed_bad_modules_detected_(0),
999 suspected_bad_modules_detected_(0),
1000 modules_to_notify_about_(0) {
1001 lock = new base::Lock();
1004 EnumerateModulesModel::~EnumerateModulesModel() {
1005 delete lock;
1008 void EnumerateModulesModel::MaybePostScanningTask() {
1009 static bool done = false;
1010 if (!done) {
1011 done = true;
1012 if (base::win::GetVersion() == base::win::VERSION_XP) {
1013 check_modules_timer_.Start(FROM_HERE,
1014 base::TimeDelta::FromMilliseconds(kModuleCheckDelayMs),
1015 this, &EnumerateModulesModel::ScanNow);
1020 void EnumerateModulesModel::DoneScanning() {
1021 confirmed_bad_modules_detected_ = 0;
1022 suspected_bad_modules_detected_ = 0;
1023 modules_to_notify_about_ = 0;
1024 for (ModuleEnumerator::ModulesVector::const_iterator module =
1025 enumerated_modules_.begin();
1026 module != enumerated_modules_.end(); ++module) {
1027 if (module->status == ModuleEnumerator::CONFIRMED_BAD) {
1028 ++confirmed_bad_modules_detected_;
1029 if (module->recommended_action & ModuleEnumerator::NOTIFY_USER)
1030 ++modules_to_notify_about_;
1031 } else if (module->status == ModuleEnumerator::SUSPECTED_BAD) {
1032 ++suspected_bad_modules_detected_;
1033 if (module->recommended_action & ModuleEnumerator::NOTIFY_USER)
1034 ++modules_to_notify_about_;
1038 scanning_ = false;
1039 lock->Release();
1041 UMA_HISTOGRAM_COUNTS_100("Conflicts.SuspectedBadModules",
1042 suspected_bad_modules_detected_);
1043 UMA_HISTOGRAM_COUNTS_100("Conflicts.ConfirmedBadModules",
1044 confirmed_bad_modules_detected_);
1046 // Notifications are not available in limited mode.
1047 if (limited_mode_)
1048 return;
1050 content::NotificationService::current()->Notify(
1051 chrome::NOTIFICATION_MODULE_LIST_ENUMERATED,
1052 content::Source<EnumerateModulesModel>(this),
1053 content::NotificationService::NoDetails());
1056 GURL EnumerateModulesModel::ConstructHelpCenterUrl(
1057 const ModuleEnumerator::Module& module) const {
1058 if (!(module.recommended_action & ModuleEnumerator::SEE_LINK) &&
1059 !(module.recommended_action & ModuleEnumerator::NOTIFY_USER))
1060 return GURL();
1062 // Construct the needed hashes.
1063 std::string filename, location, description, signer;
1064 GenerateHash(base::WideToUTF8(module.name), &filename);
1065 GenerateHash(base::WideToUTF8(module.location), &location);
1066 GenerateHash(base::WideToUTF8(module.description), &description);
1067 GenerateHash(base::WideToUTF8(module.digital_signer), &signer);
1069 base::string16 url =
1070 l10n_util::GetStringFUTF16(IDS_HELP_CENTER_VIEW_CONFLICTS,
1071 base::ASCIIToUTF16(filename), base::ASCIIToUTF16(location),
1072 base::ASCIIToUTF16(description), base::ASCIIToUTF16(signer));
1073 return GURL(base::UTF16ToUTF8(url));