summaryrefslogtreecommitdiff
path: root/chromium/components/password_manager/core/browser/ui/insecure_credentials_manager.cc
blob: fb1727e21b246f945f5433ef031effac2c4c5e22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/password_manager/core/browser/ui/insecure_credentials_manager.h"

#include <algorithm>
#include <iterator>
#include <set>
#include <string>

#include "base/bind.h"
#include "base/callback.h"
#include "base/containers/flat_map.h"
#include "base/containers/flat_set.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_functions.h"
#include "base/ranges/algorithm.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "build/build_config.h"
#include "components/password_manager/core/browser/insecure_credentials_table.h"
#include "components/password_manager/core/browser/password_form.h"
#include "components/password_manager/core/browser/password_list_sorter.h"
#include "components/password_manager/core/browser/ui/credential_utils.h"
#include "components/password_manager/core/browser/ui/saved_passwords_presenter.h"
#include "components/password_manager/core/common/password_manager_features.h"

#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
#include "components/password_manager/core/browser/ui/weak_check_utility.h"
#endif

namespace password_manager {

// Extra information about InsecureCredential which is required by UI.
struct CredentialMetadata {
  std::vector<PasswordForm> forms;
  InsecureCredentialTypeFlags type = InsecureCredentialTypeFlags::kSecure;
  base::Time latest_time;
  IsMuted is_muted;
};

namespace {

using CredentialPasswordsMap =
    std::map<CredentialView, CredentialMetadata, PasswordCredentialLess>;

// Transparent comparator that can compare InsecureCredential and
// PasswordForm.
struct CredentialWithoutPasswordLess {
  template <typename T, typename U>
  bool operator()(const T& lhs, const U& rhs) const {
    return CredentialOriginAndUsernameAndStore(lhs) <
           CredentialOriginAndUsernameAndStore(rhs);
  }

  using is_transparent = void;

 private:
  static auto CredentialOriginAndUsernameAndStore(const PasswordForm& form) {
    return std::tie(form.signon_realm, form.username_value, form.in_store);
  }

