-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathcose_common.h
More file actions
534 lines (457 loc) · 14.7 KB
/
Copy pathcose_common.h
File metadata and controls
534 lines (457 loc) · 14.7 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#pragma once
#include "ccf/crypto/openssl/openssl_wrappers.h"
#include "ccf/ds/hex.h"
#include "ccf/ds/x509_time_fmt.h"
#include "ccf/receipt.h"
#include <chrono>
#include <crypto/cbor.h>
#include <crypto/cose.h>
#include <crypto/cose_utils.h>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <variant>
namespace ccf::cose
{
using Signature = std::span<const uint8_t>;
static bool is_ecdsa_alg(int64_t cose_alg)
{
// https://www.iana.org/assignments/cose/cose.xhtml
constexpr int COSE_ALGORITHM_ES256 = -7;
constexpr int COSE_ALGORITHM_ES384 = -35;
constexpr int COSE_ALGORITHM_ES512 = -36;
return cose_alg == COSE_ALGORITHM_ES256 ||
cose_alg == COSE_ALGORITHM_ES384 || cose_alg == COSE_ALGORITHM_ES512;
}
static bool is_rsa_alg(int64_t cose_alg)
{
// https: // www.iana.org/assignments/cose/cose.xhtml
constexpr int COSE_ALGORITHM_PS256 = -37;
constexpr int COSE_ALGORITHM_PS384 = -38;
constexpr int COSE_ALGORITHM_PS512 = -39;
return cose_alg == COSE_ALGORITHM_PS256 ||
cose_alg == COSE_ALGORITHM_PS384 || cose_alg == COSE_ALGORITHM_PS512;
}
struct COSEDecodeError : public std::runtime_error
{
COSEDecodeError(const std::string& msg) : std::runtime_error(msg) {}
};
struct COSESignatureValidationError : public std::runtime_error
{
COSESignatureValidationError(const std::string& msg) :
std::runtime_error(msg)
{}
};
struct CwtClaims
{
std::optional<int64_t> iat;
std::string iss;
std::string sub;
std::optional<int64_t> svn;
};
struct Sign1ProtectedHeader
{
int64_t alg{};
std::optional<std::variant<int64_t, std::string>> cty;
std::vector<std::vector<uint8_t>> x5chain;
CwtClaims cwt;
};
static void decode_cwt_claims(const ccf::cbor::Value& cbor, CwtClaims& claims)
{
using namespace ccf::cbor;
const auto& cwt_claims = rethrow_with_msg(
[&]() -> auto& {
return cbor->map_at(make_signed(ccf::cose::header::iana::CWT_CLAIMS));
},
"Parse CWT claims map");
try
{
const auto& iat =
cwt_claims->map_at(make_signed(ccf::cwt::header::iana::IAT));
try
{
claims.iat = iat->as_signed();
}
catch (const CBORDecodeError&)
{
// CWT NumericDate values MUST omit CBOR tags:
// https://www.rfc-editor.org/rfc/rfc8392.html#section-5
// This non-conforming fallback accepts CBOR tag 1 for UVM
// endorsement compatibility.
claims.iat = iat->tag_at(ccf::cbor::tag::EPOCH_DATE_TIME)->as_signed();
}
}
catch (const CBORDecodeError& err)
{
std::ignore = err; // optional field
}
claims.iss = rethrow_with_msg(
[&]() {
return cwt_claims->map_at(make_signed(ccf::cwt::header::iana::ISS))
->as_string();
},
fmt::format(
"Parse CWT claim iss({}) field", ccf::cwt::header::iana::ISS));
claims.sub = rethrow_with_msg(
[&]() {
return cwt_claims->map_at(make_signed(ccf::cwt::header::iana::SUB))
->as_string();
},
fmt::format(
"Parse CWT claim sub({}) field", ccf::cwt::header::iana::SUB));
try
{
claims.svn =
cwt_claims->map_at(make_string(ccf::cwt::header::custom::SVN))
->as_signed();
}
catch (const CBORDecodeError& err)
{
if (err.error_code() != Error::KEY_NOT_FOUND)
{
throw;
}
}
}
static void validate_cwt_iat_against_x5chain(
const CwtClaims& claims,
const std::vector<std::vector<uint8_t>>& x5chain,
std::string_view context)
{
if (!claims.iat.has_value())
{
return;
}
if (x5chain.empty())
{
throw COSEDecodeError(
fmt::format("No certificates in {} x5chain", context));
}
const auto common_validity_period =
ccf::crypto::OpenSSL::get_x509_chain_common_validity_period(x5chain);
if (!common_validity_period.has_value())
{
throw COSEDecodeError(fmt::format(
"Certificates in {} x5chain have no common validity period", context));
}
const auto iat = ccf::nonstd::SystemClock::time_point{
std::chrono::seconds{claims.iat.value()}};
if (
iat < common_validity_period->not_before ||
iat > common_validity_period->not_after)
{
throw COSEDecodeError(fmt::format(
"CWT iat {} in {} is outside x5chain common validity period [{}, {}]",
claims.iat.value(),
context,
ccf::ds::to_x509_time_string(common_validity_period->not_before),
ccf::ds::to_x509_time_string(common_validity_period->not_after)));
}
}
static Sign1ProtectedHeader decode_sign1_protected_header(
const ccf::cbor::Value& phdr)
{
using namespace ccf::cbor;
Sign1ProtectedHeader hdr;
hdr.alg = rethrow_with_msg(
[&]() {
return phdr->map_at(make_signed(ccf::cose::header::iana::ALG))
->as_signed();
},
fmt::format(
"Parse protected header alg({})", ccf::cose::header::iana::ALG));
try
{
const auto& cty =
phdr->map_at(make_signed(ccf::cose::header::iana::CONTENT_TYPE));
try
{
hdr.cty = std::string(cty->as_string());
}
catch (const CBORDecodeError&)
{
hdr.cty = cty->as_signed();
}
}
catch (const CBORDecodeError& err)
{
std::ignore = err; // optional field
}
hdr.x5chain = rethrow_with_msg(
[&]() {
const auto& x5chain_val =
phdr->map_at(make_signed(ccf::cose::header::iana::X5CHAIN));
return ccf::cose::utils::parse_x5chain(x5chain_val);
},
fmt::format(
"Parse protected header x5chain({})",
ccf::cose::header::iana::X5CHAIN));
decode_cwt_claims(phdr, hdr.cwt);
return hdr;
}
struct CcfClaims
{
std::string txid;
};
struct CcfCoseReceiptPhdr
{
int alg{};
std::vector<uint8_t> kid;
CwtClaims cwt{};
CcfClaims ccf{};
int vds{};
};
struct Leaf
{
std::vector<uint8_t> write_set_digest;
std::string commit_evidence;
std::vector<uint8_t> claims_digest;
};
struct MerkleProof
{
Leaf leaf;
std::vector<std::pair<int64_t, std::vector<uint8_t>>> path;
};
struct CcfCoseReceipt
{
CcfCoseReceiptPhdr phdr;
std::vector<uint8_t> merkle_root;
std::vector<uint8_t> claims_digest;
};
static void validate_sha256_bytes(
std::span<const uint8_t> bytes, std::string_view field)
{
if (bytes.size() != ccf::crypto::Sha256Hash::SIZE)
{
throw COSEDecodeError(fmt::format(
"Unsupported {} size: {} (expected {})",
field,
bytes.size(),
ccf::crypto::Sha256Hash::SIZE));
}
}
static ccf::crypto::Sha256Hash sha256_from_bytes(
std::span<const uint8_t> bytes, std::string_view field)
{
validate_sha256_bytes(bytes, field);
const std::span<const uint8_t, ccf::crypto::Sha256Hash::SIZE> fixed{
bytes.data(), ccf::crypto::Sha256Hash::SIZE};
return ccf::crypto::Sha256Hash::from_span(fixed);
}
static std::vector<uint8_t> recompute_merkle_root(const MerkleProof& proof)
{
auto ce_digest = ccf::crypto::Sha256Hash(proof.leaf.commit_evidence);
auto leaf_digest = ccf::crypto::Sha256Hash(
sha256_from_bytes(
proof.leaf.write_set_digest, "Merkle proof write set digest"),
ce_digest,
sha256_from_bytes(
proof.leaf.claims_digest, "Merkle proof claims digest"));
for (const auto& element : proof.path)
{
const auto sibling =
sha256_from_bytes(element.second, "Merkle proof sibling");
if (element.first != 0)
{
leaf_digest = ccf::crypto::Sha256Hash(sibling, leaf_digest);
}
else
{
leaf_digest = ccf::crypto::Sha256Hash(leaf_digest, sibling);
}
}
return {leaf_digest.h.begin(), leaf_digest.h.end()};
}
static void decode_ccf_claims(const ccf::cbor::Value& cbor, CcfClaims& claims)
{
using namespace ccf::cbor;
const auto& ccf_claims = rethrow_with_msg(
[&]() -> auto& {
return cbor->map_at(make_string(ccf::cose::header::custom::CCF_V1));
},
"Parse CCF claims map");
claims.txid = rethrow_with_msg(
[&]() {
return ccf_claims->map_at(make_string(ccf::cose::header::custom::TX_ID))
->as_string();
},
fmt::format(
"Parse CCF claims TxID ({}) field", ccf::cose::header::custom::TX_ID));
}
static CcfCoseReceiptPhdr decode_ccf_receipt_phdr(ccf::cbor::Value& cbor)
{
using namespace ccf::cbor;
CcfCoseReceiptPhdr phdr{};
phdr.alg = rethrow_with_msg(
[&]() {
return cbor->map_at(make_signed(ccf::cose::header::iana::ALG))
->as_signed();
},
fmt::format(
"Parse protected header alg({})", ccf::cose::header::iana::ALG));
rethrow_with_msg(
[&]() {
const auto& bytes =
cbor->map_at(make_signed(ccf::cose::header::iana::KID))->as_bytes();
phdr.kid.assign(bytes.begin(), bytes.end());
},
fmt::format(
"Parse protected header kid({})", ccf::cose::header::iana::KID));
phdr.vds = rethrow_with_msg(
[&]() {
return cbor->map_at(make_signed(ccf::cose::header::iana::VDS))
->as_signed();
},
fmt::format(
"Parse protected header vds({})", ccf::cose::header::iana::VDS));
if (phdr.vds != ccf::cose::value::CCF_LEDGER_SHA256)
{
throw COSEDecodeError(fmt::format(
"Unsupported vds value ({}) in protected header", phdr.vds));
}
decode_cwt_claims(cbor, phdr.cwt);
decode_ccf_claims(cbor, phdr.ccf);
return phdr;
}
static std::vector<MerkleProof> decode_merkle_proofs(
const ccf::cbor::Value& cbor)
{
using namespace ccf::cbor;
const auto& uhdr = rethrow_with_msg(
[&]() -> auto& { return cbor->array_at(1); },
"Parse unprotected header map");
const auto& vdp = rethrow_with_msg(
[&]() -> auto& {
return uhdr->map_at(make_signed(ccf::cose::header::iana::VDP));
},
fmt::format("Parse vdp() map", ccf::cose::header::iana::VDP));
const auto& proofs_array = rethrow_with_msg(
[&]() -> auto& {
return vdp->map_at(
make_signed(ccf::cose::header::iana::INCLUSION_PROOFS));
},
"Parse inclusion proofs");
std::vector<MerkleProof> proofs;
rethrow_with_msg(
[&]() {
if (proofs_array->size() == 0)
{
throw CBORDecodeError(Error::DECODE_FAILED, "Empty proofs array");
}
},
"Check proofs array");
for (size_t i = 0; i < proofs_array->size(); ++i)
{
auto cbor_proof = rethrow_with_msg(
[&]() { return parse(proofs_array->array_at(i)->as_bytes()); },
"Parse an encoded proof");
const auto& leaf = rethrow_with_msg(
[&]() -> auto& {
return cbor_proof->map_at(
make_signed(ccf::MerkleProofLabel::MERKLE_PROOF_LEAF_LABEL));
},
"Parse proof: leaf");
MerkleProof proof;
rethrow_with_msg(
[&]() {
const auto& bytes =
leaf->array_at(ccf::MerkleProofPathBranch::LEFT)->as_bytes();
validate_sha256_bytes(bytes, "Merkle proof write set digest");
proof.leaf.write_set_digest.assign(bytes.begin(), bytes.end());
},
"Parse leaf at wsd");
proof.leaf.commit_evidence = rethrow_with_msg(
[&]() {
return leaf->array_at(ccf::MerkleProofPathBranch::RIGHT)->as_string();
},
"Parse leaf at ce");
rethrow_with_msg(
[&]() {
const auto& bytes = leaf->array_at(2)->as_bytes();
validate_sha256_bytes(bytes, "Merkle proof claims digest");
proof.leaf.claims_digest.assign(bytes.begin(), bytes.end());
},
"Parse leaf at cd");
const auto& cbor_path = rethrow_with_msg(
[&]() -> auto& {
return cbor_proof->map_at(
make_signed(ccf::MerkleProofLabel::MERKLE_PROOF_PATH_LABEL));
},
"Parse proof: path");
rethrow_with_msg(
[&]() {
if (cbor_path->size() == 0)
{
throw CBORDecodeError(Error::DECODE_FAILED, "Empty path");
}
},
"Check proof: path");
for (size_t j = 0; j < cbor_path->size(); j++)
{
std::pair<int64_t, std::vector<uint8_t>> path_item;
const auto& link = rethrow_with_msg(
[&]() -> auto& { return cbor_path->array_at(j); }, "Parse path link");
path_item.first = static_cast<int64_t>(rethrow_with_msg(
[&]() { return simple_to_boolean(link->array_at(0)->as_simple()); },
"Parse path element at direction"));
rethrow_with_msg(
[&]() {
const auto& bytes = link->array_at(1)->as_bytes();
validate_sha256_bytes(bytes, "Merkle proof sibling");
path_item.second.assign(bytes.begin(), bytes.end());
},
"Parse path element at hash");
proof.path.push_back(path_item);
}
proofs.push_back(proof);
}
return proofs;
}
static CcfCoseReceipt decode_ccf_receipt(
const std::vector<uint8_t>& cose_sign1, bool recompute_root)
{
using namespace ccf::cbor;
auto cose_cbor =
rethrow_with_msg([&]() { return parse(cose_sign1); }, "Parse COSE CBOR");
const auto& cose_envelope = rethrow_with_msg(
[&]() -> auto& { return cose_cbor->tag_at(ccf::cbor::tag::COSE_SIGN_1); },
"Parse COSE tag");
const auto& phdr_raw = rethrow_with_msg(
[&]() -> auto& { return cose_envelope->array_at(0); },
"Parse raw protected header");
auto phdr = rethrow_with_msg(
[&]() { return parse(phdr_raw->as_bytes()); }, "Parse protected header");
CcfCoseReceipt receipt;
receipt.phdr = decode_ccf_receipt_phdr(phdr);
if (recompute_root)
{
auto proofs = decode_merkle_proofs(cose_envelope);
if (proofs.empty())
{
throw COSEDecodeError("No Merkle proofs found in COSE receipt");
}
receipt.merkle_root = recompute_merkle_root(proofs[0]);
receipt.claims_digest = proofs[0].leaf.claims_digest;
for (size_t i = 1; i < proofs.size(); ++i)
{
auto root = recompute_merkle_root(proofs[i]);
if (root != receipt.merkle_root)
{
throw COSEDecodeError(
"Inconsistent Merkle roots computed from COSE receipt proofs");
}
if (proofs[i].leaf.claims_digest != receipt.claims_digest)
{
throw COSEDecodeError(fmt::format(
"Claims from proofs don't match: {} != {}",
ds::to_hex(receipt.claims_digest),
ds::to_hex(proofs[i].leaf.claims_digest)));
}
}
}
return receipt;
}
}