Revert 168224 - Update V8 to version 3.15.4.
[chromium-blink-merge.git] / chrome / browser / enumerate_modules_model_win.cc
blob699c003eb500dd420c29348e547b170a5cbc03d7
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 <algorithm>
8 #include <Tlhelp32.h>
9 #include <wintrust.h>
11 #include "base/bind.h"
12 #include "base/command_line.h"
13 #include "base/environment.h"
14 #include "base/file_path.h"
15 #include "base/file_version_info_win.h"
16 #include "base/i18n/case_conversion.h"
17 #include "base/metrics/histogram.h"
18 #include "base/string_number_conversions.h"
19 #include "base/string_util.h"
20 #include "base/time.h"
21 #include "base/utf_string_conversions.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 "crypto/sha2.h"
27 #include "chrome/browser/net/service_providers_win.h"
28 #include "chrome/common/chrome_constants.h"
29 #include "chrome/common/chrome_notification_types.h"
30 #include "chrome/common/chrome_switches.h"
31 #include "content/public/browser/notification_service.h"
32 #include "grit/generated_resources.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 = 60 * 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 string16& short_path, string16* long_path) {
92 wchar_t long_path_buf[MAX_PATH];
93 DWORD return_value = GetLongPathName(short_path.c_str(), long_path_buf,
94 MAX_PATH);
95 if (return_value != 0 && return_value < MAX_PATH) {
96 *long_path = long_path_buf;
97 return true;
100 return false;
103 } // namespace
105 // The browser process module blacklist. This lists modules that are known
106 // to cause compatibility issues within the browser process. When adding to this
107 // list, make sure that all paths are lower-case, in long pathname form, end
108 // with a slash and use environments variables (or just look at one of the
109 // comments below and keep it consistent with that). When adding an entry with
110 // an environment variable not currently used in the list below, make sure to
111 // update the list in PreparePathMappings. Filename, Description/Signer, and
112 // Location must be entered as hashes (see GenerateHash). Filename is mandatory.
113 // Entries without any Description, Signer info, or Location will never be
114 // marked as confirmed bad (only as suspicious).
115 const ModuleEnumerator::BlacklistEntry ModuleEnumerator::kModuleBlacklist[] = {
116 // NOTE: Please keep this list sorted by dll name, then location.
118 // Version 3.2.1.6 seems to be implicated in most cases (and 3.2.2.2 in some).
119 // There is a more recent version available for download.
120 // accelerator.dll, "%programfiles%\\speedbit video accelerator\\".
121 { "7ba9402f", "c9132d48", "", "", "", kInvestigatingLink },
123 // apiqq0.dll, "%temp%\\".
124 { "26134911", "59145acf", "", "", "", kUninstallLink },
126 // arking0.dll, "%systemroot%\\system32\\".
127 { "f5d8f549", "23d01d5b", "", "", "", kUninstallLink },
129 // arking1.dll, "%systemroot%\\system32\\".
130 { "c60ca062", "23d01d5b", "", "", "", kUninstallLink },
132 // Said to belong to Killer NIC from BigFoot Networks (not verified). Versions
133 // 6.0.0.7 and 6.0.0.10 implicated.
134 // bfllr.dll, "%systemroot%\\system32\\".
135 { "6bb57633", "23d01d5b", "", "", "", kInvestigatingLink },
137 // clickpotatolitesahook.dll, "". Different version each report.
138 { "0396e037.dll", "", "", "", "", kUninstallLink },
140 // cvasds0.dll, "%temp%\\".
141 { "5ce0037c", "59145acf", "", "", "", kUninstallLink },
143 // cwalsp.dll, "%systemroot%\\system32\\".
144 { "e579a039", "23d01d5b", "", "", "", kUninstallLink },
146 // datamngr.dll (1), "%programfiles%\\searchqu toolbar\\datamngr\\".
147 { "7add320b", "470a3da3", "", "", "", kUninstallLink },
149 // datamngr.dll (2), "%programfiles%\\windows searchqu toolbar\\".
150 { "7add320b", "7a3c8be3", "", "", "", kUninstallLink },
152 // dsoqq0.dll, "%temp%\\".
153 { "1c4df325", "59145acf", "", "", "", kUninstallLink },
155 // flt.dll, "%programfiles%\\tueagles\\".
156 { "6d01f4a1", "7935e9c2", "", "", "", kUninstallLink },
158 // This looks like a malware edition of a Brazilian Bank plugin, sometimes
159 // referred to as Malware.Banc.A.
160 // gbieh.dll, "%programfiles%\\gbplugin\\".
161 { "4cb4f2e3", "88e4a3b1", "", "", "", kUninstallLink },
163 // hblitesahook.dll. Each report has different version number in location.
164 { "5d10b363", "", "", "", "", kUninstallLink },
166 // icf.dll, "%systemroot%\\system32\\".
167 { "303825ed", "23d01d5b", "", "", "", INVESTIGATING },
169 // idmmbc.dll (IDM), "%systemroot%\\system32\\". See: http://crbug.com/26892/.
170 { "b8dce5c3", "23d01d5b", "", "", "6.03",
171 static_cast<RecommendedAction>(UPDATE | DISABLE) },
173 // imon.dll (NOD32), "%systemroot%\\system32\\". See: http://crbug.com/21715.
174 { "8f42f22e", "23d01d5b", "", "", "4.0",
175 static_cast<RecommendedAction>(UPDATE | DISABLE) },
177 // is3lsp.dll, "%commonprogramfiles%\\is3\\anti-spyware\\".
178 { "7ffbdce9", "bc5673f2", "", "", "",
179 static_cast<RecommendedAction>(UPDATE | DISABLE | SEE_LINK) },
181 // jsi.dll, "%programfiles%\\profilecraze\\".
182 { "f9555eea", "e3548061", "", "", "", kUninstallLink },
184 // kernel.dll, "%programfiles%\\contentwatch\\internet protection\\modules\\".
185 { "ead2768e", "4e61ce60", "", "", "", INVESTIGATING },
187 // mgking0.dll, "%systemroot%\\system32\\".
188 { "d0893e38", "23d01d5b", "", "", "", kUninstallLink },
190 // mgking0.dll, "%temp%\\".
191 { "d0893e38", "59145acf", "", "", "", kUninstallLink },
193 // mgking1.dll, "%systemroot%\\system32\\".
194 { "3e837222", "23d01d5b", "", "", "", kUninstallLink },
196 // mgking1.dll, "%temp%\\".
197 { "3e837222", "59145acf", "", "", "", kUninstallLink },
199 // mstcipha.ime, "%systemroot%\\system32\\".
200 { "5523579e", "23d01d5b", "", "", "", INVESTIGATING },
202 // mwtsp.dll, "%systemroot%\\system32\\".
203 { "9830bff6", "23d01d5b", "", "", "", kUninstallLink },
205 // nodqq0.dll, "%temp%\\".
206 { "b86ce04d", "59145acf", "", "", "", kUninstallLink },
208 // nProtect GameGuard Anti-cheat system. Every report has a different
209 // location, since it is installed into and run from a game folder. Various
210 // versions implicated.
211 // npggnt.des, no fixed location.
212 { "f2c8790d", "", "", "", "", kInvestigatingLink },
214 // nvlsp.dll,
215 // "%programfiles%\\nvidia corporation\\networkaccessmanager\\bin32\\".
216 { "37f907e2", "3ad0ff23", "", "", "", INVESTIGATING },
218 // post0.dll, "%systemroot%\\system32\\".
219 { "7405c0c8", "23d01d5b", "", "", "", kUninstallLink },
221 // questbrwsearch.dll, "%programfiles%\\questbrwsearch\\".
222 { "0953ed09", "f0d5eeda", "", "", "", kUninstallLink },
224 // questscan.dll, "%programfiles%\\questscan\\".
225 { "f4f3391e", "119d20f7", "", "", "", kUninstallLink },
227 // radhslib.dll (Naomi web filter), "%programfiles%\\rnamfler\\".
228 // See http://crbug.com/12517.
229 { "7edcd250", "0733dc3e", "", "", "", INVESTIGATING },
231 // rlls.dll, "%programfiles%\\relevantknowledge\\".
232 { "a1ed94a7", "ea9d6b36", "", "", "", kUninstallLink },
234 // rooksdol.dll, "%programfiles%\\trusteer\\rapport\\bin\\".
235 { "802aefef", "06120e13", "", "", "3.5.1008.40", UPDATE },
237 // scanquery.dll, "%programfiles%\\scanquery\\".
238 { "0b52d2ae", "a4cc88b1", "", "", "", kUninstallLink },
240 // sdata.dll, "%programdata%\\srtserv\\".
241 { "1936d5cc", "223c44be", "", "", "", kUninstallLink },
243 // searchtree.dll,
244 // "%programfiles%\\contentwatch\\internet protection\\modules\\".
245 { "f6915a31", "4e61ce60", "", "", "", INVESTIGATING },
247 // sgprxy.dll, "%commonprogramfiles%\\is3\\anti-spyware\\".
248 { "005965ea", "bc5673f2", "", "", "", INVESTIGATING },
250 // swi_filter_0001.dll (Sophos Web Intelligence),
251 // "%programfiles%\\sophos\\sophos anti-virus\\web intelligence\\".
252 // A small random sample all showed version 1.0.5.0.
253 { "61112d7b", "25fb120f", "", "", "", kInvestigatingLink },
255 // twking0.dll, "%systemroot%\\system32\\".
256 { "0355549b", "23d01d5b", "", "", "", kUninstallLink },
258 // twking1.dll, "%systemroot%\\system32\\".
259 { "02e44508", "23d01d5b", "", "", "", kUninstallLink },
261 // vksaver.dll, "%systemroot%\\system32\\".
262 { "c4a784d5", "23d01d5b", "", "", "", kUninstallLink },
264 // vlsp.dll (Venturi Firewall?), "%systemroot%\\system32\\".
265 { "2e4eb93d", "23d01d5b", "", "", "", INVESTIGATING },
267 // vmn3_1dn.dll, "%appdata%\\roaming\\vmndtxtb\\".
268 { "bba2037d", "9ab68585", "", "", "", kUninstallLink },
270 // webanalyzer.dll,
271 // "%programfiles%\\contentwatch\\internet protection\\modules\\".
272 { "c70b697d", "4e61ce60", "", "", "", INVESTIGATING },
274 // wowst0.dll, "%systemroot%\\system32\\".
275 { "38ad9963", "23d01d5b", "", "", "", kUninstallLink },
277 // wxbase28u_vc_cw.dll, "%systemroot%\\system32\\".
278 { "e967210d", "23d01d5b", "", "", "", kUninstallLink },
281 // Generates an 8 digit hash from the input given.
282 static void GenerateHash(const std::string& input, std::string* output) {
283 if (input.empty()) {
284 *output = "";
285 return;
288 uint8 hash[4];
289 crypto::SHA256HashString(input, hash, sizeof(hash));
290 *output = StringToLowerASCII(base::HexEncode(hash, sizeof(hash)));
293 // -----------------------------------------------------------------------------
295 // static
296 void ModuleEnumerator::NormalizeModule(Module* module) {
297 string16 path = module->location;
298 if (!ConvertToLongPath(path, &module->location))
299 module->location = path;
301 module->location = base::i18n::ToLower(module->location);
303 // Location contains the filename, so the last slash is where the path
304 // ends.
305 size_t last_slash = module->location.find_last_of(L"\\");
306 if (last_slash != string16::npos) {
307 module->name = module->location.substr(last_slash + 1);
308 module->location = module->location.substr(0, last_slash + 1);
309 } else {
310 module->name = module->location;
311 module->location.clear();
314 // Some version strings have things like (win7_rtm.090713-1255) appended
315 // to them. Remove that.
316 size_t first_space = module->version.find_first_of(L" ");
317 if (first_space != string16::npos)
318 module->version = module->version.substr(0, first_space);
320 module->normalized = true;
323 // static
324 ModuleEnumerator::ModuleStatus ModuleEnumerator::Match(
325 const ModuleEnumerator::Module& module,
326 const ModuleEnumerator::BlacklistEntry& blacklisted) {
327 // All modules must be normalized before matching against blacklist.
328 DCHECK(module.normalized);
329 // Filename is mandatory and version should not contain spaces.
330 DCHECK(strlen(blacklisted.filename) > 0);
331 DCHECK(!strstr(blacklisted.version_from, " "));
332 DCHECK(!strstr(blacklisted.version_to, " "));
334 std::string filename_hash, location_hash;
335 GenerateHash(WideToUTF8(module.name), &filename_hash);
336 GenerateHash(WideToUTF8(module.location), &location_hash);
338 // Filenames are mandatory. Location is mandatory if given.
339 if (filename_hash == blacklisted.filename &&
340 (std::string(blacklisted.location).empty() ||
341 location_hash == blacklisted.location)) {
342 // We have a name match against the blacklist (and possibly location match
343 // also), so check version.
344 Version module_version(UTF16ToASCII(module.version));
345 Version version_min(blacklisted.version_from);
346 Version version_max(blacklisted.version_to);
347 bool version_ok = !version_min.IsValid() && !version_max.IsValid();
348 if (!version_ok) {
349 bool too_low = version_min.IsValid() &&
350 (!module_version.IsValid() ||
351 module_version.CompareTo(version_min) < 0);
352 bool too_high = version_max.IsValid() &&
353 (!module_version.IsValid() ||
354 module_version.CompareTo(version_max) >= 0);
355 version_ok = !too_low && !too_high;
358 if (version_ok) {
359 // At this point, the names match and there is no version specified
360 // or the versions also match.
362 std::string desc_or_signer(blacklisted.desc_or_signer);
363 std::string signer_hash, description_hash;
364 GenerateHash(WideToUTF8(module.digital_signer), &signer_hash);
365 GenerateHash(WideToUTF8(module.description), &description_hash);
367 // If signatures match (or both are empty), then we have a winner.
368 if (signer_hash == desc_or_signer)
369 return CONFIRMED_BAD;
371 // If descriptions match (or both are empty) and the locations match, then
372 // we also have a confirmed match.
373 if (description_hash == desc_or_signer &&
374 !location_hash.empty() && location_hash == blacklisted.location) {
375 return CONFIRMED_BAD;
378 // We are not sure, but it is likely bad.
379 return SUSPECTED_BAD;
383 return NOT_MATCHED;
386 ModuleEnumerator::ModuleEnumerator(EnumerateModulesModel* observer)
387 : enumerated_modules_(NULL),
388 observer_(observer),
389 limited_mode_(false),
390 callback_thread_id_(BrowserThread::ID_COUNT) {
393 ModuleEnumerator::~ModuleEnumerator() {
396 void ModuleEnumerator::ScanNow(ModulesVector* list, bool limited_mode) {
397 enumerated_modules_ = list;
399 limited_mode_ = limited_mode;
401 if (!limited_mode_) {
402 CHECK(BrowserThread::GetCurrentThreadIdentifier(&callback_thread_id_));
403 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::FILE));
404 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
405 base::Bind(&ModuleEnumerator::ScanImpl, this));
406 } else {
407 // Run it synchronously.
408 ScanImpl();
412 void ModuleEnumerator::ScanImpl() {
413 base::TimeTicks start_time = base::TimeTicks::Now();
415 enumerated_modules_->clear();
417 // Make sure the path mapping vector is setup so we can collapse paths.
418 PreparePathMappings();
420 // Enumerating loaded modules must happen first since the other types of
421 // modules check for duplication against the loaded modules.
422 base::TimeTicks checkpoint = base::TimeTicks::Now();
423 EnumerateLoadedModules();
424 base::TimeTicks checkpoint2 = base::TimeTicks::Now();
425 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateLoadedModules",
426 checkpoint2 - checkpoint);
428 checkpoint = checkpoint2;
429 EnumerateShellExtensions();
430 checkpoint2 = base::TimeTicks::Now();
431 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateShellExtensions",
432 checkpoint2 - checkpoint);
434 checkpoint = checkpoint2;
435 EnumerateWinsockModules();
436 checkpoint2 = base::TimeTicks::Now();
437 UMA_HISTOGRAM_TIMES("Conflicts.EnumerateWinsockModules",
438 checkpoint2 - checkpoint);
440 MatchAgainstBlacklist();
442 std::sort(enumerated_modules_->begin(),
443 enumerated_modules_->end(), ModuleSort);
445 if (!limited_mode_) {
446 // Send a reply back on the UI thread.
447 BrowserThread::PostTask(callback_thread_id_, FROM_HERE,
448 base::Bind(&ModuleEnumerator::ReportBack, this));
449 } else {
450 // We are on the main thread already.
451 ReportBack();
454 UMA_HISTOGRAM_TIMES("Conflicts.EnumerationTotalTime",
455 base::TimeTicks::Now() - start_time);
458 void ModuleEnumerator::EnumerateLoadedModules() {
459 // Get all modules in the current process.
460 base::win::ScopedHandle snap(::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,
461 ::GetCurrentProcessId()));
462 if (!snap.Get())
463 return;
465 // Walk the module list.
466 MODULEENTRY32 module = { sizeof(module) };
467 if (!::Module32First(snap.Get(), &module))
468 return;
470 do {
471 // It would be weird to present chrome.exe as a loaded module.
472 if (_wcsicmp(chrome::kBrowserProcessExecutableName, module.szModule) == 0)
473 continue;
475 Module entry;
476 entry.type = LOADED_MODULE;
477 entry.location = module.szExePath;
478 PopulateModuleInformation(&entry);
480 NormalizeModule(&entry);
481 CollapsePath(&entry);
482 enumerated_modules_->push_back(entry);
483 } while (::Module32Next(snap.Get(), &module));
486 void ModuleEnumerator::EnumerateShellExtensions() {
487 ReadShellExtensions(HKEY_LOCAL_MACHINE);
488 ReadShellExtensions(HKEY_CURRENT_USER);
491 void ModuleEnumerator::ReadShellExtensions(HKEY parent) {
492 base::win::RegistryValueIterator registration(parent, kRegPath);
493 while (registration.Valid()) {
494 std::wstring key(std::wstring(L"CLSID\\") + registration.Name() +
495 L"\\InProcServer32");
496 base::win::RegKey clsid;
497 if (clsid.Open(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ) != ERROR_SUCCESS) {
498 ++registration;
499 continue;
501 string16 dll;
502 if (clsid.ReadValue(L"", &dll) != ERROR_SUCCESS) {
503 ++registration;
504 continue;
506 clsid.Close();
508 Module entry;
509 entry.type = SHELL_EXTENSION;
510 entry.location = dll;
511 PopulateModuleInformation(&entry);
513 NormalizeModule(&entry);
514 CollapsePath(&entry);
515 AddToListWithoutDuplicating(entry);
517 ++registration;
521 void ModuleEnumerator::EnumerateWinsockModules() {
522 // Add to this list the Winsock LSP DLLs.
523 WinsockLayeredServiceProviderList layered_providers;
524 GetWinsockLayeredServiceProviders(&layered_providers);
525 for (size_t i = 0; i < layered_providers.size(); ++i) {
526 Module entry;
527 entry.type = WINSOCK_MODULE_REGISTRATION;
528 entry.status = NOT_MATCHED;
529 entry.normalized = false;
530 entry.location = layered_providers[i].path;
531 entry.description = layered_providers[i].name;
532 entry.recommended_action = NONE;
533 entry.duplicate_count = 0;
535 wchar_t expanded[MAX_PATH];
536 DWORD size = ExpandEnvironmentStrings(
537 entry.location.c_str(), expanded, MAX_PATH);
538 if (size != 0 && size <= MAX_PATH) {
539 entry.digital_signer =
540 GetSubjectNameFromDigitalSignature(FilePath(expanded));
542 entry.version = base::IntToString16(layered_providers[i].version);
544 // Paths have already been collapsed.
545 NormalizeModule(&entry);
546 AddToListWithoutDuplicating(entry);
550 void ModuleEnumerator::PopulateModuleInformation(Module* module) {
551 module->status = NOT_MATCHED;
552 module->duplicate_count = 0;
553 module->normalized = false;
554 module->digital_signer =
555 GetSubjectNameFromDigitalSignature(FilePath(module->location));
556 module->recommended_action = NONE;
557 scoped_ptr<FileVersionInfo> version_info(
558 FileVersionInfo::CreateFileVersionInfo(FilePath(module->location)));
559 if (version_info.get()) {
560 FileVersionInfoWin* version_info_win =
561 static_cast<FileVersionInfoWin*>(version_info.get());
563 VS_FIXEDFILEINFO* fixed_file_info = version_info_win->fixed_file_info();
564 if (fixed_file_info) {
565 module->description = version_info_win->file_description();
566 module->version = version_info_win->file_version();
567 module->product_name = version_info_win->product_name();
572 void ModuleEnumerator::AddToListWithoutDuplicating(const Module& module) {
573 DCHECK(module.normalized);
574 // These are registered modules, not loaded modules so the same module
575 // can be registered multiple times, often dozens of times. There is no need
576 // to list each registration, so we just increment the count for each module
577 // that is counted multiple times.
578 ModulesVector::iterator iter;
579 iter = std::find_if(enumerated_modules_->begin(),
580 enumerated_modules_->end(),
581 FindModule(module));
582 if (iter != enumerated_modules_->end()) {
583 iter->duplicate_count++;
584 iter->type = static_cast<ModuleType>(iter->type | module.type);
585 } else {
586 enumerated_modules_->push_back(module);
590 void ModuleEnumerator::PreparePathMappings() {
591 path_mapping_.clear();
593 scoped_ptr<base::Environment> environment(base::Environment::Create());
594 std::vector<string16> env_vars;
595 env_vars.push_back(L"LOCALAPPDATA");
596 env_vars.push_back(L"ProgramFiles");
597 env_vars.push_back(L"ProgramData");
598 env_vars.push_back(L"USERPROFILE");
599 env_vars.push_back(L"SystemRoot");
600 env_vars.push_back(L"TEMP");
601 env_vars.push_back(L"TMP");
602 env_vars.push_back(L"CommonProgramFiles");
603 for (std::vector<string16>::const_iterator variable = env_vars.begin();
604 variable != env_vars.end(); ++variable) {
605 std::string path;
606 if (environment->GetVar(WideToASCII(*variable).c_str(), &path)) {
607 path_mapping_.push_back(
608 std::make_pair(base::i18n::ToLower(UTF8ToUTF16(path)) + L"\\",
609 L"%" + base::i18n::ToLower(*variable) + L"%"));
614 void ModuleEnumerator::CollapsePath(Module* entry) {
615 // Take the path and see if we can use any of the substitution values
616 // from the vector constructed above to replace c:\windows with, for
617 // example, %systemroot%. The most collapsed path (the one with the
618 // minimum length) wins.
619 size_t min_length = MAXINT;
620 string16 location = entry->location;
621 for (PathMapping::const_iterator mapping = path_mapping_.begin();
622 mapping != path_mapping_.end(); ++mapping) {
623 string16 prefix = mapping->first;
624 if (StartsWith(location, prefix, false)) {
625 string16 new_location = mapping->second +
626 location.substr(prefix.length() - 1);
627 size_t length = new_location.length() - mapping->second.length();
628 if (length < min_length) {
629 entry->location = new_location;
630 min_length = length;
636 void ModuleEnumerator::MatchAgainstBlacklist() {
637 for (size_t m = 0; m < enumerated_modules_->size(); ++m) {
638 // Match this module against the blacklist.
639 Module* module = &(*enumerated_modules_)[m];
640 module->status = GOOD; // We change this below potentially.
641 for (size_t i = 0; i < arraysize(kModuleBlacklist); ++i) {
642 #if !defined(NDEBUG)
643 // This saves time when constructing the blacklist.
644 std::string hashes(kModuleBlacklist[i].filename);
645 std::string hash1, hash2, hash3;
646 GenerateHash(kModuleBlacklist[i].filename, &hash1);
647 hashes += " - " + hash1;
648 GenerateHash(kModuleBlacklist[i].location, &hash2);
649 hashes += " - " + hash2;
650 GenerateHash(kModuleBlacklist[i].desc_or_signer, &hash3);
651 hashes += " - " + hash3;
652 #endif
654 ModuleStatus status = Match(*module, kModuleBlacklist[i]);
655 if (status != NOT_MATCHED) {
656 // We have a match against the blacklist. Mark it as such.
657 module->status = status;
658 module->recommended_action = kModuleBlacklist[i].help_tip;
659 break;
663 // Modules loaded from these locations are frequently malicious
664 // and notorious for changing frequently so they are not good candidates
665 // for blacklisting individually. Mark them as suspicious if we haven't
666 // classified them as bad yet.
667 if (module->status == NOT_MATCHED || module->status == GOOD) {
668 if (StartsWith(module->location, L"%temp%", false) ||
669 StartsWith(module->location, L"%tmp%", false)) {
670 module->status = SUSPECTED_BAD;
676 void ModuleEnumerator::ReportBack() {
677 if (!limited_mode_)
678 DCHECK(BrowserThread::CurrentlyOn(callback_thread_id_));
679 observer_->DoneScanning();
682 string16 ModuleEnumerator::GetSubjectNameFromDigitalSignature(
683 const FilePath& filename) {
684 HCERTSTORE store = NULL;
685 HCRYPTMSG message = NULL;
687 // Find the crypto message for this filename.
688 bool result = !!CryptQueryObject(CERT_QUERY_OBJECT_FILE,
689 filename.value().c_str(),
690 CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
691 CERT_QUERY_FORMAT_FLAG_BINARY,
693 NULL,
694 NULL,
695 NULL,
696 &store,
697 &message,
698 NULL);
699 if (!result)
700 return string16();
702 // Determine the size of the signer info data.
703 DWORD signer_info_size = 0;
704 result = !!CryptMsgGetParam(message,
705 CMSG_SIGNER_INFO_PARAM,
707 NULL,
708 &signer_info_size);
709 if (!result)
710 return string16();
712 // Allocate enough space to hold the signer info.
713 scoped_array<BYTE> signer_info_buffer(new BYTE[signer_info_size]);
714 CMSG_SIGNER_INFO* signer_info =
715 reinterpret_cast<CMSG_SIGNER_INFO*>(signer_info_buffer.get());
717 // Obtain the signer info.
718 result = !!CryptMsgGetParam(message,
719 CMSG_SIGNER_INFO_PARAM,
721 signer_info,
722 &signer_info_size);
723 if (!result)
724 return string16();
726 // Search for the signer certificate.
727 CERT_INFO CertInfo = {0};
728 PCCERT_CONTEXT cert_context = NULL;
729 CertInfo.Issuer = signer_info->Issuer;
730 CertInfo.SerialNumber = signer_info->SerialNumber;
732 cert_context = CertFindCertificateInStore(
733 store,
734 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
736 CERT_FIND_SUBJECT_CERT,
737 &CertInfo,
738 NULL);
739 if (!cert_context)
740 return string16();
742 // Determine the size of the Subject name.
743 DWORD subject_name_size = 0;
744 if (!(subject_name_size = CertGetNameString(cert_context,
745 CERT_NAME_SIMPLE_DISPLAY_TYPE,
747 NULL,
748 NULL,
749 0))) {
750 return string16();
753 string16 subject_name;
754 subject_name.resize(subject_name_size);
756 // Get subject name.
757 if (!(CertGetNameString(cert_context,
758 CERT_NAME_SIMPLE_DISPLAY_TYPE,
760 NULL,
761 const_cast<LPWSTR>(subject_name.c_str()),
762 subject_name_size))) {
763 return string16();
766 return subject_name;
769 // ----------------------------------------------------------------------------
771 // static
772 EnumerateModulesModel* EnumerateModulesModel::GetInstance() {
773 return Singleton<EnumerateModulesModel>::get();
776 bool EnumerateModulesModel::ShouldShowConflictWarning() const {
777 // If the user has acknowledged the conflict notification, then we don't need
778 // to show it again (because the scanning only happens once per the lifetime
779 // of the process). If we were to run the scanning more than once, then we'd
780 // need to clear the flag somewhere when we are ready to show it again.
781 if (conflict_notification_acknowledged_)
782 return false;
784 return confirmed_bad_modules_detected_ > 0;
787 void EnumerateModulesModel::AcknowledgeConflictNotification() {
788 if (!conflict_notification_acknowledged_) {
789 conflict_notification_acknowledged_ = true;
790 content::NotificationService::current()->Notify(
791 chrome::NOTIFICATION_MODULE_INCOMPATIBILITY_BADGE_CHANGE,
792 content::Source<EnumerateModulesModel>(this),
793 content::NotificationService::NoDetails());
797 void EnumerateModulesModel::ScanNow() {
798 if (scanning_)
799 return; // A scan is already in progress.
801 lock->Acquire(); // Balanced in DoneScanning();
803 scanning_ = true;
805 // Instruct the ModuleEnumerator class to load this on the File thread.
806 // ScanNow does not block.
807 if (!module_enumerator_)
808 module_enumerator_ = new ModuleEnumerator(this);
809 module_enumerator_->ScanNow(&enumerated_modules_, limited_mode_);
812 ListValue* EnumerateModulesModel::GetModuleList() const {
813 if (scanning_)
814 return NULL;
816 lock->Acquire();
818 if (enumerated_modules_.empty()) {
819 lock->Release();
820 return NULL;
823 ListValue* list = new ListValue();
825 for (ModuleEnumerator::ModulesVector::const_iterator module =
826 enumerated_modules_.begin();
827 module != enumerated_modules_.end(); ++module) {
828 DictionaryValue* data = new DictionaryValue();
829 data->SetInteger("type", module->type);
830 string16 type_string;
831 if ((module->type & ModuleEnumerator::LOADED_MODULE) == 0) {
832 // Module is not loaded, denote type of module.
833 if (module->type & ModuleEnumerator::SHELL_EXTENSION)
834 type_string = ASCIIToWide("Shell Extension");
835 if (module->type & ModuleEnumerator::WINSOCK_MODULE_REGISTRATION) {
836 if (!type_string.empty())
837 type_string += ASCIIToWide(", ");
838 type_string += ASCIIToWide("Winsock");
840 // Must be one of the above type.
841 DCHECK(!type_string.empty());
842 if (!limited_mode_) {
843 type_string += ASCIIToWide(" -- ");
844 type_string += l10n_util::GetStringUTF16(IDS_CONFLICTS_NOT_LOADED_YET);
847 data->SetString("type_description", type_string);
848 data->SetInteger("status", module->status);
849 data->SetString("location", module->location);
850 data->SetString("name", module->name);
851 data->SetString("product_name", module->product_name);
852 data->SetString("description", module->description);
853 data->SetString("version", module->version);
854 data->SetString("digital_signer", module->digital_signer);
856 if (!limited_mode_) {
857 // Figure out the possible resolution help string.
858 string16 actions;
859 string16 separator = ASCIIToWide(" ") + l10n_util::GetStringUTF16(
860 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_SEPERATOR) +
861 ASCIIToWide(" ");
863 if (module->recommended_action & ModuleEnumerator::NONE) {
864 actions = l10n_util::GetStringUTF16(
865 IDS_CONFLICTS_CHECK_INVESTIGATING);
867 if (module->recommended_action & ModuleEnumerator::UNINSTALL) {
868 if (!actions.empty())
869 actions += separator;
870 actions = l10n_util::GetStringUTF16(
871 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_UNINSTALL);
873 if (module->recommended_action & ModuleEnumerator::UPDATE) {
874 if (!actions.empty())
875 actions += separator;
876 actions += l10n_util::GetStringUTF16(
877 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_UPDATE);
879 if (module->recommended_action & ModuleEnumerator::DISABLE) {
880 if (!actions.empty())
881 actions += separator;
882 actions += l10n_util::GetStringUTF16(
883 IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_DISABLE);
885 string16 possible_resolution = actions.empty() ? ASCIIToWide("") :
886 l10n_util::GetStringUTF16(IDS_CONFLICTS_CHECK_POSSIBLE_ACTIONS) +
887 ASCIIToWide(" ") +
888 actions;
889 data->SetString("possibleResolution", possible_resolution);
890 data->SetString("help_url",
891 ConstructHelpCenterUrl(*module).spec().c_str());
894 list->Append(data);
897 lock->Release();
898 return list;
901 EnumerateModulesModel::EnumerateModulesModel()
902 : limited_mode_(false),
903 scanning_(false),
904 conflict_notification_acknowledged_(false),
905 confirmed_bad_modules_detected_(0),
906 suspected_bad_modules_detected_(0) {
907 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
908 if (cmd_line.HasSwitch(switches::kConflictingModulesCheck)) {
909 check_modules_timer_.Start(FROM_HERE,
910 base::TimeDelta::FromMilliseconds(kModuleCheckDelayMs),
911 this, &EnumerateModulesModel::ScanNow);
914 lock = new base::Lock();
917 EnumerateModulesModel::~EnumerateModulesModel() {
918 delete lock;
921 void EnumerateModulesModel::DoneScanning() {
922 confirmed_bad_modules_detected_ = 0;
923 suspected_bad_modules_detected_ = 0;
924 for (ModuleEnumerator::ModulesVector::const_iterator module =
925 enumerated_modules_.begin();
926 module != enumerated_modules_.end(); ++module) {
927 if (module->status == ModuleEnumerator::CONFIRMED_BAD)
928 ++confirmed_bad_modules_detected_;
929 if (module->status == ModuleEnumerator::SUSPECTED_BAD)
930 ++suspected_bad_modules_detected_;
933 scanning_ = false;
934 lock->Release();
936 UMA_HISTOGRAM_COUNTS_100("Conflicts.SuspectedBadModules",
937 suspected_bad_modules_detected_);
938 UMA_HISTOGRAM_COUNTS_100("Conflicts.ConfirmedBadModules",
939 confirmed_bad_modules_detected_);
941 // Notifications are not available in limited mode.
942 if (limited_mode_)
943 return;
945 content::NotificationService::current()->Notify(
946 chrome::NOTIFICATION_MODULE_LIST_ENUMERATED,
947 content::Source<EnumerateModulesModel>(this),
948 content::NotificationService::NoDetails());
950 // Command line flag must be enabled for the notification to get sent out.
951 // Otherwise we'd get the badge (while the feature is disabled) when we
952 // navigate to about:conflicts and find confirmed matches.
953 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
954 if (!cmd_line.HasSwitch(switches::kConflictingModulesCheck))
955 return;
957 content::NotificationService::current()->Notify(
958 chrome::NOTIFICATION_MODULE_INCOMPATIBILITY_BADGE_CHANGE,
959 content::Source<EnumerateModulesModel>(this),
960 content::NotificationService::NoDetails());
963 GURL EnumerateModulesModel::ConstructHelpCenterUrl(
964 const ModuleEnumerator::Module& module) const {
965 if (!(module.recommended_action & ModuleEnumerator::SEE_LINK))
966 return GURL();
968 // Construct the needed hashes.
969 std::string filename, location, description, signer;
970 GenerateHash(WideToUTF8(module.name), &filename);
971 GenerateHash(WideToUTF8(module.location), &location);
972 GenerateHash(WideToUTF8(module.description), &description);
973 GenerateHash(WideToUTF8(module.digital_signer), &signer);
975 string16 url = l10n_util::GetStringFUTF16(IDS_HELP_CENTER_VIEW_CONFLICTS,
976 ASCIIToUTF16(filename), ASCIIToUTF16(location),
977 ASCIIToUTF16(description), ASCIIToUTF16(signer));
978 return GURL(UTF16ToUTF8(url));