File: root_store_tool.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 (526 lines) | stat: -rw-r--r-- 18,525 bytes parent folder | download | duplicates (5)
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
// 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.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
#pragma allow_unsafe_buffers
#endif

#include <inttypes.h>

#include <iostream>
#include <map>
#include <optional>
#include <set>
#include <string>
#include <string_view>

#include "base/at_exit.h"
#include "base/base_paths.h"
#include "base/command_line.h"
#include "base/containers/span.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "base/path_service.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "crypto/sha2.h"
#include "net/cert/root_store_proto_full/root_store.pb.h"
#include "third_party/boringssl/src/include/openssl/bio.h"
#include "third_party/boringssl/src/include/openssl/err.h"
#include "third_party/boringssl/src/include/openssl/pem.h"
#include "third_party/protobuf/src/google/protobuf/text_format.h"

using chrome_root_store::RootStore;
using chrome_root_store::TrustAnchor;

namespace {

// Returns a map from hex-encoded SHA-256 hash to DER certificate, or
// `std::nullopt` if not found.
std::optional<std::map<std::string, std::string>> DecodeCerts(
    std::string_view in) {
  // TODO(crbug.com/40770548): net/cert/pem.h has a much nicer API, but
  // it would require some build refactoring to avoid a circular dependency.
  // This is assuming that the chrome trust store code goes in
  // net/cert/internal, which it may not.
  bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(in.data(), in.size()));
  if (!bio) {
    return std::nullopt;
  }
  std::map<std::string, std::string> certs;
  for (;;) {
    char* name;
    char* header;
    unsigned char* data;
    long len;
    if (!PEM_read_bio(bio.get(), &name, &header, &data, &len)) {
      uint32_t err = ERR_get_error();
      if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
          ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
        // Found the last PEM block.
        break;
      }
      LOG(ERROR) << "Error reading PEM.";
      return std::nullopt;
    }
    bssl::UniquePtr<char> scoped_name(name);
    bssl::UniquePtr<char> scoped_header(header);
    bssl::UniquePtr<unsigned char> scoped_data(data);
    if (strcmp(name, "CERTIFICATE") != 0) {
      LOG(ERROR) << "Found PEM block of type " << name
                 << " instead of CERTIFICATE";
      return std::nullopt;
    }
    std::string sha256_hex = base::ToLowerASCII(base::HexEncode(
        crypto::SHA256Hash(base::span(data, base::checked_cast<size_t>(len)))));
    certs[sha256_hex] = std::string(data, data + len);
  }
  return std::move(certs);
}

// ReplaceTrustAnchors takes a repeated trust_anchors field from a proto and
// replaces certs identified by a SHA-256 hash with the full cert bytes, using
// the file found at certs_file_path to provide the full cert bytes.
bool ReplaceTrustAnchors(
    google::protobuf::RepeatedPtrField<TrustAnchor>* trust_anchors,
    const base::FilePath& certs_file_path) {
  std::map<std::string, std::string> certs;
  if (!certs_file_path.empty()) {
    std::string certs_data;
    if (!base::ReadFileToString(base::MakeAbsoluteFilePath(certs_file_path),
                                &certs_data)) {
      LOG(ERROR) << "Could not read " << certs_file_path;
      return false;
    }
    auto certs_opt = DecodeCerts(certs_data);
    if (!certs_opt) {
      LOG(ERROR) << "Could not decode " << certs_file_path;
      return false;
    }
    certs = std::move(*certs_opt);
  }

  // Replace the filenames with the actual certificate contents.
  for (auto& anchor : *trust_anchors) {
    if (anchor.certificate_case() !=
        chrome_root_store::TrustAnchor::kSha256Hex) {
      continue;
    }

    auto iter = certs.find(anchor.sha256_hex());
    if (iter == certs.end()) {
      LOG(ERROR) << "Could not find certificate " << anchor.sha256_hex();
      return false;
    }

    // Remove the certificate from `certs`. This both checks for duplicate
    // certificates and allows us to check for unused certificates later.
    anchor.set_der(std::move(iter->second));
    certs.erase(iter);
  }

  if (!certs.empty()) {
    LOG(ERROR) << "Unused certificate (SHA-256 hash " << certs.begin()->first
               << ") in " << certs_file_path;
    return false;
  }
  return true;
}

