Home | History | Annotate | Download | only in risk
      1 // Copyright 2013 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 // Generating a fingerprint consists of two major steps:
      6 //   (1) Gather all the necessary data.
      7 //   (2) Write it into a protocol buffer.
      8 //
      9 // Step (2) is as simple as it sounds -- it's really just a matter of copying
     10 // data.  Step (1) requires waiting on several asynchronous callbacks, which are
     11 // managed by the FingerprintDataLoader class.
     12 
     13 #include "components/autofill/content/browser/risk/fingerprint.h"
     14 
     15 #include "base/bind.h"
     16 #include "base/callback.h"
     17 #include "base/cpu.h"
     18 #include "base/logging.h"
     19 #include "base/memory/weak_ptr.h"
     20 #include "base/scoped_observer.h"
     21 #include "base/strings/string_split.h"
     22 #include "base/strings/utf_string_conversions.h"
     23 #include "base/sys_info.h"
     24 #include "base/time/time.h"
     25 #include "base/timer/timer.h"
     26 #include "base/values.h"
     27 #include "components/autofill/content/browser/risk/proto/fingerprint.pb.h"
     28 #include "content/public/browser/browser_thread.h"
     29 #include "content/public/browser/font_list_async.h"
     30 #include "content/public/browser/geolocation_provider.h"
     31 #include "content/public/browser/gpu_data_manager.h"
     32 #include "content/public/browser/gpu_data_manager_observer.h"
     33 #include "content/public/browser/plugin_service.h"
     34 #include "content/public/browser/render_widget_host.h"
     35 #include "content/public/browser/render_widget_host_view.h"
     36 #include "content/public/browser/web_contents.h"
     37 #include "content/public/common/geoposition.h"
     38 #include "content/public/common/webplugininfo.h"
     39 #include "gpu/config/gpu_info.h"
     40 #include "third_party/WebKit/public/platform/WebRect.h"
     41 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
     42 #include "ui/gfx/rect.h"
     43 #include "ui/gfx/screen.h"
     44 
     45 using blink::WebScreenInfo;
     46 
     47 namespace autofill {
     48 namespace risk {
     49 
     50 namespace {
     51 
     52 const int32 kFingerprinterVersion = 1;
     53 
     54 // Maximum amount of time, in seconds, to wait for loading asynchronous
     55 // fingerprint data.
     56 const int kTimeoutSeconds = 4;
     57 
     58 // Returns the delta between the local timezone and UTC.
     59 base::TimeDelta GetTimezoneOffset() {
     60   const base::Time utc = base::Time::Now();
     61 
     62   base::Time::Exploded local;
     63   utc.LocalExplode(&local);
     64 
     65   return base::Time::FromUTCExploded(local) - utc;
     66 }
     67 
     68 // Returns the concatenation of the operating system name and version, e.g.
     69 // "Mac OS X 10.6.8".
     70 std::string GetOperatingSystemVersion() {
     71   return base::SysInfo::OperatingSystemName() + " " +
     72       base::SysInfo::OperatingSystemVersion();
     73 }
     74 
     75 // Adds the list of |fonts| to the |machine|.
     76 void AddFontsToFingerprint(const base::ListValue& fonts,
     77                            Fingerprint::MachineCharacteristics* machine) {
     78   for (base::ListValue::const_iterator it = fonts.begin();
     79        it != fonts.end(); ++it) {
     80     // Each item in the list is a two-element list such that the first element
     81     // is the font family and the second is the font name.
     82     const base::ListValue* font_description = NULL;
     83     bool success = (*it)->GetAsList(&font_description);
     84     DCHECK(success);
     85 
     86     std::string font_name;
     87     success = font_description->GetString(1, &font_name);
     88     DCHECK(success);
     89 
     90     machine->add_font(font_name);
     91   }
     92 }
     93 
     94 // Adds the list of |plugins| to the |machine|.
     95 void AddPluginsToFingerprint(const std::vector<content::WebPluginInfo>& plugins,
     96                              Fingerprint::MachineCharacteristics* machine) {
     97   for (std::vector<content::WebPluginInfo>::const_iterator it = plugins.begin();
     98        it != plugins.end(); ++it) {
     99     Fingerprint::MachineCharacteristics::Plugin* plugin =
    100         machine->add_plugin();
    101     plugin->set_name(base::UTF16ToUTF8(it->name));
    102     plugin->set_description(base::UTF16ToUTF8(it->desc));
    103     for (std::vector<content::WebPluginMimeType>::const_iterator mime_type =
    104              it->mime_types.begin();
    105          mime_type != it->mime_types.end(); ++mime_type) {
    106       plugin->add_mime_type(mime_type->mime_type);
    107     }
    108     plugin->set_version(base::UTF16ToUTF8(it->version));
    109   }
    110 }
    111 
    112 // Adds the list of HTTP accept languages to the |machine|.
    113 void AddAcceptLanguagesToFingerprint(
    114     const std::string& accept_languages_str,
    115     Fingerprint::MachineCharacteristics* machine) {
    116   std::vector<std::string> accept_languages;
    117   base::SplitString(accept_languages_str, ',', &accept_languages);
    118   for (std::vector<std::string>::const_iterator it = accept_languages.begin();
    119        it != accept_languages.end(); ++it) {
    120     machine->add_requested_language(*it);
    121   }
    122 }
    123 
    124 // This function writes
    125 //   (a) the number of screens,
    126 //   (b) the primary display's screen size,
    127 //   (c) the screen's color depth, and
    128 //   (d) the size of the screen unavailable to web page content,
    129 //       i.e. the Taskbar size on Windows
    130 // into the |machine|.
    131 void AddScreenInfoToFingerprint(const WebScreenInfo& screen_info,
    132                                 Fingerprint::MachineCharacteristics* machine) {
    133   // TODO(scottmg): NativeScreen maybe wrong. http://crbug.com/133312
    134   machine->set_screen_count(
    135       gfx::Screen::GetNativeScreen()->GetNumDisplays());
    136 
    137   const gfx::Size screen_size =
    138       gfx::Screen::GetNativeScreen()->GetPrimaryDisplay().GetSizeInPixel();
    139   machine->mutable_screen_size()->set_width(screen_size.width());
    140   machine->mutable_screen_size()->set_height(screen_size.height());
    141 
    142   machine->set_screen_color_depth(screen_info.depth);
    143 
    144   const gfx::Rect screen_rect(screen_info.rect);
    145   const gfx::Rect available_rect(screen_info.availableRect);
    146   const gfx::Rect unavailable_rect =
    147       gfx::SubtractRects(screen_rect, available_rect);
    148   machine->mutable_unavailable_screen_size()->set_width(
    149       unavailable_rect.width());
    150   machine->mutable_unavailable_screen_size()->set_height(
    151       unavailable_rect.height());
    152 }
    153 
    154 // Writes info about the machine's CPU into the |machine|.
    155 void AddCpuInfoToFingerprint(Fingerprint::MachineCharacteristics* machine) {
    156   base::CPU cpu;
    157   machine->mutable_cpu()->set_vendor_name(cpu.vendor_name());
    158   machine->mutable_cpu()->set_brand(cpu.cpu_brand());
    159 }
    160 
    161 // Writes info about the machine's GPU into the |machine|.
    162 void AddGpuInfoToFingerprint(Fingerprint::MachineCharacteristics* machine) {
    163   const gpu::GPUInfo& gpu_info =
    164       content::GpuDataManager::GetInstance()->GetGPUInfo();
    165   if (!gpu_info.finalized)
    166     return;
    167 
    168   Fingerprint::MachineCharacteristics::Graphics* graphics =
    169       machine->mutable_graphics_card();
    170   graphics->set_vendor_id(gpu_info.gpu.vendor_id);
    171   graphics->set_device_id(gpu_info.gpu.device_id);
    172   graphics->set_driver_version(gpu_info.driver_version);
    173   graphics->set_driver_date(gpu_info.driver_date);
    174 
    175   Fingerprint::MachineCharacteristics::Graphics::PerformanceStatistics*
    176       gpu_performance = graphics->mutable_performance_statistics();
    177   gpu_performance->set_graphics_score(gpu_info.performance_stats.graphics);
    178   gpu_performance->set_gaming_score(gpu_info.performance_stats.gaming);
    179   gpu_performance->set_overall_score(gpu_info.performance_stats.overall);
    180 }
    181 
    182 // Waits for all asynchronous data required for the fingerprint to be loaded,
    183 // then fills out the fingerprint.
    184 class FingerprintDataLoader : public content::GpuDataManagerObserver {
    185  public:
    186   FingerprintDataLoader(
    187       uint64 obfuscated_gaia_id,
    188       const gfx::Rect& window_bounds,
    189       const gfx::Rect& content_bounds,
    190       const WebScreenInfo& screen_info,
    191       const std::string& version,
    192       const std::string& charset,
    193       const std::string& accept_languages,
    194       const base::Time& install_time,
    195       const std::string& app_locale,
    196       const std::string& user_agent,
    197       const base::TimeDelta& timeout,
    198       const base::Callback<void(scoped_ptr<Fingerprint>)>& callback);
    199 
    200  private:
    201   virtual ~FingerprintDataLoader() {}
    202 
    203   // content::GpuDataManagerObserver:
    204   virtual void OnGpuInfoUpdate() OVERRIDE;
    205 
    206   // Callbacks for asynchronously loaded data.
    207   void OnGotFonts(scoped_ptr<base::ListValue> fonts);
    208   void OnGotPlugins(const std::vector<content::WebPluginInfo>& plugins);
    209   void OnGotGeoposition(const content::Geoposition& geoposition);
    210 
    211   // If all of the asynchronous data has been loaded, calls |callback_| with
    212   // the fingerprint data.
    213   void MaybeFillFingerprint();
    214 
    215   // Calls |callback_| with the fingerprint data.
    216   void FillFingerprint();
    217 
    218   // The GPU data provider.
    219   // Weak reference because the GpuDataManager class is a singleton.
    220   content::GpuDataManager* const gpu_data_manager_;
    221 
    222   // Ensures that any observer registrations for the GPU data are cleaned up by
    223   // the time this object is destroyed.
    224   ScopedObserver<content::GpuDataManager, FingerprintDataLoader> gpu_observer_;
    225 
    226   // Data that will be passed on to the next loading phase.  See the comment for
    227   // GetFingerprint() for a description of these variables.
    228   const uint64 obfuscated_gaia_id_;
    229   const gfx::Rect window_bounds_;
    230   const gfx::Rect content_bounds_;
    231   const WebScreenInfo screen_info_;
    232   const std::string version_;
    233   const std::string charset_;
    234   const std::string accept_languages_;
    235   const std::string app_locale_;
    236   const std::string user_agent_;
    237   const base::Time install_time_;
    238 
    239   // Data that will be loaded asynchronously.
    240   scoped_ptr<base::ListValue> fonts_;
    241   std::vector<content::WebPluginInfo> plugins_;
    242   bool waiting_on_plugins_;
    243   content::Geoposition geoposition_;
    244 
    245   // Timer to enforce a maximum timeout before the |callback_| is called, even
    246   // if not all asynchronous data has been loaded.
    247   base::OneShotTimer<FingerprintDataLoader> timeout_timer_;
    248 
    249   // For invalidating asynchronous callbacks that might arrive after |this|
    250   // instance is destroyed.
    251   base::WeakPtrFactory<FingerprintDataLoader> weak_ptr_factory_;
    252 
    253   // The callback that will be called once all the data is available.
    254   base::Callback<void(scoped_ptr<Fingerprint>)> callback_;
    255 
    256   // The callback used as an "observer" of the GeolocationProvider.
    257   scoped_ptr<content::GeolocationProvider::Subscription>
    258       geolocation_subscription_;
    259 
    260   DISALLOW_COPY_AND_ASSIGN(FingerprintDataLoader);
    261 };
    262 
    263 FingerprintDataLoader::FingerprintDataLoader(
    264     uint64 obfuscated_gaia_id,
    265     const gfx::Rect& window_bounds,
    266     const gfx::Rect& content_bounds,
    267     const WebScreenInfo& screen_info,
    268     const std::string& version,
    269     const std::string& charset,
    270     const std::string& accept_languages,
    271     const base::Time& install_time,
    272     const std::string& app_locale,
    273     const std::string& user_agent,
    274     const base::TimeDelta& timeout,
    275     const base::Callback<void(scoped_ptr<Fingerprint>)>& callback)
    276     : gpu_data_manager_(content::GpuDataManager::GetInstance()),
    277       gpu_observer_(this),
    278       obfuscated_gaia_id_(obfuscated_gaia_id),
    279       window_bounds_(window_bounds),
    280       content_bounds_(content_bounds),
    281       screen_info_(screen_info),
    282       version_(version),
    283       charset_(charset),
    284       accept_languages_(accept_languages),
    285       app_locale_(app_locale),
    286       user_agent_(user_agent),
    287       install_time_(install_time),
    288       waiting_on_plugins_(true),
    289       weak_ptr_factory_(this),
    290       callback_(callback) {
    291   DCHECK(!install_time_.is_null());
    292 
    293   timeout_timer_.Start(FROM_HERE, timeout,
    294                        base::Bind(&FingerprintDataLoader::MaybeFillFingerprint,
    295                                   weak_ptr_factory_.GetWeakPtr()));
    296 
    297   // Load GPU data if needed.
    298   if (gpu_data_manager_->GpuAccessAllowed(NULL) &&
    299       !gpu_data_manager_->IsCompleteGpuInfoAvailable()) {
    300     gpu_observer_.Add(gpu_data_manager_);
    301     gpu_data_manager_->RequestCompleteGpuInfoIfNeeded();
    302   }
    303 
    304 #if defined(ENABLE_PLUGINS)
    305   // Load plugin data.
    306   content::PluginService::GetInstance()->GetPlugins(
    307       base::Bind(&FingerprintDataLoader::OnGotPlugins,
    308                  weak_ptr_factory_.GetWeakPtr()));
    309 #else
    310   waiting_on_plugins_ = false;
    311 #endif
    312 
    313   // Load font data.
    314   content::GetFontListAsync(
    315       base::Bind(&FingerprintDataLoader::OnGotFonts,
    316                  weak_ptr_factory_.GetWeakPtr()));
    317 
    318   // Load geolocation data.
    319   geolocation_subscription_ = content::GeolocationProvider::GetInstance()->
    320       AddLocationUpdateCallback(
    321           base::Bind(&FingerprintDataLoader::OnGotGeoposition,
    322                       weak_ptr_factory_.GetWeakPtr()),
    323           false);
    324 }
    325 
    326 void FingerprintDataLoader::OnGpuInfoUpdate() {
    327   if (!gpu_data_manager_->IsCompleteGpuInfoAvailable())
    328     return;
    329 
    330   gpu_observer_.Remove(gpu_data_manager_);
    331   MaybeFillFingerprint();
    332 }
    333 
    334 void FingerprintDataLoader::OnGotFonts(scoped_ptr<base::ListValue> fonts) {
    335   DCHECK(!fonts_);
    336   fonts_.reset(fonts.release());
    337   MaybeFillFingerprint();
    338 }
    339 
    340 void FingerprintDataLoader::OnGotPlugins(
    341     const std::vector<content::WebPluginInfo>& plugins) {
    342   DCHECK(waiting_on_plugins_);
    343   waiting_on_plugins_ = false;
    344   plugins_ = plugins;
    345   MaybeFillFingerprint();
    346 }
    347 
    348 void FingerprintDataLoader::OnGotGeoposition(
    349     const content::Geoposition& geoposition) {
    350   DCHECK(!geoposition_.Validate());
    351 
    352   geoposition_ = geoposition;
    353   DCHECK(geoposition_.Validate() ||
    354          geoposition_.error_code != content::Geoposition::ERROR_CODE_NONE);
    355   geolocation_subscription_.reset();
    356 
    357   MaybeFillFingerprint();
    358 }
    359 
    360 void FingerprintDataLoader::MaybeFillFingerprint() {
    361   // If all of the data has been loaded, or if the |timeout_timer_| has expired,
    362   // fill the fingerprint and clean up.
    363   if (!timeout_timer_.IsRunning() ||
    364       ((!gpu_data_manager_->GpuAccessAllowed(NULL) ||
    365         gpu_data_manager_->IsCompleteGpuInfoAvailable()) &&
    366        fonts_ &&
    367        !waiting_on_plugins_ &&
    368        (geoposition_.Validate() ||
    369         geoposition_.error_code != content::Geoposition::ERROR_CODE_NONE))) {
    370     FillFingerprint();
    371     delete this;
    372   }
    373 }
    374 
    375 void FingerprintDataLoader::FillFingerprint() {
    376   scoped_ptr<Fingerprint> fingerprint(new Fingerprint);
    377   Fingerprint::MachineCharacteristics* machine =
    378       fingerprint->mutable_machine_characteristics();
    379 
    380   machine->set_operating_system_build(GetOperatingSystemVersion());
    381   // We use the delta between the install time and the Unix epoch, in hours.
    382   machine->set_browser_install_time_hours(
    383       (install_time_ - base::Time::UnixEpoch()).InHours());
    384   machine->set_utc_offset_ms(GetTimezoneOffset().InMilliseconds());
    385   machine->set_browser_language(app_locale_);
    386   machine->set_charset(charset_);
    387   machine->set_user_agent(user_agent_);
    388   machine->set_ram(base::SysInfo::AmountOfPhysicalMemory());
    389   machine->set_browser_build(version_);
    390   machine->set_browser_feature(
    391       Fingerprint::MachineCharacteristics::FEATURE_REQUEST_AUTOCOMPLETE);
    392   if (fonts_)
    393     AddFontsToFingerprint(*fonts_, machine);
    394   AddPluginsToFingerprint(plugins_, machine);
    395   AddAcceptLanguagesToFingerprint(accept_languages_, machine);
    396   AddScreenInfoToFingerprint(screen_info_, machine);
    397   AddCpuInfoToFingerprint(machine);
    398   AddGpuInfoToFingerprint(machine);
    399 
    400   // TODO(isherman): Record the user_and_device_name_hash.
    401   // TODO(isherman): Record the partition size of the hard drives?
    402 
    403   Fingerprint::TransientState* transient_state =
    404       fingerprint->mutable_transient_state();
    405   Fingerprint::Dimension* inner_window_size =
    406       transient_state->mutable_inner_window_size();
    407   inner_window_size->set_width(content_bounds_.width());
    408   inner_window_size->set_height(content_bounds_.height());
    409   Fingerprint::Dimension* outer_window_size =
    410       transient_state->mutable_outer_window_size();
    411   outer_window_size->set_width(window_bounds_.width());
    412   outer_window_size->set_height(window_bounds_.height());
    413 
    414   // TODO(isherman): Record network performance data, which is theoretically
    415   // available to JS.
    416 
    417   // TODO(isherman): Record more user behavior data.
    418   if (geoposition_.Validate() &&
    419       geoposition_.error_code == content::Geoposition::ERROR_CODE_NONE) {
    420     Fingerprint::UserCharacteristics::Location* location =
    421         fingerprint->mutable_user_characteristics()->mutable_location();
    422     location->set_altitude(geoposition_.altitude);
    423     location->set_latitude(geoposition_.latitude);
    424     location->set_longitude(geoposition_.longitude);
    425     location->set_accuracy(geoposition_.accuracy);
    426     location->set_time_in_ms(
    427         (geoposition_.timestamp - base::Time::UnixEpoch()).InMilliseconds());
    428   }
    429 
    430   Fingerprint::Metadata* metadata = fingerprint->mutable_metadata();
    431   metadata->set_timestamp_ms(
    432       (base::Time::Now() - base::Time::UnixEpoch()).InMilliseconds());
    433   metadata->set_obfuscated_gaia_id(obfuscated_gaia_id_);
    434   metadata->set_fingerprinter_version(kFingerprinterVersion);
    435 
    436   callback_.Run(fingerprint.Pass());
    437 }
    438 
    439 }  // namespace
    440 
    441 namespace internal {
    442 
    443 void GetFingerprintInternal(
    444     uint64 obfuscated_gaia_id,
    445     const gfx::Rect& window_bounds,
    446     const gfx::Rect& content_bounds,
    447     const blink::WebScreenInfo& screen_info,
    448     const std::string& version,
    449     const std::string& charset,
    450     const std::string& accept_languages,
    451     const base::Time& install_time,
    452     const std::string& app_locale,
    453     const std::string& user_agent,
    454     const base::TimeDelta& timeout,
    455     const base::Callback<void(scoped_ptr<Fingerprint>)>& callback) {
    456   // Begin loading all of the data that we need to load asynchronously.
    457   // This class is responsible for freeing its own memory.
    458   new FingerprintDataLoader(obfuscated_gaia_id, window_bounds, content_bounds,
    459                             screen_info, version, charset, accept_languages,
    460                             install_time, app_locale, user_agent, timeout,
    461                             callback);
    462 }
    463 
    464 }  // namespace internal
    465 
    466 void GetFingerprint(
    467     uint64 obfuscated_gaia_id,
    468     const gfx::Rect& window_bounds,
    469     content::WebContents* web_contents,
    470     const std::string& version,
    471     const std::string& charset,
    472     const std::string& accept_languages,
    473     const base::Time& install_time,
    474     const std::string& app_locale,
    475     const std::string& user_agent,
    476     const base::Callback<void(scoped_ptr<Fingerprint>)>& callback) {
    477   gfx::Rect content_bounds = web_contents->GetContainerBounds();
    478 
    479   blink::WebScreenInfo screen_info;
    480   content::RenderWidgetHostView* host_view =
    481       web_contents->GetRenderWidgetHostView();
    482   if (host_view)
    483     host_view->GetRenderWidgetHost()->GetWebScreenInfo(&screen_info);
    484 
    485   internal::GetFingerprintInternal(
    486       obfuscated_gaia_id, window_bounds, content_bounds, screen_info, version,
    487       charset, accept_languages, install_time, app_locale, user_agent,
    488       base::TimeDelta::FromSeconds(kTimeoutSeconds), callback);
    489 }
    490 
    491 }  // namespace risk
    492 }  // namespace autofill
    493