summaryrefslogtreecommitdiffstats
path: root/security/ct/BTVerifier.cpp
blob: 02281fcffd4b4ed819404ae0b77bc95f94be031b (plain)
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "BTVerifier.h"

#include <stdint.h>

#include "CTUtils.h"
#include "SignedCertificateTimestamp.h"
#include "hasht.h"
#include "mozpkix/pkixnss.h"
#include "mozpkix/pkixutil.h"

namespace mozilla {
namespace ct {

using namespace mozilla::pkix;

typedef mozilla::pkix::Result Result;

// Common prefix lengths
static const size_t kLogIdPrefixLengthBytes = 1;
static const size_t kBTTreeSizeLength = 8;
static const size_t kNodeHashPrefixLengthBytes = 1;

// Members of a SignedTreeHeadDataV2 struct
static const size_t kSTHTimestampLength = 8;
static const size_t kSTHExtensionsLengthBytes = 2;
static const size_t kSTHSignatureLengthBytes = 2;

// Members of a Inclusion Proof struct
static const size_t kLeafIndexLength = 8;
static const size_t kInclusionPathLengthBytes = 2;

static Result GetDigestAlgorithmLengthAndIdentifier(
    DigestAlgorithm digestAlgorithm,
    /* out */ size_t& digestAlgorithmLength,
    /* out */ SECOidTag& digestAlgorithmId) {
  switch (digestAlgorithm) {
    case DigestAlgorithm::sha512:
      digestAlgorithmLength = SHA512_LENGTH;
      digestAlgorithmId = SEC_OID_SHA512;
      return Success;
    case DigestAlgorithm::sha256:
      digestAlgorithmLength = SHA256_LENGTH;
      digestAlgorithmId = SEC_OID_SHA256;
      return Success;
    default:
      return pkix::Result::FATAL_ERROR_INVALID_ARGS;
  }
}

Result DecodeAndVerifySignedTreeHead(
    Input signerSubjectPublicKeyInfo, DigestAlgorithm digestAlgorithm,
    der::PublicKeyAlgorithm publicKeyAlgorithm, Input signedTreeHeadInput,
    /* out */ SignedTreeHeadDataV2& signedTreeHead) {
  SignedTreeHeadDataV2 result;
  Reader reader(signedTreeHeadInput);

  Input logId;
  Result rv = ReadVariableBytes<kLogIdPrefixLengthBytes>(reader, logId);
  if (rv != Success) {
    return rv;
  }
  InputToBuffer(logId, result.logId);

  // This is the beginning of the data covered by the signature.
  Reader::Mark signedDataMark = reader.GetMark();

  rv = ReadUint<kSTHTimestampLength>(reader, result.timestamp);
  if (rv != Success) {
    return rv;
  }

  rv = ReadUint<kBTTreeSizeLength>(reader, result.treeSize);
  if (rv != Success) {
    return rv;
  }

  Input hash;
  rv = ReadVariableBytes<kNodeHashPrefixLengthBytes>(reader, hash);
  if (rv != Success) {
    return rv;
  }
  InputToBuffer(hash, result.rootHash);

  // We ignore any extensions, but we have to read them.
  Input extensionsInput;
  rv = ReadVariableBytes<kSTHExtensionsLengthBytes>(reader, extensionsInput);
  if (rv != Success) {
    return rv;
  }

  Input signedDataInput;
  rv = reader.GetInput(signedDataMark, signedDataInput);
  if (rv != Success) {
    return rv;
  }

  Input signatureInput;
  rv = ReadVariableBytes<kSTHSignatureLengthBytes>(reader, signatureInput);
  if (rv != Success) {
    return rv;
  }

  switch (publicKeyAlgorithm) {
    case der::PublicKeyAlgorithm::ECDSA:
      rv = VerifyECDSASignedDataNSS(signedDataInput, digestAlgorithm,
                                    signatureInput, signerSubjectPublicKeyInfo,
                                    nullptr);
      break;
    case der::PublicKeyAlgorithm::RSA_PKCS1:
    default:
      return Result::FATAL_ERROR_INVALID_ARGS;
  }
  if (rv != Success) {
    return rv;
  }

  if (!reader.AtEnd()) {
    return pkix::Result::ERROR_BAD_DER;
  }

  signedTreeHead = std::move(result);
  return Success;
}

Result DecodeInclusionProof(Input input, InclusionProofDataV2& output) {
  InclusionProofDataV2 result;
  Reader reader(input);

  Input logId;
  Result rv = ReadVariableBytes<kLogIdPrefixLengthBytes>(reader, logId);
  if (rv != Success) {
    return rv;
  }

  rv = ReadUint<kBTTreeSizeLength>(reader, result.treeSize);
  if (rv != Success) {
    return rv;
  }

  if (result.treeSize < 1) {
    return pkix::Result::ERROR_BAD_DER;
  }

  rv = ReadUint<kLeafIndexLength>(reader, result.leafIndex);
  if (rv != Success) {
    return rv;
  }

  if (result.leafIndex >= result.treeSize) {
    return pkix::Result::ERROR_BAD_DER;
  }

  Input pathInput;
  rv = ReadVariableBytes<kInclusionPathLengthBytes>(reader, pathInput);
  if (rv != Success) {
    return rv;
  }

  if (pathInput.GetLength() < 1) {
    return pkix::Result::ERROR_BAD_DER;
  }

  Reader pathReader(pathInput);
  std::vector<Buffer> inclusionPath;

  while (!pathReader.AtEnd()) {
    Input hash;
    rv = ReadVariableBytes<kNodeHashPrefixLengthBytes>(pathReader, hash);
    if (rv != Success) {
      return rv;
    }

    Buffer hashBuffer;
    InputToBuffer(hash, hashBuffer);

    inclusionPath.push_back(std::move(hashBuffer));
  }

  if (!reader.AtEnd()) {
    return pkix::Result::ERROR_BAD_DER;
  }

  InputToBuffer(logId, result.logId);

  result.inclusionPath = std::move(inclusionPath);

  output = std::move(result);
  return Success;
}

static Result CommonFinishDigest(UniquePK11Context& context,
                                 size_t digestAlgorithmLength,
                                 /* out */ Buffer& outputBuffer) {
  uint32_t outLen = 0;
  outputBuffer.assign(digestAlgorithmLength, 0);
  if (PK11_DigestFinal(context.get(), outputBuffer.data(), &outLen,
                       digestAlgorithmLength) != SECSuccess) {
    return Result::FATAL_ERROR_LIBRARY_FAILURE;
  }
  if (outLen != digestAlgorithmLength) {
    return Result::FATAL_ERROR_LIBRARY_FAILURE;
  }
  return Success;
}

static Result LeafHash(Input leafEntry, size_t digestAlgorithmLength,
                       SECOidTag digestAlgorithmId,
                       /* out */ Buffer& calculatedHash) {
  UniquePK11Context context(PK11_CreateDigestContext(digestAlgorithmId));
  if (!context) {
    return Result::FATAL_ERROR_LIBRARY_FAILURE;
  }
  const unsigned char zero = 0;
  if (PK11_DigestOp(context.get(), &zero, 1u) != SECSuccess) {
    return Result::FATAL_ERROR_LIBRARY_FAILURE;
  }
  SECItem leafEntryItem = UnsafeMapInputToSECItem(leafEntry);
  if (PK11_DigestOp(context.get(), leafEntryItem.data, leafEntryItem.len) !=
      SECSuccess) {
    return Result::FATAL_ERROR_LIBRARY_FAILURE;
  }
  return CommonFinishDigest(context, digestAlgorithmLength, calculatedHash);
}

static Result NodeHash(const Buffer& left, const Buffer& right,
                       size_t digestAlgorithmLength,
                       SECOidTag digestAlgorithmId,
                       /* out */ Buffer& calculatedHash) {
  UniquePK11Context context(PK11_CreateDigestContext(digestAlgorithmId));
  if (!context) {
    return Result::FATAL_ERROR_LIBRARY_FAILURE;
  }
  const unsigned char one = 1;
  if (PK11_DigestOp(context.get(), &one, 1u) != SECSuccess) {
    return Result::FATAL_ERROR_LIBRARY_FAILURE;
  }
  if (PK11_DigestOp(context.get(), left.data(), left.size()) != SECSuccess) {
    return Result::FATAL_ERROR_LIBRARY_FAILURE;
  }
  if (PK11_DigestOp(context.get(), right.data(), right.size()) != SECSuccess) {
    return Result::FATAL_ERROR_LIBRARY_FAILURE;
  }
  return CommonFinishDigest(context, digestAlgorithmLength, calculatedHash);
}

// This algorithm is specified by:
// https://tools.ietf.org/html/draft-ietf-trans-rfc6962-bis-28#section-2.1.3.2
Result VerifyInclusionProof(const InclusionProofDataV2& proof, Input leafEntry,
                            Input expectedRootHash,
                            DigestAlgorithm digestAlgorithm) {
  if (proof.treeSize == 0) {
    return pkix::Result::ERROR_BAD_SIGNATURE;
  }
  size_t digestAlgorithmLength;
  SECOidTag digestAlgorithmId;
  Result rv = GetDigestAlgorithmLengthAndIdentifier(
      digestAlgorithm, digestAlgorithmLength, digestAlgorithmId);
  if (rv != Success) {
    return rv;
  }
  if (proof.leafIndex >= proof.treeSize) {
    return pkix::Result::ERROR_BAD_SIGNATURE;
  }
  if (expectedRootHash.GetLength() != digestAlgorithmLength) {
    return pkix::Result::ERROR_BAD_SIGNATURE;
  }
  uint64_t leafIndex = proof.leafIndex;
  uint64_t lastNodeIndex = proof.treeSize - 1;
  Buffer calculatedHash;
  rv = LeafHash(leafEntry, digestAlgorithmLength, digestAlgorithmId,
                calculatedHash);
  if (rv != Success) {
    return rv;
  }
  for (const auto& hash : proof.inclusionPath) {
    if (lastNodeIndex == 0) {
      return pkix::Result::ERROR_BAD_SIGNATURE;
    }
    if (leafIndex % 2 == 1 || leafIndex == lastNodeIndex) {
      rv = NodeHash(hash, calculatedHash, digestAlgorithmLength,
                    digestAlgorithmId, calculatedHash);
      if (rv != Success) {
        return rv;
      }
      if (leafIndex % 2 == 0) {
        while (leafIndex % 2 == 0 && lastNodeIndex > 0) {
          leafIndex >>= 1;
          lastNodeIndex >>= 1;
        }
      }
    } else {
      rv = NodeHash(calculatedHash, hash, digestAlgorithmLength,
                    digestAlgorithmId, calculatedHash);
      if (rv != Success) {
        return rv;
      }
    }
    leafIndex >>= 1;
    lastNodeIndex >>= 1;
  }
  if (lastNodeIndex != 0) {
    return pkix::Result::ERROR_BAD_SIGNATURE;
  }
  assert(calculatedHash.size() == digestAlgorithmLength);
  if (calculatedHash.size() != digestAlgorithmLength) {
    return pkix::Result::FATAL_ERROR_LIBRARY_FAILURE;
  }
  if (memcmp(calculatedHash.data(), expectedRootHash.UnsafeGetData(),
             digestAlgorithmLength) != 0) {
    return pkix::Result::ERROR_BAD_SIGNATURE;
  }
  return Success;
}

}  // namespace ct
}  // namespace mozilla