Popular sites on the NTP: check that experiment group StartsWith (rather than IS...
[chromium-blink-merge.git] / chrome / browser / enumerate_modules_model_win.cc
blob8eff4f3476119b788cedf4e1095b0a5240ccbee7
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::ToLowerASCII(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 const base::string16& prefix = mapping->first;
693 if (base::StartsWith(base::i18n::ToLower(location),
694 base::i18n::ToLower(prefix),
695 base::CompareCase::SENSITIVE)) {
696 base::string16 new_location = mapping->second +
697 location.substr(prefix.length() - 1);
698 size_t length = new_location.length() - mapping->second.length();
699 if (length < min_length) {
700 entry->location = new_location;
701 min_length = length;
707 void ModuleEnumerator::MatchAgainstBlacklist() {
708 for (size_t m = 0; m < enumerated_modules_->size(); ++m) {
709 // Match this module against the blacklist.
710 Module* module = &(*enumerated_modules_)[m];
711 module->status = GOOD; // We change this below potentially.
712 for (size_t i = 0; i < arraysize(kModuleBlacklist); ++i) {
713 #if !defined(NDEBUG)
714 // This saves time when constructing the blacklist.
715 std::string hashes(kModuleBlacklist[i].filename);
716 std::string hash1, hash2, hash3;
717 GenerateHash(kModuleBlacklist[i].filename, &hash1);
718 hashes += " - " + hash1;
719 GenerateHash(kModuleBlacklist[i].location, &hash2);
720 hashes += " - " + hash2;
721 GenerateHash(kModuleBlacklist[i].desc_or_signer, &hash3);
722 hashes += " - " + hash3;
723 #endif
725 ModuleStatus status = Match(*module, kModuleBlacklist[i]);
726 if (status != NOT_MATCHED) {
727 // We have a match against the blacklist. Mark it as such.
728 module->status = status;
729 module->recommended_action = kModuleBlacklist[i].help_tip;
730 break;
734 // Modules loaded from these locations are frequently malicious
735 // and notorious for changing frequently so they are not good candidates
736 // for blacklisting individually. Mark them as suspicious if we haven't
737 // classified them as bad yet.
738 if (module->status == NOT_MATCHED || module->status == GOOD) {
739 if (base::StartsWith(module->location, L"%temp%",
740 base::CompareCase::INSENSITIVE_ASCII) ||
741 base::StartsWith(module->location, L"%tmp%",
742 base::CompareCase::INSENSITIVE_ASCII)) {
743 module->status = SUSPECTED_BAD;
749 void ModuleEnumerator::ReportBack() {
750 if (!limited_mode_)
751 DCHECK_CURRENTLY_ON(callback_thread_id_);
752 observer_->DoneScanning();
755 base::string16 ModuleEnumerator::GetSubjectNameFromDigitalSignature(
756 const base::FilePath& filename) {
757 HCERTSTORE store = NULL;
758 HCRYPTMSG message = NULL;
760 // Find the crypto message for this filename.
761 bool result = !!CryptQueryObject(CERT_QUERY_OBJECT_FILE,
762 filename.value().c_str(),
763 CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
764 CERT_QUERY_FORMAT_FLAG_BINARY,
766 NULL,
767 NULL,
768 NULL,
769 &store,
770 &message,
771 NULL);
772 if (!result)
773 return base::string16();
775 // Determine the size of the signer info data.
776 DWORD signer_info_size = 0;
777 result = !!CryptMsgGetParam(message,
778 CMSG_SIGNER_INFO_PARAM,
780 NULL,
781 &signer_info_size);
782 if (!result)
783 return base::string16();
785 // Allocate enough space to hold the signer info.
786 scoped_ptr<BYTE[]> signer_info_buffer(new BYTE[signer_info_size]);
787 CMSG_SIGNER_INFO* signer_info =
788 reinterpret_cast<CMSG_SIGNER_INFO*>(signer_info_buffer.get());
790 // Obtain the signer info.
791 result = !!CryptMsgGetParam(message,
792 CMSG_SIGNER_INFO_PARAM,
794 signer_info,
795 &signer_info_size);
796 if (!result)
797 return base::string16();
799 // Search for the signer certificate.
800 CERT_INFO CertInfo = {0};
801 PCCERT_CONTEXT cert_context = NULL;
802 CertInfo.Issuer = signer_info->Issuer;
803 CertInfo.SerialNumber = signer_info->SerialNumber;
805 cert_context = CertFindCertificateInStore(
806 store,
807 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
809 CERT_FIND_SUBJECT_CERT,
810 &CertInfo,
811 NULL);
812 if (!cert_context)
813 return base::string16();
815 // Determine the size of the Subject name.
816 DWORD subject_name_size = CertGetNameString(
817 cert_context, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, NULL, 0);
818 if (!subject_name_size)
819 return base::string16();
821 base::string16 subject_name;
822 subject_name.resize(subject_name_size);
824 // Get subject name.
825 if (!(CertGetNameString(cert_context,
826 CERT_NAME_SIMPLE_DISPLAY_TYPE,
828 NULL,
829 const_cast<LPWSTR>(subject_name.c_str()),
830 subject_name_size))) {
831 return base::string16();
834 return subject_name;
837 // ----------------------------------------------------------------------------
839 // static
840 EnumerateModulesModel* EnumerateModulesModel::GetInstance() {
841 return Singleton<EnumerateModulesModel>::get();
844 bool EnumerateModulesModel::ShouldShowConflictWarning() const {
845 // If the user has acknowledged the conflict notification, then we don't need
846 // to show it again (because the scanning only happens once per the lifetime
847 // of the process). If we were to run the scanning more than once, then we'd
848 // need to clear the flag somewhere when we are ready to show it again.
849 if (conflict_notification_acknowledged_)
850 return false;
852 return confirmed_bad_modules_detected_ > 0;
855 void EnumerateModulesModel::AcknowledgeConflictNotification() {
856 if (!conflict_notification_acknowledged_) {
857 conflict_notification_acknowledged_ = true;
858 content::NotificationService::current()->Notify(
859 chrome::NOTIFICATION_MODULE_INCOMPATIBILITY_BADGE_CHANGE,
860 content::Source<EnumerateModulesModel>(this),
861 content::NotificationService::NoDetails());
865 void EnumerateModulesModel::ScanNow() {
866 if (scanning_)
867 return; // A scan is already in progress.
869 lock->Acquire(); // Balanced in DoneScanning();
871 scanning_ = true;
873 // Instruct the ModuleEnumerator class to load this on the File thread.
874 // ScanNow does not block.
875 if (!module_enumerator_.get())
876 module_enumerator_ = new ModuleEnumerator(this);
877 module_enumerator_->ScanNow(&enumerated_modules_, limited_mode_);
880 base::ListValue* EnumerateModulesModel::GetModuleList() const {
881 if (scanning_)
882 return NULL;
884 lock->Acquire();
886 if (enumerated_modules_.empty()) {
887 lock->Release();
888 return NULL;
891 base::ListValue* list = new base::ListValue();
893 for (ModuleEnumerator::ModulesVector::const_iterator module =
894 enumerated_modules_.begin();
895 module != enumerated_modules_.end(); ++module) {
896 base::DictionaryValue* data = new base::DictionaryValue();
897 data->SetInteger("type", module->type);
898 base::string16 type_string;
899 if ((module->type & ModuleEnumerator::LOADED_MODULE) == 0) {
900 // Module is not loaded, denote type of module.
901 if (module->type & ModuleEnumerator::SHELL_EXTENSION)
902 type_string = L"Shell Extension";
903 if (module->type & ModuleEnumerator::WINSOCK_MODULE_REGISTRATION) {
904 if (!type_string.empty())
905 type_string += L", ";
906 type_string += L"Winsock";
908 // Must be one of the above type.
909 DCHECK(!type_string.empty());
910 if (!limited_mode_) {
911 type_string += L" -- ";
912 type_string += l10n_util::GetStringUTF16(IDS_CONFLICTS_NOT_LOADED_YET);
915 data->SetString("type_description", type_string);
916 data->SetInteger("status", module->status);
917 data->SetString("location", module->location);
918 data->SetString("name", module->name);
919 data->SetString("product_name", module->product_name);
920 data->SetString("description", module->description);
921 data->SetString("version", module->version);
922 data->SetString("digital_signer", module->digital_signer);
924 if (!limited_mode_) {
925 // Figure out the possible resolution help string.
926 base::string16 actions;
927 base::string16 separator = L" " +
928 l10n_util::GetStringUTF16(
929 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_SEPARATOR) +
930 L" ";
932 if (module->recommended_action & ModuleEnumerator::INVESTIGATING) {
933 actions = l10n_util::GetStringUTF16(
934 IDS_CONFLICTS_CHECK_INVESTIGATING);
935 } else {
936 if (module->recommended_action & ModuleEnumerator::UNINSTALL) {
937 if (!actions.empty())
938 actions += separator;
939 actions = l10n_util::GetStringUTF16(
940 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_UNINSTALL);
942 if (module->recommended_action & ModuleEnumerator::UPDATE) {
943 if (!actions.empty())
944 actions += separator;
945 actions += l10n_util::GetStringUTF16(
946 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_UPDATE);
948 if (module->recommended_action & ModuleEnumerator::DISABLE) {
949 if (!actions.empty())
950 actions += separator;
951 actions += l10n_util::GetStringUTF16(
952 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_DISABLE);
955 base::string16 possible_resolution;
956 if (!actions.empty()) {
957 possible_resolution =
958 l10n_util::GetStringUTF16(IDS_CONFLICTS_CHECK_POSSIBLE_ACTIONS) +
959 L" " + actions;
961 data->SetString("possibleResolution", possible_resolution);
962 data->SetString("help_url",
963 ConstructHelpCenterUrl(*module).spec().c_str());
966 list->Append(data);
969 lock->Release();
970 return list;
973 GURL EnumerateModulesModel::GetFirstNotableConflict() {
974 lock->Acquire();
975 GURL url;
977 if (enumerated_modules_.empty()) {
978 lock->Release();
979 return GURL();
982 for (ModuleEnumerator::ModulesVector::const_iterator module =
983 enumerated_modules_.begin();
984 module != enumerated_modules_.end(); ++module) {
985 if (!(module->recommended_action & ModuleEnumerator::NOTIFY_USER))
986 continue;
988 url = ConstructHelpCenterUrl(*module);
989 DCHECK(url.is_valid());
990 break;
993 lock->Release();
994 return url;
997 EnumerateModulesModel::EnumerateModulesModel()
998 : limited_mode_(false),
999 scanning_(false),
1000 conflict_notification_acknowledged_(false),
1001 confirmed_bad_modules_detected_(0),
1002 modules_to_notify_about_(0),
1003 suspected_bad_modules_detected_(0) {
1004 lock = new base::Lock();
1007 EnumerateModulesModel::~EnumerateModulesModel() {
1008 delete lock;
1011 void EnumerateModulesModel::MaybePostScanningTask() {
1012 static bool done = false;
1013 if (!done) {
1014 done = true;
1015 if (base::win::GetVersion() == base::win::VERSION_XP) {
1016 check_modules_timer_.Start(FROM_HERE,
1017 base::TimeDelta::FromMilliseconds(kModuleCheckDelayMs),
1018 this, &EnumerateModulesModel::ScanNow);
1023 void EnumerateModulesModel::DoneScanning() {
1024 confirmed_bad_modules_detected_ = 0;
1025 suspected_bad_modules_detected_ = 0;
1026 modules_to_notify_about_ = 0;
1027 for (ModuleEnumerator::ModulesVector::const_iterator module =
1028 enumerated_modules_.begin();
1029 module != enumerated_modules_.end(); ++module) {
1030 if (module->status == ModuleEnumerator::CONFIRMED_BAD) {
1031 ++confirmed_bad_modules_detected_;
1032 if (module->recommended_action & ModuleEnumerator::NOTIFY_USER)
1033 ++modules_to_notify_about_;
1034 } else if (module->status == ModuleEnumerator::SUSPECTED_BAD) {
1035 ++suspected_bad_modules_detected_;
1036 if (module->recommended_action & ModuleEnumerator::NOTIFY_USER)
1037 ++modules_to_notify_about_;
1041 scanning_ = false;
1042 lock->Release();
1044 UMA_HISTOGRAM_COUNTS_100("Conflicts.SuspectedBadModules",
1045 suspected_bad_modules_detected_);
1046 UMA_HISTOGRAM_COUNTS_100("Conflicts.ConfirmedBadModules",
1047 confirmed_bad_modules_detected_);
1049 // Notifications are not available in limited mode.
1050 if (limited_mode_)
1051 return;
1053 content::NotificationService::current()->Notify(
1054 chrome::NOTIFICATION_MODULE_LIST_ENUMERATED,
1055 content::Source<EnumerateModulesModel>(this),
1056 content::NotificationService::NoDetails());
1059 GURL EnumerateModulesModel::ConstructHelpCenterUrl(
1060 const ModuleEnumerator::Module& module) const {
1061 if (!(module.recommended_action & ModuleEnumerator::SEE_LINK) &&
1062 !(module.recommended_action & ModuleEnumerator::NOTIFY_USER))
1063 return GURL();
1065 // Construct the needed hashes.
1066 std::string filename, location, description, signer;
1067 GenerateHash(base::WideToUTF8(module.name), &filename);
1068 GenerateHash(base::WideToUTF8(module.location), &location);
1069 GenerateHash(base::WideToUTF8(module.description), &description);
1070 GenerateHash(base::WideToUTF8(module.digital_signer), &signer);
1072 base::string16 url =
1073 l10n_util::GetStringFUTF16(IDS_HELP_CENTER_VIEW_CONFLICTS,
1074 base::ASCIIToUTF16(filename), base::ASCIIToUTF16(location),
1075 base::ASCIIToUTF16(description), base::ASCIIToUTF16(signer));
1076 return GURL(base::UTF16ToUTF8(url));