File: serializer.cc

package info (click to toggle)
golang-github-google-certificate-transparency 0.0~git20160709.0.0f6e3d1~ds1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 5,676 kB
  • sloc: cpp: 35,278; python: 11,838; java: 1,911; sh: 1,885; makefile: 950; xml: 520; ansic: 225
file content (720 lines) | stat: -rw-r--r-- 24,464 bytes parent folder | download
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
/* -*- indent-tabs-mode: nil -*- */
#include "proto/serializer.h"

#include <gflags/gflags.h>
#include <glog/logging.h>
#include <math.h>
#include <string>

#include "proto/ct.pb.h"

using cert_trans::serialization::internal::PrefixLength;
using cert_trans::serialization::SerializeResult;
using cert_trans::serialization::DeserializeResult;
using cert_trans::serialization::WriteDigitallySigned;
using cert_trans::serialization::WriteFixedBytes;
using cert_trans::serialization::WriteUint;
using cert_trans::serialization::WriteVarBytes;
using cert_trans::serialization::constants::kMaxSignatureLength;
using cert_trans::serialization::constants::kHashAlgorithmLengthInBytes;
using cert_trans::serialization::constants::kSigAlgorithmLengthInBytes;
using ct::DigitallySigned;
using ct::DigitallySigned_HashAlgorithm_IsValid;
using ct::DigitallySigned_SignatureAlgorithm_IsValid;
using ct::LogEntry;
using ct::MerkleTreeLeaf;
using ct::PrecertChainEntry;
using ct::SignedCertificateTimestamp;
using ct::SignedCertificateTimestampList;
using ct::SthExtension;
using ct::SctExtension;
using ct::Version_IsValid;
using ct::X509ChainEntry;
using google::protobuf::RepeatedPtrField;
using std::function;
using std::string;

const size_t Serializer::kMaxV2ExtensionType = (1 << 16) - 1;
const size_t Serializer::kMaxV2ExtensionsCount = (1 << 16) - 2;
const size_t Serializer::kMaxExtensionsLength = (1 << 16) - 1;
const size_t Serializer::kMaxSerializedSCTLength = (1 << 16) - 1;
const size_t Serializer::kMaxSCTListLength = (1 << 16) - 1;

const size_t Serializer::kLogEntryTypeLengthInBytes = 2;
const size_t Serializer::kSignatureTypeLengthInBytes = 1;
const size_t Serializer::kVersionLengthInBytes = 1;
const size_t Serializer::kKeyIDLengthInBytes = 32;
const size_t Serializer::kMerkleLeafTypeLengthInBytes = 1;
const size_t Serializer::kKeyHashLengthInBytes = 32;
const size_t Serializer::kTimestampLengthInBytes = 8;

DEFINE_bool(allow_reconfigure_serializer_test_only, false,
            "Allow tests to reconfigure the serializer multiple times.");

// TODO(pphaneuf): This is just to avoid causing diff churn while
// refactoring. Functions for internal use only should be put together
// in an anonymous namespace.
SerializeResult CheckSthExtensionsFormat(
    const repeated_sth_extension& extension);


namespace {


function<string(const ct::LogEntry&)> leaf_data;

function<SerializeResult(const ct::SignedCertificateTimestamp& sct,
                         const ct::LogEntry& entry, std::string* result)>
    serialize_sct_sig_input;

function<SerializeResult(const ct::SignedCertificateTimestamp& sct,
                         const ct::LogEntry& entry, std::string* result)>
    serialize_sct_merkle_leaf;

function<SerializeResult(uint64_t timestamp, int64_t tree_size,
                         const std::string& root_hash, std::string* result)>
    serialize_sth_sig_input_v1;

function<SerializeResult(uint64_t timestamp, int64_t tree_size,
                         const std::string& root_hash,
                         const repeated_sth_extension& sth_extension,
                         const std::string& log_id, std::string* result)>
    serialize_sth_sig_input_v2;

function<DeserializeResult(TLSDeserializer* d, ct::MerkleTreeLeaf* leaf)>
    read_merkle_tree_leaf;


}  // namespace