  static auto CredentialOriginAndUsernameAndStore(const InsecureCredential& c) {
    return std::tie(c.signon_realm, c.username, c.in_store);
  }
};

InsecureCredentialTypeFlags ConvertInsecureType(InsecureType type) {
  switch (type) {
    case InsecureType::kLeaked:
      return InsecureCredentialTypeFlags::kCredentialLeaked;
    case InsecureType::kPhished:
      return InsecureCredentialTypeFlags::kCredentialPhished;
    case InsecureType::kWeak:
      return InsecureCredentialTypeFlags::kWeakCredential;
    case InsecureType::kReused:
      return InsecureCredentialTypeFlags::kReusedCredential;
  }
  NOTREACHED();
}

bool IsPasswordFormLeaked(const PasswordForm& form) {
  return form.password_issues.find(InsecureType::kLeaked) !=
         form.password_issues.end();
}

bool IsPasswordFormPhished(const PasswordForm& form) {
  return form.password_issues.find(InsecureType::kPhished) !=
         form.password_issues.end();
}

// This function takes two lists: weak passwords and saved passwords and joins
// them, producing a map that contains CredentialWithPassword as keys and
// vector<PasswordForm> as values.
CredentialPasswordsMap GetInsecureCredentialsFromPasswords(
    const base::flat_set<std::u16string>& weak_passwords,
    SavedPasswordsPresenter::SavedPasswordsView saved_passwords) {
  CredentialPasswordsMap credentials_to_forms;

  bool mark_all_credentials_leaked_for_testing =
      base::GetFieldTrialParamByFeatureAsBool(
          password_manager::features::kPasswordChangeInSettings,
          password_manager::features::
              kPasswordChangeInSettingsWithForcedWarningForEverySite,
          false);
  if (mark_all_credentials_leaked_for_testing) {
    for (const auto& form : saved_passwords) {
      CredentialView insecure_credential(form);
      auto& credential_to_form = credentials_to_forms[insecure_credential];
      credential_to_form.type = InsecureCredentialTypeFlags::kCredentialLeaked;
      credential_to_form.forms.push_back(form);
      credential_to_form.latest_time = form.date_created;
    }
    return credentials_to_forms;
  }

  for (const auto& form : saved_passwords) {
    if (IsPasswordFormLeaked(form) || IsPasswordFormPhished(form)) {
      CredentialView insecure_credential(form);
      auto& credential_to_form = credentials_to_forms[insecure_credential];
      for (const auto& pair : form.password_issues) {
        credential_to_form.type |= ConvertInsecureType(pair.first);
        credential_to_form.latest_time =
            std::max(credential_to_form.latest_time, pair.second.create_time);
        credential_to_form.is_muted = pair.second.is_muted;
      }
      // Populate the map. The values are vectors, because it is
      // possible that multiple saved passwords match to the same
      // insecure credential.
      credential_to_form.forms.push_back(form);
    }
    if (weak_passwords.contains(form.password_value)) {
      CredentialView weak_credential(form);
      auto& credential_to_form = credentials_to_forms[weak_credential];
      credential_to_form.type |= InsecureCredentialTypeFlags::kWeakCredential;

      // This helps not to create a copy of the |form| in case the credential
      // has also been insecure. This is important because we don't want to
      // delete the form twice in the RemoveCredential.
      if (!IsInsecure(credential_to_form.type)) {
        credential_to_form.forms.push_back(form);
      }
    }
  }

  return credentials_to_forms;
}

std::vector<CredentialWithPassword> ExtractInsecureCredentials(
    const CredentialPasswordsMap& credentials_to_forms,
    bool (*condition)(const InsecureCredentialTypeFlags&)) {
  std::vector<CredentialWithPassword> credentials;
  for (const auto& credential_to_forms : credentials_to_forms) {
    if (condition(credential_to_forms.second.type)) {
      CredentialWithPassword credential(credential_to_forms.first);
      credential.insecure_type = credential_to_forms.second.type;
      credential.create_time = credential_to_forms.second.latest_time;
      credential.is_muted = credential_to_forms.second.is_muted;
      credentials.push_back(std::move(credential));
    }
  }
  return credentials;
}

// The function is only used by the weak check.
#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
base::flat_set<std::u16string> ExtractPasswords(
    SavedPasswordsPresenter::SavedPasswordsView password_forms) {
  return base::MakeFlatSet<std::u16string>(password_forms, {},
                                           &PasswordForm::password_value);
}
#endif  // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)

}  // namespace

CredentialView::CredentialView(std::string signon_realm,
                               GURL url,
                               std::u16string username,
                               std::u16string password,
                               base::Time last_used_time)
    : signon_realm(std::move(signon_realm)),
      url(std::move(url)),
      username(std::move(username)),
      password(std::move(password)),
      last_used_time(last_used_time) {}

CredentialView::CredentialView(const PasswordForm& form)
    : signon_realm(form.signon_realm),
      url(form.url),
      username(form.username_value),
      password(form.password_value),
      last_used_time(form.date_last_used) {}

CredentialView::CredentialView(const CredentialView& credential) = default;
CredentialView::CredentialView(CredentialView&& credential) = default;
CredentialView& CredentialView::operator=(const CredentialView& credential) =
    default;
CredentialView& CredentialView::operator=(CredentialView&& credential) =
    default;
CredentialView::~CredentialView() = default;

CredentialWithPassword::CredentialWithPassword(const CredentialView& credential)
    : CredentialView(credential) {}
CredentialWithPassword::~CredentialWithPassword() = default;
CredentialWithPassword::CredentialWithPassword(
    const CredentialWithPassword& other) = default;

CredentialWithPassword::CredentialWithPassword(CredentialWithPassword&& other) =
    default;
CredentialWithPassword::CredentialWithPassword(
    const InsecureCredential& credential)
    : CredentialView(credential.signon_realm,
                     GURL(credential.signon_realm),
                     credential.username,
                     /*password=*/{},
                     /*last_used_time=*/base::Time()),
      create_time(credential.create_time),
      insecure_type(ConvertInsecureType(credential.insecure_type)),
      is_muted(credential.is_muted) {}

CredentialWithPassword& CredentialWithPassword::operator=(
    const CredentialWithPassword& other) = default;
CredentialWithPassword& CredentialWithPassword::operator=(
    CredentialWithPassword&& other) = default;

InsecureCredentialsManager::InsecureCredentialsManager(
    SavedPasswordsPresenter* presenter,
    scoped_refptr<PasswordStoreInterface> profile_store,
    scoped_refptr<PasswordStoreInterface> account_store)
    : presenter_(presenter),
      profile_store_(std::move(profile_store)),
      account_store_(std::move(account_store)) {
  observed_saved_password_presenter_.Observe(presenter_.get());
}

InsecureCredentialsManager::~InsecureCredentialsManager() = default;

void InsecureCredentialsManager::Init() {}

#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
void InsecureCredentialsManager::StartWeakCheck(
    base::OnceClosure on_check_done) {
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
      base::BindOnce(&BulkWeakCheck,
                     ExtractPasswords(presenter_->GetSavedPasswords())),
      base::BindOnce(&InsecureCredentialsManager::OnWeakCheckDone,
                     weak_ptr_factory_.GetWeakPtr(), base::ElapsedTimer())
          .Then(std::move(on_check_done)));
}
#endif  // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)

