1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/password_manager/password_store_factory.h"
7 #include "base/command_line.h"
8 #include "base/environment.h"
9 #include "base/metrics/histogram_macros.h"
10 #include "base/prefs/pref_service.h"
11 #include "base/thread_task_runner_handle.h"
12 #include "chrome/browser/password_manager/sync_metrics.h"
13 #include "chrome/browser/profiles/incognito_helpers.h"
14 #include "chrome/browser/profiles/profile.h"
15 #include "chrome/browser/sync/glue/sync_start_util.h"
16 #include "chrome/browser/sync/profile_sync_service.h"
17 #include "chrome/browser/sync/profile_sync_service_factory.h"
18 #include "chrome/browser/web_data_service_factory.h"
19 #include "chrome/common/chrome_constants.h"
20 #include "chrome/common/chrome_switches.h"
21 #include "components/keyed_service/content/browser_context_dependency_manager.h"
22 #include "components/os_crypt/os_crypt_switches.h"
23 #include "components/password_manager/core/browser/affiliated_match_helper.h"
24 #include "components/password_manager/core/browser/affiliation_service.h"
25 #include "components/password_manager/core/browser/affiliation_utils.h"
26 #include "components/password_manager/core/browser/login_database.h"
27 #include "components/password_manager/core/browser/password_manager_util.h"
28 #include "components/password_manager/core/browser/password_store.h"
29 #include "components/password_manager/core/browser/password_store_default.h"
30 #include "components/password_manager/core/common/password_manager_pref_names.h"
31 #include "components/pref_registry/pref_registry_syncable.h"
32 #include "content/public/browser/browser_thread.h"
35 #include "chrome/browser/password_manager/password_store_win.h"
36 #include "components/password_manager/core/browser/webdata/password_web_data_service_win.h"
37 #elif defined(OS_MACOSX)
38 #include "chrome/browser/password_manager/password_store_proxy_mac.h"
39 #include "crypto/apple_keychain.h"
40 #include "crypto/mock_apple_keychain.h"
41 #elif defined(OS_CHROMEOS) || defined(OS_ANDROID)
42 // Don't do anything. We're going to use the default store.
43 #elif defined(USE_X11)
44 #include "base/nix/xdg_util.h"
45 #if defined(USE_GNOME_KEYRING)
46 #include "chrome/browser/password_manager/native_backend_gnome_x.h"
48 #if defined(USE_LIBSECRET)
49 #include "base/metrics/field_trial.h"
50 #include "chrome/browser/password_manager/native_backend_libsecret.h"
52 #include "chrome/browser/password_manager/native_backend_kwallet_x.h"
53 #include "chrome/browser/password_manager/password_store_x.h"
56 using password_manager::PasswordStore
;
60 #if !defined(OS_CHROMEOS) && defined(USE_X11)
61 const LocalProfileId kInvalidLocalProfileId
=
62 static_cast<LocalProfileId
>(0);
65 #if defined(USE_LIBSECRET)
66 const char kLibsecretFieldTrialName
[] = "Libsecret";
67 const char kLibsecretFieldTrialDisabledGroupName
[] = "Disabled";
70 void ReportOsPassword(password_manager_util::OsPasswordStatus status
) {
71 UMA_HISTOGRAM_ENUMERATION("PasswordManager.OsPasswordStatus",
73 password_manager_util::MAX_PASSWORD_STATUS
);
76 void DelayReportOsPassword() {
77 // Avoid checking OS password until later on in browser startup
78 // since it calls a few Windows APIs.
79 content::BrowserThread::PostDelayedTask(
80 content::BrowserThread::UI
,
82 base::Bind(&password_manager_util::GetOsPasswordStatus
,
83 base::Bind(&ReportOsPassword
)),
84 base::TimeDelta::FromSeconds(40));
87 base::FilePath
GetAffiliationDatabasePath(Profile
* profile
) {
89 return profile
->GetPath().Append(chrome::kAffiliationDatabaseFileName
);
92 bool ShouldAffiliationBasedMatchingBeActive(Profile
* profile
) {
93 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
94 if (!password_manager::IsAffiliationBasedMatchingEnabled(*command_line
))
98 ProfileSyncService
* profile_sync_service
=
99 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile
);
100 return profile_sync_service
&&
101 profile_sync_service
->CanSyncStart() &&
102 profile_sync_service
->IsSyncActive() &&
103 profile_sync_service
->GetPreferredDataTypes().Has(syncer::PASSWORDS
) &&
104 !profile_sync_service
->IsUsingSecondaryPassphrase();
107 bool ShouldPropagatingPasswordChangesToWebCredentialsBeEnabled() {
108 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
109 return password_manager::IsPropagatingPasswordChangesToWebCredentialsEnabled(
113 void ActivateAffiliationBasedMatching(PasswordStore
* password_store
,
115 DCHECK(password_store
);
118 // The PasswordStore is so far the only consumer of the AffiliationService,
119 // therefore the service is owned by the AffiliatedMatchHelper, which in
120 // turn is owned by the PasswordStore.
121 // TODO(engedy): Double-check which request context we want.
122 scoped_refptr
<base::SingleThreadTaskRunner
> db_thread_runner(
123 content::BrowserThread::GetMessageLoopProxyForThread(
124 content::BrowserThread::DB
));
125 scoped_ptr
<password_manager::AffiliationService
> affiliation_service(
126 new password_manager::AffiliationService(db_thread_runner
));
127 affiliation_service
->Initialize(profile
->GetRequestContext(),
128 GetAffiliationDatabasePath(profile
));
129 scoped_ptr
<password_manager::AffiliatedMatchHelper
> affiliated_match_helper(
130 new password_manager::AffiliatedMatchHelper(password_store
,
131 affiliation_service
.Pass()));
132 affiliated_match_helper
->Initialize();
133 password_store
->SetAffiliatedMatchHelper(affiliated_match_helper
.Pass());
134 password_store
->enable_propagating_password_changes_to_web_credentials(
135 ShouldPropagatingPasswordChangesToWebCredentialsBeEnabled());
141 PasswordStoreService::PasswordStoreService(
142 scoped_refptr
<PasswordStore
> password_store
)
143 : password_store_(password_store
) {}
145 PasswordStoreService::~PasswordStoreService() {}
147 scoped_refptr
<PasswordStore
> PasswordStoreService::GetPasswordStore() {
148 return password_store_
;
151 void PasswordStoreService::Shutdown() {
152 if (password_store_
.get())
153 password_store_
->Shutdown();
157 scoped_refptr
<PasswordStore
> PasswordStoreFactory::GetForProfile(
159 ServiceAccessType sat
) {
160 if (sat
== ServiceAccessType::IMPLICIT_ACCESS
&& profile
->IsOffTheRecord()) {
161 NOTREACHED() << "This profile is OffTheRecord";
165 PasswordStoreFactory
* factory
= GetInstance();
166 PasswordStoreService
* service
= static_cast<PasswordStoreService
*>(
167 factory
->GetServiceForBrowserContext(profile
, true));
170 return service
->GetPasswordStore();
174 PasswordStoreFactory
* PasswordStoreFactory::GetInstance() {
175 return Singleton
<PasswordStoreFactory
>::get();
179 void PasswordStoreFactory::OnPasswordsSyncedStatePotentiallyChanged(
181 scoped_refptr
<PasswordStore
> password_store
=
182 GetForProfile(profile
, ServiceAccessType::EXPLICIT_ACCESS
);
186 if (ShouldAffiliationBasedMatchingBeActive(profile
) &&
187 !password_store
->HasAffiliatedMatchHelper()) {
188 ActivateAffiliationBasedMatching(password_store
.get(), profile
);
189 } else if (!ShouldAffiliationBasedMatchingBeActive(profile
) &&
190 password_store
->HasAffiliatedMatchHelper()) {
191 password_store
->SetAffiliatedMatchHelper(
192 make_scoped_ptr
<password_manager::AffiliatedMatchHelper
>(nullptr));
197 void PasswordStoreFactory::TrimOrDeleteAffiliationCache(Profile
* profile
) {
198 scoped_refptr
<PasswordStore
> password_store
=
199 GetForProfile(profile
, ServiceAccessType::EXPLICIT_ACCESS
);
200 if (password_store
&& password_store
->HasAffiliatedMatchHelper()) {
201 password_store
->TrimAffiliationCache();
203 scoped_refptr
<base::SingleThreadTaskRunner
> db_thread_runner(
204 content::BrowserThread::GetMessageLoopProxyForThread(
205 content::BrowserThread::DB
));
206 password_manager::AffiliationService::DeleteCache(
207 GetAffiliationDatabasePath(profile
), db_thread_runner
.get());
211 PasswordStoreFactory::PasswordStoreFactory()
212 : BrowserContextKeyedServiceFactory(
214 BrowserContextDependencyManager::GetInstance()) {
215 DependsOn(WebDataServiceFactory::GetInstance());
218 PasswordStoreFactory::~PasswordStoreFactory() {}
220 #if !defined(OS_CHROMEOS) && defined(USE_X11)
221 LocalProfileId
PasswordStoreFactory::GetLocalProfileId(
222 PrefService
* prefs
) const {
224 prefs
->GetInteger(password_manager::prefs::kLocalProfileId
);
225 if (id
== kInvalidLocalProfileId
) {
226 // Note that there are many more users than this. Thus, by design, this is
227 // not a unique id. However, it is large enough that it is very unlikely
228 // that it would be repeated twice on a single machine. It is still possible
229 // for that to occur though, so the potential results of it actually
230 // happening should be considered when using this value.
231 static const LocalProfileId kLocalProfileIdMask
=
232 static_cast<LocalProfileId
>((1 << 24) - 1);
234 id
= rand() & kLocalProfileIdMask
;
235 // TODO(mdm): scan other profiles to make sure they are not using this id?
236 } while (id
== kInvalidLocalProfileId
);
237 prefs
->SetInteger(password_manager::prefs::kLocalProfileId
, id
);
243 KeyedService
* PasswordStoreFactory::BuildServiceInstanceFor(
244 content::BrowserContext
* context
) const {
245 DelayReportOsPassword();
246 Profile
* profile
= static_cast<Profile
*>(context
);
248 // Given that LoginDatabase::Init() takes ~100ms on average; it will be called
249 // by PasswordStore::Init() on the background thread to avoid UI jank.
250 base::FilePath login_db_file_path
= profile
->GetPath();
251 login_db_file_path
= login_db_file_path
.Append(chrome::kLoginDataFileName
);
252 scoped_ptr
<password_manager::LoginDatabase
> login_db(
253 new password_manager::LoginDatabase(login_db_file_path
));
255 scoped_refptr
<base::SingleThreadTaskRunner
> main_thread_runner(
256 base::ThreadTaskRunnerHandle::Get());
257 scoped_refptr
<base::SingleThreadTaskRunner
> db_thread_runner(
258 content::BrowserThread::GetMessageLoopProxyForThread(
259 content::BrowserThread::DB
));
261 scoped_refptr
<PasswordStore
> ps
;
263 ps
= new PasswordStoreWin(main_thread_runner
, db_thread_runner
,
265 WebDataServiceFactory::GetPasswordWebDataForProfile(
266 profile
, ServiceAccessType::EXPLICIT_ACCESS
));
267 #elif defined(OS_MACOSX)
268 scoped_ptr
<crypto::AppleKeychain
> keychain(
269 base::CommandLine::ForCurrentProcess()->HasSwitch(
270 os_crypt::switches::kUseMockKeychain
)
271 ? new crypto::MockAppleKeychain()
272 : new crypto::AppleKeychain());
273 ps
= new PasswordStoreProxyMac(main_thread_runner
, keychain
.Pass(),
274 login_db
.Pass(), profile
->GetPrefs());
275 #elif defined(OS_CHROMEOS) || defined(OS_ANDROID)
276 // For now, we use PasswordStoreDefault. We might want to make a native
277 // backend for PasswordStoreX (see below) in the future though.
278 ps
= new password_manager::PasswordStoreDefault(
279 main_thread_runner
, db_thread_runner
, login_db
.Pass());
280 #elif defined(USE_X11)
281 // On POSIX systems, we try to use the "native" password management system of
282 // the desktop environment currently running, allowing GNOME Keyring in XFCE.
283 // (In all cases we fall back on the basic store in case of failure.)
284 base::nix::DesktopEnvironment desktop_env
= GetDesktopEnvironment();
285 base::nix::DesktopEnvironment used_desktop_env
;
286 std::string store_type
=
287 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
288 switches::kPasswordStore
);
289 LinuxBackendUsed used_backend
= PLAINTEXT
;
290 if (store_type
== "kwallet") {
291 used_desktop_env
= base::nix::DESKTOP_ENVIRONMENT_KDE4
;
292 } else if (store_type
== "gnome") {
293 used_desktop_env
= base::nix::DESKTOP_ENVIRONMENT_GNOME
;
294 } else if (store_type
== "basic") {
295 used_desktop_env
= base::nix::DESKTOP_ENVIRONMENT_OTHER
;
297 // Detect the store to use automatically.
298 used_desktop_env
= desktop_env
;
299 const char* name
= base::nix::GetDesktopEnvironmentName(desktop_env
);
300 VLOG(1) << "Password storage detected desktop environment: "
301 << (name
? name
: "(unknown)");
304 PrefService
* prefs
= profile
->GetPrefs();
305 LocalProfileId id
= GetLocalProfileId(prefs
);
307 scoped_ptr
<PasswordStoreX::NativeBackend
> backend
;
308 if (used_desktop_env
== base::nix::DESKTOP_ENVIRONMENT_KDE4
) {
309 // KDE3 didn't use DBus, which our KWallet store uses.
310 VLOG(1) << "Trying KWallet for password storage.";
311 backend
.reset(new NativeBackendKWallet(id
));
312 if (backend
->Init()) {
313 VLOG(1) << "Using KWallet for password storage.";
314 used_backend
= KWALLET
;
318 } else if (used_desktop_env
== base::nix::DESKTOP_ENVIRONMENT_GNOME
||
319 used_desktop_env
== base::nix::DESKTOP_ENVIRONMENT_UNITY
||
320 used_desktop_env
== base::nix::DESKTOP_ENVIRONMENT_XFCE
) {
321 #if defined(USE_LIBSECRET)
322 if (base::FieldTrialList::FindFullName(kLibsecretFieldTrialName
) !=
323 kLibsecretFieldTrialDisabledGroupName
) {
324 VLOG(1) << "Trying libsecret for password storage.";
325 backend
.reset(new NativeBackendLibsecret(id
));
326 if (backend
->Init()) {
327 VLOG(1) << "Using libsecret keyring for password storage.";
328 used_backend
= LIBSECRET
;
333 #endif // defined(USE_LIBSECRET)
334 if (!backend
.get()) {
335 #if defined(USE_GNOME_KEYRING)
336 VLOG(1) << "Trying GNOME keyring for password storage.";
337 backend
.reset(new NativeBackendGnome(id
));
338 if (backend
->Init()) {
339 VLOG(1) << "Using GNOME keyring for password storage.";
340 used_backend
= GNOME_KEYRING
;
344 #endif // defined(USE_GNOME_KEYRING)
348 if (!backend
.get()) {
349 LOG(WARNING
) << "Using basic (unencrypted) store for password storage. "
350 "See http://code.google.com/p/chromium/wiki/LinuxPasswordStorage for "
351 "more information about password storage options.";
354 ps
= new PasswordStoreX(main_thread_runner
, db_thread_runner
, login_db
.Pass(),
356 RecordBackendStatistics(desktop_env
, store_type
, used_backend
);
357 #elif defined(USE_OZONE)
358 ps
= new password_manager::PasswordStoreDefault(
359 main_thread_runner
, db_thread_runner
, login_db
.Pass());
365 sync_start_util::GetFlareForSyncableService(profile
->GetPath()))) {
366 NOTREACHED() << "Could not initialize password manager.";
370 return new PasswordStoreService(ps
);
373 void PasswordStoreFactory::RegisterProfilePrefs(
374 user_prefs::PrefRegistrySyncable
* registry
) {
375 #if !defined(OS_CHROMEOS) && defined(USE_X11)
376 // Notice that the preprocessor conditions above are exactly those that will
377 // result in using PasswordStoreX in BuildServiceInstanceFor().
378 registry
->RegisterIntegerPref(password_manager::prefs::kLocalProfileId
,
379 kInvalidLocalProfileId
);
383 content::BrowserContext
* PasswordStoreFactory::GetBrowserContextToUse(
384 content::BrowserContext
* context
) const {
385 return chrome::GetBrowserContextRedirectedInIncognito(context
);
388 bool PasswordStoreFactory::ServiceIsNULLWhileTesting() const {
393 base::nix::DesktopEnvironment
PasswordStoreFactory::GetDesktopEnvironment() {
394 scoped_ptr
<base::Environment
> env(base::Environment::Create());
395 return base::nix::GetDesktopEnvironment(env
.get());
398 void PasswordStoreFactory::RecordBackendStatistics(
399 base::nix::DesktopEnvironment desktop_env
,
400 const std::string
& command_line_flag
,
401 LinuxBackendUsed used_backend
) {
402 LinuxBackendUsage usage
= OTHER_PLAINTEXT
;
403 if (desktop_env
== base::nix::DESKTOP_ENVIRONMENT_KDE4
) {
404 if (command_line_flag
== "kwallet") {
405 usage
= used_backend
== KWALLET
? KDE_KWALLETFLAG_KWALLET
406 : KDE_KWALLETFLAG_PLAINTEXT
;
407 } else if (command_line_flag
== "gnome") {
408 usage
= used_backend
== PLAINTEXT
409 ? KDE_GNOMEFLAG_PLAINTEXT
410 : (used_backend
== GNOME_KEYRING
? KDE_GNOMEFLAG_KEYRING
411 : KDE_GNOMEFLAG_LIBSECRET
);
412 } else if (command_line_flag
== "basic") {
413 usage
= KDE_BASICFLAG_PLAINTEXT
;
416 used_backend
== KWALLET
? KDE_NOFLAG_KWALLET
: KDE_NOFLAG_PLAINTEXT
;
418 } else if (desktop_env
== base::nix::DESKTOP_ENVIRONMENT_GNOME
||
419 desktop_env
== base::nix::DESKTOP_ENVIRONMENT_UNITY
||
420 desktop_env
== base::nix::DESKTOP_ENVIRONMENT_XFCE
) {
421 if (command_line_flag
== "kwallet") {
422 usage
= used_backend
== KWALLET
? GNOME_KWALLETFLAG_KWALLET
423 : GNOME_KWALLETFLAG_PLAINTEXT
;
424 } else if (command_line_flag
== "gnome") {
425 usage
= used_backend
== PLAINTEXT
426 ? GNOME_GNOMEFLAG_PLAINTEXT
427 : (used_backend
== GNOME_KEYRING
? GNOME_GNOMEFLAG_KEYRING
428 : GNOME_GNOMEFLAG_LIBSECRET
);
429 } else if (command_line_flag
== "basic") {
430 usage
= GNOME_BASICFLAG_PLAINTEXT
;
432 usage
= used_backend
== PLAINTEXT
433 ? GNOME_NOFLAG_PLAINTEXT
434 : (used_backend
== GNOME_KEYRING
? GNOME_NOFLAG_KEYRING
435 : GNOME_NOFLAG_LIBSECRET
);
438 // It is neither Gnome nor KDE environment.
439 switch (used_backend
) {
441 usage
= OTHER_PLAINTEXT
;
444 usage
= OTHER_KWALLET
;
447 usage
= OTHER_KEYRING
;
450 usage
= OTHER_LIBSECRET
;
454 UMA_HISTOGRAM_ENUMERATION("PasswordManager.LinuxBackendStatistics", usage
,
455 MAX_BACKEND_USAGE_VALUE
);