// static
string Serializer::LeafData(const LogEntry& entry) {
  CHECK(leaf_data);
  return leaf_data(entry);
}


// static
SerializeResult Serializer::SerializeV1STHSignatureInput(
    uint64_t timestamp, int64_t tree_size, const string& root_hash,
    string* result) {
  CHECK(result);
  // result will be cleared by SerializeV1STHSignatureInput
  CHECK(serialize_sth_sig_input_v1);
  return serialize_sth_sig_input_v1(timestamp, tree_size, root_hash, result);
}


static SerializeResult SerializeV1STHSignatureInput(uint64_t timestamp,
                                                    int64_t tree_size,
                                                    const string& root_hash,
                                                    string* result) {
  CHECK_GE(tree_size, 0);
  result->clear();
  if (root_hash.size() != 32)
    return SerializeResult::INVALID_HASH_LENGTH;
  WriteUint(ct::V1, Serializer::kVersionLengthInBytes, result);
  WriteUint(ct::TREE_HEAD, Serializer::kSignatureTypeLengthInBytes, result);
  WriteUint(timestamp, Serializer::kTimestampLengthInBytes, result);
  WriteUint(tree_size, 8, result);
  WriteFixedBytes(root_hash, result);
  return SerializeResult::OK;
}


// static
SerializeResult Serializer::SerializeV2STHSignatureInput(
    uint64_t timestamp, int64_t tree_size, const string& root_hash,
    const repeated_sth_extension& sth_extension, const string& log_id,
    string* result) {
  CHECK(result);
  CHECK(serialize_sth_sig_input_v2);
  return serialize_sth_sig_input_v2(timestamp, tree_size, root_hash,
                                     sth_extension, log_id, result);
}


static SerializeResult SerializeV2STHSignatureInput(
    uint64_t timestamp, int64_t tree_size, const string& root_hash,
    const RepeatedPtrField<SthExtension>& sth_extension, const string& log_id,
    string* result) {
  CHECK_GE(tree_size, 0);
  result->clear();
  if (root_hash.size() != 32) {
    return SerializeResult::INVALID_HASH_LENGTH;
  }
  SerializeResult res = CheckSthExtensionsFormat(sth_extension);
  if (res != SerializeResult::OK) {
    return res;
  }
  if (log_id.size() != Serializer::kKeyIDLengthInBytes) {
    return SerializeResult::INVALID_KEYID_LENGTH;
  }

  WriteUint(ct::V2, Serializer::kVersionLengthInBytes, result);
  WriteUint(ct::TREE_HEAD, Serializer::kSignatureTypeLengthInBytes, result);
  // TODO(eranm): This is wrong, V2 Log IDs are OIDs.
  WriteFixedBytes(log_id, result);
  WriteUint(timestamp, Serializer::kTimestampLengthInBytes, result);
  WriteUint(tree_size, 8, result);
  WriteFixedBytes(root_hash, result);
  // V2 STH can have multiple extensions
  WriteUint(sth_extension.size(), 2, result);
  for (auto it = sth_extension.begin(); it != sth_extension.end(); ++it) {
    WriteUint(it->sth_extension_type(), 2, result);
    WriteVarBytes(it->sth_extension_data(), Serializer::kMaxExtensionsLength,
                  result);
  }

  return SerializeResult::OK;
}


// static
SerializeResult Serializer::SerializeSTHSignatureInput(
    const ct::SignedTreeHead& sth, std::string* result) {
  CHECK(result);
  // result will be cleared by
  // SerializeV1STHSignatureInput or SerializeV2STHSignatureInput
  // TODO(alcutter): this should know whether it's V1 or V2 from the
  // Configure()
  switch (sth.version()) {
    case ct::V1:
      return SerializeV1STHSignatureInput(sth.timestamp(), sth.tree_size(),
                                          sth.sha256_root_hash(), result);
    case ct::V2:
      return SerializeV2STHSignatureInput(sth.timestamp(), sth.tree_size(),
                                          sth.sha256_root_hash(),
                                          sth.sth_extension(),
                                          sth.id().key_id(), result);
    default:
      break;
  }
  return SerializeResult::UNSUPPORTED_VERSION;
}


