File: input_file_parsers.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 (548 lines) | stat: -rw-r--r-- 18,764 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
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/tools/transport_security_state_generator/input_file_parsers.h"

#include <set>
#include <sstream>
#include <string_view>
#include <vector>

#include "base/containers/contains.h"
#include "base/containers/fixed_flat_set.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/time/time.h"
#include "base/values.h"
#include "net/tools/transport_security_state_generator/cert_util.h"
#include "net/tools/transport_security_state_generator/pinset.h"
#include "net/tools/transport_security_state_generator/pinsets.h"
#include "net/tools/transport_security_state_generator/spki_hash.h"
#include "third_party/boringssl/src/include/openssl/x509v3.h"

namespace net::transport_security_state {

namespace {

bool IsImportantWordInCertificateName(std::string_view name) {
  const char* const important_words[] = {"Universal", "Global", "EV", "G1",
                                         "G2",        "G3",     "G4", "G5"};
  for (auto* important_word : important_words) {
    if (name == important_word) {
      return true;
    }
  }
  return false;
}

// Strips all characters not matched by the RegEx [A-Za-z0-9_] from |name| and
// returns the result.
std::string FilterName(std::string_view name) {
  std::string filtered;
  for (const char& character : name) {
    if ((character >= '0' && character <= '9') ||
        (character >= 'a' && character <= 'z') ||
        (character >= 'A' && character <= 'Z') || character == '_') {
      filtered += character;
    }
  }
  return base::ToLowerASCII(filtered);
}

// Returns true if |pin_name| is a reasonable match for the certificate name
// |name|.
bool MatchCertificateName(std::string_view name, std::string_view pin_name) {
  std::vector<std::string_view> words = base::SplitStringPiece(
      name, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
  if (words.empty()) {
    LOG(ERROR) << "No words in certificate name for pin " << pin_name;
    return false;
  }
  std::string_view first_word = words[0];

  if (first_word.ends_with(",")) {
    first_word = first_word.substr(0, first_word.size() - 1);
  }

  if (first_word.starts_with("*.")) {
    first_word = first_word.substr(2, first_word.size() - 2);
  }

  size_t pos = first_word.find('.');
  if (pos != std::string::npos) {
    first_word = first_word.substr(0, first_word.size() - pos);
  }

  pos = first_word.find('-');
  if (pos != std::string::npos) {
    first_word = first_word.substr(0, first_word.size() - pos);
  }

  if (first_word.empty()) {
    LOG(ERROR) << "First word of certificate name (" << name << ") is empty";
    return false;
  }

  std::string filtered_word = FilterName(first_word);
  first_word = filtered_word;
  if (!base::EqualsCaseInsensitiveASCII(pin_name.substr(0, first_word.size()),
                                        first_word)) {
    LOG(ERROR) << "The first word of the certificate name (" << first_word
               << ") isn't a prefix of the variable name (" << pin_name << ")";
    return false;
  }

  for (size_t i = 0; i < words.size(); ++i) {
    std::string_view word = words[i];
    if (word == "Class" && (i + 1) < words.size()) {
      std::string class_name = base::StrCat({word, words[i + 1]});

      pos = pin_name.find(class_name);
      if (pos == std::string::npos) {
        LOG(ERROR)
            << "Certficate class specification doesn't appear in the variable "
               "name ("
            << pin_name << ")";
        return false;
      }
    } else if (word.size() == 1 && word[0] >= '0' && word[0] <= '9') {
      pos = pin_name.find(word);
      if (pos == std::string::npos) {
        LOG(ERROR) << "Number doesn't appear in the certificate variable name ("
                   << pin_name << ")";
        return false;
      }
    } else if (IsImportantWordInCertificateName(word)) {
      pos = pin_name.find(word);
      if (pos == std::string::npos) {
        LOG(ERROR) << std::string(word) +
                          " doesn't appear in the certificate variable name ("
                   << pin_name << ")";
        return false;
      }
    }
  }

  return true;
}

// Returns true iff |candidate| is not empty, the first character is in the
// range A-Z, and the remaining characters are in the ranges a-Z, 0-9, or '_'.
bool IsValidName(std::string_view candidate) {
  if (candidate.empty() || candidate[0] < 'A' || candidate[0] > 'Z') {
    return false;
  }

  bool isValid = true;
  for (const char& character : candidate) {
    isValid = (character >= '0' && character <= '9') ||
              (character >= 'a' && character <= 'z') ||
              (character >= 'A' && character <= 'Z') || character == '_';
    if (!isValid) {
      return false;
    }
  }
  return true;
}

static const char kStartOfCert[] = "-----BEGIN CERTIFICATE";
static const char kStartOfPublicKey[] = "-----BEGIN PUBLIC KEY";
static const char kEndOfCert[] = "-----END CERTIFICATE";
static const char kEndOfPublicKey[] = "-----END PUBLIC KEY";
static const char kStartOfSHA256[] = "sha256/";

enum class CertificateParserState {
  PRE_NAME,
  POST_NAME,
  IN_CERTIFICATE,
  IN_PUBLIC_KEY,
  PRE_TIMESTAMP,
};

// Valid keys for entries in the input JSON. These fields will be included in
// the output.
static constexpr char kNameJSONKey[] = "name";
static constexpr char kIncludeSubdomainsJSONKey[] = "include_subdomains";
static constexpr char kModeJSONKey[] = "mode";
static constexpr char kPinsJSONKey[] = "pins";
static constexpr char kTimestampName[] = "PinsListTimestamp";

// Additional valid keys for entries in the input JSON that will not be included
// in the output and contain metadata (e.g., for list maintenance).
static constexpr char kPolicyJSONKey[] = "policy";

}  // namespace

bool ParseCertificatesFile(std::string_view certs_input,
                           Pinsets* pinsets,
                           base::Time* timestamp) {
  if (certs_input.find("\r\n") != std::string_view::npos) {
    LOG(ERROR) << "CRLF line-endings found in the pins file. All files must "
                  "use LF (unix style) line-endings.";
    return false;
  }

  CertificateParserState current_state = CertificateParserState::PRE_NAME;
  bool timestamp_parsed = false;

  const base::CompareCase& compare_mode = base::CompareCase::INSENSITIVE_ASCII;
  std::string name;
  std::string buffer;
  std::string subject_name;
  bssl::UniquePtr<X509> certificate;
  SPKIHash hash;

  for (std::string_view line : SplitStringPiece(
           certs_input, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL)) {
    if (!line.empty() && line[0] == '#') {
      continue;
    }

    if (line.empty() && current_state == CertificateParserState::PRE_NAME) {
      continue;
    }

    switch (current_state) {
      case CertificateParserState::PRE_NAME:
        if (line == kTimestampName) {
          current_state = CertificateParserState::PRE_TIMESTAMP;
          break;
        }
        if (!IsValidName(line)) {
          LOG(ERROR) << "Invalid name in pins file: " << line;
          return false;
        }
        name = std::string(line);
        current_state = CertificateParserState::POST_NAME;
        break;
      case CertificateParserState::POST_NAME:
        if (base::StartsWith(line, kStartOfSHA256, compare_mode)) {
          if (!hash.FromString(line)) {
            LOG(ERROR) << "Invalid hash value in pins file for " << name;
            return false;
          }

          pinsets->RegisterSPKIHash(name, hash);
          current_state = CertificateParserState::PRE_NAME;
        } else if (base::StartsWith(line, kStartOfCert, compare_mode)) {
          buffer = std::string(line) + '\n';
          current_state = CertificateParserState::IN_CERTIFICATE;
        } else if (base::StartsWith(line, kStartOfPublicKey, compare_mode)) {
          buffer = std::string(line) + '\n';
          current_state = CertificateParserState::IN_PUBLIC_KEY;
        } else {
          LOG(ERROR) << "Invalid value in pins file for " << name;
          return false;
        }
        break;
      case CertificateParserState::IN_CERTIFICATE:
        buffer += std::string(line) + '\n';
        if (!base::StartsWith(line, kEndOfCert, compare_mode)) {
          continue;
        }

        certificate = GetX509CertificateFromPEM(buffer);
        if (!certificate) {
          LOG(ERROR) << "Could not parse certificate " << name;
          return false;
        }

        if (!CalculateSPKIHashFromCertificate(certificate.get(), &hash)) {
          LOG(ERROR) << "Could not extract SPKI from certificate " << name;
          return false;
        }

        if (!ExtractSubjectNameFromCertificate(certificate.get(),
                                               &subject_name)) {
          LOG(ERROR) << "Could not extract name from certificate " << name;
          return false;
        }

        if (!MatchCertificateName(subject_name, name)) {
          LOG(ERROR) << name << " is not a reasonable name for "
                     << subject_name;
          return false;
        }

        pinsets->RegisterSPKIHash(name, hash);
        current_state = CertificateParserState::PRE_NAME;
        break;
      case CertificateParserState::IN_PUBLIC_KEY:
        buffer += std::string(line) + '\n';
        if (!base::StartsWith(line, kEndOfPublicKey, compare_mode)) {
          continue;
        }

        if (!CalculateSPKIHashFromKey(buffer, &hash)) {
          LOG(ERROR) << "Could not parse the public key for " << name;
          return false;
        }

        pinsets->RegisterSPKIHash(name, hash);
        current_state = CertificateParserState::PRE_NAME;
        break;
      case CertificateParserState::PRE_TIMESTAMP:
        uint64_t timestamp_epoch;
        if (!base::StringToUint64(line, &timestamp_epoch) ||
            !base::IsValueInRangeForNumericType<time_t>(timestamp_epoch)) {
          LOG(ERROR) << "Could not parse the timestamp value";
          return false;
        }
        *timestamp = base::Time::FromTimeT(timestamp_epoch);
        if (timestamp_parsed) {
          LOG(ERROR) << "File contains multiple timestamps";
          return false;
        }
        timestamp_parsed = true;
        current_state = CertificateParserState::PRE_NAME;
        break;
      default:
        DCHECK(false) << "Unknown parser state";
    }
  }

  if (!timestamp_parsed) {
    LOG(ERROR) << "Timestamp is missing";
    return false;
  }
  return true;
}

bool ParseJSON(std::string_view hsts_json,
               std::string_view pins_json,
               TransportSecurityStateEntries* entries,
               Pinsets* pinsets) {
  static constexpr auto valid_hsts_keys =
      base::MakeFixedFlatSet<std::string_view>({
          kNameJSONKey,
          kPolicyJSONKey,
          kIncludeSubdomainsJSONKey,
          kModeJSONKey,
          kPinsJSONKey,
      });

  static constexpr auto valid_pins_keys =
      base::MakeFixedFlatSet<std::string_view>({
          kNameJSONKey,
          kIncludeSubdomainsJSONKey,
          kPinsJSONKey,
      });

  // See the comments in net/http/transport_security_state_static.json for more
  // info on these policies.
  std::set<std::string> valid_policies = {
      "test",        "public-suffix", "google",      "custom",
      "bulk-legacy", "bulk-18-weeks", "bulk-1-year", "public-suffix-requested"};

  std::optional<base::Value::Dict> hsts_dict =
      base::JSONReader::ReadDict(hsts_json);
  if (!hsts_dict) {
    LOG(ERROR) << "Could not parse the input HSTS JSON file";
    return false;
  }

  std::optional<base::Value::Dict> pins_dict =
      base::JSONReader::ReadDict(pins_json);
  if (!pins_dict) {
    LOG(ERROR) << "Could not parse the input pins JSON file";
    return false;
  }

  const base::Value::List* pinning_entries_list =
      pins_dict->FindList("entries");
  if (!pinning_entries_list) {
    LOG(ERROR) << "Could not parse the entries in the input pins JSON";
    return false;
  }
  std::map<std::string, std::pair<std::string, bool>> pins_map;
  for (size_t i = 0; i < pinning_entries_list->size(); ++i) {
    const base::Value::Dict* parsed = (*pinning_entries_list)[i].GetIfDict();
    if (!parsed) {
      LOG(ERROR) << "Could not parse entry " << base::NumberToString(i)
                 << " in the input pins JSON";
      return false;
    }
    const std::string* maybe_hostname = parsed->FindString(kNameJSONKey);
    if (!maybe_hostname) {
      LOG(ERROR) << "Could not extract the hostname for entry "
                 << base::NumberToString(i) << " from the input pins JSON";
      return false;
    }

    if (maybe_hostname->empty()) {
      LOG(ERROR) << "The hostname for entry " << base::NumberToString(i)
                 << " is empty";
      return false;
    }

    for (auto entry_value : *parsed) {
      if (!base::Contains(valid_pins_keys, entry_value.first)) {
        LOG(ERROR) << "The entry for " << *maybe_hostname
                   << " contains an unknown " << entry_value.first << " field";
        return false;
      }
    }

    const std::string* maybe_pinset = parsed->FindString(kPinsJSONKey);
    if (!maybe_pinset) {
      LOG(ERROR) << "Could not extract the pinset for entry "
                 << base::NumberToString(i) << " from the input pins JSON";
      return false;
    }

    if (pins_map.find(*maybe_hostname) != pins_map.end()) {
      LOG(ERROR) << *maybe_hostname
                 << " has duplicate entries in the input pins JSON";
      return false;
    }

    pins_map[*maybe_hostname] =
        std::pair(*maybe_pinset,
                  parsed->FindBool(kIncludeSubdomainsJSONKey).value_or(false));
  }

  const base::Value::List* preload_entries_list =
      hsts_dict->FindList("entries");
  if (!preload_entries_list) {
    LOG(ERROR) << "Could not parse the entries in the input HSTS JSON";
    return false;
  }

  for (size_t i = 0; i < preload_entries_list->size(); ++i) {
    const base::Value::Dict* parsed = (*preload_entries_list)[i].GetIfDict();
    if (!parsed) {
      LOG(ERROR) << "Could not parse entry " << base::NumberToString(i)
                 << " in the input HSTS JSON";
      return false;
    }

    auto entry = std::make_unique<TransportSecurityStateEntry>();
    const std::string* maybe_hostname = parsed->FindString(kNameJSONKey);
    if (!maybe_hostname) {
      LOG(ERROR) << "Could not extract the hostname for entry "
                 << base::NumberToString(i) << " from the input HSTS JSON";
      return false;
    }
    entry->hostname = *maybe_hostname;

    if (entry->hostname.empty()) {
      LOG(ERROR) << "The hostname for entry " << base::NumberToString(i)
                 << " is empty";
      return false;
    }

    for (auto entry_value : *parsed) {
      if (!base::Contains(valid_hsts_keys, entry_value.first)) {
        LOG(ERROR) << "The entry for " << entry->hostname
                   << " contains an unknown " << entry_value.first << " field";
        return false;
      }
    }

    const std::string* policy = parsed->FindString(kPolicyJSONKey);
    if (!policy || !base::Contains(valid_policies, *policy)) {
      LOG(ERROR) << "The entry for " << entry->hostname
                 << " does not have a valid policy";
      return false;
    }

    const std::string* maybe_mode = parsed->FindString(kModeJSONKey);
    std::string mode = maybe_mode ? *maybe_mode : std::string();
    entry->force_https = false;
    if (mode == "force-https") {
      entry->force_https = true;
    } else if (!mode.empty()) {
      LOG(ERROR) << "An unknown mode is set for entry " << entry->hostname;
      return false;
    }

    entry->include_subdomains =
        parsed->FindBool(kIncludeSubdomainsJSONKey).value_or(false);

    auto pins_it = pins_map.find(entry->hostname);
    if (pins_it != pins_map.end()) {
      entry->pinset = pins_it->second.first;
      entry->hpkp_include_subdomains = pins_it->second.second;
      pins_map.erase(entry->hostname);
    }

    entries->push_back(std::move(entry));
  }

  // Any remaining entries in pins_map have pinning information, but are not
  // HSTS preloaded.
  for (auto const& pins_entry : pins_map) {
    auto entry = std::make_unique<TransportSecurityStateEntry>();
    entry->hostname = pins_entry.first;
    entry->force_https = false;
    entry->pinset = pins_entry.second.first;
    entry->hpkp_include_subdomains = pins_entry.second.second;
    entries->push_back(std::move(entry));
  }

  base::Value::List* pinsets_list = pins_dict->FindList("pinsets");
  if (!pinsets_list) {
    LOG(ERROR) << "Could not parse the pinsets in the input JSON";
    return false;
  }

  for (size_t i = 0; i < pinsets_list->size(); ++i) {
    const base::Value::Dict* parsed = (*pinsets_list)[i].GetIfDict();
    if (!parsed) {
      LOG(ERROR) << "Could not parse pinset " << base::NumberToString(i)
                 << " in the input JSON";
      return false;
    }

    const std::string* maybe_name = parsed->FindString("name");
    if (!maybe_name) {
      LOG(ERROR) << "Could not extract the name for pinset "
                 << base::NumberToString(i) << " from the input JSON";
      return false;
    }
    std::string name = *maybe_name;

    const std::string* maybe_report_uri = parsed->FindString("report_uri");
    std::string report_uri =
        maybe_report_uri ? *maybe_report_uri : std::string();

    auto pinset = std::make_unique<Pinset>(name, report_uri);

    const base::Value::List* pinset_static_hashes_list =
        parsed->FindList("static_spki_hashes");
    if (pinset_static_hashes_list) {
      for (const auto& hash : *pinset_static_hashes_list) {
        if (!hash.is_string()) {
          LOG(ERROR) << "Could not parse static spki hash "
                     << hash.DebugString() << " in the input JSON";
          return false;
        }
        pinset->AddStaticSPKIHash(hash.GetString());
      }
    }

    const base::Value::List* pinset_bad_static_hashes_list =
        parsed->FindList("bad_static_spki_hashes");
    if (pinset_bad_static_hashes_list) {
      for (const auto& hash : *pinset_bad_static_hashes_list) {
        if (!hash.is_string()) {
          LOG(ERROR) << "Could not parse bad static spki hash "
                     << hash.DebugString() << " in the input JSON";
          return false;
        }
        pinset->AddBadStaticSPKIHash(hash.GetString());
      }
    }

    pinsets->RegisterPinset(std::move(pinset));
  }

  return true;
}

}  // namespace net::transport_security_state