File: chaps_util_impl.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (275 lines) | stat: -rw-r--r-- 10,138 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
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
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/chaps_util/chaps_util_impl.h"

#include <dlfcn.h>
#include <keyhi.h>
#include <pk11pub.h>
#include <pkcs11.h>
#include <pkcs11t.h>
#include <stdint.h>

#include <optional>
#include <ostream>
#include <string>
#include <string_view>
#include <vector>

#include "base/check.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "chromeos/ash/components/chaps_util/chaps_slot_session.h"
#include "crypto/chaps_support.h"
#include "crypto/scoped_nss_types.h"
#include "third_party/boringssl/src/include/openssl/base.h"
#include "third_party/boringssl/src/include/openssl/mem.h"
#include "third_party/boringssl/src/include/openssl/pkcs8.h"
#include "third_party/boringssl/src/include/openssl/stack.h"

namespace chromeos {

namespace {

// TODO(b/202374261): Move these into a shared header.
// Signals to chaps that a generated key should be software-backed.
constexpr CK_ATTRIBUTE_TYPE kForceSoftwareAttribute = CKA_VENDOR_DEFINED + 4;
// Chaps sets this for keys that are software-backed.
constexpr CK_ATTRIBUTE_TYPE kKeyInSoftware = CKA_VENDOR_DEFINED + 5;
struct KeyPairHandles {
  CK_OBJECT_HANDLE public_key;
  CK_OBJECT_HANDLE private_key;
};

using Pkcs11Operation = base::RepeatingCallback<CK_RV()>;

// Performs |operation| and handles return values indicating that the PKCS11
// session has been closed by attempting to re-open the |chaps_session|.
// This is useful because the session could be closed e.g. because NSS could
// have called C_CloseAllSessions.
bool PerformWithRetries(ChapsSlotSession* chaps_session,
                        std::string_view operation_name,
                        const Pkcs11Operation& operation) {
  const int kMaxAttempts = 5;

  for (int attempt = 0; attempt < kMaxAttempts; ++attempt) {
    CK_RV result = operation.Run();
    if (result == CKR_OK) {
      return true;
    }
    if (result != CKR_SESSION_HANDLE_INVALID && result != CKR_SESSION_CLOSED) {
      LOG(ERROR) << operation_name << " failed with " << result;
      return false;
    }
    if (!chaps_session->ReopenSession()) {
      return false;
    }
  }
  LOG(ERROR) << operation_name << " failed";
  return false;
}

// Uses |chaps_session| to generate a software-backed RSA key pair with modulus
// length |num_bits|.
std::optional<KeyPairHandles> GenerateSoftwareBackedRSAKeyPair(
    ChapsSlotSession* chaps_session,
    uint16_t num_bits) {
  CK_ULONG modulus_bits = num_bits;
  CK_BBOOL true_value = CK_TRUE;
  CK_BBOOL false_value = CK_FALSE;
  CK_BYTE public_exponent[3] = {0x01, 0x00, 0x01};  // 65537

  // Public key attributes
  // Note: CKA_ID is set later (computed from the public key modulus) and
  // CKA_LABEL is not set to match NSS behavior
  // (https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/PKCS11_Implement).
  CK_ATTRIBUTE pub_attributes[] = {
      {CKA_TOKEN, &true_value, sizeof(true_value)},
      {CKA_PRIVATE, &false_value, sizeof(false_value)},
      {CKA_VERIFY, &true_value, sizeof(true_value)},
      {CKA_MODULUS_BITS, &modulus_bits, sizeof(modulus_bits)},
      {CKA_PUBLIC_EXPONENT, public_exponent, sizeof(public_exponent)}};

  // Private key attributes
  // Note: CKA_ID is set later (computed from the public key modulus) and
  // CKA_LABEL is not set to match NSS behavior
  // (https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/PKCS11_Implement).
  CK_ATTRIBUTE priv_attributes[] = {
      {CKA_TOKEN, &true_value, sizeof(true_value)},
      {CKA_PRIVATE, &true_value, sizeof(true_value)},
      {CKA_SENSITIVE, &true_value, sizeof(true_value)},
      {CKA_EXTRACTABLE, &false_value, sizeof(false_value)},
      {kForceSoftwareAttribute, &true_value, sizeof(true_value)},
      {CKA_SIGN, &true_value, sizeof(true_value)}};
  CK_MECHANISM mechanism = {CKM_RSA_PKCS_KEY_PAIR_GEN, /* pParameter */ nullptr,
                            /* ulParameterLen*/ 0};

  KeyPairHandles key_pair;

  if (!PerformWithRetries(
          chaps_session, "GenerateKeyPair",
          base::BindRepeating(&ChapsSlotSession::GenerateKeyPair,
                              base::Unretained(chaps_session), &mechanism,
                              pub_attributes, std::size(pub_attributes),
                              priv_attributes, std::size(priv_attributes),
                              &(key_pair.public_key),
                              &(key_pair.private_key)))) {
    return {};
  }
  return key_pair;
}

// Read the modulus of the public key identified by |pub_key_handle| and return
// it.
std::optional<std::vector<CK_BYTE>> ExtractModulus(
    ChapsSlotSession* chaps_session,
    CK_OBJECT_HANDLE pub_key_handle) {
  std::vector<CK_BYTE> modulus(256);
  CK_ATTRIBUTE attrs_get_modulus[] = {
      {CKA_MODULUS, modulus.data(), modulus.size()}};
  if (!PerformWithRetries(
          chaps_session, "GetAttributeValue",
          base::BindRepeating(&ChapsSlotSession::GetAttributeValue,
                              base::Unretained(chaps_session), pub_key_handle,
                              attrs_get_modulus,
                              std::size(attrs_get_modulus)))) {
    return {};
  }
  return modulus;
}

crypto::ScopedSECItem MakeIdFromPubKeyNss(
    const std::vector<uint8_t>& public_key_bytes) {
  SECItem secitem_modulus;
  secitem_modulus.data = const_cast<uint8_t*>(public_key_bytes.data());
  secitem_modulus.len = public_key_bytes.size();
  return crypto::ScopedSECItem(PK11_MakeIDFromPubKey(&secitem_modulus));
}

// Read the modulus of the public key identified by |pub_key_handle| and return
// it.
std::optional<bool> IsKeySoftwareBacked(ChapsSlotSession* chaps_session,
                                        CK_OBJECT_HANDLE private_key_handle) {
  CK_BBOOL key_in_software = CK_FALSE;
  CK_ATTRIBUTE attrs_get_key_in_software[] = {
      {kKeyInSoftware, &key_in_software, sizeof(key_in_software)}};
  if (!PerformWithRetries(
          chaps_session, "GetAttributeValue",
          base::BindRepeating(&ChapsSlotSession::GetAttributeValue,
                              base::Unretained(chaps_session),
                              private_key_handle, attrs_get_key_in_software,
                              std::size(attrs_get_key_in_software)))) {
    return {};
  }
  return key_in_software;
}

// Create the CKA_ID value that NSS would use for |key_pair| and return it.
crypto::ScopedSECItem CreateNssCkaId(ChapsSlotSession* chaps_session,
                                     const KeyPairHandles& key_pair) {
  auto modulus = ExtractModulus(chaps_session, key_pair.public_key);
  if (!modulus) {
    return nullptr;
  }
  return MakeIdFromPubKeyNss(modulus.value());
}

// Set the CKA_ID attribute of the public and private key objects in |key_pair|
// to |cka_id|.
bool SetCkaId(ChapsSlotSession* chaps_session,
              KeyPairHandles& key_pair,
              SECItem* cka_id) {
  CK_ATTRIBUTE attrs_set_id[] = {{CKA_ID, cka_id->data, cka_id->len}};
  if (!PerformWithRetries(
          chaps_session, "SetAttributeValue",
          base::BindRepeating(&ChapsSlotSession::SetAttributeValue,
                              base::Unretained(chaps_session),
                              key_pair.private_key, attrs_set_id,
                              std::size(attrs_set_id)))) {
    return false;
  }
  if (!PerformWithRetries(
          chaps_session, "SetAttributeValue",
          base::BindRepeating(&ChapsSlotSession::SetAttributeValue,
                              base::Unretained(chaps_session),
                              key_pair.public_key, attrs_set_id,
                              std::size(attrs_set_id)))) {
    return false;
  }
  return true;
}

}  // namespace

ChapsUtilImpl::ChapsUtilImpl(
    std::unique_ptr<ChapsSlotSessionFactory> chaps_slot_session_factory)
    : chaps_slot_session_factory_(std::move(chaps_slot_session_factory)) {}
ChapsUtilImpl::~ChapsUtilImpl() = default;

bool ChapsUtilImpl::GenerateSoftwareBackedRSAKey(
    PK11SlotInfo* slot,
    uint16_t num_bits,
    crypto::ScopedSECKEYPublicKey* out_public_key,
    crypto::ScopedSECKEYPrivateKey* out_private_key) {
  DCHECK(out_public_key);
  DCHECK(out_private_key);

  std::unique_ptr<ChapsSlotSession> chaps_session =
      GetChapsSlotSessionForSlot(slot);
  if (!chaps_session) {
    return false;
  }

  std::optional<KeyPairHandles> key_pair =
      GenerateSoftwareBackedRSAKeyPair(chaps_session.get(), num_bits);
  if (!key_pair) {
    return false;
  }

  // Safety check that software-backed key generation was triggered.
  std::optional<bool> is_software_backed =
      IsKeySoftwareBacked(chaps_session.get(), key_pair->private_key);
  if (!is_software_backed || !is_software_backed.value()) {
    return false;
  }

  crypto::ScopedSECItem cka_id =
      CreateNssCkaId(chaps_session.get(), key_pair.value());
  if (!cka_id) {
    return false;
  }
  if (!SetCkaId(chaps_session.get(), key_pair.value(), cka_id.get())) {
    return false;
  }

  out_private_key->reset(PK11_FindKeyByKeyID(slot, cka_id.get(), nullptr));
  if (!*out_private_key) {
    LOG(ERROR) << "Failed to find private key.";
    return false;
  }
  out_public_key->reset(SECKEY_ConvertToPublicKey(out_private_key->get()));
  if (!*out_public_key) {
    LOG(ERROR) << "Failed to extract public key.";
    return false;
  }
  return true;
}

std::unique_ptr<ChapsSlotSession> ChapsUtilImpl::GetChapsSlotSessionForSlot(
    PK11SlotInfo* slot) {
  if (!slot || (!is_chaps_provided_slot_for_testing_ &&
                !crypto::IsSlotProvidedByChaps(slot))) {
    return nullptr;
  }

  // Note that ChapsSlotSession(Factory) expects something else to have called
  // C_Initialize. It is a safe assumption that NSS has called C_Initialize for
  // chaps if |slot| is actually a chaps-provided slot, which is verified above.
  return chaps_slot_session_factory_->CreateChapsSlotSession(
      PK11_GetSlotID(slot));
}

}  // namespace chromeos