// static
SerializeResult Serializer::SerializeSCTMerkleTreeLeaf(
    const ct::SignedCertificateTimestamp& sct, const ct::LogEntry& entry,
    std::string* result) {
  CHECK(result);
  CHECK(serialize_sct_merkle_leaf);
  return serialize_sct_merkle_leaf(sct, entry, result);
}


// static
SerializeResult Serializer::SerializeSCTSignatureInput(
    const SignedCertificateTimestamp& sct, const LogEntry& entry,
    string* result) {
  CHECK(result);
  CHECK(serialize_sct_sig_input);
  return serialize_sct_sig_input(sct, entry, result);
}

SerializeResult WriteSCTV1(const SignedCertificateTimestamp& sct,
                           std::string* output) {
  CHECK(sct.version() == ct::V1);
  // output is cleared by SerializeSCT
  SerializeResult res = CheckExtensionsFormat(sct.extensions());
  if (res != SerializeResult::OK) {
    return res;
  }
  if (sct.id().key_id().size() != Serializer::kKeyIDLengthInBytes) {
    return SerializeResult::INVALID_KEYID_LENGTH;
  }
  WriteUint(sct.version(), Serializer::kVersionLengthInBytes, output);
  WriteFixedBytes(sct.id().key_id(), output);
  WriteUint(sct.timestamp(), Serializer::kTimestampLengthInBytes, output);
  WriteVarBytes(sct.extensions(), Serializer::kMaxExtensionsLength, output);
  return WriteDigitallySigned(sct.signature(), output);
}

void WriteSctExtension(const RepeatedPtrField<SctExtension>& extension,
                       std::string* output) {
  WriteUint(extension.size(), 2, output);
  for (auto it = extension.begin(); it != extension.end(); ++it) {
    WriteUint(it->sct_extension_type(), 2, output);
    WriteVarBytes(it->sct_extension_data(), Serializer::kMaxExtensionsLength,
                  output);
  }
}

SerializeResult WriteSCTV2(const SignedCertificateTimestamp& sct,
                           std::string* output) {
  CHECK(sct.version() == ct::V2);
  // output is cleared by SerializeSCT
  SerializeResult res = CheckSctExtensionsFormat(sct.sct_extension());
  if (res != SerializeResult::OK) {
    return res;
  }
  if (sct.id().key_id().size() != Serializer::kKeyIDLengthInBytes) {
    return SerializeResult::INVALID_KEYID_LENGTH;
  }
  WriteUint(sct.version(), Serializer::kVersionLengthInBytes, output);
  WriteFixedBytes(sct.id().key_id(), output);
  WriteUint(sct.timestamp(), Serializer::kTimestampLengthInBytes, output);
  // V2 SCT can have a number of extensions. They must be ordered by type
  // but we already checked that above.
  WriteSctExtension(sct.sct_extension(), output);
  return WriteDigitallySigned(sct.signature(), output);
}

// static
SerializeResult Serializer::SerializeSCT(const SignedCertificateTimestamp& sct,
                                         string* result) {
  SerializeResult res = SerializeResult::UNSUPPORTED_VERSION;

  result->clear();
  switch (sct.version()) {
    case ct::V1:
      res = WriteSCTV1(sct, result);
      break;
    case ct::V2:
      res = WriteSCTV2(sct, result);
      break;
    default:
      res = SerializeResult::UNSUPPORTED_VERSION;
  }
  if (res != SerializeResult::OK) {
    result->clear();
    return res;
  }
  return SerializeResult::OK;
}

// static
SerializeResult Serializer::SerializeSCTList(
    const SignedCertificateTimestampList& sct_list, string* result) {
  if (sct_list.sct_list_size() == 0) {
    return SerializeResult::EMPTY_LIST;
  }
  return SerializeList(sct_list.sct_list(),
                       Serializer::kMaxSerializedSCTLength,
                       Serializer::kMaxSCTListLength, result);
}

