File: kcer_rollback_helper.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (228 lines) | stat: -rw-r--r-- 8,369 bytes parent folder | download | duplicates (6)
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
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/kcer/nssdb_migration/kcer_rollback_helper.h"

#include <optional>

#include "ash/constants/ash_features.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/task/bind_post_task.h"
#include "chrome/common/pref_names.h"
#include "chromeos/ash/components/tpm/tpm_token_info_getter.h"
#include "chromeos/constants/chromeos_features.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_manager.h"
#include "content/public/browser/browser_thread.h"
#include "crypto/chaps_support.h"

namespace kcer::internal {
namespace {
const char kDefaultErrorMessage[] = "NssDbClientCertsRollback aborted ";
const char kNssDbClientCertsRollbackMessage[] = "NssDbClientCertsRollback ";

extern "C" SECStatus PK11_ClearCertsCache(PK11SlotInfo* slot_info)
    __attribute__((weak));

NssDbClientCertsRollbackEvent GetListSizeEvent(
    const std::vector<SessionChapsClient::ObjectHandle>& handles_list) {
  switch (handles_list.size()) {
    case 0u:
      return NssDbClientCertsRollbackEvent::kRollbackListSize0;
    case 1u:
      return NssDbClientCertsRollbackEvent::kRollbackListSize1;
    case 2u:
      return NssDbClientCertsRollbackEvent::kRollbackListSize2;
    case 3u:
      return NssDbClientCertsRollbackEvent::kRollbackListSize3;
    default:
      return NssDbClientCertsRollbackEvent::kRollbackListSizeAbove3;
  }
}
}  // namespace

void RecordUmaEvent(NssDbClientCertsRollbackEvent event) {
  base::UmaHistogramEnumeration(kNssDbClientCertsRollback, event);
}

void ResetCertCacheData(SessionChapsClient::SlotId slot_id) {
  if (!PK11_ClearCertsCache) {
    return;
  }
  crypto::ScopedPK11SlotList slot_list(PK11_GetAllTokens(
      CKM_INVALID_MECHANISM, PR_FALSE, PR_FALSE, /**wincx*/ nullptr));
  if (!slot_list) {
    return;
  }
  for (PK11SlotListElement* elem = slot_list->head; elem; elem = elem->next) {
    crypto::ScopedPK11Slot slot_info =
        crypto::ScopedPK11Slot(PK11_ReferenceSlot(elem->slot));

    if (!crypto::IsSlotProvidedByChaps(slot_info.get())) {
      continue;
    }

    kcer::SessionChapsClient::SlotId cur_slot_id =
        kcer::SessionChapsClient::SlotId(PK11_GetSlotID(slot_info.get()));

    if (slot_id == cur_slot_id) {
      SECStatus result = PK11_ClearCertsCache(slot_info.get());
      if (result != SECSuccess) {
        RecordUmaEvent(NssDbClientCertsRollbackEvent::kCertCacheResetFailed);
        LOG(ERROR) << "Resetting slot certificates cache has failed with:"
                   << result;
      } else {
        RecordUmaEvent(
            NssDbClientCertsRollbackEvent::kCertCacheResetSuccessful);
      }
      break;
    }
  }
}

KcerRollbackHelper::KcerRollbackHelper(
    HighLevelChapsClient* high_level_chaps_client,
    PrefService* prefs_service)
    : high_level_chaps_client_(high_level_chaps_client),
      prefs_service_(prefs_service) {}

KcerRollbackHelper::~KcerRollbackHelper() = default;

// static
bool KcerRollbackHelper::IsChapsRollbackRequired(PrefService* pref_service) {
  if (!pref_service) {
    return false;
  }
  bool is_only_rollback_active =
      ash::features::IsNssDbClientCertsRollbackEnabled() &&
      !chromeos::features::IsPkcs12ToChapsDualWriteEnabled();

  if (is_only_rollback_active) {
    const PrefService::Preference* rollback_flag =
        pref_service->FindPreference(prefs::kNssChapsDualWrittenCertsExist);
    if (!rollback_flag) {
      RecordUmaEvent(NssDbClientCertsRollbackEvent::kRollbackFlagNotPresent);
      return false;
    }
    RecordUmaEvent(NssDbClientCertsRollbackEvent::kRollbackFlagPresent);
    return rollback_flag->GetValue()->GetBool();
  }
  return false;
}

std::optional<AccountId> GetAccountId() {
  if (!user_manager::UserManager::IsInitialized()) {
    LOG(ERROR) << kDefaultErrorMessage << "user manager is not initialised!";
    return std::nullopt;
  }

  const user_manager::User* active_user =
      user_manager::UserManager::Get()->GetActiveUser();
  if (!active_user) {
    LOG(ERROR) << kDefaultErrorMessage << "no active user!";
    return std::nullopt;
  }
  return std::make_optional(active_user->GetAccountId());
}

void KcerRollbackHelper::PerformRollback() const {
  RecordUmaEvent(NssDbClientCertsRollbackEvent::kRollbackScheduled);
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&KcerRollbackHelper::FindUserToken,
                     weak_factory_.GetWeakPtr()),
      base::Seconds(30));
}