void InsecureCredentialsManager::SaveInsecureCredential(
    const LeakCheckCredential& credential) {
  // Iterate over all currently saved credentials and mark those as insecure
  // that have the same canonicalized username and password.
  const std::u16string canonicalized_username =
      CanonicalizeUsername(credential.username());
  for (const PasswordForm& saved_password : presenter_->GetSavedPasswords()) {
    if (saved_password.password_value == credential.password() &&
        CanonicalizeUsername(saved_password.username_value) ==
            canonicalized_username &&
        !saved_password.password_issues.contains(InsecureType::kLeaked)) {
      PasswordForm form_to_update = saved_password;
      form_to_update.password_issues.insert_or_assign(
          InsecureType::kLeaked,
          InsecurityMetadata(base::Time::Now(), IsMuted(false)));
      GetStoreFor(saved_password).UpdateLogin(form_to_update);
    }
  }
}

bool InsecureCredentialsManager::MuteCredential(
    const CredentialView& credential) {
  auto it = credentials_to_forms_.find(credential);
  if (it == credentials_to_forms_.end())
    return false;

  // Mute all matching compromised credentials from the store.
  // For a match, all insecureity types saved in the store are muted.
  // Return whether any credentials were muted.
  const auto& saved_passwords = it->second.forms;
  bool muted = false;
  for (const PasswordForm& saved_password : saved_passwords) {
    PasswordForm form_to_update = saved_password;
    bool form_changed = false;
    for (const auto& password_issue : saved_password.password_issues) {
      if (!password_issue.second.is_muted.value()) {
        form_to_update.password_issues.insert_or_assign(
            password_issue.first,
            InsecurityMetadata(password_issue.second.create_time,
                               IsMuted(true)));
        form_changed = true;
      }
    }
    if (form_changed) {
      GetStoreFor(saved_password).UpdateLogin(form_to_update);
      muted = true;
    }
  }
  return muted;
}

bool InsecureCredentialsManager::UnmuteCredential(
    const CredentialView& credential) {
  auto it = credentials_to_forms_.find(credential);
  if (it == credentials_to_forms_.end())
    return false;

  // Unmute all matching compromised credentials from the store.
  // For a match, all insecureity types saved in the store are unmuted.
  // Return whether any credentials were unmuted.
  const auto& saved_passwords = it->second.forms;
  bool unmuted = false;

  for (const PasswordForm& saved_password : saved_passwords) {
    PasswordForm form_to_update = saved_password;
    bool form_changed = false;
    for (const auto& password_issue : saved_password.password_issues) {
      if (password_issue.second.is_muted.value()) {
        form_to_update.password_issues.insert_or_assign(
            password_issue.first,
            InsecurityMetadata(password_issue.second.create_time,
                               IsMuted(false)));
        form_changed = true;
      }
    }
    if (form_changed) {
      GetStoreFor(saved_password).UpdateLogin(form_to_update);
      unmuted = true;
    }
  }
  return unmuted;
}

bool InsecureCredentialsManager::UpdateCredential(
    const CredentialView& credential,
    const base::StringPiece password) {
  auto it = credentials_to_forms_.find(credential);
  if (it == credentials_to_forms_.end())
    return false;

  // Make sure there are matching password forms. Also erase duplicates if there
  // are any.
  const auto& forms = it->second.forms;
  if (forms.empty())
    return false;

  for (size_t i = 1; i < forms.size(); ++i)
    GetStoreFor(forms[i]).RemoveLogin(forms[i]);

  // Note: We Invoke EditPassword on the presenter rather than UpdateLogin() on
  // the store, so that observers of the presenter get notified of this event.
  return presenter_->EditPassword(forms[0], base::UTF8ToUTF16(password));
}