// static
SerializeResult Serializer::SerializeDigitallySigned(
    const DigitallySigned& sig, string* result) {
  result->clear();
  return WriteDigitallySigned(sig, result);
}

// static
SerializeResult Serializer::SerializeList(const repeated_string& in,
                                          size_t max_elem_length,
                                          size_t max_total_length,
                                          string* result) {
  std::string output;
  SerializeResult res =
      cert_trans::serialization::WriteList(in, max_elem_length,
                                           max_total_length, &output);
  if (res != SerializeResult::OK)
    return res;
  result->assign(output);
  return SerializeResult::OK;
}

SerializeResult CheckKeyHashFormat(const string& key_hash) {
  if (key_hash.size() != Serializer::kKeyHashLengthInBytes)
    return SerializeResult::INVALID_HASH_LENGTH;
  return SerializeResult::OK;
}


SerializeResult CheckExtensionsFormat(const string& extensions) {
  if (extensions.size() > Serializer::kMaxExtensionsLength)
    return SerializeResult::EXTENSIONS_TOO_LONG;
  return SerializeResult::OK;
}


// Checks the (v2) STH extensions are correct. The RFC defines that there can
// be up to 65534 of them and each one can contain up to 65535 bytes.
// They must be in ascending order of extension type.
SerializeResult CheckSthExtensionsFormat(
    const repeated_sth_extension& extension) {
  if (extension.size() > static_cast<int>(Serializer::kMaxV2ExtensionsCount)) {
    return SerializeResult::EXTENSIONS_TOO_LONG;
  }

  uint32_t last_type_seen = 0;

  for (auto it = extension.begin(); it != extension.end(); ++it) {
    if (it->sth_extension_type() > Serializer::kMaxV2ExtensionType) {
      return SerializeResult::INVALID_ENTRY_TYPE;
    }

    if (it->sth_extension_data().size() > Serializer::kMaxExtensionsLength) {
      return SerializeResult::EXTENSIONS_TOO_LONG;
    }

    if (it->sth_extension_type() < last_type_seen) {
      // It's out of order - reject
      return SerializeResult::EXTENSIONS_NOT_ORDERED;
    }

    last_type_seen = it->sth_extension_type();
  }

  return SerializeResult::OK;
}


// Checks the (v2) SCT extensions are correct. The RFC defines that there can
// be up to 65534 of them and each one can contain up to 65535 bytes. They
// must be in ascending order of extension type
SerializeResult CheckSctExtensionsFormat(
    const RepeatedPtrField<SctExtension>& extension) {
  if (extension.size() > static_cast<int>(Serializer::kMaxV2ExtensionsCount)) {
    return SerializeResult::EXTENSIONS_TOO_LONG;
  }

  uint32_t last_type_seen = 0;

  for (auto it = extension.begin(); it != extension.end(); ++it) {
    if (it->sct_extension_data().size() > Serializer::kMaxExtensionsLength) {
      return SerializeResult::EXTENSIONS_TOO_LONG;
    }

    if (it->sct_extension_type() > Serializer::kMaxV2ExtensionType) {
      return SerializeResult::INVALID_ENTRY_TYPE;
    }

    if (it->sct_extension_type() < last_type_seen) {
      // It's out of order - reject
      return SerializeResult::EXTENSIONS_NOT_ORDERED;
    }

    last_type_seen = it->sct_extension_type();
  }

  return SerializeResult::OK;
}


const size_t TLSDeserializer::kV2ExtensionCountLengthInBytes = 2;
const size_t TLSDeserializer::kV2ExtensionTypeLengthInBytes = 2;


TLSDeserializer::TLSDeserializer(const string& input)
    : current_pos_(input.data()), bytes_remaining_(input.size()) {
}


