Adding a router class to handle messages that expect responses.
[chromium-blink-merge.git] / chrome / browser / enumerate_modules_model_win.cc
blob278f7950f7c3a2c653c02a6dc1ed0e06d1bcb70b
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 "content/public/browser/notification_service.h"
31 #include "crypto/sha2.h"
32 #include "grit/generated_resources.h"
33 #include "grit/google_chrome_strings.h"
34 #include "ui/base/l10n/l10n_util.h"
36 using content::BrowserThread;
38 // The period of time (in milliseconds) to wait until checking to see if any
39 // incompatible modules exist.
40 static const int kModuleCheckDelayMs = 45 * 1000;
42 // The path to the Shell Extension key in the Windows registry.
43 static const wchar_t kRegPath[] =
44 L"Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved";
46 // Short-hand for things on the blacklist you should simply get rid of.
47 static const ModuleEnumerator::RecommendedAction kUninstallLink =
48 static_cast<ModuleEnumerator::RecommendedAction>(
49 ModuleEnumerator::UNINSTALL | ModuleEnumerator::SEE_LINK);
51 // Short-hand for things on the blacklist we are investigating and have info.
52 static const ModuleEnumerator::RecommendedAction kInvestigatingLink =
53 static_cast<ModuleEnumerator::RecommendedAction>(
54 ModuleEnumerator::INVESTIGATING | ModuleEnumerator::SEE_LINK);
56 // A sort method that sorts by bad modules first, then by full name (including
57 // path).
58 static bool ModuleSort(const ModuleEnumerator::Module& a,
59 const ModuleEnumerator::Module& b) {
60 if (a.status != b.status)
61 return a.status > b.status;
63 if (a.location == b.location)
64 return a.name < b.name;
66 return a.location < b.location;
69 namespace {
71 // Used to protect the LoadedModuleVector which is accessed
72 // from both the UI thread and the FILE thread.
73 base::Lock* lock = NULL;
75 // A struct to help de-duping modules before adding them to the enumerated
76 // modules vector.
77 struct FindModule {
78 public:
79 explicit FindModule(const ModuleEnumerator::Module& x)
80 : module(x) {}
81 bool operator()(const ModuleEnumerator::Module& module_in) const {
82 return (module.location == module_in.location) &&
83 (module.name == module_in.name);
86 const ModuleEnumerator::Module& module;
89 // Returns the long path name given a short path name. A short path name is a
90 // path that follows the 8.3 convention and has ~x in it. If the path is already
91 // a long path name, the function returns the current path without modification.
92 bool ConvertToLongPath(const base::string16& short_path,
93 base::string16* long_path) {
94 wchar_t long_path_buf[MAX_PATH];
95 DWORD return_value = GetLongPathName(short_path.c_str(), long_path_buf,
96 MAX_PATH);
97 if (return_value != 0 && return_value < MAX_PATH) {
98 *long_path = long_path_buf;
99 return true;
102 return false;
105 } // namespace
107 // The browser process module blacklist. This lists modules that are known
108 // to cause compatibility issues within the browser process. When adding to this
109 // list, make sure that all paths are lower-case, in long pathname form, end
110 // with a slash and use environments variables (or just look at one of the
111 // comments below and keep it consistent with that). When adding an entry with
112 // an environment variable not currently used in the list below, make sure to
113 // update the list in PreparePathMappings. Filename, Description/Signer, and
114 // Location must be entered as hashes (see GenerateHash). Filename is mandatory.
115 // Entries without any Description, Signer info, or Location will never be
116 // marked as confirmed bad (only as suspicious).
117 const ModuleEnumerator::BlacklistEntry ModuleEnumerator::kModuleBlacklist[] = {
118 // NOTE: Please keep this list sorted by dll name, then location.
120 // Version 3.2.1.6 seems to be implicated in most cases (and 3.2.2.2 in some).
121 // There is a more recent version available for download.
122 // accelerator.dll, "%programfiles%\\speedbit video accelerator\\".
123 { "7ba9402f", "c9132d48", "", "", "", ALL, kInvestigatingLink },
125 // apiqq0.dll, "%temp%\\".
126 { "26134911", "59145acf", "", "", "", ALL, kUninstallLink },
128 // arking0.dll, "%systemroot%\\system32\\".
129 { "f5d8f549", "23d01d5b", "", "", "", ALL, kUninstallLink },
131 // arking1.dll, "%systemroot%\\system32\\".
132 { "c60ca062", "23d01d5b", "", "", "", ALL, kUninstallLink },
134 // aswjsflt.dll, "%ProgramFiles%\\avast software\\avast\\", "AVAST Software".
135 // NOTE: The digital signature of the DLL is double null terminated.
136 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
137 // when blocked from running.
138 { "2ea5422a", "6b3a1b00", "a7db0e0c", "", "8.0", XP,
139 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
141 // aswjsflt.dll, "%ProgramFiles%\\alwil software\\avast5\\", "AVAST Software".
142 // NOTE: The digital signature of the DLL is double null terminated.
143 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
144 // when blocked from running.
145 { "2ea5422a", "d8686924", "a7db0e0c", "", "8.0", XP,
146 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
148 // Said to belong to Killer NIC from BigFoot Networks (not verified). Versions
149 // 6.0.0.7 and 6.0.0.10 implicated.
150 // bfllr.dll, "%systemroot%\\system32\\".
151 { "6bb57633", "23d01d5b", "", "", "", ALL, kInvestigatingLink },
153 // clickpotatolitesahook.dll, "". Different version each report.
154 { "0396e037.dll", "", "", "", "", ALL, kUninstallLink },
156 // cvasds0.dll, "%temp%\\".
157 { "5ce0037c", "59145acf", "", "", "", ALL, kUninstallLink },
159 // cwalsp.dll, "%systemroot%\\system32\\".
160 { "e579a039", "23d01d5b", "", "", "", ALL, kUninstallLink },
162 // datamngr.dll (1), "%programfiles%\\searchqu toolbar\\datamngr\\".
163 { "7add320b", "470a3da3", "", "", "", ALL, kUninstallLink },
165 // datamngr.dll (2), "%programfiles%\\windows searchqu toolbar\\".
166 { "7add320b", "7a3c8be3", "", "", "", ALL, kUninstallLink },
168 // dsoqq0.dll, "%temp%\\".
169 { "1c4df325", "59145acf", "", "", "", ALL, kUninstallLink },
171 // flt.dll, "%programfiles%\\tueagles\\".
172 { "6d01f4a1", "7935e9c2", "", "", "", ALL, kUninstallLink },
174 // This looks like a malware edition of a Brazilian Bank plugin, sometimes
175 // referred to as Malware.Banc.A.
176 // gbieh.dll, "%programfiles%\\gbplugin\\".
177 { "4cb4f2e3", "88e4a3b1", "", "", "", ALL, kUninstallLink },
179 // hblitesahook.dll. Each report has different version number in location.
180 { "5d10b363", "", "", "", "", ALL, kUninstallLink },
182 // icf.dll, "%systemroot%\\system32\\".
183 { "303825ed", "23d01d5b", "", "", "", ALL, INVESTIGATING },
185 // idmmbc.dll (IDM), "%systemroot%\\system32\\". See: http://crbug.com/26892/.
186 { "b8dce5c3", "23d01d5b", "", "", "6.03", ALL,
187 static_cast<RecommendedAction>(UPDATE | DISABLE) },
189 // imon.dll (NOD32), "%systemroot%\\system32\\". See: http://crbug.com/21715.
190 { "8f42f22e", "23d01d5b", "", "", "4.0", ALL,
191 static_cast<RecommendedAction>(UPDATE | DISABLE) },
193 // is3lsp.dll, "%commonprogramfiles%\\is3\\anti-spyware\\".
194 { "7ffbdce9", "bc5673f2", "", "", "", ALL,
195 static_cast<RecommendedAction>(UPDATE | DISABLE | SEE_LINK) },
197 // jsi.dll, "%programfiles%\\profilecraze\\".
198 { "f9555eea", "e3548061", "", "", "", ALL, kUninstallLink },
200 // kernel.dll, "%programfiles%\\contentwatch\\internet protection\\modules\\".
201 { "ead2768e", "4e61ce60", "", "", "", ALL, INVESTIGATING },
203 // mgking0.dll, "%systemroot%\\system32\\".
204 { "d0893e38", "23d01d5b", "", "", "", ALL, kUninstallLink },
206 // mgking0.dll, "%temp%\\".
207 { "d0893e38", "59145acf", "", "", "", ALL, kUninstallLink },
209 // mgking1.dll, "%systemroot%\\system32\\".
210 { "3e837222", "23d01d5b", "", "", "", ALL, kUninstallLink },
212 // mgking1.dll, "%temp%\\".
213 { "3e837222", "59145acf", "", "", "", ALL, kUninstallLink },
215 // mstcipha.ime, "%systemroot%\\system32\\".
216 { "5523579e", "23d01d5b", "", "", "", ALL, INVESTIGATING },
218 // mwtsp.dll, "%systemroot%\\system32\\".
219 { "9830bff6", "23d01d5b", "", "", "", ALL, kUninstallLink },
221 // nodqq0.dll, "%temp%\\".
222 { "b86ce04d", "59145acf", "", "", "", ALL, kUninstallLink },
224 // nProtect GameGuard Anti-cheat system. Every report has a different
225 // location, since it is installed into and run from a game folder. Various
226 // versions implicated.
227 // npggnt.des, no fixed location.
228 { "f2c8790d", "", "", "", "", ALL, kInvestigatingLink },
230 // nvlsp.dll,
231 // "%programfiles%\\nvidia corporation\\networkaccessmanager\\bin32\\".
232 { "37f907e2", "3ad0ff23", "", "", "", ALL, INVESTIGATING },
234 // post0.dll, "%systemroot%\\system32\\".
235 { "7405c0c8", "23d01d5b", "", "", "", ALL, kUninstallLink },
237 // questbrwsearch.dll, "%programfiles%\\questbrwsearch\\".
238 { "0953ed09", "f0d5eeda", "", "", "", ALL, kUninstallLink },
240 // questscan.dll, "%programfiles%\\questscan\\".
241 { "f4f3391e", "119d20f7", "", "", "", ALL, kUninstallLink },
243 // radhslib.dll (Naomi web filter), "%programfiles%\\rnamfler\\".
244 // See http://crbug.com/12517.
245 { "7edcd250", "0733dc3e", "", "", "", ALL, INVESTIGATING },
247 // rlls.dll, "%programfiles%\\relevantknowledge\\".
248 { "a1ed94a7", "ea9d6b36", "", "", "", ALL, kUninstallLink },
250 // rooksdol.dll, "%programfiles%\\trusteer\\rapport\\bin\\".
251 { "802aefef", "06120e13", "", "", "3.5.1008.40", ALL, UPDATE },
253 // scanquery.dll, "%programfiles%\\scanquery\\".
254 { "0b52d2ae", "a4cc88b1", "", "", "", ALL, kUninstallLink },
256 // sdata.dll, "%programdata%\\srtserv\\".
257 { "1936d5cc", "223c44be", "", "", "", ALL, kUninstallLink },
259 // searchtree.dll,
260 // "%programfiles%\\contentwatch\\internet protection\\modules\\".
261 { "f6915a31", "4e61ce60", "", "", "", ALL, INVESTIGATING },
263 // sgprxy.dll, "%commonprogramfiles%\\is3\\anti-spyware\\".
264 { "005965ea", "bc5673f2", "", "", "", ALL, INVESTIGATING },
266 // snxhk.dll, "%ProgramFiles%\\avast software\\avast\\", "AVAST Software".
267 // NOTE: The digital signature of the DLL is double null terminated.
268 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
269 // when blocked from running.
270 { "46c16aa8", "6b3a1b00", "a7db0e0c", "", "8.0", XP,
271 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
273 // snxhk.dll, "%ProgramFiles%\\alwil software\\avast5\\", "AVAST Software".
274 // NOTE: The digital signature of the DLL is double null terminated.
275 // Avast Antivirus prior to version 8.0 would kill the Chrome child process
276 // when blocked from running.
277 { "46c16aa8", "d8686924", "a7db0e0c", "", "8.0", XP,
278 static_cast<RecommendedAction>(UPDATE | SEE_LINK | NOTIFY_USER) },
280 // sprotector.dll, "". Different location each report.
281 { "24555d74", "", "", "", "", ALL, kUninstallLink },
283 // swi_filter_0001.dll (Sophos Web Intelligence),
284 // "%programfiles%\\sophos\\sophos anti-virus\\web intelligence\\".
285 // A small random sample all showed version 1.0.5.0.
286 { "61112d7b", "25fb120f", "", "", "", ALL, kInvestigatingLink },
288 // twking0.dll, "%systemroot%\\system32\\".
289 { "0355549b", "23d01d5b", "", "", "", ALL, kUninstallLink },
291 // twking1.dll, "%systemroot%\\system32\\".
292 { "02e44508", "23d01d5b", "", "", "", ALL, kUninstallLink },
294 // vksaver.dll, "%systemroot%\\system32\\".
295 { "c4a784d5", "23d01d5b", "", "", "", ALL, kUninstallLink },
297 // vlsp.dll (Venturi Firewall?), "%systemroot%\\system32\\".
298 { "2e4eb93d", "23d01d5b", "", "", "", ALL, INVESTIGATING },
300 // vmn3_1dn.dll, "%appdata%\\roaming\\vmndtxtb\\".
301 { "bba2037d", "9ab68585", "", "", "", ALL, kUninstallLink },
303 // webanalyzer.dll,
304 // "%programfiles%\\contentwatch\\internet protection\\modules\\".
305 { "c70b697d", "4e61ce60", "", "", "", ALL, INVESTIGATING },
307 // wowst0.dll, "%systemroot%\\system32\\".
308 { "38ad9963", "23d01d5b", "", "", "", ALL, kUninstallLink },
310 // wxbase28u_vc_cw.dll, "%systemroot%\\system32\\".
311 { "e967210d", "23d01d5b", "", "", "", ALL, kUninstallLink },
314 // Generates an 8 digit hash from the input given.
315 static void GenerateHash(const std::string& input, std::string* output) {
316 if (input.empty()) {
317 *output = "";
318 return;
321 uint8 hash[4];
322 crypto::SHA256HashString(input, hash, sizeof(hash));
323 *output = StringToLowerASCII(base::HexEncode(hash, sizeof(hash)));
326 // -----------------------------------------------------------------------------
328 // static
329 void ModuleEnumerator::NormalizeModule(Module* module) {
330 base::string16 path = module->location;
331 if (!ConvertToLongPath(path, &module->location))
332 module->location = path;
334 module->location = base::i18n::ToLower(module->location);
336 // Location contains the filename, so the last slash is where the path
337 // ends.
338 size_t last_slash = module->location.find_last_of(L"\\");
339 if (last_slash != base::string16::npos) {
340 module->name = module->location.substr(last_slash + 1);
341 module->location = module->location.substr(0, last_slash + 1);
342 } else {
343 module->name = module->location;
344 module->location.clear();
347 // Some version strings have things like (win7_rtm.090713-1255) appended
348 // to them. Remove that.
349 size_t first_space = module->version.find_first_of(L" ");
350 if (first_space != base::string16::npos)
351 module->version = module->version.substr(0, first_space);
353 module->normalized = true;
356 // static
357 ModuleEnumerator::ModuleStatus ModuleEnumerator::Match(
358 const ModuleEnumerator::Module& module,
359 const ModuleEnumerator::BlacklistEntry& blacklisted) {
360 // All modules must be normalized before matching against blacklist.
361 DCHECK(module.normalized);
362 // Filename is mandatory and version should not contain spaces.
363 DCHECK(strlen(blacklisted.filename) > 0);
364 DCHECK(!strstr(blacklisted.version_from, " "));
365 DCHECK(!strstr(blacklisted.version_to, " "));
367 base::win::Version version = base::win::GetVersion();
368 switch (version) {
369 case base::win::VERSION_XP:
370 if (!(blacklisted.os & XP)) return NOT_MATCHED;
371 break;
372 default:
373 break;
376 std::string filename_hash, location_hash;
377 GenerateHash(base::WideToUTF8(module.name), &filename_hash);
378 GenerateHash(base::WideToUTF8(module.location), &location_hash);
380 // Filenames are mandatory. Location is mandatory if given.
381 if (filename_hash == blacklisted.filename &&
382 (std::string(blacklisted.location).empty() ||
383 location_hash == blacklisted.location)) {
384 // We have a name match against the blacklist (and possibly location match
385 // also), so check version.
386 Version module_version(base::UTF16ToASCII(module.version));
387 Version version_min(blacklisted.version_from);
388 Version version_max(blacklisted.version_to);
389 bool version_ok = !version_min.IsValid() && !version_max.IsValid();
390 if (!version_ok) {
391 bool too_low = version_min.IsValid() &&
392 (!module_version.IsValid() ||
393 module_version.CompareTo(version_min) < 0);
394 bool too_high = version_max.IsValid() &&
395 (!module_version.IsValid() ||
396 module_version.CompareTo(version_max) >= 0);
397 version_ok = !too_low && !too_high;
400 if (version_ok) {
401 // At this point, the names match and there is no version specified
402 // or the versions also match.
404 std::string desc_or_signer(blacklisted.desc_or_signer);
405 std::string signer_hash, description_hash;
406 GenerateHash(base::WideToUTF8(module.digital_signer), &signer_hash);
407 GenerateHash(base::WideToUTF8(module.description), &description_hash);
409 // If signatures match (or both are empty), then we have a winner.
410 if (signer_hash == desc_or_signer)
411 return CONFIRMED_BAD;
413 // If descriptions match (or both are empty) and the locations match, then
414 // we also have a confirmed match.
415 if (description_hash == desc_or_signer &&
416 !location_hash.empty() && location_hash == blacklisted.location)
417 return CONFIRMED_BAD;
419 // We are not sure, but it is likely bad.
420 return SUSPECTED_BAD;
424 return NOT_MATCHED;
427 ModuleEnumerator::ModuleEnumerator(EnumerateModulesModel* observer)
428 : enumerated_modules_(NULL),
429 observer_(observer),
430 limited_mode_(false),
431 callback_thread_id_(BrowserThread::ID_COUNT) {
434 ModuleEnumerator::~ModuleEnumerator() {
437 void ModuleEnumerator::ScanNow(ModulesVector* list, bool limited_mode) {
438 enumerated_modules_ = list;
440 limited_mode_ = limited_mode;
442 if (!limited_mode_) {
443 CHECK(BrowserThread::GetCurrentThreadIdentifier(&callback_thread_id_));
444 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
445 base::Bind(&ModuleEnumerator::ScanImpl, this));
446 } else {
447 // Run it synchronously.
448 ScanImpl();
452 void ModuleEnumerator::ScanImpl() {
453 base::TimeTicks start_time = base::TimeTicks::Now();
455 enumerated_modules_->clear();
457 // Make sure the path mapping vector is setup so we can collapse paths.
458 PreparePathMappings();
460 // Enumerating loaded modules must happen first since the other types of
461 // modules check for duplication against the loaded modules.
462 base::TimeTicks checkpoint = base::TimeTicks::Now();
463 EnumerateLoadedModules();
464 base::TimeTicks checkpoint2 = base::TimeTicks::Now();
465 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateLoadedModules",
466 checkpoint2 - checkpoint);
468 checkpoint = checkpoint2;
469 EnumerateShellExtensions();
470 checkpoint2 = base::TimeTicks::Now();
471 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateShellExtensions",
472 checkpoint2 - checkpoint);
474 checkpoint = checkpoint2;
475 EnumerateWinsockModules();
476 checkpoint2 = base::TimeTicks::Now();
477 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateWinsockModules",
478 checkpoint2 - checkpoint);
480 MatchAgainstBlacklist();
482 std::sort(enumerated_modules_->begin(),
483 enumerated_modules_->end(), ModuleSort);
485 if (!limited_mode_) {
486 // Send a reply back on the UI thread.
487 BrowserThread::PostTask(callback_thread_id_, FROM_HERE,
488 base::Bind(&ModuleEnumerator::ReportBack, this));
489 } else {
490 // We are on the main thread already.
491 ReportBack();
494 UMA_HISTOGRAM_TIMES("Conflicts.EnumerationTotalTime",
495 base::TimeTicks::Now() - start_time);
498 void ModuleEnumerator::EnumerateLoadedModules() {
499 // Get all modules in the current process.
500 base::win::ScopedHandle snap(::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,
501 ::GetCurrentProcessId()));
502 if (!snap.Get())
503 return;
505 // Walk the module list.
506 MODULEENTRY32 module = { sizeof(module) };
507 if (!::Module32First(snap.Get(), &module))
508 return;
510 do {
511 // It would be weird to present chrome.exe as a loaded module.
512 if (_wcsicmp(chrome::kBrowserProcessExecutableName, module.szModule) == 0)
513 continue;
515 Module entry;
516 entry.type = LOADED_MODULE;
517 entry.location = module.szExePath;
518 PopulateModuleInformation(&entry);
520 NormalizeModule(&entry);
521 CollapsePath(&entry);
522 enumerated_modules_->push_back(entry);
523 } while (::Module32Next(snap.Get(), &module));
526 void ModuleEnumerator::EnumerateShellExtensions() {
527 ReadShellExtensions(HKEY_LOCAL_MACHINE);
528 ReadShellExtensions(HKEY_CURRENT_USER);
531 void ModuleEnumerator::ReadShellExtensions(HKEY parent) {
532 base::win::RegistryValueIterator registration(parent, kRegPath);
533 while (registration.Valid()) {
534 std::wstring key(std::wstring(L"CLSID\\") + registration.Name() +
535 L"\\InProcServer32");
536 base::win::RegKey clsid;
537 if (clsid.Open(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ) != ERROR_SUCCESS) {
538 ++registration;
539 continue;
541 base::string16 dll;
542 if (clsid.ReadValue(L"", &dll) != ERROR_SUCCESS) {
543 ++registration;
544 continue;
546 clsid.Close();
548 Module entry;
549 entry.type = SHELL_EXTENSION;
550 entry.location = dll;
551 PopulateModuleInformation(&entry);
553 NormalizeModule(&entry);
554 CollapsePath(&entry);
555 AddToListWithoutDuplicating(entry);
557 ++registration;
561 void ModuleEnumerator::EnumerateWinsockModules() {
562 // Add to this list the Winsock LSP DLLs.
563 WinsockLayeredServiceProviderList layered_providers;
564 GetWinsockLayeredServiceProviders(&layered_providers);
565 for (size_t i = 0; i < layered_providers.size(); ++i) {
566 Module entry;
567 entry.type = WINSOCK_MODULE_REGISTRATION;
568 entry.status = NOT_MATCHED;
569 entry.normalized = false;
570 entry.location = layered_providers[i].path;
571 entry.description = layered_providers[i].name;
572 entry.recommended_action = NONE;
573 entry.duplicate_count = 0;
575 wchar_t expanded[MAX_PATH];
576 DWORD size = ExpandEnvironmentStrings(
577 entry.location.c_str(), expanded, MAX_PATH);
578 if (size != 0 && size <= MAX_PATH) {
579 entry.digital_signer =
580 GetSubjectNameFromDigitalSignature(base::FilePath(expanded));
582 entry.version = base::IntToString16(layered_providers[i].version);
584 // Paths have already been collapsed.
585 NormalizeModule(&entry);
586 AddToListWithoutDuplicating(entry);
590 void ModuleEnumerator::PopulateModuleInformation(Module* module) {
591 module->status = NOT_MATCHED;
592 module->duplicate_count = 0;
593 module->normalized = false;
594 module->digital_signer =
595 GetSubjectNameFromDigitalSignature(base::FilePath(module->location));
596 module->recommended_action = NONE;
597 scoped_ptr<FileVersionInfo> version_info(
598 FileVersionInfo::CreateFileVersionInfo(base::FilePath(module->location)));
599 if (version_info.get()) {
600 FileVersionInfoWin* version_info_win =
601 static_cast<FileVersionInfoWin*>(version_info.get());
603 VS_FIXEDFILEINFO* fixed_file_info = version_info_win->fixed_file_info();
604 if (fixed_file_info) {
605 module->description = version_info_win->file_description();
606 module->version = version_info_win->file_version();
607 module->product_name = version_info_win->product_name();
612 void ModuleEnumerator::AddToListWithoutDuplicating(const Module& module) {
613 DCHECK(module.normalized);
614 // These are registered modules, not loaded modules so the same module
615 // can be registered multiple times, often dozens of times. There is no need
616 // to list each registration, so we just increment the count for each module
617 // that is counted multiple times.
618 ModulesVector::iterator iter;
619 iter = std::find_if(enumerated_modules_->begin(),
620 enumerated_modules_->end(),
621 FindModule(module));
622 if (iter != enumerated_modules_->end()) {
623 iter->duplicate_count++;
624 iter->type = static_cast<ModuleType>(iter->type | module.type);
625 } else {
626 enumerated_modules_->push_back(module);
630 void ModuleEnumerator::PreparePathMappings() {
631 path_mapping_.clear();
633 scoped_ptr<base::Environment> environment(base::Environment::Create());
634 std::vector<base::string16> env_vars;
635 env_vars.push_back(L"LOCALAPPDATA");
636 env_vars.push_back(L"ProgramFiles");
637 env_vars.push_back(L"ProgramData");
638 env_vars.push_back(L"USERPROFILE");
639 env_vars.push_back(L"SystemRoot");
640 env_vars.push_back(L"TEMP");
641 env_vars.push_back(L"TMP");
642 env_vars.push_back(L"CommonProgramFiles");
643 for (std::vector<base::string16>::const_iterator variable = env_vars.begin();
644 variable != env_vars.end(); ++variable) {
645 std::string path;
646 if (environment->GetVar(base::UTF16ToASCII(*variable).c_str(), &path)) {
647 path_mapping_.push_back(
648 std::make_pair(base::i18n::ToLower(base::UTF8ToUTF16(path)) + L"\\",
649 L"%" + base::i18n::ToLower(*variable) + L"%"));
654 void ModuleEnumerator::CollapsePath(Module* entry) {
655 // Take the path and see if we can use any of the substitution values
656 // from the vector constructed above to replace c:\windows with, for
657 // example, %systemroot%. The most collapsed path (the one with the
658 // minimum length) wins.
659 size_t min_length = MAXINT;
660 base::string16 location = entry->location;
661 for (PathMapping::const_iterator mapping = path_mapping_.begin();
662 mapping != path_mapping_.end(); ++mapping) {
663 base::string16 prefix = mapping->first;
664 if (StartsWith(location, prefix, false)) {
665 base::string16 new_location = mapping->second +
666 location.substr(prefix.length() - 1);
667 size_t length = new_location.length() - mapping->second.length();
668 if (length < min_length) {
669 entry->location = new_location;
670 min_length = length;
676 void ModuleEnumerator::MatchAgainstBlacklist() {
677 for (size_t m = 0; m < enumerated_modules_->size(); ++m) {
678 // Match this module against the blacklist.
679 Module* module = &(*enumerated_modules_)[m];
680 module->status = GOOD; // We change this below potentially.
681 for (size_t i = 0; i < arraysize(kModuleBlacklist); ++i) {
682 #if !defined(NDEBUG)
683 // This saves time when constructing the blacklist.
684 std::string hashes(kModuleBlacklist[i].filename);
685 std::string hash1, hash2, hash3;
686 GenerateHash(kModuleBlacklist[i].filename, &hash1);
687 hashes += " - " + hash1;
688 GenerateHash(kModuleBlacklist[i].location, &hash2);
689 hashes += " - " + hash2;
690 GenerateHash(kModuleBlacklist[i].desc_or_signer, &hash3);
691 hashes += " - " + hash3;
692 #endif
694 ModuleStatus status = Match(*module, kModuleBlacklist[i]);
695 if (status != NOT_MATCHED) {
696 // We have a match against the blacklist. Mark it as such.
697 module->status = status;
698 module->recommended_action = kModuleBlacklist[i].help_tip;
699 break;
703 // Modules loaded from these locations are frequently malicious
704 // and notorious for changing frequently so they are not good candidates
705 // for blacklisting individually. Mark them as suspicious if we haven't
706 // classified them as bad yet.
707 if (module->status == NOT_MATCHED || module->status == GOOD) {
708 if (StartsWith(module->location, L"%temp%", false) ||
709 StartsWith(module->location, L"%tmp%", false)) {
710 module->status = SUSPECTED_BAD;
716 void ModuleEnumerator::ReportBack() {
717 if (!limited_mode_)
718 DCHECK(BrowserThread::CurrentlyOn(callback_thread_id_));
719 observer_->DoneScanning();
722 base::string16 ModuleEnumerator::GetSubjectNameFromDigitalSignature(
723 const base::FilePath& filename) {
724 HCERTSTORE store = NULL;
725 HCRYPTMSG message = NULL;
727 // Find the crypto message for this filename.
728 bool result = !!CryptQueryObject(CERT_QUERY_OBJECT_FILE,
729 filename.value().c_str(),
730 CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
731 CERT_QUERY_FORMAT_FLAG_BINARY,
733 NULL,
734 NULL,
735 NULL,
736 &store,
737 &message,
738 NULL);
739 if (!result)
740 return base::string16();
742 // Determine the size of the signer info data.
743 DWORD signer_info_size = 0;
744 result = !!CryptMsgGetParam(message,
745 CMSG_SIGNER_INFO_PARAM,
747 NULL,
748 &signer_info_size);
749 if (!result)
750 return base::string16();
752 // Allocate enough space to hold the signer info.
753 scoped_ptr<BYTE[]> signer_info_buffer(new BYTE[signer_info_size]);
754 CMSG_SIGNER_INFO* signer_info =
755 reinterpret_cast<CMSG_SIGNER_INFO*>(signer_info_buffer.get());
757 // Obtain the signer info.
758 result = !!CryptMsgGetParam(message,
759 CMSG_SIGNER_INFO_PARAM,
761 signer_info,
762 &signer_info_size);
763 if (!result)
764 return base::string16();
766 // Search for the signer certificate.
767 CERT_INFO CertInfo = {0};
768 PCCERT_CONTEXT cert_context = NULL;
769 CertInfo.Issuer = signer_info->Issuer;
770 CertInfo.SerialNumber = signer_info->SerialNumber;
772 cert_context = CertFindCertificateInStore(
773 store,
774 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
776 CERT_FIND_SUBJECT_CERT,
777 &CertInfo,
778 NULL);
779 if (!cert_context)
780 return base::string16();
782 // Determine the size of the Subject name.
783 DWORD subject_name_size = CertGetNameString(
784 cert_context, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, NULL, 0);
785 if (!subject_name_size)
786 return base::string16();
788 base::string16 subject_name;
789 subject_name.resize(subject_name_size);
791 // Get subject name.
792 if (!(CertGetNameString(cert_context,
793 CERT_NAME_SIMPLE_DISPLAY_TYPE,
795 NULL,
796 const_cast<LPWSTR>(subject_name.c_str()),
797 subject_name_size))) {
798 return base::string16();
801 return subject_name;
804 // ----------------------------------------------------------------------------
806 // static
807 EnumerateModulesModel* EnumerateModulesModel::GetInstance() {
808 return Singleton<EnumerateModulesModel>::get();
811 bool EnumerateModulesModel::ShouldShowConflictWarning() const {
812 // If the user has acknowledged the conflict notification, then we don't need
813 // to show it again (because the scanning only happens once per the lifetime
814 // of the process). If we were to run the scanning more than once, then we'd
815 // need to clear the flag somewhere when we are ready to show it again.
816 if (conflict_notification_acknowledged_)
817 return false;
819 return confirmed_bad_modules_detected_ > 0;
822 void EnumerateModulesModel::AcknowledgeConflictNotification() {
823 if (!conflict_notification_acknowledged_) {
824 conflict_notification_acknowledged_ = true;
825 content::NotificationService::current()->Notify(
826 chrome::NOTIFICATION_MODULE_INCOMPATIBILITY_BADGE_CHANGE,
827 content::Source<EnumerateModulesModel>(this),
828 content::NotificationService::NoDetails());
832 void EnumerateModulesModel::ScanNow() {
833 if (scanning_)
834 return; // A scan is already in progress.
836 lock->Acquire(); // Balanced in DoneScanning();
838 scanning_ = true;
840 // Instruct the ModuleEnumerator class to load this on the File thread.
841 // ScanNow does not block.
842 if (!module_enumerator_)
843 module_enumerator_ = new ModuleEnumerator(this);
844 module_enumerator_->ScanNow(&enumerated_modules_, limited_mode_);
847 base::ListValue* EnumerateModulesModel::GetModuleList() const {
848 if (scanning_)
849 return NULL;
851 lock->Acquire();
853 if (enumerated_modules_.empty()) {
854 lock->Release();
855 return NULL;
858 base::ListValue* list = new base::ListValue();
860 for (ModuleEnumerator::ModulesVector::const_iterator module =
861 enumerated_modules_.begin();
862 module != enumerated_modules_.end(); ++module) {
863 base::DictionaryValue* data = new base::DictionaryValue();
864 data->SetInteger("type", module->type);
865 base::string16 type_string;
866 if ((module->type & ModuleEnumerator::LOADED_MODULE) == 0) {
867 // Module is not loaded, denote type of module.
868 if (module->type & ModuleEnumerator::SHELL_EXTENSION)
869 type_string = base::ASCIIToWide("Shell Extension");
870 if (module->type & ModuleEnumerator::WINSOCK_MODULE_REGISTRATION) {
871 if (!type_string.empty())
872 type_string += base::ASCIIToWide(", ");
873 type_string += base::ASCIIToWide("Winsock");
875 // Must be one of the above type.
876 DCHECK(!type_string.empty());
877 if (!limited_mode_) {
878 type_string += base::ASCIIToWide(" -- ");
879 type_string += l10n_util::GetStringUTF16(IDS_CONFLICTS_NOT_LOADED_YET);
882 data->SetString("type_description", type_string);
883 data->SetInteger("status", module->status);
884 data->SetString("location", module->location);
885 data->SetString("name", module->name);
886 data->SetString("product_name", module->product_name);
887 data->SetString("description", module->description);
888 data->SetString("version", module->version);
889 data->SetString("digital_signer", module->digital_signer);
891 if (!limited_mode_) {
892 // Figure out the possible resolution help string.
893 base::string16 actions;
894 base::string16 separator = base::ASCIIToWide(" ") +
895 l10n_util::GetStringUTF16(
896 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_SEPARATOR) +
897 base::ASCIIToWide(" ");
899 if (module->recommended_action & ModuleEnumerator::NONE) {
900 actions = l10n_util::GetStringUTF16(
901 IDS_CONFLICTS_CHECK_INVESTIGATING);
903 if (module->recommended_action & ModuleEnumerator::UNINSTALL) {
904 if (!actions.empty())
905 actions += separator;
906 actions = l10n_util::GetStringUTF16(
907 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_UNINSTALL);
909 if (module->recommended_action & ModuleEnumerator::UPDATE) {
910 if (!actions.empty())
911 actions += separator;
912 actions += l10n_util::GetStringUTF16(
913 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_UPDATE);
915 if (module->recommended_action & ModuleEnumerator::DISABLE) {
916 if (!actions.empty())
917 actions += separator;
918 actions += l10n_util::GetStringUTF16(
919 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_DISABLE);
921 base::string16 possible_resolution =
922 actions.empty() ? base::ASCIIToWide("")
923 : l10n_util::GetStringUTF16(
924 IDS_CONFLICTS_CHECK_POSSIBLE_ACTIONS) +
925 base::ASCIIToWide(" ") +
926 actions;
927 data->SetString("possibleResolution", possible_resolution);
928 data->SetString("help_url",
929 ConstructHelpCenterUrl(*module).spec().c_str());
932 list->Append(data);
935 lock->Release();
936 return list;
939 GURL EnumerateModulesModel::GetFirstNotableConflict() {
940 lock->Acquire();
941 GURL url;
943 if (enumerated_modules_.empty()) {
944 lock->Release();
945 return GURL();
948 for (ModuleEnumerator::ModulesVector::const_iterator module =
949 enumerated_modules_.begin();
950 module != enumerated_modules_.end(); ++module) {
951 if (!(module->recommended_action & ModuleEnumerator::NOTIFY_USER))
952 continue;
954 url = ConstructHelpCenterUrl(*module);
955 DCHECK(url.is_valid());
956 break;
959 lock->Release();
960 return url;
964 EnumerateModulesModel::EnumerateModulesModel()
965 : limited_mode_(false),
966 scanning_(false),
967 conflict_notification_acknowledged_(false),
968 confirmed_bad_modules_detected_(0),
969 suspected_bad_modules_detected_(0),
970 modules_to_notify_about_(0) {
971 lock = new base::Lock();
974 EnumerateModulesModel::~EnumerateModulesModel() {
975 delete lock;
978 void EnumerateModulesModel::MaybePostScanningTask() {
979 static bool done = false;
980 if (!done) {
981 done = true;
983 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
984 if (base::win::GetVersion() == base::win::VERSION_XP) {
985 check_modules_timer_.Start(FROM_HERE,
986 base::TimeDelta::FromMilliseconds(kModuleCheckDelayMs),
987 this, &EnumerateModulesModel::ScanNow);
992 void EnumerateModulesModel::DoneScanning() {
993 confirmed_bad_modules_detected_ = 0;
994 suspected_bad_modules_detected_ = 0;
995 modules_to_notify_about_ = 0;
996 for (ModuleEnumerator::ModulesVector::const_iterator module =
997 enumerated_modules_.begin();
998 module != enumerated_modules_.end(); ++module) {
999 if (module->status == ModuleEnumerator::CONFIRMED_BAD) {
1000 ++confirmed_bad_modules_detected_;
1001 if (module->recommended_action & ModuleEnumerator::NOTIFY_USER)
1002 ++modules_to_notify_about_;
1003 } else if (module->status == ModuleEnumerator::SUSPECTED_BAD) {
1004 ++suspected_bad_modules_detected_;
1005 if (module->recommended_action & ModuleEnumerator::NOTIFY_USER)
1006 ++modules_to_notify_about_;
1010 scanning_ = false;
1011 lock->Release();
1013 UMA_HISTOGRAM_COUNTS_100("Conflicts.SuspectedBadModules",
1014 suspected_bad_modules_detected_);
1015 UMA_HISTOGRAM_COUNTS_100("Conflicts.ConfirmedBadModules",
1016 confirmed_bad_modules_detected_);
1018 // Notifications are not available in limited mode.
1019 if (limited_mode_)
1020 return;
1022 content::NotificationService::current()->Notify(
1023 chrome::NOTIFICATION_MODULE_LIST_ENUMERATED,
1024 content::Source<EnumerateModulesModel>(this),
1025 content::NotificationService::NoDetails());
1028 GURL EnumerateModulesModel::ConstructHelpCenterUrl(
1029 const ModuleEnumerator::Module& module) const {
1030 if (!(module.recommended_action & ModuleEnumerator::SEE_LINK) &&
1031 !(module.recommended_action & ModuleEnumerator::NOTIFY_USER))
1032 return GURL();
1034 // Construct the needed hashes.
1035 std::string filename, location, description, signer;
1036 GenerateHash(base::WideToUTF8(module.name), &filename);
1037 GenerateHash(base::WideToUTF8(module.location), &location);
1038 GenerateHash(base::WideToUTF8(module.description), &description);
1039 GenerateHash(base::WideToUTF8(module.digital_signer), &signer);
1041 base::string16 url =
1042 l10n_util::GetStringFUTF16(IDS_HELP_CENTER_VIEW_CONFLICTS,
1043 base::ASCIIToUTF16(filename), base::ASCIIToUTF16(location),
1044 base::ASCIIToUTF16(description), base::ASCIIToUTF16(signer));
1045 return GURL(base::UTF16ToUTF8(url));