• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #include "chrome/browser/enumerate_modules_model_win.h"
6 
7 #include <Tlhelp32.h>
8 #include <wintrust.h>
9 #include <algorithm>
10 
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"
36 
37 using content::BrowserThread;
38 
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;
42 
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";
46 
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);
51 
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);
56 
57 // A sort method that sorts by bad modules first, then by full name (including
58 // path).
ModuleSort(const ModuleEnumerator::Module & a,const ModuleEnumerator::Module & b)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;
63 
64   if (a.location == b.location)
65     return a.name < b.name;
66 
67   return a.location < b.location;
68 }
69 
70 namespace {
71 
72 // Used to protect the LoadedModuleVector which is accessed
73 // from both the UI thread and the FILE thread.
74 base::Lock* lock = NULL;
75 
76 // A struct to help de-duping modules before adding them to the enumerated
77 // modules vector.
78 struct FindModule {
79  public:
FindModule__anon03716c440111::FindModule80   explicit FindModule(const ModuleEnumerator::Module& x)
81     : module(x) {}
operator ()__anon03716c440111::FindModule82   bool operator()(const ModuleEnumerator::Module& module_in) const {
83     return (module.location == module_in.location) &&
84            (module.name == module_in.name);
85   }
86 
87   const ModuleEnumerator::Module& module;
88 };
89 
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.
ConvertToLongPath(const base::string16 & short_path,base::string16 * long_path)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;
101   }
102 
103   return false;
104 }
105 
106 }  // namespace
107 
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.
120 
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 },
125 
126   // apiqq0.dll, "%temp%\\".
127   { "26134911", "59145acf", "", "", "", ALL, kUninstallLink },
128 
129   // arking0.dll, "%systemroot%\\system32\\".
130   { "f5d8f549", "23d01d5b", "", "", "", ALL, kUninstallLink },
131 
132   // arking1.dll, "%systemroot%\\system32\\".
133   { "c60ca062", "23d01d5b", "", "", "", ALL, kUninstallLink },
134 
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) },
141 
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) },
148 
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 },
153 
154   // clickpotatolitesahook.dll, "". Different version each report.
155   { "0396e037.dll", "", "", "", "", ALL, kUninstallLink },
156 
157   // cvasds0.dll, "%temp%\\".
158   { "5ce0037c", "59145acf", "", "", "", ALL, kUninstallLink },
159 
160   // cwalsp.dll, "%systemroot%\\system32\\".
161   { "e579a039", "23d01d5b", "", "", "", ALL, kUninstallLink },
162 
163   // datamngr.dll (1), "%programfiles%\\searchqu toolbar\\datamngr\\".
164   { "7add320b", "470a3da3", "", "", "", ALL, kUninstallLink },
165 
166   // datamngr.dll (2), "%programfiles%\\windows searchqu toolbar\\".
167   { "7add320b", "7a3c8be3", "", "", "", ALL, kUninstallLink },
168 
169   // dsoqq0.dll, "%temp%\\".
170   { "1c4df325", "59145acf", "", "", "", ALL, kUninstallLink },
171 
172   // flt.dll, "%programfiles%\\tueagles\\".
173   { "6d01f4a1", "7935e9c2", "", "", "", ALL, kUninstallLink },
174 
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 },
179 
180   // hblitesahook.dll. Each report has different version number in location.
181   { "5d10b363", "", "", "", "", ALL, kUninstallLink },
182 
183   // icf.dll, "%systemroot%\\system32\\".
184   { "303825ed", "23d01d5b", "", "", "", ALL, INVESTIGATING },
185 
186   // idmmbc.dll (IDM), "%systemroot%\\system32\\". See: http://crbug.com/26892/.
187   { "b8dce5c3", "23d01d5b", "", "", "6.03", ALL,
188       static_cast<RecommendedAction>(UPDATE | DISABLE) },
189 
190   // imon.dll (NOD32), "%systemroot%\\system32\\". See: http://crbug.com/21715.
191   { "8f42f22e", "23d01d5b", "", "", "4.0", ALL,
192       static_cast<RecommendedAction>(UPDATE | DISABLE) },
193 
194   // is3lsp.dll, "%commonprogramfiles%\\is3\\anti-spyware\\".
195   { "7ffbdce9", "bc5673f2", "", "", "", ALL,
196       static_cast<RecommendedAction>(UPDATE | DISABLE | SEE_LINK) },
197 
198   // jsi.dll, "%programfiles%\\profilecraze\\".
199   { "f9555eea", "e3548061", "", "", "", ALL, kUninstallLink },
200 
201   // kernel.dll, "%programfiles%\\contentwatch\\internet protection\\modules\\".
202   { "ead2768e", "4e61ce60", "", "", "", ALL, INVESTIGATING },
203 
204   // mgking0.dll, "%systemroot%\\system32\\".
205   { "d0893e38", "23d01d5b", "", "", "", ALL, kUninstallLink },
206 
207   // mgking0.dll, "%temp%\\".
208   { "d0893e38", "59145acf", "", "", "", ALL, kUninstallLink },
209 
210   // mgking1.dll, "%systemroot%\\system32\\".
211   { "3e837222", "23d01d5b", "", "", "", ALL, kUninstallLink },
212 
213   // mgking1.dll, "%temp%\\".
214   { "3e837222", "59145acf", "", "", "", ALL, kUninstallLink },
215 
216   // mstcipha.ime, "%systemroot%\\system32\\".
217   { "5523579e", "23d01d5b", "", "", "", ALL, INVESTIGATING },
218 
219   // mwtsp.dll, "%systemroot%\\system32\\".
220   { "9830bff6", "23d01d5b", "", "", "", ALL, kUninstallLink },
221 
222   // nodqq0.dll, "%temp%\\".
223   { "b86ce04d", "59145acf", "", "", "", ALL, kUninstallLink },
224 
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 },
230 
231   // nvlsp.dll,
232   // "%programfiles%\\nvidia corporation\\networkaccessmanager\\bin32\\".
233   { "37f907e2", "3ad0ff23", "", "", "", ALL, INVESTIGATING },
234 
235   // post0.dll, "%systemroot%\\system32\\".
236   { "7405c0c8", "23d01d5b", "", "", "", ALL, kUninstallLink },
237 
238   // questbrwsearch.dll, "%programfiles%\\questbrwsearch\\".
239   { "0953ed09", "f0d5eeda", "", "", "", ALL, kUninstallLink },
240 
241   // questscan.dll, "%programfiles%\\questscan\\".
242   { "f4f3391e", "119d20f7", "", "", "", ALL, kUninstallLink },
243 
244   // radhslib.dll (Naomi web filter), "%programfiles%\\rnamfler\\".
245   // See http://crbug.com/12517.
246   { "7edcd250", "0733dc3e", "", "", "", ALL, INVESTIGATING },
247 
248   // rlls.dll, "%programfiles%\\relevantknowledge\\".
249   { "a1ed94a7", "ea9d6b36", "", "", "", ALL, kUninstallLink },
250 
251   // rooksdol.dll, "%programfiles%\\trusteer\\rapport\\bin\\".
252   { "802aefef", "06120e13", "", "", "3.5.1008.40", ALL, UPDATE },
253 
254   // scanquery.dll, "%programfiles%\\scanquery\\".
255   { "0b52d2ae", "a4cc88b1", "", "", "", ALL, kUninstallLink },
256 
257   // sdata.dll, "%programdata%\\srtserv\\".
258   { "1936d5cc", "223c44be", "", "", "", ALL, kUninstallLink },
259 
260   // searchtree.dll,
261   // "%programfiles%\\contentwatch\\internet protection\\modules\\".
262   { "f6915a31", "4e61ce60", "", "", "", ALL, INVESTIGATING },
263 
264   // sgprxy.dll, "%commonprogramfiles%\\is3\\anti-spyware\\".
265   { "005965ea", "bc5673f2", "", "", "", ALL, INVESTIGATING },
266 
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) },
273 
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) },
280 
281   // sprotector.dll, "". Different location each report.
282   { "24555d74", "", "", "", "", ALL, kUninstallLink },
283 
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 },
288 
289   // twking0.dll, "%systemroot%\\system32\\".
290   { "0355549b", "23d01d5b", "", "", "", ALL, kUninstallLink },
291 
292   // twking1.dll, "%systemroot%\\system32\\".
293   { "02e44508", "23d01d5b", "", "", "", ALL, kUninstallLink },
294 
295   // vksaver.dll, "%systemroot%\\system32\\".
296   { "c4a784d5", "23d01d5b", "", "", "", ALL, kUninstallLink },
297 
298   // vlsp.dll (Venturi Firewall?), "%systemroot%\\system32\\".
299   { "2e4eb93d", "23d01d5b", "", "", "", ALL, INVESTIGATING },
300 
301   // vmn3_1dn.dll, "%appdata%\\roaming\\vmndtxtb\\".
302   { "bba2037d", "9ab68585", "", "", "", ALL, kUninstallLink },
303 
304   // webanalyzer.dll,
305   // "%programfiles%\\contentwatch\\internet protection\\modules\\".
306   { "c70b697d", "4e61ce60", "", "", "", ALL, INVESTIGATING },
307 
308   // wowst0.dll, "%systemroot%\\system32\\".
309   { "38ad9963", "23d01d5b", "", "", "", ALL, kUninstallLink },
310 
311   // wxbase28u_vc_cw.dll, "%systemroot%\\system32\\".
312   { "e967210d", "23d01d5b", "", "", "", ALL, kUninstallLink },
313 };
314 
315 // Generates an 8 digit hash from the input given.
GenerateHash(const std::string & input,std::string * output)316 static void GenerateHash(const std::string& input, std::string* output) {
317   if (input.empty()) {
318     *output = "";
319     return;
320   }
321 
322   uint8 hash[4];
323   crypto::SHA256HashString(input, hash, sizeof(hash));
324   *output = StringToLowerASCII(base::HexEncode(hash, sizeof(hash)));
325 }
326 
327 // -----------------------------------------------------------------------------
328 
329 // static
NormalizeModule(Module * module)330 void ModuleEnumerator::NormalizeModule(Module* module) {
331   base::string16 path = module->location;
332   if (!ConvertToLongPath(path, &module->location))
333     module->location = path;
334 
335   module->location = base::i18n::ToLower(module->location);
336 
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();
346   }
347 
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);
353 
354   module->normalized = true;
355 }
356 
357 // static
Match(const ModuleEnumerator::Module & module,const ModuleEnumerator::BlacklistEntry & blacklisted)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, " "));
367 
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;
375   }
376 
377   std::string filename_hash, location_hash;
378   GenerateHash(WideToUTF8(module.name), &filename_hash);
379   GenerateHash(WideToUTF8(module.location), &location_hash);
380 
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;
399     }
400 
401     if (version_ok) {
402       // At this point, the names match and there is no version specified
403       // or the versions also match.
404 
405       std::string desc_or_signer(blacklisted.desc_or_signer);
406       std::string signer_hash, description_hash;
407       GenerateHash(WideToUTF8(module.digital_signer), &signer_hash);
408       GenerateHash(WideToUTF8(module.description), &description_hash);
409 
410       // If signatures match (or both are empty), then we have a winner.
411       if (signer_hash == desc_or_signer)
412         return CONFIRMED_BAD;
413 
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;
419 
420       // We are not sure, but it is likely bad.
421       return SUSPECTED_BAD;
422     }
423   }
424 
425   return NOT_MATCHED;
426 }
427 
ModuleEnumerator(EnumerateModulesModel * observer)428 ModuleEnumerator::ModuleEnumerator(EnumerateModulesModel* observer)
429     : enumerated_modules_(NULL),
430       observer_(observer),
431       limited_mode_(false),
432       callback_thread_id_(BrowserThread::ID_COUNT) {
433 }
434 
~ModuleEnumerator()435 ModuleEnumerator::~ModuleEnumerator() {
436 }
437 
ScanNow(ModulesVector * list,bool limited_mode)438 void ModuleEnumerator::ScanNow(ModulesVector* list, bool limited_mode) {
439   enumerated_modules_ = list;
440 
441   limited_mode_ = limited_mode;
442 
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();
450   }
451 }
452 
ScanImpl()453 void ModuleEnumerator::ScanImpl() {
454   base::TimeTicks start_time = base::TimeTicks::Now();
455 
456   enumerated_modules_->clear();
457 
458   // Make sure the path mapping vector is setup so we can collapse paths.
459   PreparePathMappings();
460 
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);
468 
469   checkpoint = checkpoint2;
470   EnumerateShellExtensions();
471   checkpoint2 = base::TimeTicks::Now();
472   UMA_HISTOGRAM_TIMES("Conflicts.EnumerateShellExtensions",
473                       checkpoint2 - checkpoint);
474 
475   checkpoint = checkpoint2;
476   EnumerateWinsockModules();
477   checkpoint2 = base::TimeTicks::Now();
478   UMA_HISTOGRAM_TIMES("Conflicts.EnumerateWinsockModules",
479                       checkpoint2 - checkpoint);
480 
481   MatchAgainstBlacklist();
482 
483   std::sort(enumerated_modules_->begin(),
484             enumerated_modules_->end(), ModuleSort);
485 
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();
493   }
494 
495   UMA_HISTOGRAM_TIMES("Conflicts.EnumerationTotalTime",
496                       base::TimeTicks::Now() - start_time);
497 }
498 
EnumerateLoadedModules()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;
505 
506   // Walk the module list.
507   MODULEENTRY32 module = { sizeof(module) };
508   if (!::Module32First(snap.Get(), &module))
509     return;
510 
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;
515 
516     Module entry;
517     entry.type = LOADED_MODULE;
518     entry.location = module.szExePath;
519     PopulateModuleInformation(&entry);
520 
521     NormalizeModule(&entry);
522     CollapsePath(&entry);
523     enumerated_modules_->push_back(entry);
524   } while (::Module32Next(snap.Get(), &module));
525 }
526 
EnumerateShellExtensions()527 void ModuleEnumerator::EnumerateShellExtensions() {
528   ReadShellExtensions(HKEY_LOCAL_MACHINE);
529   ReadShellExtensions(HKEY_CURRENT_USER);
530 }
531 
ReadShellExtensions(HKEY parent)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;
541     }
542     base::string16 dll;
543     if (clsid.ReadValue(L"", &dll) != ERROR_SUCCESS) {
544       ++registration;
545       continue;
546     }
547     clsid.Close();
548 
549     Module entry;
550     entry.type = SHELL_EXTENSION;
551     entry.location = dll;
552     PopulateModuleInformation(&entry);
553 
554     NormalizeModule(&entry);
555     CollapsePath(&entry);
556     AddToListWithoutDuplicating(entry);
557 
558     ++registration;
559   }
560 }
561 
EnumerateWinsockModules()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;
575 
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));
582     }
583     entry.version = base::IntToString16(layered_providers[i].version);
584 
585     // Paths have already been collapsed.
586     NormalizeModule(&entry);
587     AddToListWithoutDuplicating(entry);
588   }
589 }
590 
PopulateModuleInformation(Module * module)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());
603 
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();
609     }
610   }
611 }
612 
AddToListWithoutDuplicating(const Module & module)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);
628   }
629 }
630 
PreparePathMappings()631 void ModuleEnumerator::PreparePathMappings() {
632   path_mapping_.clear();
633 
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(UTF8ToUTF16(path)) + L"\\",
650                          L"%" + base::i18n::ToLower(*variable) + L"%"));
651     }
652   }
653 }
654 
CollapsePath(Module * entry)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;
672       }
673     }
674   }
675 }
676 
MatchAgainstBlacklist()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
694 
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;
701       }
702     }
703 
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;
712       }
713     }
714   }
715 }
716 
ReportBack()717 void ModuleEnumerator::ReportBack() {
718   if (!limited_mode_)
719     DCHECK(BrowserThread::CurrentlyOn(callback_thread_id_));
720   observer_->DoneScanning();
721 }
722 
GetSubjectNameFromDigitalSignature(const base::FilePath & filename)723 base::string16 ModuleEnumerator::GetSubjectNameFromDigitalSignature(
724     const base::FilePath& filename) {
725   HCERTSTORE store = NULL;
726   HCRYPTMSG message = NULL;
727 
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,
733                                    0,
734                                    NULL,
735                                    NULL,
736                                    NULL,
737                                    &store,
738                                    &message,
739                                    NULL);
740   if (!result)
741     return base::string16();
742 
743   // Determine the size of the signer info data.
744   DWORD signer_info_size = 0;
745   result = !!CryptMsgGetParam(message,
746                               CMSG_SIGNER_INFO_PARAM,
747                               0,
748                               NULL,
749                               &signer_info_size);
750   if (!result)
751     return base::string16();
752 
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());
757 
758   // Obtain the signer info.
759   result = !!CryptMsgGetParam(message,
760                               CMSG_SIGNER_INFO_PARAM,
761                               0,
762                               signer_info,
763                               &signer_info_size);
764   if (!result)
765     return base::string16();
766 
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;
772 
773   cert_context = CertFindCertificateInStore(
774       store,
775       X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
776       0,
777       CERT_FIND_SUBJECT_CERT,
778       &CertInfo,
779       NULL);
780   if (!cert_context)
781     return base::string16();
782 
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,
787                                               0,
788                                               NULL,
789                                               NULL,
790                                               0))) {
791     return base::string16();
792   }
793 
794   base::string16 subject_name;
795   subject_name.resize(subject_name_size);
796 
797   // Get subject name.
798   if (!(CertGetNameString(cert_context,
799                           CERT_NAME_SIMPLE_DISPLAY_TYPE,
800                           0,
801                           NULL,
802                           const_cast<LPWSTR>(subject_name.c_str()),
803                           subject_name_size))) {
804     return base::string16();
805   }
806 
807   return subject_name;
808 }
809 
810 //  ----------------------------------------------------------------------------
811 
812 // static
GetInstance()813 EnumerateModulesModel* EnumerateModulesModel::GetInstance() {
814   return Singleton<EnumerateModulesModel>::get();
815 }
816 
817 // static
RecordLearnMoreStat(bool from_menu)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);
822 }
823 
ShouldShowConflictWarning() const824 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;
831 
832   return confirmed_bad_modules_detected_ > 0;
833 }
834 
AcknowledgeConflictNotification()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());
842   }
843 }
844 
ScanNow()845 void EnumerateModulesModel::ScanNow() {
846   if (scanning_)
847     return;  // A scan is already in progress.
848 
849   lock->Acquire();  // Balanced in DoneScanning();
850 
851   scanning_ = true;
852 
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_);
858 }
859 
GetModuleList() const860 ListValue* EnumerateModulesModel::GetModuleList() const {
861   if (scanning_)
862     return NULL;
863 
864   lock->Acquire();
865 
866   if (enumerated_modules_.empty()) {
867     lock->Release();
868     return NULL;
869   }
870 
871   ListValue* list = new ListValue();
872 
873   for (ModuleEnumerator::ModulesVector::const_iterator module =
874            enumerated_modules_.begin();
875        module != enumerated_modules_.end(); ++module) {
876     DictionaryValue* data = new 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 = ASCIIToWide("Shell Extension");
883       if (module->type & ModuleEnumerator::WINSOCK_MODULE_REGISTRATION) {
884         if (!type_string.empty())
885           type_string += ASCIIToWide(", ");
886         type_string += ASCIIToWide("Winsock");
887       }
888       // Must be one of the above type.
889       DCHECK(!type_string.empty());
890       if (!limited_mode_) {
891         type_string += ASCIIToWide(" -- ");
892         type_string += l10n_util::GetStringUTF16(IDS_CONFLICTS_NOT_LOADED_YET);
893       }
894     }
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);
903 
904     if (!limited_mode_) {
905       // Figure out the possible resolution help string.
906       base::string16 actions;
907       base::string16 separator = ASCIIToWide(" ") + l10n_util::GetStringUTF16(
908           IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_SEPERATOR) +
909           ASCIIToWide(" ");
910 
911       if (module->recommended_action & ModuleEnumerator::NONE) {
912         actions = l10n_util::GetStringUTF16(
913             IDS_CONFLICTS_CHECK_INVESTIGATING);
914       }
915       if (module->recommended_action & ModuleEnumerator::UNINSTALL) {
916         if (!actions.empty())
917           actions += separator;
918         actions = l10n_util::GetStringUTF16(
919             IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_UNINSTALL);
920       }
921       if (module->recommended_action & ModuleEnumerator::UPDATE) {
922         if (!actions.empty())
923           actions += separator;
924         actions += l10n_util::GetStringUTF16(
925             IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_UPDATE);
926       }
927       if (module->recommended_action & ModuleEnumerator::DISABLE) {
928         if (!actions.empty())
929           actions += separator;
930         actions += l10n_util::GetStringUTF16(
931             IDS_CONFLICTS_CHECK_POSSIBLE_ACTION_DISABLE);
932       }
933       base::string16 possible_resolution = actions.empty() ? ASCIIToWide("") :
934           l10n_util::GetStringUTF16(IDS_CONFLICTS_CHECK_POSSIBLE_ACTIONS) +
935           ASCIIToWide(" ") +
936           actions;
937       data->SetString("possibleResolution", possible_resolution);
938       data->SetString("help_url",
939                       ConstructHelpCenterUrl(*module).spec().c_str());
940     }
941 
942     list->Append(data);
943   }
944 
945   lock->Release();
946   return list;
947 }
948 
GetFirstNotableConflict()949 GURL EnumerateModulesModel::GetFirstNotableConflict() {
950   lock->Acquire();
951   GURL url;
952 
953   if (enumerated_modules_.empty()) {
954     lock->Release();
955     return GURL();
956   }
957 
958   for (ModuleEnumerator::ModulesVector::const_iterator module =
959            enumerated_modules_.begin();
960        module != enumerated_modules_.end(); ++module) {
961     if (!(module->recommended_action & ModuleEnumerator::NOTIFY_USER))
962       continue;
963 
964     url = ConstructHelpCenterUrl(*module);
965     DCHECK(url.is_valid());
966     break;
967   }
968 
969   lock->Release();
970   return url;
971 }
972 
973 
EnumerateModulesModel()974 EnumerateModulesModel::EnumerateModulesModel()
975     : limited_mode_(false),
976       scanning_(false),
977       conflict_notification_acknowledged_(false),
978       confirmed_bad_modules_detected_(0),
979       suspected_bad_modules_detected_(0),
980       modules_to_notify_about_(0) {
981   lock = new base::Lock();
982 }
983 
~EnumerateModulesModel()984 EnumerateModulesModel::~EnumerateModulesModel() {
985   delete lock;
986 }
987 
MaybePostScanningTask()988 void EnumerateModulesModel::MaybePostScanningTask() {
989   static bool done = false;
990   if (!done) {
991     done = true;
992 
993     const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
994     if (cmd_line.HasSwitch(switches::kConflictingModulesCheck) ||
995         base::win::GetVersion() == base::win::VERSION_XP) {
996       check_modules_timer_.Start(FROM_HERE,
997           base::TimeDelta::FromMilliseconds(kModuleCheckDelayMs),
998           this, &EnumerateModulesModel::ScanNow);
999     }
1000   }
1001 }
1002 
DoneScanning()1003 void EnumerateModulesModel::DoneScanning() {
1004   confirmed_bad_modules_detected_ = 0;
1005   suspected_bad_modules_detected_ = 0;
1006   modules_to_notify_about_ = 0;
1007   for (ModuleEnumerator::ModulesVector::const_iterator module =
1008        enumerated_modules_.begin();
1009        module != enumerated_modules_.end(); ++module) {
1010     if (module->status == ModuleEnumerator::CONFIRMED_BAD) {
1011       ++confirmed_bad_modules_detected_;
1012       if (module->recommended_action & ModuleEnumerator::NOTIFY_USER)
1013         ++modules_to_notify_about_;
1014     } else if (module->status == ModuleEnumerator::SUSPECTED_BAD) {
1015       ++suspected_bad_modules_detected_;
1016       if (module->recommended_action & ModuleEnumerator::NOTIFY_USER)
1017         ++modules_to_notify_about_;
1018     }
1019   }
1020 
1021   scanning_ = false;
1022   lock->Release();
1023 
1024   UMA_HISTOGRAM_COUNTS_100("Conflicts.SuspectedBadModules",
1025                            suspected_bad_modules_detected_);
1026   UMA_HISTOGRAM_COUNTS_100("Conflicts.ConfirmedBadModules",
1027                            confirmed_bad_modules_detected_);
1028 
1029   // Notifications are not available in limited mode.
1030   if (limited_mode_)
1031     return;
1032 
1033   content::NotificationService::current()->Notify(
1034       chrome::NOTIFICATION_MODULE_LIST_ENUMERATED,
1035       content::Source<EnumerateModulesModel>(this),
1036       content::NotificationService::NoDetails());
1037 
1038   // Command line flag must be enabled for the notification to get sent out.
1039   // Otherwise we'd get the badge (while the feature is disabled) when we
1040   // navigate to about:conflicts and find confirmed matches.
1041   const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
1042   if (!cmd_line.HasSwitch(switches::kConflictingModulesCheck))
1043     return;
1044 
1045   content::NotificationService::current()->Notify(
1046       chrome::NOTIFICATION_MODULE_INCOMPATIBILITY_BADGE_CHANGE,
1047       content::Source<EnumerateModulesModel>(this),
1048       content::NotificationService::NoDetails());
1049 }
1050 
ConstructHelpCenterUrl(const ModuleEnumerator::Module & module) const1051 GURL EnumerateModulesModel::ConstructHelpCenterUrl(
1052     const ModuleEnumerator::Module& module) const {
1053   if (!(module.recommended_action & ModuleEnumerator::SEE_LINK) &&
1054       !(module.recommended_action & ModuleEnumerator::NOTIFY_USER))
1055     return GURL();
1056 
1057   // Construct the needed hashes.
1058   std::string filename, location, description, signer;
1059   GenerateHash(WideToUTF8(module.name), &filename);
1060   GenerateHash(WideToUTF8(module.location), &location);
1061   GenerateHash(WideToUTF8(module.description), &description);
1062   GenerateHash(WideToUTF8(module.digital_signer), &signer);
1063 
1064   base::string16 url =
1065       l10n_util::GetStringFUTF16(IDS_HELP_CENTER_VIEW_CONFLICTS,
1066           ASCIIToUTF16(filename), ASCIIToUTF16(location),
1067           ASCIIToUTF16(description), ASCIIToUTF16(signer));
1068   return GURL(UTF16ToUTF8(url));
1069 }
1070