DeserializeResult TLSDeserializer::ReadSCTV1(SignedCertificateTimestamp* sct) {
  sct->set_version(ct::V1);
  if (!ReadFixedBytes(Serializer::kKeyIDLengthInBytes,
                      sct->mutable_id()->mutable_key_id())) {
    return DeserializeResult::INPUT_TOO_SHORT;
  }
  // V1 encoding.
  uint64_t timestamp = 0;
  if (!ReadUint(Serializer::kTimestampLengthInBytes, &timestamp)) {
    return DeserializeResult::INPUT_TOO_SHORT;
  }
  sct->set_timestamp(timestamp);
  string extensions;
  if (!ReadVarBytes(Serializer::kMaxExtensionsLength, &extensions)) {
    // In theory, could also be an invalid length prefix, but not if
    // length limits follow byte boundaries.
    return DeserializeResult::INPUT_TOO_SHORT;
  }
  return ReadDigitallySigned(sct->mutable_signature());
}

DeserializeResult TLSDeserializer::ReadSCTV2(SignedCertificateTimestamp* sct) {
  sct->set_version(ct::V2);
  if (!ReadFixedBytes(Serializer::kKeyIDLengthInBytes,
                      sct->mutable_id()->mutable_key_id())) {
    return DeserializeResult::INPUT_TOO_SHORT;
  }
  // V2 encoding.
  uint64_t timestamp = 0;
  if (!ReadUint(Serializer::kTimestampLengthInBytes, &timestamp)) {
    return DeserializeResult::INPUT_TOO_SHORT;
  }
  sct->set_timestamp(timestamp);
  // Extensions are handled differently for V2
  const DeserializeResult res = ReadSctExtension(sct->mutable_sct_extension());
  if (res != DeserializeResult::OK) {
    return res;
  }
  return ReadDigitallySigned(sct->mutable_signature());
}


DeserializeResult TLSDeserializer::ReadSCT(SignedCertificateTimestamp* sct) {
  int version;
  if (!ReadUint(Serializer::kVersionLengthInBytes, &version)) {
    return DeserializeResult::INPUT_TOO_SHORT;
  }
  if (!Version_IsValid(version) || (version != ct::V1 && version != ct::V2)) {
    return DeserializeResult::UNSUPPORTED_VERSION;
  }

  switch (version) {
    case ct::V1:
      return ReadSCTV1(sct);
      break;

    case ct::V2:

      return ReadSCTV2(sct);
      break;

    default:
      return DeserializeResult::UNSUPPORTED_VERSION;
  }
}


// static
DeserializeResult Deserializer::DeserializeSCT(
    const string& in, SignedCertificateTimestamp* sct) {
  TLSDeserializer deserializer(in);
  DeserializeResult res = deserializer.ReadSCT(sct);
  if (res != DeserializeResult::OK) {
    return res;
  }
  if (!deserializer.ReachedEnd()) {
    return DeserializeResult::INPUT_TOO_LONG;
  }
  return DeserializeResult::OK;
}


// static
DeserializeResult Deserializer::DeserializeSCTList(
    const string& in, SignedCertificateTimestampList* sct_list) {
  sct_list->clear_sct_list();
  DeserializeResult res = DeserializeList(in, Serializer::kMaxSCTListLength,
                                          Serializer::kMaxSerializedSCTLength,
                                          sct_list->mutable_sct_list());
  if (res != DeserializeResult::OK)
    return res;
  if (sct_list->sct_list_size() == 0)
    return DeserializeResult::EMPTY_LIST;
  return DeserializeResult::OK;
}


// static
DeserializeResult Deserializer::DeserializeDigitallySigned(
    const string& in, DigitallySigned* sig) {
  TLSDeserializer deserializer(in);
  DeserializeResult res = deserializer.ReadDigitallySigned(sig);
  if (res != DeserializeResult::OK)
    return res;
  if (!deserializer.ReachedEnd())
    return DeserializeResult::INPUT_TOO_LONG;
  return DeserializeResult::OK;
}


