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