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