bool TLSDeserializer::ReadFixedBytes(size_t bytes, string* result) {
  if (bytes_remaining_ < bytes)
    return false;
  result->assign(current_pos_, bytes);
  current_pos_ += bytes;
  bytes_remaining_ -= bytes;
  return true;
}


bool TLSDeserializer::ReadLengthPrefix(size_t max_length, size_t* result) {
  size_t prefix_length = PrefixLength(max_length);
  size_t length;
  if (!ReadUint(prefix_length, &length) || length > max_length)
    return false;
  *result = length;
  return true;
}


bool TLSDeserializer::ReadVarBytes(size_t max_length, string* result) {
  size_t length;
  if (!ReadLengthPrefix(max_length, &length))
    return false;
  return ReadFixedBytes(length, result);
}


// static
DeserializeResult Deserializer::DeserializeList(const string& in,
                                                size_t max_total_length,
                                                size_t max_elem_length,
                                                repeated_string* out) {
  TLSDeserializer deserializer(in);
  DeserializeResult res =
      deserializer.ReadList(max_total_length, max_elem_length, out);
  if (res != DeserializeResult::OK)
    return res;
  if (!deserializer.ReachedEnd())
    return DeserializeResult::INPUT_TOO_LONG;
  return DeserializeResult::OK;
}


DeserializeResult TLSDeserializer::ReadList(size_t max_total_length,
                                            size_t max_elem_length,
                                            repeated_string* out) {
  string serialized_list;
  if (!ReadVarBytes(max_total_length, &serialized_list))
    // TODO(ekasper): could also be a length that's too large, if
    // length limits don't follow byte boundaries.
    return DeserializeResult::INPUT_TOO_SHORT;
  if (!ReachedEnd())
    return DeserializeResult::INPUT_TOO_LONG;

  TLSDeserializer list_reader(serialized_list);
  while (!list_reader.ReachedEnd()) {
    string elem;
    if (!list_reader.ReadVarBytes(max_elem_length, &elem))
      return DeserializeResult::INVALID_LIST_ENCODING;
    if (elem.empty())
      return DeserializeResult::EMPTY_ELEM_IN_LIST;
    *(out->Add()) = elem;
  }
  return DeserializeResult::OK;
}


DeserializeResult TLSDeserializer::ReadSctExtension(
    RepeatedPtrField<SctExtension>* extension) {
  uint32_t ext_count;
  if (!ReadUint(kV2ExtensionCountLengthInBytes, &ext_count)) {
    return DeserializeResult::INPUT_TOO_SHORT;
  }

  if (ext_count > Serializer::kMaxV2ExtensionsCount) {
    return DeserializeResult::EXTENSIONS_TOO_LONG;
  }

  for (uint32_t ext = 0; ext < ext_count; ++ext) {
    uint32_t ext_type;
    if (!ReadUint(kV2ExtensionTypeLengthInBytes, &ext_type)) {
      return DeserializeResult::INPUT_TOO_SHORT;
    }

    string ext_data;
    if (!ReadVarBytes(Serializer::kMaxExtensionsLength, &ext_data)) {
      return DeserializeResult::INPUT_TOO_SHORT;
    }

    SctExtension* new_ext = extension->Add();
    new_ext->set_sct_extension_type(ext_type);
    new_ext->set_sct_extension_data(ext_data);
  }

  // This makes sure they're correctly ordered (See RFC section 5.3)
  return CheckSctExtensionsFormat(*extension) == SerializeResult::OK
             ? DeserializeResult::OK
             : DeserializeResult::EXTENSIONS_NOT_ORDERED;
}