std::optional<RootStore> ReadTextRootStore(
    const base::FilePath& root_store_path,
    const base::FilePath& certs_path,
    const base::FilePath& additional_certs_path) {
  std::string root_store_text;
  if (!base::ReadFileToString(base::MakeAbsoluteFilePath(root_store_path),
                              &root_store_text)) {
    LOG(ERROR) << "Could not read " << root_store_path;
    return std::nullopt;
  }

  RootStore root_store;
  if (!google::protobuf::TextFormat::ParseFromString(root_store_text,
                                                     &root_store)) {
    LOG(ERROR) << "Could not parse " << root_store_path;
    return std::nullopt;
  }

  if (!ReplaceTrustAnchors(root_store.mutable_trust_anchors(), certs_path)) {
    LOG(ERROR) << "Failed to process " << certs_path;
    return std::nullopt;
  }
  if (!ReplaceTrustAnchors(root_store.mutable_additional_certs(),
                           additional_certs_path)) {
    LOG(ERROR) << "Failed to process " << additional_certs_path;
    return std::nullopt;
  }
  return std::move(root_store);
}

std::string SecondsFromEpochToBaseTime(int64_t t) {
  return base::StrCat({"base::Time::UnixEpoch() + base::Seconds(",
                       base::NumberToString(t), ")"});
}

std::string VersionFromString(std::string_view version_str) {
  return base::StrCat({"\"", version_str, "\""});
}

void WriteTrustAnchors(
    const google::protobuf::RepeatedPtrField<TrustAnchor>& trust_anchors,
    const std::string& cert_name_prefix,
    std::string* string_to_write) {
  const std::string kNulloptString = "std::nullopt";

  for (int i = 0; i < trust_anchors.size(); i++) {
    const auto& anchor = trust_anchors.Get(i);
    // Every trust anchor at this point should have a DER.
    CHECK(!anchor.der().empty());
    std::string der = anchor.der();

    base::StringAppendF(string_to_write, "constexpr uint8_t k%sCert%d[] = {",
                        cert_name_prefix, i);

    // Convert each character to hex representation, escaped.
    for (auto c : der) {
      base::StringAppendF(string_to_write, "0x%02xu,", static_cast<uint8_t>(c));
    }

    // End struct
    *string_to_write += "};\n";

    if (!anchor.trust_anchor_id().empty()) {
      base::StringAppendF(string_to_write,
                          "constexpr uint8_t k%sTrustAnchorID%d[] = {",
                          cert_name_prefix, i);
      // Convert each character to hex representation, escaped.
      for (auto c : anchor.trust_anchor_id()) {
        base::StringAppendF(string_to_write, "0x%02xu,",
                            static_cast<uint8_t>(c));
      }
      *string_to_write += "};\n";
    }

    if (anchor.constraints_size() > 0) {
      int constraint_num = 0;
      for (const auto& constraint : anchor.constraints()) {
        if (constraint.permitted_dns_names_size() > 0) {
          base::StringAppendF(string_to_write,
                              "constexpr std::string_view "
                              "k%sConstraint%dNames%d[] = {",
                              cert_name_prefix, i, constraint_num);
          for (const auto& name : constraint.permitted_dns_names()) {
            base::StringAppendF(string_to_write, "\"%s\",", name);
          }
          *string_to_write += "};\n";
        }
        constraint_num++;
      }

      base::StringAppendF(string_to_write,
                          "constexpr StaticChromeRootCertConstraints "
                          "k%sConstraints%d[] = {",
                          cert_name_prefix, i);

      std::vector<std::string> constraint_strings;
      constraint_num = 0;
      for (const auto& constraint : anchor.constraints()) {
        std::vector<std::string> constraint_params;

        constraint_params.push_back(
            constraint.has_sct_not_after_sec()
                ? SecondsFromEpochToBaseTime(constraint.sct_not_after_sec())
                : kNulloptString);

        constraint_params.push_back(
            constraint.has_sct_all_after_sec()
                ? SecondsFromEpochToBaseTime(constraint.sct_all_after_sec())
                : kNulloptString);

        constraint_params.push_back(
            constraint.has_min_version()
                ? VersionFromString(constraint.min_version())
                : kNulloptString);

        constraint_params.push_back(
            constraint.has_max_version_exclusive()
                ? VersionFromString(constraint.max_version_exclusive())
                : kNulloptString);

        if (constraint.permitted_dns_names_size() > 0) {
          constraint_params.push_back(base::StringPrintf(
              "k%sConstraint%dNames%d", cert_name_prefix, i, constraint_num));
        } else {
          constraint_params.push_back("{}");
        }

        constraint_strings.push_back(
            base::StrCat({"{", base::JoinString(constraint_params, ","), "}"}));

        constraint_num++;
      }

      *string_to_write += base::JoinString(constraint_strings, ",");
      *string_to_write += "};\n";
    }
  }
}

