Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / browser / enumerate_modules_model_win.cc
blob80fa25594a255b193b991774adc4821239987397
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/common/chrome_switches.h"
31 #include "content/public/browser/notification_service.h"
32 #include "crypto/sha2.h"
33 #include "grit/generated_resources.h"
34 #include "grit/google_chrome_strings.h"
35 #include "ui/base/l10n/l10n_util.h"
37 using content::BrowserThread;
39 // The period of time (in milliseconds) to wait until checking to see if any
40 // incompatible modules exist.
41 static const int kModuleCheckDelayMs = 45 * 1000;
43 // The path to the Shell Extension key in the Windows registry.
44 static const wchar_t kRegPath[] =
45 L"Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved";
47 // Short-hand for things on the blacklist you should simply get rid of.
48 static const ModuleEnumerator::RecommendedAction kUninstallLink =
49 static_cast<ModuleEnumerator::RecommendedAction>(
50 ModuleEnumerator::UNINSTALL | ModuleEnumerator::SEE_LINK);
52 // Short-hand for things on the blacklist we are investigating and have info.
53 static const ModuleEnumerator::RecommendedAction kInvestigatingLink =
54 static_cast<ModuleEnumerator::RecommendedAction>(
55 ModuleEnumerator::INVESTIGATING | ModuleEnumerator::SEE_LINK);
57 // A sort method that sorts by bad modules first, then by full name (including
58 // path).
59 static bool ModuleSort(const ModuleEnumerator::Module& a,
60 const ModuleEnumerator::Module& b) {
61 if (a.status != b.status)
62 return a.status > b.status;
64 if (a.location == b.location)
65 return a.name < b.name;
67 return a.location < b.location;
70 namespace {
72 // Used to protect the LoadedModuleVector which is accessed
73 // from both the UI thread and the FILE thread.
74 base::Lock* lock = NULL;
76 // A struct to help de-duping modules before adding them to the enumerated
77 // modules vector.
78 struct FindModule {
79 public:
80 explicit FindModule(const ModuleEnumerator::Module& x)
81 : module(x) {}
82 bool operator()(const ModuleEnumerator::Module& module_in) const {
83 return (module.location == module_in.location) &&
84 (module.name == module_in.name);
87 const ModuleEnumerator::Module& module;
90 // Returns the long path name given a short path name. A short path name is a
91 // path that follows the 8.3 convention and has ~x in it. If the path is already
92 // a long path name, the function returns the current path without modification.
93 bool ConvertToLongPath(const base::string16& short_path,
94 base::string16* long_path) {
95 wchar_t long_path_buf[MAX_PATH];
96 DWORD return_value = GetLongPathName(short_path.c_str(), long_path_buf,
97 MAX_PATH);
98 if (return_value != 0 && return_value < MAX_PATH) {
99 *long_path = long_path_buf;
100 return true;
103 return false;
106 } // namespace
108 // The browser process module blacklist. This lists modules that are known
109 // to cause compatibility issues within the browser process. When adding to this
110 // list, make sure that all paths are lower-case, in long pathname form, end
111 // with a slash and use environments variables (or just look at one of the
112 // comments below and keep it consistent with that). When adding an entry with
113 // an environment variable not currently used in the list below, make sure to
114 // update the list in PreparePathMappings. Filename, Description/Signer, and
115 // Location must be entered as hashes (see GenerateHash). Filename is mandatory.
116 // Entries without any Description, Signer info, or Location will never be
117 // marked as confirmed bad (only as suspicious).
118 const ModuleEnumerator::BlacklistEntry ModuleEnumerator::kModuleBlacklist[] = {
119 // NOTE: Please keep this list sorted by dll name, then location.
121 // Version 3.2.1.6 seems to be implicated in most cases (and 3.2.2.2 in some).
122 // There is a more recent version available for download.
123 // accelerator.dll, "%programfiles%\\speedbit video accelerator\\".
124 { "7ba9402f", "c9132d48", "", "", "", ALL, kInvestigatingLink },
126 // apiqq0.dll, "%temp%\\".
127 { "26134911", "59145acf", "", "", "", ALL, kUninstallLink },
129 // arking0.dll, "%systemroot%\\system32\\".
130 { "f5d8f549", "23d01d5b", "", "", "", ALL, kUninstallLink },
132 // arking1.dll, "%systemroot%\\system32\\".
133 { "c60ca062", "23d01d5b", "", "", "", ALL, kUninstallLink },
135 // aswjsflt.dll, "%ProgramFiles%\\avast software\\avast\\", "AVAST Software".
136 // NOTE: The digital signature of the DLL is double null terminated.
137 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
138 // when blocked from running.
139 { "2ea5422a", "6b3a1b00", "a7db0e0c", "", "8.0", XP,
140 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
142 // aswjsflt.dll, "%ProgramFiles%\\alwil software\\avast5\\", "AVAST Software".
143 // NOTE: The digital signature of the DLL is double null terminated.
144 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
145 // when blocked from running.
146 { "2ea5422a", "d8686924", "a7db0e0c", "", "8.0", XP,
147 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
149 // Said to belong to Killer NIC from BigFoot Networks (not verified). Versions
150 // 6.0.0.7 and 6.0.0.10 implicated.
151 // bfllr.dll, "%systemroot%\\system32\\".
152 { "6bb57633", "23d01d5b", "", "", "", ALL, kInvestigatingLink },
154 // clickpotatolitesahook.dll, "". Different version each report.
155 { "0396e037.dll", "", "", "", "", ALL, kUninstallLink },
157 // cvasds0.dll, "%temp%\\".
158 { "5ce0037c", "59145acf", "", "", "", ALL, kUninstallLink },
160 // cwalsp.dll, "%systemroot%\\system32\\".
161 { "e579a039", "23d01d5b", "", "", "", ALL, kUninstallLink },
163 // datamngr.dll (1), "%programfiles%\\searchqu toolbar\\datamngr\\".
164 { "7add320b", "470a3da3", "", "", "", ALL, kUninstallLink },
166 // datamngr.dll (2), "%programfiles%\\windows searchqu toolbar\\".
167 { "7add320b", "7a3c8be3", "", "", "", ALL, kUninstallLink },
169 // dsoqq0.dll, "%temp%\\".
170 { "1c4df325", "59145acf", "", "", "", ALL, kUninstallLink },
172 // flt.dll, "%programfiles%\\tueagles\\".
173 { "6d01f4a1", "7935e9c2", "", "", "", ALL, kUninstallLink },
175 // This looks like a malware edition of a Brazilian Bank plugin, sometimes
176 // referred to as Malware.Banc.A.
177 // gbieh.dll, "%programfiles%\\gbplugin\\".
178 { "4cb4f2e3", "88e4a3b1", "", "", "", ALL, kUninstallLink },
180 // hblitesahook.dll. Each report has different version number in location.
181 { "5d10b363", "", "", "", "", ALL, kUninstallLink },
183 // icf.dll, "%systemroot%\\system32\\".
184 { "303825ed", "23d01d5b", "", "", "", ALL, INVESTIGATING },
186 // idmmbc.dll (IDM), "%systemroot%\\system32\\". See: http://crbug.com/26892/.
187 { "b8dce5c3", "23d01d5b", "", "", "6.03", ALL,
188 static_cast<RecommendedAction>(UPDATE | DISABLE) },
190 // imon.dll (NOD32), "%systemroot%\\system32\\". See: http://crbug.com/21715.
191 { "8f42f22e", "23d01d5b", "", "", "4.0", ALL,
192 static_cast<RecommendedAction>(UPDATE | DISABLE) },
194 // is3lsp.dll, "%commonprogramfiles%\\is3\\anti-spyware\\".
195 { "7ffbdce9", "bc5673f2", "", "", "", ALL,
196 static_cast<RecommendedAction>(UPDATE | DISABLE | SEE_LINK) },
198 // jsi.dll, "%programfiles%\\profilecraze\\".
199 { "f9555eea", "e3548061", "", "", "", ALL, kUninstallLink },
201 // kernel.dll, "%programfiles%\\contentwatch\\internet protection\\modules\\".
202 { "ead2768e", "4e61ce60", "", "", "", ALL, INVESTIGATING },
204 // mgking0.dll, "%systemroot%\\system32\\".
205 { "d0893e38", "23d01d5b", "", "", "", ALL, kUninstallLink },
207 // mgking0.dll, "%temp%\\".
208 { "d0893e38", "59145acf", "", "", "", ALL, kUninstallLink },
210 // mgking1.dll, "%systemroot%\\system32\\".
211 { "3e837222", "23d01d5b", "", "", "", ALL, kUninstallLink },
213 // mgking1.dll, "%temp%\\".
214 { "3e837222", "59145acf", "", "", "", ALL, kUninstallLink },
216 // mstcipha.ime, "%systemroot%\\system32\\".
217 { "5523579e", "23d01d5b", "", "", "", ALL, INVESTIGATING },
219 // mwtsp.dll, "%systemroot%\\system32\\".
220 { "9830bff6", "23d01d5b", "", "", "", ALL, kUninstallLink },
222 // nodqq0.dll, "%temp%\\".
223 { "b86ce04d", "59145acf", "", "", "", ALL, kUninstallLink },
225 // nProtect GameGuard Anti-cheat system. Every report has a different
226 // location, since it is installed into and run from a game folder. Various
227 // versions implicated.
228 // npggnt.des, no fixed location.
229 { "f2c8790d", "", "", "", "", ALL, kInvestigatingLink },
231 // nvlsp.dll,
232 // "%programfiles%\\nvidia corporation\\networkaccessmanager\\bin32\\".
233 { "37f907e2", "3ad0ff23", "", "", "", ALL, INVESTIGATING },
235 // post0.dll, "%systemroot%\\system32\\".
236 { "7405c0c8", "23d01d5b", "", "", "", ALL, kUninstallLink },
238 // questbrwsearch.dll, "%programfiles%\\questbrwsearch\\".
239 { "0953ed09", "f0d5eeda", "", "", "", ALL, kUninstallLink },
241 // questscan.dll, "%programfiles%\\questscan\\".
242 { "f4f3391e", "119d20f7", "", "", "", ALL, kUninstallLink },
244 // radhslib.dll (Naomi web filter), "%programfiles%\\rnamfler\\".
245 // See http://crbug.com/12517.
246 { "7edcd250", "0733dc3e", "", "", "", ALL, INVESTIGATING },
248 // rlls.dll, "%programfiles%\\relevantknowledge\\".
249 { "a1ed94a7", "ea9d6b36", "", "", "", ALL, kUninstallLink },
251 // rooksdol.dll, "%programfiles%\\trusteer\\rapport\\bin\\".
252 { "802aefef", "06120e13", "", "", "3.5.1008.40", ALL, UPDATE },
254 // scanquery.dll, "%programfiles%\\scanquery\\".
255 { "0b52d2ae", "a4cc88b1", "", "", "", ALL, kUninstallLink },
257 // sdata.dll, "%programdata%\\srtserv\\".
258 { "1936d5cc", "223c44be", "", "", "", ALL, kUninstallLink },
260 // searchtree.dll,
261 // "%programfiles%\\contentwatch\\internet protection\\modules\\".
262 { "f6915a31", "4e61ce60", "", "", "", ALL, INVESTIGATING },
264 // sgprxy.dll, "%commonprogramfiles%\\is3\\anti-spyware\\".
265 { "005965ea", "bc5673f2", "", "", "", ALL, INVESTIGATING },
267 // snxhk.dll, "%ProgramFiles%\\avast software\\avast\\", "AVAST Software".
268 // NOTE: The digital signature of the DLL is double null terminated.
269 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
270 // when blocked from running.
271 { "46c16aa8", "6b3a1b00", "a7db0e0c", "", "8.0", XP,
272 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
274 // snxhk.dll, "%ProgramFiles%\\alwil software\\avast5\\", "AVAST Software".
275 // NOTE: The digital signature of the DLL is double null terminated.
276 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
277 // when blocked from running.
278 { "46c16aa8", "d8686924", "a7db0e0c", "", "8.0", XP,
279 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
281 // sprotector.dll, "". Different location each report.
282 { "24555d74", "", "", "", "", ALL, kUninstallLink },
284 // swi_filter_0001.dll (Sophos Web Intelligence),
285 // "%programfiles%\\sophos\\sophos anti-virus\\web intelligence\\".
286 // A small random sample all showed version 1.0.5.0.
287 { "61112d7b", "25fb120f", "", "", "", ALL, kInvestigatingLink },
289 // twking0.dll, "%systemroot%\\system32\\".
290 { "0355549b", "23d01d5b", "", "", "", ALL, kUninstallLink },
292 // twking1.dll, "%systemroot%\\system32\\".
293 { "02e44508", "23d01d5b", "", "", "", ALL, kUninstallLink },
295 // vksaver.dll, "%systemroot%\\system32\\".
296 { "c4a784d5", "23d01d5b", "", "", "", ALL, kUninstallLink },
298 // vlsp.dll (Venturi Firewall?), "%systemroot%\\system32\\".
299 { "2e4eb93d", "23d01d5b", "", "", "", ALL, INVESTIGATING },
301 // vmn3_1dn.dll, "%appdata%\\roaming\\vmndtxtb\\".
302 { "bba2037d", "9ab68585", "", "", "", ALL, kUninstallLink },
304 // webanalyzer.dll,
305 // "%programfiles%\\contentwatch\\internet protection\\modules\\".
306 { "c70b697d", "4e61ce60", "", "", "", ALL, INVESTIGATING },
308 // wowst0.dll, "%systemroot%\\system32\\".
309 { "38ad9963", "23d01d5b", "", "", "", ALL, kUninstallLink },
311 // wxbase28u_vc_cw.dll, "%systemroot%\\system32\\".
312 { "e967210d", "23d01d5b", "", "", "", ALL, kUninstallLink },
315 // Generates an 8 digit hash from the input given.
316 static void GenerateHash(const std::string& input, std::string* output) {
317 if (input.empty()) {
318 *output = "";
319 return;
322 uint8 hash[4];
323 crypto::SHA256HashString(input, hash, sizeof(hash));
324 *output = StringToLowerASCII(base::HexEncode(hash, sizeof(hash)));
327 // -----------------------------------------------------------------------------
329 // static
330 void ModuleEnumerator::NormalizeModule(Module* module) {
331 base::string16 path = module->location;
332 if (!ConvertToLongPath(path, &module->location))
333 module->location = path;
335 module->location = base::i18n::ToLower(module->location);
337 // Location contains the filename, so the last slash is where the path
338 // ends.
339 size_t last_slash = module->location.find_last_of(L"\\");
340 if (last_slash != base::string16::npos) {
341 module->name = module->location.substr(last_slash + 1);
342 module->location = module->location.substr(0, last_slash + 1);
343 } else {
344 module->name = module->location;
345 module->location.clear();
348 // Some version strings have things like (win7_rtm.090713-1255) appended
349 // to them. Remove that.
350 size_t first_space = module->version.find_first_of(L" ");
351 if (first_space != base::string16::npos)
352 module->version = module->version.substr(0, first_space);
354 module->normalized = true;
357 // static
358 ModuleEnumerator::ModuleStatus ModuleEnumerator::Match(
359 const ModuleEnumerator::Module& module,
360 const ModuleEnumerator::BlacklistEntry& blacklisted) {
361 // All modules must be normalized before matching against blacklist.
362 DCHECK(module.normalized);
363 // Filename is mandatory and version should not contain spaces.
364 DCHECK(strlen(blacklisted.filename) > 0);
365 DCHECK(!strstr(blacklisted.version_from, " "));
366 DCHECK(!strstr(blacklisted.version_to, " "));
368 base::win::Version version = base::win::GetVersion();
369 switch (version) {
370 case base::win::VERSION_XP:
371 if (!(blacklisted.os & XP)) return NOT_MATCHED;
372 break;
373 default:
374 break;
377 std::string filename_hash, location_hash;
378 GenerateHash(base::WideToUTF8(module.name), &filename_hash);
379 GenerateHash(base::WideToUTF8(module.location), &location_hash);
381 // Filenames are mandatory. Location is mandatory if given.
382 if (filename_hash == blacklisted.filename &&
383 (std::string(blacklisted.location).empty() ||
384 location_hash == blacklisted.location)) {
385 // We have a name match against the blacklist (and possibly location match
386 // also), so check version.
387 Version module_version(UTF16ToASCII(module.version));
388 Version version_min(blacklisted.version_from);
389 Version version_max(blacklisted.version_to);
390 bool version_ok = !version_min.IsValid() && !version_max.IsValid();
391 if (!version_ok) {
392 bool too_low = version_min.IsValid() &&
393 (!module_version.IsValid() ||
394 module_version.CompareTo(version_min) < 0);
395 bool too_high = version_max.IsValid() &&
396 (!module_version.IsValid() ||
397 module_version.CompareTo(version_max) >= 0);
398 version_ok = !too_low && !too_high;
401 if (version_ok) {
402 // At this point, the names match and there is no version specified
403 // or the versions also match.
405 std::string desc_or_signer(blacklisted.desc_or_signer);
406 std::string signer_hash, description_hash;
407 GenerateHash(base::WideToUTF8(module.digital_signer), &signer_hash);
408 GenerateHash(base::WideToUTF8(module.description), &description_hash);
410 // If signatures match (or both are empty), then we have a winner.
411 if (signer_hash == desc_or_signer)
412 return CONFIRMED_BAD;
414 // If descriptions match (or both are empty) and the locations match, then
415 // we also have a confirmed match.
416 if (description_hash == desc_or_signer &&
417 !location_hash.empty() && location_hash == blacklisted.location)
418 return CONFIRMED_BAD;
420 // We are not sure, but it is likely bad.
421 return SUSPECTED_BAD;
425 return NOT_MATCHED;
428 ModuleEnumerator::ModuleEnumerator(EnumerateModulesModel* observer)
429 : enumerated_modules_(NULL),
430 observer_(observer),
431 limited_mode_(false),
432 callback_thread_id_(BrowserThread::ID_COUNT) {
435 ModuleEnumerator::~ModuleEnumerator() {
438 void ModuleEnumerator::ScanNow(ModulesVector* list, bool limited_mode) {
439 enumerated_modules_ = list;
441 limited_mode_ = limited_mode;
443 if (!limited_mode_) {
444 CHECK(BrowserThread::GetCurrentThreadIdentifier(&callback_thread_id_));
445 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
446 base::Bind(&ModuleEnumerator::ScanImpl, this));
447 } else {
448 // Run it synchronously.
449 ScanImpl();
453 void ModuleEnumerator::ScanImpl() {
454 base::TimeTicks start_time = base::TimeTicks::Now();
456 enumerated_modules_->clear();
458 // Make sure the path mapping vector is setup so we can collapse paths.
459 PreparePathMappings();
461 // Enumerating loaded modules must happen first since the other types of
462 // modules check for duplication against the loaded modules.
463 base::TimeTicks checkpoint = base::TimeTicks::Now();
464 EnumerateLoadedModules();
465 base::TimeTicks checkpoint2 = base::TimeTicks::Now();
466 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateLoadedModules",
467 checkpoint2 - checkpoint);
469 checkpoint = checkpoint2;
470 EnumerateShellExtensions();
471 checkpoint2 = base::TimeTicks::Now();
472 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateShellExtensions",
473 checkpoint2 - checkpoint);
475 checkpoint = checkpoint2;
476 EnumerateWinsockModules();
477 checkpoint2 = base::TimeTicks::Now();
478 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateWinsockModules",
479 checkpoint2 - checkpoint);
481 MatchAgainstBlacklist();
483 std::sort(enumerated_modules_->begin(),
484 enumerated_modules_->end(), ModuleSort);
486 if (!limited_mode_) {
487 // Send a reply back on the UI thread.
488 BrowserThread::PostTask(callback_thread_id_, FROM_HERE,
489 base::Bind(&ModuleEnumerator::ReportBack, this));
490 } else {
491 // We are on the main thread already.
492 ReportBack();
495 UMA_HISTOGRAM_TIMES("Conflicts.EnumerationTotalTime",
496 base::TimeTicks::Now() - start_time);
499 void ModuleEnumerator::EnumerateLoadedModules() {
500 // Get all modules in the current process.
501 base::win::ScopedHandle snap(::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,
502 ::GetCurrentProcessId()));
503 if (!snap.Get())
504 return;
506 // Walk the module list.
507 MODULEENTRY32 module = { sizeof(module) };
508 if (!::Module32First(snap.Get(), &module))
509 return;
511 do {
512 // It would be weird to present chrome.exe as a loaded module.
513 if (_wcsicmp(chrome::kBrowserProcessExecutableName, module.szModule) == 0)
514 continue;
516 Module entry;
517 entry.type = LOADED_MODULE;
518 entry.location = module.szExePath;
519 PopulateModuleInformation(&entry);
521 NormalizeModule(&entry);
522 CollapsePath(&entry);
523 enumerated_modules_->push_back(entry);
524 } while (::Module32Next(snap.Get(), &module));
527 void ModuleEnumerator::EnumerateShellExtensions() {
528 ReadShellExtensions(HKEY_LOCAL_MACHINE);
529 ReadShellExtensions(HKEY_CURRENT_USER);
532 void ModuleEnumerator::ReadShellExtensions(HKEY parent) {
533 base::win::RegistryValueIterator registration(parent, kRegPath);
534 while (registration.Valid()) {
535 std::wstring key(std::wstring(L"CLSID\\") + registration.Name() +
536 L"\\InProcServer32");
537 base::win::RegKey clsid;
538 if (clsid.Open(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ) != ERROR_SUCCESS) {
539 ++registration;
540 continue;
542 base::string16 dll;
543 if (clsid.ReadValue(L"", &dll) != ERROR_SUCCESS) {
544 ++registration;
545 continue;
547 clsid.Close();
549 Module entry;
550 entry.type = SHELL_EXTENSION;
551 entry.location = dll;
552 PopulateModuleInformation(&entry);
554 NormalizeModule(&entry);
555 CollapsePath(&entry);
556 AddToListWithoutDuplicating(entry);
558 ++registration;
562 void ModuleEnumerator::EnumerateWinsockModules() {
563 // Add to this list the Winsock LSP DLLs.
564 WinsockLayeredServiceProviderList layered_providers;
565 GetWinsockLayeredServiceProviders(&layered_providers);
566 for (size_t i = 0; i < layered_providers.size(); ++i) {
567 Module entry;
568 entry.type = WINSOCK_MODULE_REGISTRATION;
569 entry.status = NOT_MATCHED;
570 entry.normalized = false;
571 entry.location = layered_providers[i].path;
572 entry.description = layered_providers[i].name;
573 entry.recommended_action = NONE;
574 entry.duplicate_count = 0;
576 wchar_t expanded[MAX_PATH];
577 DWORD size = ExpandEnvironmentStrings(
578 entry.location.c_str(), expanded, MAX_PATH);
579 if (size != 0 && size <= MAX_PATH) {
580 entry.digital_signer =
581 GetSubjectNameFromDigitalSignature(base::FilePath(expanded));
583 entry.version = base::IntToString16(layered_providers[i].version);
585 // Paths have already been collapsed.
586 NormalizeModule(&entry);
587 AddToListWithoutDuplicating(entry);
591 void ModuleEnumerator::PopulateModuleInformation(Module* module) {
592 module->status = NOT_MATCHED;
593 module->duplicate_count = 0;
594 module->normalized = false;
595 module->digital_signer =
596 GetSubjectNameFromDigitalSignature(base::FilePath(module->location));
597 module->recommended_action = NONE;
598 scoped_ptr<FileVersionInfo> version_info(
599 FileVersionInfo::CreateFileVersionInfo(base::FilePath(module->location)));
600 if (version_info.get()) {
601 FileVersionInfoWin* version_info_win =
602 static_cast<FileVersionInfoWin*>(version_info.get());
604 VS_FIXEDFILEINFO* fixed_file_info = version_info_win->fixed_file_info();
605 if (fixed_file_info) {
606 module->description = version_info_win->file_description();
607 module->version = version_info_win->file_version();
608 module->product_name = version_info_win->product_name();
613 void ModuleEnumerator::AddToListWithoutDuplicating(const Module& module) {
614 DCHECK(module.normalized);
615 // These are registered modules, not loaded modules so the same module
616 // can be registered multiple times, often dozens of times. There is no need
617 // to list each registration, so we just increment the count for each module
618 // that is counted multiple times.
619 ModulesVector::iterator iter;
620 iter = std::find_if(enumerated_modules_->begin(),
621 enumerated_modules_->end(),
622 FindModule(module));
623 if (iter != enumerated_modules_->end()) {
624 iter->duplicate_count++;
625 iter->type = static_cast<ModuleType>(iter->type | module.type);
626 } else {
627 enumerated_modules_->push_back(module);
631 void ModuleEnumerator::PreparePathMappings() {
632 path_mapping_.clear();
634 scoped_ptr<base::Environment> environment(base::Environment::Create());
635 std::vector<base::string16> env_vars;
636 env_vars.push_back(L"LOCALAPPDATA");
637 env_vars.push_back(L"ProgramFiles");
638 env_vars.push_back(L"ProgramData");
639 env_vars.push_back(L"USERPROFILE");
640 env_vars.push_back(L"SystemRoot");
641 env_vars.push_back(L"TEMP");
642 env_vars.push_back(L"TMP");
643 env_vars.push_back(L"CommonProgramFiles");
644 for (std::vector<base::string16>::const_iterator variable = env_vars.begin();
645 variable != env_vars.end(); ++variable) {
646 std::string path;
647 if (environment->GetVar(WideToASCII(*variable).c_str(), &path)) {
648 path_mapping_.push_back(
649 std::make_pair(base::i18n::ToLower(base::UTF8ToUTF16(path)) + L"\\",
650 L"%" + base::i18n::ToLower(*variable) + L"%"));
655 void ModuleEnumerator::CollapsePath(Module* entry) {
656 // Take the path and see if we can use any of the substitution values
657 // from the vector constructed above to replace c:\windows with, for
658 // example, %systemroot%. The most collapsed path (the one with the
659 // minimum length) wins.
660 size_t min_length = MAXINT;
661 base::string16 location = entry->location;
662 for (PathMapping::const_iterator mapping = path_mapping_.begin();
663 mapping != path_mapping_.end(); ++mapping) {
664 base::string16 prefix = mapping->first;
665 if (StartsWith(location, prefix, false)) {
666 base::string16 new_location = mapping->second +
667 location.substr(prefix.length() - 1);
668 size_t length = new_location.length() - mapping->second.length();
669 if (length < min_length) {
670 entry->location = new_location;
671 min_length = length;
677 void ModuleEnumerator::MatchAgainstBlacklist() {
678 for (size_t m = 0; m < enumerated_modules_->size(); ++m) {
679 // Match this module against the blacklist.
680 Module* module = &(*enumerated_modules_)[m];
681 module->status = GOOD; // We change this below potentially.
682 for (size_t i = 0; i < arraysize(kModuleBlacklist); ++i) {
683 #if !defined(NDEBUG)
684 // This saves time when constructing the blacklist.
685 std::string hashes(kModuleBlacklist[i].filename);
686 std::string hash1, hash2, hash3;
687 GenerateHash(kModuleBlacklist[i].filename, &hash1);
688 hashes += " - " + hash1;
689 GenerateHash(kModuleBlacklist[i].location, &hash2);
690 hashes += " - " + hash2;
691 GenerateHash(kModuleBlacklist[i].desc_or_signer, &hash3);
692 hashes += " - " + hash3;
693 #endif
695 ModuleStatus status = Match(*module, kModuleBlacklist[i]);
696 if (status != NOT_MATCHED) {
697 // We have a match against the blacklist. Mark it as such.
698 module->status = status;
699 module->recommended_action = kModuleBlacklist[i].help_tip;
700 break;
704 // Modules loaded from these locations are frequently malicious
705 // and notorious for changing frequently so they are not good candidates
706 // for blacklisting individually. Mark them as suspicious if we haven't
707 // classified them as bad yet.
708 if (module->status == NOT_MATCHED || module->status == GOOD) {
709 if (StartsWith(module->location, L"%temp%", false) ||
710 StartsWith(module->location, L"%tmp%", false)) {
711 module->status = SUSPECTED_BAD;
717 void ModuleEnumerator::ReportBack() {
718 if (!limited_mode_)
719 DCHECK(BrowserThread::CurrentlyOn(callback_thread_id_));
720 observer_->DoneScanning();
723 base::string16 ModuleEnumerator::GetSubjectNameFromDigitalSignature(
724 const base::FilePath& filename) {
725 HCERTSTORE store = NULL;
726 HCRYPTMSG message = NULL;
728 // Find the crypto message for this filename.
729 bool result = !!CryptQueryObject(CERT_QUERY_OBJECT_FILE,
730 filename.value().c_str(),
731 CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
732 CERT_QUERY_FORMAT_FLAG_BINARY,
734 NULL,
735 NULL,
736 NULL,
737 &store,
738 &message,
739 NULL);
740 if (!result)
741 return base::string16();
743 // Determine the size of the signer info data.
744 DWORD signer_info_size = 0;
745 result = !!CryptMsgGetParam(message,
746 CMSG_SIGNER_INFO_PARAM,
748 NULL,
749 &signer_info_size);
750 if (!result)
751 return base::string16();
753 // Allocate enough space to hold the signer info.
754 scoped_ptr<BYTE[]> signer_info_buffer(new BYTE[signer_info_size]);
755 CMSG_SIGNER_INFO* signer_info =
756 reinterpret_cast<CMSG_SIGNER_INFO*>(signer_info_buffer.get());
758 // Obtain the signer info.
759 result = !!CryptMsgGetParam(message,
760 CMSG_SIGNER_INFO_PARAM,
762 signer_info,
763 &signer_info_size);
764 if (!result)
765 return base::string16();
767 // Search for the signer certificate.
768 CERT_INFO CertInfo = {0};
769 PCCERT_CONTEXT cert_context = NULL;
770 CertInfo.Issuer = signer_info->Issuer;
771 CertInfo.SerialNumber = signer_info->SerialNumber;
773 cert_context = CertFindCertificateInStore(
774 store,
775 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
777 CERT_FIND_SUBJECT_CERT,
778 &CertInfo,
779 NULL);
780 if (!cert_context)
781 return base::string16();
783 // Determine the size of the Subject name.
784 DWORD subject_name_size = 0;
785 if (!(subject_name_size = CertGetNameString(cert_context,
786 CERT_NAME_SIMPLE_DISPLAY_TYPE,
788 NULL,
789 NULL,
790 0))) {
791 return base::string16();
794 base::string16 subject_name;
795 subject_name.resize(subject_name_size);
797 // Get subject name.
798 if (!(CertGetNameString(cert_context,
799 CERT_NAME_SIMPLE_DISPLAY_TYPE,
801 NULL,
802 const_cast<LPWSTR>(subject_name.c_str()),
803 subject_name_size))) {
804 return base::string16();
807 return subject_name;
810 // ----------------------------------------------------------------------------
812 // static
813 EnumerateModulesModel* EnumerateModulesModel::GetInstance() {
814 return Singleton<EnumerateModulesModel>::get();
817 // static
818 void EnumerateModulesModel::RecordLearnMoreStat(bool from_menu) {
819 UMA_HISTOGRAM_ENUMERATION("ConflictingModule.UserSelection",
820 from_menu ? ACTION_MENU_LEARN_MORE : ACTION_BUBBLE_LEARN_MORE,
821 ACTION_BOUNDARY);
824 bool EnumerateModulesModel::ShouldShowConflictWarning() const {
825 // If the user has acknowledged the conflict notification, then we don't need
826 // to show it again (because the scanning only happens once per the lifetime
827 // of the process). If we were to run the scanning more than once, then we'd
828 // need to clear the flag somewhere when we are ready to show it again.
829 if (conflict_notification_acknowledged_)
830 return false;
832 return confirmed_bad_modules_detected_ > 0;
835 void EnumerateModulesModel::AcknowledgeConflictNotification() {
836 if (!conflict_notification_acknowledged_) {
837 conflict_notification_acknowledged_ = true;
838 content::NotificationService::current()->Notify(
839 chrome::NOTIFICATION_MODULE_INCOMPATIBILITY_BADGE_CHANGE,
840 content::Source<EnumerateModulesModel>(this),
841 content::NotificationService::NoDetails());
845 void EnumerateModulesModel::ScanNow() {
846 if (scanning_)
847 return; // A scan is already in progress.
849 lock->Acquire(); // Balanced in DoneScanning();
851 scanning_ = true;
853 // Instruct the ModuleEnumerator class to load this on the File thread.
854 // ScanNow does not block.
855 if (!module_enumerator_)
856 module_enumerator_ = new ModuleEnumerator(this);
857 module_enumerator_->ScanNow(&enumerated_modules_, limited_mode_);
860 base::ListValue* EnumerateModulesModel::GetModuleList() const {
861 if (scanning_)
862 return NULL;
864 lock->Acquire();
866 if (enumerated_modules_.empty()) {
867 lock->Release();
868 return NULL;
871 base::ListValue* list = new base::ListValue();
873 for (ModuleEnumerator::ModulesVector::const_iterator module =
874 enumerated_modules_.begin();
875 module != enumerated_modules_.end(); ++module) {
876 base::DictionaryValue* data = new base::DictionaryValue();
877 data->SetInteger("type", module->type);
878 base::string16 type_string;
879 if ((module->type & ModuleEnumerator::LOADED_MODULE) == 0) {
880 // Module is not loaded, denote type of module.
881 if (module->type & ModuleEnumerator::SHELL_EXTENSION)
882 type_string = base::ASCIIToWide("Shell Extension");
883 if (module->type & ModuleEnumerator::WINSOCK_MODULE_REGISTRATION) {
884 if (!type_string.empty())
885 type_string += base::ASCIIToWide(", ");
886 type_string += base::ASCIIToWide("Winsock");
888 // Must be one of the above type.
889 DCHECK(!type_string.empty());
890 if (!limited_mode_) {
891 type_string += base::ASCIIToWide(" -- ");
892 type_string += l10n_util::GetStringUTF16(IDS_CONFLICTS_NOT_LOADED_YET);
895 data->SetString("type_description", type_string);
896 data->SetInteger("status", module->status);
897 data->SetString("location", module->location);
898 data->SetString("name", module->name);
899 data->SetString("product_name", module->product_name);
900 data->SetString("description", module->description);
901 data->SetString("version", module->version);
902 data->SetString("digital_signer", module->digital_signer);
904 if (!limited_mode_) {
905 // Figure out the possible resolution help string.
906 base::string16 actions;
907 base::string16 separator = base::ASCIIToWide(" ") +
908 l10n_util::GetStringUTF16(
909 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_SEPERATOR) +
910 base::ASCIIToWide(" ");
912 if (module->recommended_action & ModuleEnumerator::NONE) {
913 actions = l10n_util::GetStringUTF16(
914 IDS_CONFLICTS_CHECK_INVESTIGATING);
916 if (module->recommended_action & ModuleEnumerator::UNINSTALL) {
917 if (!actions.empty())
918 actions += separator;
919 actions = l10n_util::GetStringUTF16(
920 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_UNINSTALL);
922 if (module->recommended_action & ModuleEnumerator::UPDATE) {
923 if (!actions.empty())
924 actions += separator;
925 actions += l10n_util::GetStringUTF16(
926 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_UPDATE);
928 if (module->recommended_action & ModuleEnumerator::DISABLE) {
929 if (!actions.empty())
930 actions += separator;
931 actions += l10n_util::GetStringUTF16(
932 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_DISABLE);
934 base::string16 possible_resolution =
935 actions.empty() ? base::ASCIIToWide("")
936 : l10n_util::GetStringUTF16(
937 IDS_CONFLICTS_CHECK_POSSIBLE_ACTIONS) +
938 base::ASCIIToWide(" ") +
939 actions;
940 data->SetString("possibleResolution", possible_resolution);
941 data->SetString("help_url",
942 ConstructHelpCenterUrl(*module).spec().c_str());
945 list->Append(data);
948 lock->Release();
949 return list;
952 GURL EnumerateModulesModel::GetFirstNotableConflict() {
953 lock->Acquire();
954 GURL url;
956 if (enumerated_modules_.empty()) {
957 lock->Release();
958 return GURL();
961 for (ModuleEnumerator::ModulesVector::const_iterator module =
962 enumerated_modules_.begin();
963 module != enumerated_modules_.end(); ++module) {
964 if (!(module->recommended_action & ModuleEnumerator::NOTIFY_USER))
965 continue;
967 url = ConstructHelpCenterUrl(*module);
968 DCHECK(url.is_valid());
969 break;
972 lock->Release();
973 return url;
977 EnumerateModulesModel::EnumerateModulesModel()
978 : limited_mode_(false),
979 scanning_(false),
980 conflict_notification_acknowledged_(false),
981 confirmed_bad_modules_detected_(0),
982 suspected_bad_modules_detected_(0),
983 modules_to_notify_about_(0) {
984 lock = new base::Lock();
987 EnumerateModulesModel::~EnumerateModulesModel() {
988 delete lock;
991 void EnumerateModulesModel::MaybePostScanningTask() {
992 static bool done = false;
993 if (!done) {
994 done = true;
996 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
997 if (cmd_line.HasSwitch(switches::kConflictingModulesCheck) ||
998 base::win::GetVersion() == base::win::VERSION_XP) {
999 check_modules_timer_.Start(FROM_HERE,
1000 base::TimeDelta::FromMilliseconds(kModuleCheckDelayMs),
1001 this, &EnumerateModulesModel::ScanNow);
1006 void EnumerateModulesModel::DoneScanning() {
1007 confirmed_bad_modules_detected_ = 0;
1008 suspected_bad_modules_detected_ = 0;
1009 modules_to_notify_about_ = 0;
1010 for (ModuleEnumerator::ModulesVector::const_iterator module =
1011 enumerated_modules_.begin();
1012 module != enumerated_modules_.end(); ++module) {
1013 if (module->status == ModuleEnumerator::CONFIRMED_BAD) {
1014 ++confirmed_bad_modules_detected_;
1015 if (module->recommended_action & ModuleEnumerator::NOTIFY_USER)
1016 ++modules_to_notify_about_;
1017 } else if (module->status == ModuleEnumerator::SUSPECTED_BAD) {
1018 ++suspected_bad_modules_detected_;
1019 if (module->recommended_action & ModuleEnumerator::NOTIFY_USER)
1020 ++modules_to_notify_about_;
1024 scanning_ = false;
1025 lock->Release();
1027 UMA_HISTOGRAM_COUNTS_100("Conflicts.SuspectedBadModules",
1028 suspected_bad_modules_detected_);
1029 UMA_HISTOGRAM_COUNTS_100("Conflicts.ConfirmedBadModules",
1030 confirmed_bad_modules_detected_);
1032 // Notifications are not available in limited mode.
1033 if (limited_mode_)
1034 return;
1036 content::NotificationService::current()->Notify(
1037 chrome::NOTIFICATION_MODULE_LIST_ENUMERATED,
1038 content::Source<EnumerateModulesModel>(this),
1039 content::NotificationService::NoDetails());
1041 // Command line flag must be enabled for the notification to get sent out.
1042 // Otherwise we'd get the badge (while the feature is disabled) when we
1043 // navigate to about:conflicts and find confirmed matches.
1044 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
1045 if (!cmd_line.HasSwitch(switches::kConflictingModulesCheck))
1046 return;
1048 content::NotificationService::current()->Notify(
1049 chrome::NOTIFICATION_MODULE_INCOMPATIBILITY_BADGE_CHANGE,
1050 content::Source<EnumerateModulesModel>(this),
1051 content::NotificationService::NoDetails());
1054 GURL EnumerateModulesModel::ConstructHelpCenterUrl(
1055 const ModuleEnumerator::Module& module) const {
1056 if (!(module.recommended_action & ModuleEnumerator::SEE_LINK) &&
1057 !(module.recommended_action & ModuleEnumerator::NOTIFY_USER))
1058 return GURL();
1060 // Construct the needed hashes.
1061 std::string filename, location, description, signer;
1062 GenerateHash(base::WideToUTF8(module.name), &filename);
1063 GenerateHash(base::WideToUTF8(module.location), &location);
1064 GenerateHash(base::WideToUTF8(module.description), &description);
1065 GenerateHash(base::WideToUTF8(module.digital_signer), &signer);
1067 base::string16 url =
1068 l10n_util::GetStringFUTF16(IDS_HELP_CENTER_VIEW_CONFLICTS,
1069 base::ASCIIToUTF16(filename), base::ASCIIToUTF16(location),
1070 base::ASCIIToUTF16(description), base::ASCIIToUTF16(signer));
1071 return GURL(base::UTF16ToUTF8(url));