void KcerRollbackHelper::FindUserToken() const {
  RecordUmaEvent(NssDbClientCertsRollbackEvent::kRollbackStarted);
  std::optional<AccountId> account_id = GetAccountId();
  if (!account_id.has_value()) {
    LOG(ERROR) << kDefaultErrorMessage << "no account_id";
    RecordUmaEvent(NssDbClientCertsRollbackEvent::kFailedNoUserAccountId);
    return;
  }

  std::unique_ptr<ash::TPMTokenInfoGetter> scoped_user_token_info_getter =
      ash::TPMTokenInfoGetter::CreateForUserToken(
          account_id.value(), ash::CryptohomePkcs11Client::Get(),
          base::SingleThreadTaskRunner::GetCurrentDefault());

  ash::TPMTokenInfoGetter* user_token_info_getter =
      scoped_user_token_info_getter.get();
  // Pass scoped_user_token_info_getter to keep it alive.
  user_token_info_getter->Start(base::BindOnce(
      &KcerRollbackHelper::FindUserSlotId, weak_factory_.GetWeakPtr(),
      std::move(scoped_user_token_info_getter)));
}

void KcerRollbackHelper::FindUserSlotId(
    std::unique_ptr<ash::TPMTokenInfoGetter> scoped_user_token_info_getter,
    std::optional<user_data_auth::TpmTokenInfo> user_token_info) const {
  SessionChapsClient::SlotId user_slot_id;
  if (user_token_info) {
    user_slot_id = SessionChapsClient::SlotId(
        static_cast<uint64_t>(user_token_info->slot()));
  } else {
    LOG(ERROR) << kDefaultErrorMessage << "no slot info was found";
    RecordUmaEvent(NssDbClientCertsRollbackEvent::kFailedNoSlotInfoFound);
    return;
  }
  SelectAndDeleteDoubleWrittenObjects(user_slot_id);
}

void KcerRollbackHelper::SelectAndDeleteDoubleWrittenObjects(
    SessionChapsClient::SlotId slot_id) const {
  constexpr chromeos::PKCS11_CK_BBOOL kTrue = chromeos::PKCS11_CK_TRUE;

  chaps::AttributeList attributes;
  kcer::AddAttribute(attributes,
                     pkcs11_custom_attributes::kCkaChromeOsMigratedFromNss,
                     kcer::MakeSpan(&kTrue));

  SessionChapsClient::FindObjectsCallback find_callback =
      base::BindOnce(&KcerRollbackHelper::DestroyObjectsInSlot,
                     weak_factory_.GetWeakPtr(), slot_id);
  return high_level_chaps_client_->FindObjects(slot_id, std::move(attributes),
                                               std::move(find_callback));
}

void KcerRollbackHelper::DestroyObjectsInSlot(
    SessionChapsClient::SlotId slot_id,
    std::vector<SessionChapsClient::ObjectHandle> handles_list,
    uint32_t result_code) const {
  RecordUmaEvent(GetListSizeEvent(handles_list));
  SessionChapsClient::DestroyObjectCallback destroy_objects_callback =
      base::BindOnce(&KcerRollbackHelper::ResetCacheAndRollbackFlag,
                     weak_factory_.GetWeakPtr(), slot_id);

  return high_level_chaps_client_->DestroyObjectsWithRetries(
      slot_id, handles_list, std::move(destroy_objects_callback));
}

void KcerRollbackHelper::ResetCacheAndRollbackFlag(
    SessionChapsClient::SlotId slot_id,
    uint32_t result_code) const {
  ResetCertCacheData(slot_id);
  if (result_code != chromeos::PKCS11_CKR_OK) {
    LOG(ERROR) << "Not all objects were deleted due to" << result_code;
    RecordUmaEvent(NssDbClientCertsRollbackEvent::kFailedNotAllObjectsDeleted);
    return;
  }

  const PrefService::Preference* rollback_flag =
      prefs_service_->FindPreference(prefs::kNssChapsDualWrittenCertsExist);
  if (!rollback_flag) {
    LOG(ERROR) << "Resetting " << kNssDbClientCertsRollbackMessage
               << "flag while it was not set";
    RecordUmaEvent(
        NssDbClientCertsRollbackEvent::kFailedFlagResetNotSuccessful);
    return;
  }
  prefs_service_->ClearPref(prefs::kNssChapsDualWrittenCertsExist);
  RecordUmaEvent(NssDbClientCertsRollbackEvent::kRollbackSuccessful);
}

}  // namespace kcer::internal