// Returns true if file was correctly written, false otherwise.
bool WriteRootCppFile(const RootStore& root_store,
                      const base::FilePath cpp_path) {
  // Root store should have at least one trust anchor.
  CHECK_GT(root_store.trust_anchors_size(), 0);

  std::string string_to_write =
      "// This file is auto-generated, DO NOT EDIT.\n\n";

  WriteTrustAnchors(root_store.trust_anchors(), "ChromeRoot", &string_to_write);
  WriteTrustAnchors(root_store.additional_certs(), "Additional",
                    &string_to_write);

  // Assemble list of trust anchors.
  string_to_write += "constexpr ChromeRootCertInfo kChromeRootCertList[] = {\n";
  for (int i = 0; i < root_store.trust_anchors_size(); i++) {
    const auto& anchor = root_store.trust_anchors(i);
    if (anchor.has_tls_trust_anchor()) {
      // Anchors in |trust_anchors| are not supposed to have |tls_trust_anchor|
      // set, because they are definitionally TLS trust anchors.
      return false;
    }
    base::StringAppendF(&string_to_write, "    {kChromeRootCert%d, ", i);
    if (anchor.constraints_size() > 0) {
      base::StringAppendF(&string_to_write, "kChromeRootConstraints%d", i);
    } else {
      string_to_write += "{}";
    }

    base::StringAppendF(
        &string_to_write,
        ", /*enforce_anchor_expiry=*/%s, /*enforce_anchor_constraints=*/%s",
        anchor.enforce_anchor_expiry() ? "true" : "false",
        anchor.enforce_anchor_constraints() ? "true" : "false");

    if (anchor.trust_anchor_id().empty()) {
      string_to_write += ", {}";
    } else {
      base::StringAppendF(&string_to_write, ", kChromeRootTrustAnchorID%d", i);
    }
    string_to_write += "},\n";
  }
  // Append additional_certs as TLS trust anchors, if they are marked as such.
  for (int i = 0; i < root_store.additional_certs_size(); i++) {
    const auto& anchor = root_store.additional_certs(i);
    if (!anchor.tls_trust_anchor()) {
      continue;
    }
    base::StringAppendF(&string_to_write, "    {kAdditionalCert%d, ", i);
    if (anchor.constraints_size() > 0) {
      base::StringAppendF(&string_to_write, "kAdditionalConstraints%d", i);
    } else {
      string_to_write += "{}";
    }

    base::StringAppendF(
        &string_to_write,
        ", /*enforce_anchor_expiry=*/%s, /*enforce_anchor_constraints=*/%s",
        anchor.enforce_anchor_expiry() ? "true" : "false",
        anchor.enforce_anchor_constraints() ? "true" : "false");

    if (anchor.trust_anchor_id().empty()) {
      string_to_write += ", {}";
    } else {
      base::StringAppendF(&string_to_write, ", kAdditionalTrustAnchorID%d", i);
    }
    string_to_write += "},\n";
  }
  string_to_write += "};\n\n";

  // Assemble list of QWAC issuers, which can come from both trust_anchors and
  // additional_certs.
  string_to_write +=
      "constexpr base::span<const uint8_t> kEutlRootCertList[] = {\n";
  for (int i = 0; i < root_store.trust_anchors_size(); i++) {
    const auto& anchor = root_store.trust_anchors(i);
    if (!anchor.eutl()) {
      continue;
    }
    base::StringAppendF(&string_to_write, "    kChromeRootCert%d,\n", i);
  }
  for (int i = 0; i < root_store.additional_certs_size(); i++) {
    const auto& anchor = root_store.additional_certs(i);
    if (!anchor.eutl()) {
      continue;
    }
    base::StringAppendF(&string_to_write, "    kAdditionalCert%d,\n", i);
  }
  string_to_write += "};\n\n";

  base::StringAppendF(&string_to_write,
                      "\nstatic const int64_t kRootStoreVersion = %" PRId64
                      ";\n",
                      root_store.version_major());
  if (!base::WriteFile(cpp_path, string_to_write)) {
    return false;
  }
  return true;
}