bool InsecureCredentialsManager::RemoveCredential(
    const CredentialView& credential) {
  auto it = credentials_to_forms_.find(credential);
  if (it == credentials_to_forms_.end())
    return false;

  // Erase all matching credentials from the store. Return whether any
  // credentials were deleted.
  const auto& saved_passwords = it->second.forms;
  for (const PasswordForm& saved_password : saved_passwords)
    GetStoreFor(saved_password).RemoveLogin(saved_password);

  return !saved_passwords.empty();
}

std::vector<CredentialWithPassword>
InsecureCredentialsManager::GetInsecureCredentials() const {
  return ExtractInsecureCredentials(credentials_to_forms_, &IsInsecure);
}

std::vector<CredentialWithPassword>
InsecureCredentialsManager::GetWeakCredentials() const {
  std::vector<CredentialWithPassword> weak_credentials =
      ExtractInsecureCredentials(credentials_to_forms_, &IsWeak);

  auto get_sort_key = [this](const CredentialWithPassword& credential) {
    return CreateSortKey(GetSavedPasswordsFor(credential)[0],
                         IgnoreStore(true));
  };
  base::ranges::sort(weak_credentials, {}, get_sort_key);
  return weak_credentials;
}

SavedPasswordsPresenter::SavedPasswordsView
InsecureCredentialsManager::GetSavedPasswordsFor(
    const CredentialView& credential) const {
  auto it = credentials_to_forms_.find(credential);
  return it != credentials_to_forms_.end()
             ? it->second.forms
             : SavedPasswordsPresenter::SavedPasswordsView();
}

void InsecureCredentialsManager::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void InsecureCredentialsManager::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

void InsecureCredentialsManager::UpdateInsecureCredentials() {
  credentials_to_forms_ = GetInsecureCredentialsFromPasswords(
      weak_passwords_, presenter_->GetSavedPasswords());
}

void InsecureCredentialsManager::OnWeakCheckDone(
    base::ElapsedTimer timer_since_weak_check_start,
    base::flat_set<std::u16string> weak_passwords) {
  base::UmaHistogramTimes("PasswordManager.WeakCheck.Time",
                          timer_since_weak_check_start.Elapsed());
  weak_passwords_ = std::move(weak_passwords);
  UpdateInsecureCredentials();
  NotifyWeakCredentialsChanged();
}

void InsecureCredentialsManager::OnEdited(const PasswordForm& form) {
  // The WeakCheck is a Desktop only feature for now. Disable on Mobile to avoid
  // pulling in a big dependency on zxcvbn.
#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
  const std::u16string& password = form.password_value;
  if (weak_passwords_.contains(password) || !IsWeak(password)) {
    // Either the password is already known to be weak, or it is not weak at
    // all. In both cases there is nothing to do.
    return;
  }

  weak_passwords_.insert(password);
  UpdateInsecureCredentials();
  NotifyWeakCredentialsChanged();
#endif
}

// Re-computes the list of insecure credentials with passwords after obtaining a
// new list of saved passwords.
void InsecureCredentialsManager::OnSavedPasswordsChanged(
    SavedPasswordsPresenter::SavedPasswordsView saved_passwords) {
  credentials_to_forms_ =
      GetInsecureCredentialsFromPasswords(weak_passwords_, saved_passwords);
  NotifyInsecureCredentialsChanged();
  NotifyWeakCredentialsChanged();
}

void InsecureCredentialsManager::NotifyInsecureCredentialsChanged() {
  std::vector<CredentialWithPassword> insecure_credentials =
      ExtractInsecureCredentials(credentials_to_forms_, &IsInsecure);
  for (auto& observer : observers_) {
    observer.OnInsecureCredentialsChanged(insecure_credentials);
  }
}

void InsecureCredentialsManager::NotifyWeakCredentialsChanged() {
  for (auto& observer : observers_) {
    observer.OnWeakCredentialsChanged();
  }
}

PasswordStoreInterface& InsecureCredentialsManager::GetStoreFor(
    const PasswordForm& form) {
  return form.IsUsingAccountStore() ? *account_store_ : *profile_store_;
}

}  // namespace password_manager