DeserializeResult TLSDeserializer::ReadDigitallySigned(DigitallySigned* sig) {
  int hash_algo = -1, sig_algo = -1;
  if (!ReadUint(kHashAlgorithmLengthInBytes, &hash_algo))
    return DeserializeResult::INPUT_TOO_SHORT;
  if (!DigitallySigned_HashAlgorithm_IsValid(hash_algo))
    return DeserializeResult::INVALID_HASH_ALGORITHM;
  if (!ReadUint(kSigAlgorithmLengthInBytes, &sig_algo))
    return DeserializeResult::INPUT_TOO_SHORT;
  if (!DigitallySigned_SignatureAlgorithm_IsValid(sig_algo))
    return DeserializeResult::INVALID_SIGNATURE_ALGORITHM;

  string sig_string;
  if (!ReadVarBytes(kMaxSignatureLength, &sig_string))
    return DeserializeResult::INPUT_TOO_SHORT;
  sig->set_hash_algorithm(
      static_cast<DigitallySigned::HashAlgorithm>(hash_algo));
  sig->set_sig_algorithm(
      static_cast<DigitallySigned::SignatureAlgorithm>(sig_algo));
  sig->set_signature(sig_string);
  return DeserializeResult::OK;
}


DeserializeResult TLSDeserializer::ReadExtensions(
    ct::TimestampedEntry* entry) {
  string extensions;
  if (!ReadVarBytes(Serializer::kMaxExtensionsLength, &extensions)) {
    return DeserializeResult::INPUT_TOO_SHORT;
  }
  CHECK_NOTNULL(entry)->set_extensions(extensions);
  return DeserializeResult::OK;
}


DeserializeResult Deserializer::DeserializeMerkleTreeLeaf(
    const std::string& in, ct::MerkleTreeLeaf* leaf) {
  TLSDeserializer des(in);

  DeserializeResult ret = read_merkle_tree_leaf(&des, leaf);
  if (ret != DeserializeResult::OK) {
    return ret;
  }

  if (!des.ReachedEnd()) {
    return DeserializeResult::INPUT_TOO_LONG;
  }

  return DeserializeResult::OK;
}


// static
void Serializer::ConfigureV1(
    const function<string(const ct::LogEntry&)>& leaf_data_func,
    const function<SerializeResult(
        const ct::SignedCertificateTimestamp& sct, const ct::LogEntry& entry,
        std::string* result)>& serialize_sct_sig_input_func,
    const function<SerializeResult(
        const ct::SignedCertificateTimestamp& sct, const ct::LogEntry& entry,
        std::string* result)>& serialize_sct_merkle_leaf_func) {
  CHECK(FLAGS_allow_reconfigure_serializer_test_only ||
        (!leaf_data&& !serialize_sct_sig_input &&
         !serialize_sct_merkle_leaf))
      << "Serializer already configured";
  leaf_data = leaf_data_func;
  serialize_sct_sig_input = serialize_sct_sig_input_func;
  serialize_sct_merkle_leaf = serialize_sct_merkle_leaf_func;
  serialize_sth_sig_input_v1 = ::SerializeV1STHSignatureInput;
}


// static
void Serializer::ConfigureV2(
    const function<string(const ct::LogEntry&)>& leaf_data_func,
    const function<SerializeResult(
        const ct::SignedCertificateTimestamp& sct, const ct::LogEntry& entry,
        std::string* result)>& serialize_sct_sig_input_func,
    const function<SerializeResult(
        const ct::SignedCertificateTimestamp& sct, const ct::LogEntry& entry,
        std::string* result)>& serialize_sct_merkle_leaf_func) {
  CHECK(FLAGS_allow_reconfigure_serializer_test_only ||
        (!leaf_data && !serialize_sct_sig_input &&
         !serialize_sct_merkle_leaf))
      << "Serializer already configured";
  leaf_data = leaf_data_func;
  serialize_sct_sig_input = serialize_sct_sig_input_func;
  serialize_sct_merkle_leaf = serialize_sct_merkle_leaf_func;
  serialize_sth_sig_input_v2 = ::SerializeV2STHSignatureInput;
}


// static
void Deserializer::Configure(
    const function<DeserializeResult(TLSDeserializer* d,
                                     ct::MerkleTreeLeaf* leaf)>&
        read_merkle_tree_leaf_func) {
  CHECK(FLAGS_allow_reconfigure_serializer_test_only ||
        !read_merkle_tree_leaf)
      << "Deserializer already configured";
  read_merkle_tree_leaf = read_merkle_tree_leaf_func;
}