// Returns true if file was correctly written, false otherwise.
bool WriteEvCppFile(const RootStore& root_store,
                    const base::FilePath cpp_path) {
  // There should be at least one EV root.
  CHECK_GT(root_store.trust_anchors_size(), 0);

  std::string string_to_write =
      "// This file is auto-generated, DO NOT EDIT.\n\n"
      "static const EVMetadata kEvRootCaMetadata[] = {\n";

  for (auto& anchor : root_store.trust_anchors()) {
    // Every trust anchor at this point should have a DER.
    CHECK(!anchor.der().empty());
    if (anchor.ev_policy_oids_size() == 0) {
      // The same input file is used for the Chrome Root Store and EV enabled
      // certificates. Skip anchors that have no EV policy OIDs when generating
      // the EV include file.
      continue;
    }

    std::string sha256_hash = crypto::SHA256HashString(anchor.der());

    // Begin struct. Assumed type of EVMetadata:
    //
    // struct EVMetadata {
    //  static const size_t kMaxOIDsPerCA = 2;
    //  SHA256HashValue fingerprint;
    //  const std::string_view policy_oids[kMaxOIDsPerCA];
    // };
    string_to_write += "    {\n";
    string_to_write += "        {{";

    int wrap_count = 0;
    for (auto c : sha256_hash) {
      if (wrap_count != 0) {
        if (wrap_count % 11 == 0) {
          string_to_write += ",\n          ";
        } else {
          string_to_write += ", ";
        }
      }
      base::StringAppendF(&string_to_write, "0x%02x", static_cast<uint8_t>(c));
      wrap_count++;
    }

    string_to_write += "}},\n";
    string_to_write += "        {\n";

    // struct expects exactly two policy oids, and we can only support 1 or 2
    // policy OIDs. These checks will need to change if we ever merge the EV and
    // Chrome Root Store textprotos.
    const int kMaxPolicyOids = 2;
    int oids_size = anchor.ev_policy_oids_size();
    std::string hexencode_hash = base::HexEncode(sha256_hash);
    if (oids_size > kMaxPolicyOids) {
      PLOG(ERROR) << hexencode_hash << " has too many OIDs!";
      return false;
    }
    for (int i = 0; i < kMaxPolicyOids; i++) {
      std::string oid;
      if (i < oids_size) {
        oid = anchor.ev_policy_oids(i);
      }
      string_to_write += "            \"" + oid + "\",\n";
    }

    // End struct
    string_to_write += "        },\n";
    string_to_write += "    },\n";
  }
  string_to_write += "};\n";
  if (!base::WriteFile(cpp_path, string_to_write)) {
    PLOG(ERROR) << "Error writing cpp include file";
    return false;
  }
  return true;
}

}  // namespace

int main(int argc, char** argv) {
  base::AtExitManager at_exit_manager;
  base::CommandLine::Init(argc, argv);

  logging::LoggingSettings settings;
  settings.logging_dest =
      logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR;
  logging::InitLogging(settings);

  base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess();
  base::FilePath proto_path = command_line.GetSwitchValuePath("write-proto");
  base::FilePath root_store_cpp_path =
      command_line.GetSwitchValuePath("write-cpp-root-store");
  base::FilePath ev_roots_cpp_path =
      command_line.GetSwitchValuePath("write-cpp-ev-roots");
  base::FilePath root_store_path =
      command_line.GetSwitchValuePath("root-store");
  base::FilePath certs_path = command_line.GetSwitchValuePath("certs");
  base::FilePath additional_certs_path =
      command_line.GetSwitchValuePath("additional-certs");

  if ((proto_path.empty() && root_store_cpp_path.empty() &&
       ev_roots_cpp_path.empty()) ||
      root_store_path.empty() || command_line.HasSwitch("help")) {
    std::cerr << "Usage: root_store_tool "
              << "--root-store=TEXTPROTO_FILE "
              << "[--certs=CERTS_FILE] "
              << "[--additional-certs=ADDITIONAL_CERTS_FILE] "
              << "[--write-proto=PROTO_FILE] "
              << "[--write-cpp-root-store=CPP_FILE] "
              << "[--write-cpp-ev-roots=CPP_FILE] " << std::endl;
    return 1;
  }

  std::optional<RootStore> root_store =
      ReadTextRootStore(root_store_path, certs_path, additional_certs_path);
  if (!root_store) {
    return 1;
  }

  // TODO(crbug.com/40770548): Figure out how to use the serialized
  // proto to support component update.
  // components/resources/ssl/ssl_error_assistant/push_proto.py
  // does it through a GCS bucket (I think) so that might be an option.
  if (!proto_path.empty()) {
    std::string serialized;
    if (!root_store->SerializeToString(&serialized)) {
      LOG(ERROR) << "Error serializing root store proto"
                 << root_store->DebugString();
      return 1;
    }
    if (!base::WriteFile(proto_path, serialized)) {
      PLOG(ERROR) << "Error writing serialized proto root store";
      return 1;
    }
  }

  if (!root_store_cpp_path.empty() &&
      !WriteRootCppFile(*root_store, root_store_cpp_path)) {
    PLOG(ERROR) << "Error writing root store C++ include file";
    return 1;
  }
  if (!ev_roots_cpp_path.empty() &&
      !WriteEvCppFile(*root_store, ev_roots_cpp_path)) {
    PLOG(ERROR) << "Error writing EV roots C++ include file";
    return 1;
  }

  return 0;
}