File: cert_provisioning_serializer.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 6,122,156 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 (428 lines) | stat: -rw-r--r-- 15,719 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
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
// Copyright 2020 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/cert_provisioning/cert_provisioning_serializer.h"

#include <optional>
#include <string>

#include "base/base64.h"
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "base/time/time.h"
#include "chrome/browser/ash/cert_provisioning/cert_provisioning_common.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"

namespace ash {
namespace cert_provisioning {

namespace {

constexpr char kKeyNameProcessId[] = "process_id";
constexpr char kKeyNameCertScope[] = "cert_scope";
constexpr char kKeyNameCertProfile[] = "cert_profile";
constexpr char kKeyNameState[] = "state";
constexpr char kKeyNamePublicKey[] = "public_key";
constexpr char kKeyNameInvalidationTopic[] = "invalidation_topic";
constexpr char kKeyNameKeyLocation[] = "key_location";
constexpr char kKeyNameAttemptedVaChallenge[] = "attempted_va_challenge";
constexpr char kKeyNameAttemptedProofOfPossession[] =
    "attempted_proof_of_possession";
constexpr char kKeyNameProofOfPossessionSignature[] =
    "proof_of_possession_signature";

constexpr char kKeyNameCertProfileId[] = "profile_id";
constexpr char kKeyNameCertProfileName[] = "name";
constexpr char kKeyNameCertProfileVersion[] = "policy_version";
constexpr char kKeyNameCertProfileProtocolVersion[] = "protocol_version";
constexpr char kKeyNameCertProfileVaEnabled[] = "va_enabled";
constexpr char kKeyNameCertProfileRenewalPeriod[] = "renewal_period";
constexpr char kKeyNameCertProfileKeyType[] = "key_type";

template <typename T>
bool ConvertToEnum(int value, T* dst) {
  if ((value < 0) || (value > static_cast<int>(T::kMaxValue))) {
    return false;
  }
  *dst = static_cast<T>(value);
  return true;
}

template <typename T>
bool DeserializeEnumValue(const base::Value::Dict& parent_dict,
                          const char* value_name,
                          T* dst) {
  std::optional<int> serialized_enum = parent_dict.FindInt(value_name);
  if (!serialized_enum.has_value()) {
    return false;
  }
  return ConvertToEnum<T>(*serialized_enum, dst);
}

bool DeserializeStringValue(const base::Value::Dict& parent_dict,
                            const char* value_name,
                            std::string* dst) {
  const std::string* serialized_string = parent_dict.FindString(value_name);
  if (!serialized_string) {
    return false;
  }
  *dst = *serialized_string;
  return true;
}

bool DeserializeBoolValue(const base::Value::Dict& parent_dict,
                          const char* value_name,
                          bool* dst) {
  std::optional<bool> serialized_bool = parent_dict.FindBool(value_name);
  if (!serialized_bool.has_value()) {
    return false;
  }
  *dst = *serialized_bool;
  return true;
}

bool DeserializeRenewalPeriod(const base::Value::Dict& parent_dict,
                              const char* value_name,
                              base::TimeDelta* dst) {
  std::optional<int> serialized_time = parent_dict.FindInt(value_name);
  *dst = base::Seconds(serialized_time.value_or(0));
  return true;
}

bool DeserializeProtocolVersion(const base::Value::Dict& parent_value,
                                const char* value_name,
                                ProtocolVersion* dst) {
  std::optional<int> protocol_version_value = parent_value.FindInt(value_name);
  std::optional<ProtocolVersion> protocol_version =
      ParseProtocolVersion(protocol_version_value);
  if (!protocol_version.has_value()) {
    return false;
  }
  *dst = *protocol_version;
  return true;
}

base::Value::Dict SerializeCertProfile(const CertProfile& profile) {
  static_assert(CertProfile::kVersion == 7, "This function should be updated");

  base::Value::Dict result;
  result.Set(kKeyNameCertProfileId, profile.profile_id);
  result.Set(kKeyNameCertProfileName, profile.name);
  result.Set(kKeyNameCertProfileVersion, profile.policy_version);
  result.Set(kKeyNameCertProfileVaEnabled, profile.is_va_enabled);
  if (profile.protocol_version != ProtocolVersion::kStatic) {
    // Only set the protocol_version and key type if it's not kStatic to avoid
    // changing how "static flow" workers are serialized.
    result.Set(kKeyNameCertProfileProtocolVersion,
               static_cast<int>(profile.protocol_version));
    result.Set(kKeyNameCertProfileKeyType, static_cast<int>(profile.key_type));
  }

  if (!profile.renewal_period.is_zero()) {
    result.Set(kKeyNameCertProfileRenewalPeriod,
               base::saturated_cast<int>(profile.renewal_period.InSeconds()));
  }

  return result;
}

bool DeserializeCertProfile(const base::Value::Dict& parent_dict,
                            const char* value_name,
                            CertProfile* dst) {
  static_assert(CertProfile::kVersion == 7, "This function should be updated");

  const base::Value::Dict* serialized_profile =
      parent_dict.FindDict(value_name);

  if (!serialized_profile) {
    return false;
  }

  bool is_ok = true;
  is_ok = is_ok &&
          DeserializeStringValue(*serialized_profile, kKeyNameCertProfileId,
                                 &(dst->profile_id));
  is_ok =
      is_ok && DeserializeStringValue(*serialized_profile,
                                      kKeyNameCertProfileName, &(dst->name));
  is_ok = is_ok && DeserializeStringValue(*serialized_profile,
                                          kKeyNameCertProfileVersion,
                                          &(dst->policy_version));
  is_ok = is_ok && DeserializeBoolValue(*serialized_profile,
                                        kKeyNameCertProfileVaEnabled,
                                        &(dst->is_va_enabled));
  is_ok = is_ok && DeserializeRenewalPeriod(*serialized_profile,
                                            kKeyNameCertProfileRenewalPeriod,
                                            &(dst->renewal_period));
  is_ok = is_ok && DeserializeProtocolVersion(
                       *serialized_profile, kKeyNameCertProfileProtocolVersion,
                       &(dst->protocol_version));

  // The static protocol does not support key types other than RSA, and should
  // not serialize the key type, so we hardcode it here instead.
  if (is_ok && dst->protocol_version == ProtocolVersion::kStatic) {
    dst->key_type = KeyType::kRsa;
  } else {
    is_ok = is_ok &&
            DeserializeEnumValue(*serialized_profile,
                                 kKeyNameCertProfileKeyType, &(dst->key_type));
  }

  return is_ok;
}

std::string SerializeBase64Encoded(const std::vector<uint8_t>& public_key) {
  return base::Base64Encode(public_key);
}

bool DeserializeBase64Encoded(const base::Value::Dict& parent_dict,
                              const char* value_name,
                              std::vector<uint8_t>* dst) {
  const std::string* serialized_public_key = parent_dict.FindString(value_name);

  if (!serialized_public_key) {
    return false;
  }

  std::optional<std::vector<uint8_t>> public_key =
      base::Base64Decode(*serialized_public_key);
  if (!public_key) {
    return false;
  }
  *dst = std::move(*public_key);

  return true;
}

}  // namespace

void CertProvisioningSerializer::SerializeWorkerToPrefs(
    PrefService* pref_service,
    const CertProvisioningWorkerStatic& worker) {
  ScopedDictPrefUpdate scoped_dict_updater(
      pref_service, GetPrefNameForSerialization(worker.cert_scope_));
  base::Value::Dict& saved_workers = scoped_dict_updater.Get();
  saved_workers.Set(worker.cert_profile_.profile_id, SerializeWorker(worker));
}

void CertProvisioningSerializer::SerializeWorkerToPrefs(
    PrefService* pref_service,
    const CertProvisioningWorkerDynamic& worker) {
  ScopedDictPrefUpdate scoped_dict_updater(
      pref_service, GetPrefNameForSerialization(worker.cert_scope_));
  base::Value::Dict& saved_workers = scoped_dict_updater.Get();
  saved_workers.Set(worker.cert_profile_.profile_id, SerializeWorker(worker));
}

void CertProvisioningSerializer::DeleteWorkerFromPrefs(
    PrefService* pref_service,
    const CertProvisioningWorkerStatic& worker) {
  ScopedDictPrefUpdate scoped_dict_updater(
      pref_service, GetPrefNameForSerialization(worker.cert_scope_));

  base::Value::Dict& saved_workers = scoped_dict_updater.Get();

  saved_workers.Remove(worker.cert_profile_.profile_id);
}

void CertProvisioningSerializer::DeleteWorkerFromPrefs(
    PrefService* pref_service,
    const CertProvisioningWorkerDynamic& worker) {
  ScopedDictPrefUpdate scoped_dict_updater(
      pref_service, GetPrefNameForSerialization(worker.cert_scope_));

  base::Value::Dict& saved_workers = scoped_dict_updater.Get();

  saved_workers.Remove(worker.cert_profile_.profile_id);
}

// Serialization scheme:
// {
//   "cert_scope": <number>,
//   "cert_profile": <CertProfile>,
//   "state": <number>,
//   "public_key": <string>,
//   "invalidation_topic": <string>,
// }
base::Value::Dict CertProvisioningSerializer::SerializeWorker(
    const CertProvisioningWorkerStatic& worker) {
  static_assert(CertProvisioningWorkerStatic::kVersion == 2,
                "This function should be updated");

  base::Value::Dict result;

  result.Set(kKeyNameProcessId, worker.process_id_);
  result.Set(kKeyNameCertProfile, SerializeCertProfile(worker.cert_profile_));
  result.Set(kKeyNameCertScope, static_cast<int>(worker.cert_scope_));
  result.Set(kKeyNameState, static_cast<int>(worker.state_));
  result.Set(kKeyNamePublicKey, SerializeBase64Encoded(worker.public_key_));
  result.Set(kKeyNameInvalidationTopic, worker.invalidation_topic_);
  return result;
}

// Serialization scheme:
// {
//   "cert_scope": <number>,
//   "cert_profile": <CertProfile>,
//   "state": <number>,
//   "public_key": <string>,
//   "invalidation_topic": <string>,
//   "key_location": <number>,
//   "attempted_va_challenge": <bool>,
//   "proof_of_possession_count": <number>,
// }
base::Value::Dict CertProvisioningSerializer::SerializeWorker(
    const CertProvisioningWorkerDynamic& worker) {
  static_assert(CertProvisioningWorkerDynamic::kVersion == 3,
                "This function should be updated");

  base::Value::Dict result;

  result.Set(kKeyNameProcessId, worker.process_id_);
  result.Set(kKeyNameCertProfile, SerializeCertProfile(worker.cert_profile_));
  result.Set(kKeyNameCertScope, static_cast<int>(worker.cert_scope_));
  result.Set(kKeyNameState, static_cast<int>(worker.state_));
  result.Set(kKeyNamePublicKey, SerializeBase64Encoded(worker.public_key_));
  result.Set(kKeyNameInvalidationTopic, worker.invalidation_topic_);
  result.Set(kKeyNameKeyLocation, static_cast<int>(worker.key_location_));
  result.Set(kKeyNameAttemptedVaChallenge, worker.attempted_va_challenge_);
  result.Set(kKeyNameAttemptedProofOfPossession,
             worker.attempted_proof_of_possession_);
  result.Set(kKeyNameProofOfPossessionSignature,
             SerializeBase64Encoded(worker.signature_));
  return result;
}

bool CertProvisioningSerializer::DeserializeWorker(
    const base::Value::Dict& saved_worker,
    CertProvisioningWorkerStatic* worker) {
  static_assert(CertProvisioningWorkerStatic::kVersion == 2,
                "This function should be updated");

  // This will show to the scheduler that the worker is not doing anything yet
  // and that it should be continued manually.
  worker->is_waiting_ = true;

  bool is_ok = true;
  int error_code = 0;

  // Try to only add new deserialize statements at the end so error_code values
  // are stable.
  is_ok = is_ok && ++error_code &&
          DeserializeEnumValue<CertScope>(saved_worker, kKeyNameCertScope,
                                          &(worker->cert_scope_));

  is_ok = is_ok && ++error_code &&
          DeserializeCertProfile(saved_worker, kKeyNameCertProfile,
                                 &(worker->cert_profile_));

  is_ok = is_ok && ++error_code &&
          DeserializeEnumValue<CertProvisioningWorkerState>(
              saved_worker, kKeyNameState, &(worker->state_));

  is_ok = is_ok && ++error_code &&
          DeserializeBase64Encoded(saved_worker, kKeyNamePublicKey,
                                   &(worker->public_key_));

  is_ok = is_ok && ++error_code &&
          DeserializeStringValue(saved_worker, kKeyNameInvalidationTopic,
                                 &(worker->invalidation_topic_));

  is_ok = is_ok && ++error_code &&
          DeserializeStringValue(saved_worker, kKeyNameProcessId,
                                 &(worker->process_id_));

  if (!is_ok) {
    LOG(ERROR)
        << " Failed to deserialize cert provisioning worker, error code: "
        << error_code;
    return false;
  }

  worker->InitAfterDeserialization();

  return true;
}

bool CertProvisioningSerializer::DeserializeWorker(
    const base::Value::Dict& saved_worker,
    CertProvisioningWorkerDynamic* worker) {
  static_assert(CertProvisioningWorkerDynamic::kVersion == 3,
                "This function should be updated");

  // This will show to the scheduler that the worker is not doing anything yet
  // and that it should be continued manually.
  worker->is_waiting_ = true;

  bool is_ok = true;
  int error_code = 0;

  // Try to only add new deserialize statements at the end so error_code values
  // are stable.
  is_ok = is_ok && ++error_code &&
          DeserializeEnumValue<CertScope>(saved_worker, kKeyNameCertScope,
                                          &(worker->cert_scope_));

  is_ok = is_ok && ++error_code &&
          DeserializeCertProfile(saved_worker, kKeyNameCertProfile,
                                 &(worker->cert_profile_));

  is_ok = is_ok && ++error_code &&
          DeserializeEnumValue<CertProvisioningWorkerState>(
              saved_worker, kKeyNameState, &(worker->state_));

  is_ok = is_ok && ++error_code &&
          DeserializeBase64Encoded(saved_worker, kKeyNamePublicKey,
                                   &(worker->public_key_));

  is_ok = is_ok && ++error_code &&
          DeserializeStringValue(saved_worker, kKeyNameInvalidationTopic,
                                 &(worker->invalidation_topic_));

  is_ok = is_ok && ++error_code &&
          DeserializeEnumValue<KeyLocation>(saved_worker, kKeyNameKeyLocation,
                                            &(worker->key_location_));

  is_ok = is_ok && ++error_code &&
          DeserializeBoolValue(saved_worker, kKeyNameAttemptedVaChallenge,
                               &(worker->attempted_va_challenge_));

  is_ok = is_ok && ++error_code &&
          DeserializeBoolValue(saved_worker, kKeyNameAttemptedProofOfPossession,
                               &(worker->attempted_proof_of_possession_));

  is_ok =
      is_ok && ++error_code &&
      DeserializeBase64Encoded(saved_worker, kKeyNameProofOfPossessionSignature,
                               &(worker->signature_));

  is_ok = is_ok && ++error_code &&
          DeserializeStringValue(saved_worker, kKeyNameProcessId,
                                 &(worker->process_id_));

  if (!is_ok) {
    LOG(ERROR)
        << " Failed to deserialize cert provisioning worker, error code: "
        << error_code;
    return false;
  }

  worker->InitAfterDeserialization();

  return true;
}

std::optional<ProtocolVersion> CertProvisioningSerializer::GetProtocolVersion(
    const base::Value::Dict& saved_worker) {
  CertProfile cert_profile;
  if (!DeserializeCertProfile(saved_worker, kKeyNameCertProfile,
                              &cert_profile)) {
    return {};
  }
  return cert_profile.protocol_version;
}

}  // namespace cert_provisioning
}  // namespace ash