Home | History | Annotate | Download | only in browser
      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).
     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:
     80   explicit FindModule(const ModuleEnumerator::Module& x)
     81     : module(x) {}
     82   bool operator()(const ModuleEnumerator::Module& module_in) const {
     83     return (module.location == module_in.location) &&
     84            (module.name == module_in.name);
     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.
     93 bool ConvertToLongPath(const string16& short_path, 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.
    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
    329 void ModuleEnumerator::NormalizeModule(Module* module) {
    330   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 != 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 != string16::npos)
    351     module->version = module->version.substr(0, first_space);
    352 
    353   module->normalized = true;
    354 }
    355 
    356 // static
    357 ModuleEnumerator::ModuleStatus ModuleEnumerator::Match(
    358     const ModuleEnumerator::Module& module,
    359     const ModuleEnumerator::BlacklistEntry& blacklisted) {
    360   // All modules must be normalized before matching against blacklist.
    361   DCHECK(module.normalized);
    362   // Filename is mandatory and version should not contain spaces.
    363   DCHECK(strlen(blacklisted.filename) > 0);
    364   DCHECK(!strstr(blacklisted.version_from, " "));
    365   DCHECK(!strstr(blacklisted.version_to, " "));
    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(WideToUTF8(module.name), &filename_hash);
    378   GenerateHash(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(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(WideToUTF8(module.digital_signer), &signer_hash);
    407       GenerateHash(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 
    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 
    434 ModuleEnumerator::~ModuleEnumerator() {
    435 }
    436 
    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     DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::FILE));
    445     BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
    446                             base::Bind(&ModuleEnumerator::ScanImpl, this));
    447   } else {
    448     // Run it synchronously.
    449     ScanImpl();
    450   }
    451 }
    452 
    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 
    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 
    527 void ModuleEnumerator::EnumerateShellExtensions() {
    528   ReadShellExtensions(HKEY_LOCAL_MACHINE);
    529   ReadShellExtensions(HKEY_CURRENT_USER);
    530 }
    531 
    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     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 
    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 
    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 
    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 
    631 void ModuleEnumerator::PreparePathMappings() {
    632   path_mapping_.clear();
    633 
    634   scoped_ptr<base::Environment> environment(base::Environment::Create());
    635   std::vector<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<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 
    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   string16 location = entry->location;
    662   for (PathMapping::const_iterator mapping = path_mapping_.begin();
    663        mapping != path_mapping_.end(); ++mapping) {
    664     string16 prefix = mapping->first;
    665     if (StartsWith(location, prefix, false)) {
    666       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 
    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 
    717 void ModuleEnumerator::ReportBack() {
    718   if (!limited_mode_)
    719     DCHECK(BrowserThread::CurrentlyOn(callback_thread_id_));
    720   observer_->DoneScanning();
    721 }
    722 
    723 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 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 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 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 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 string16();
    792   }
    793 
    794   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 string16();
    805   }
    806 
    807   return subject_name;
    808 }
    809 
    810 //  ----------------------------------------------------------------------------
    811 
    812 // static
    813 EnumerateModulesModel* EnumerateModulesModel::GetInstance() {
    814   return Singleton<EnumerateModulesModel>::get();
    815 }
    816 
    817 // static
    818 void EnumerateModulesModel::RecordLearnMoreStat(bool from_menu) {
    819   UMA_HISTOGRAM_ENUMERATION("ConflictingModule.UserSelection",
    820       from_menu ? ACTION_MENU_LEARN_MORE : ACTION_BUBBLE_LEARN_MORE,
    821       ACTION_BOUNDARY);
    822 }
    823 
    824 bool EnumerateModulesModel::ShouldShowConflictWarning() const {
    825   // If the user has acknowledged the conflict notification, then we don't need
    826   // to show it again (because the scanning only happens once per the lifetime
    827   // of the process). If we were to run the scanning more than once, then we'd
    828   // need to clear the flag somewhere when we are ready to show it again.
    829   if (conflict_notification_acknowledged_)
    830     return false;
    831 
    832   return confirmed_bad_modules_detected_ > 0;
    833 }
    834 
    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 
    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 
    860 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     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       string16 actions;
    907       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       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 
    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 
    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 
    984 EnumerateModulesModel::~EnumerateModulesModel() {
    985   delete lock;
    986 }
    987 
    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 
   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 
   1051 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   string16 url = l10n_util::GetStringFUTF16(IDS_HELP_CENTER_VIEW_CONFLICTS,
   1065       ASCIIToUTF16(filename), ASCIIToUTF16(location),
   1066       ASCIIToUTF16(description), ASCIIToUTF16(signer));
   1067   return GURL(UTF16ToUTF8(url));
   1068 }
   1069