-
Notifications
You must be signed in to change notification settings - Fork 251
Expand file tree
/
Copy pathnode_state.h
More file actions
3050 lines (2665 loc) · 99.9 KB
/
node_state.h
File metadata and controls
3050 lines (2665 loc) · 99.9 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
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#pragma once
#include "ccf/crypto/entropy.h"
#include "ccf/crypto/pem.h"
#include "ccf/crypto/symmetric_key.h"
#include "ccf/crypto/verifier.h"
#include "ccf/ds/json.h"
#include "ccf/entity_id.h"
#include "ccf/js/core/context.h"
#include "ccf/node/cose_signatures_config.h"
#include "ccf/pal/attestation_sev_snp.h"
#include "ccf/pal/locking.h"
#include "ccf/pal/platform.h"
#include "ccf/pal/snp_ioctl.h"
#include "ccf/pal/uvm_endorsements.h"
#include "ccf/service/node_info_network.h"
#include "ccf/service/reconfiguration_type.h"
#include "ccf/service/tables/self_healing_open.h"
#include "ccf/service/tables/service.h"
#include "ccf/tx.h"
#include "consensus/aft/raft.h"
#include "consensus/ledger_enclave.h"
#include "crypto/certs.h"
#include "ds/ccf_assert.h"
#include "ds/files.h"
#include "ds/internal_logger.h"
#include "ds/state_machine.h"
#include "enclave/rpc_sessions.h"
#include "encryptor.h"
#include "history.h"
#include "http/http_parser.h"
#include "indexing/indexer.h"
#include "js/global_class_ids.h"
#include "network_state.h"
#include "node/hooks.h"
#include "node/http_node_client.h"
#include "node/jwt_key_auto_refresh.h"
#include "node/ledger_secret.h"
#include "node/ledger_secrets.h"
#include "node/local_sealing.h"
#include "node/node_to_node_channel_manager.h"
#include "node/recovery_decision_protocol.h"
#include "node/snapshotter.h"
#include "node_to_node.h"
#include "pal/quote_generation.h"
#include "quote_endorsements_client.h"
#include "rpc/frontend.h"
#include "rpc/serialization.h"
#include "secret_broadcast.h"
#include "service/internal_tables_access.h"
#include "service/tables/local_sealing.h"
#include "service/tables/recovery_type.h"
#include "share_manager.h"
#include "snapshots/fetch.h"
#include "snapshots/filenames.h"
#include "uvm_endorsements.h"
#include <optional>
#ifdef USE_NULL_ENCRYPTOR
# include "kv/test/null_encryptor.h"
#endif
#include <algorithm>
#include <atomic>
#include <chrono>
#define FMT_HEADER_ONLY
#include <fmt/format.h>
#include <nlohmann/json.hpp>
#include <stdexcept>
#include <unordered_set>
#include <vector>
namespace ccf
{
using RaftType = aft::Aft<::consensus::LedgerEnclave>;
struct NodeCreateInfo
{
ccf::crypto::Pem self_signed_node_cert;
ccf::crypto::Pem service_cert;
};
inline void reset_data(std::vector<uint8_t>& data)
{
data.clear();
data.shrink_to_fit();
}
class NodeState : public AbstractNodeState
{
friend class RecoveryDecisionProtocolSubsystem;
struct FetchSnapshot : public ccf::tasks::BaseTask
{
const ccf::StartupConfig::Join join_config;
const ccf::CCFConfig::Snapshots snapshot_config;
NodeState* owner;
FetchSnapshot(
ccf::StartupConfig::Join join_config_,
ccf::CCFConfig::Snapshots snapshot_config_,
NodeState* owner_) :
join_config(std::move(join_config_)),
snapshot_config(std::move(snapshot_config_)),
owner(owner_)
{}
void do_task_implementation() override
{
// NB: Eventually this shouldn't be blocking, but reusing the current
// (blocking) helper for now
auto latest_peer_snapshot = snapshots::fetch_from_peer(
join_config.target_rpc_address,
join_config.service_cert,
join_config.fetch_snapshot_max_attempts,
join_config.fetch_snapshot_retry_interval.count_ms(),
join_config.fetch_snapshot_max_size.count_bytes());
// Ensure the in-flight task reference is cleared when this
// task completes, regardless of outcome, so that a subsequent
// join-retry can schedule a new fetch if needed.
struct ClearOnExit
{
NodeState* owner;
~ClearOnExit()
{
std::lock_guard<pal::Mutex> guard(owner->lock);
owner->snapshot_fetch_task = nullptr;
}
} clear_on_exit{owner};
if (latest_peer_snapshot.has_value())
{
LOG_INFO_FMT(
"Received snapshot {} from peer (size: {})",
latest_peer_snapshot->snapshot_name,
latest_peer_snapshot->snapshot_data.size());
try
{
const auto segments =
separate_segments(latest_peer_snapshot->snapshot_data);
verify_snapshot(segments, join_config.service_cert);
}
catch (const std::exception& e)
{
LOG_FAIL_FMT(
"Error while verifying fetched snapshot {}: {}",
latest_peer_snapshot->snapshot_name,
e.what());
return;
}
const auto snapshot_path =
std::filesystem::path(latest_peer_snapshot->snapshot_name);
// Ensure snapshot name is a simple filename (no directories, no "..",
// not absolute) before using it as a filesystem path.
if (
snapshot_path.empty() || snapshot_path.is_absolute() ||
snapshot_path.has_parent_path() ||
snapshot_path.filename() != snapshot_path)
{
LOG_FAIL_FMT(
"Rejecting snapshot with invalid name '{}' from peer",
latest_peer_snapshot->snapshot_name);
return;
}
const auto dst_path =
std::filesystem::path(snapshot_config.directory) / snapshot_path;
LOG_INFO_FMT(
"Snapshot verified - now writing to {}", dst_path.string());
if (files::exists(dst_path))
{
LOG_FAIL_FMT(
"Overwriting existing snapshot at {} with data retrieved from "
"peer",
dst_path);
}
files::dump(latest_peer_snapshot->snapshot_data, dst_path);
const auto snapshot_seqno =
snapshots::get_snapshot_idx_from_file_name(
latest_peer_snapshot->snapshot_name);
std::lock_guard<pal::Mutex> guard(owner->lock);
owner->set_startup_snapshot(
snapshot_seqno, std::move(latest_peer_snapshot->snapshot_data));
}
}
[[nodiscard]] const std::string& get_name() const override
{
static const std::string name = "FetchSnapshot";
return name;
}
};
private:
//
// this node's core state
//
::ds::StateMachine<NodeStartupState> sm;
pal::Mutex lock;
StartType start_type = StartType::Start;
ccf::crypto::CurveID curve_id;
std::vector<ccf::crypto::SubjectAltName> subject_alt_names;
std::shared_ptr<ccf::crypto::ECKeyPair_OpenSSL> node_sign_kp;
NodeId self;
std::shared_ptr<ccf::crypto::RSAKeyPair> node_encrypt_kp;
ccf::crypto::Pem self_signed_node_cert;
std::optional<ccf::crypto::Pem> endorsed_node_cert = std::nullopt;
QuoteInfo quote_info;
pal::PlatformAttestationMeasurement node_measurement;
std::optional<pal::snp::TcbVersionRaw> snp_tcb_version = std::nullopt;
ccf::StartupConfig config;
std::optional<pal::UVMEndorsements> snp_uvm_endorsements = std::nullopt;
std::shared_ptr<QuoteEndorsementsClient> quote_endorsements_client =
nullptr;
std::atomic<bool> stop_noticed = false;
//
// kv store, replication, and I/O
//
ringbuffer::AbstractWriterFactory& writer_factory;
ringbuffer::WriterPtr to_host;
ccf::consensus::Configuration consensus_config;
size_t sig_tx_interval = 0;
size_t sig_ms_interval = 0;
NetworkState& network;
std::shared_ptr<ccf::kv::Consensus> consensus;
std::shared_ptr<RPCMap> rpc_map;
std::shared_ptr<indexing::Indexer> indexer;
std::shared_ptr<NodeToNode> n2n_channels;
std::shared_ptr<Forwarder<NodeToNode>> cmd_forwarder;
std::shared_ptr<RPCSessions> rpcsessions;
std::shared_ptr<ccf::kv::TxHistory> history;
std::shared_ptr<ccf::kv::AbstractTxEncryptor> encryptor;
ShareManager share_manager;
std::shared_ptr<Snapshotter> snapshotter;
//
// recovery
//
std::shared_ptr<ccf::kv::Store> recovery_store;
ccf::kv::Version recovery_v = 0;
ccf::crypto::Sha256Hash recovery_root;
std::vector<ccf::kv::Version> view_history;
::consensus::Index last_recovered_signed_idx = 0;
RecoveredEncryptedLedgerSecrets recovered_encrypted_ledger_secrets;
std::optional<
std::tuple<ccf::NodeId, std::vector<uint8_t>, SealedRecoveryKey>>
cached_sealed_recovery_data = std::nullopt;
::consensus::Index last_recovered_idx = 0;
static const size_t recovery_batch_size = 100;
//
// JWT key auto-refresh
//
std::shared_ptr<JwtKeyAutoRefresh> jwt_key_auto_refresh;
std::unique_ptr<StartupSnapshotInfo> startup_snapshot_info = nullptr;
// Set to the snapshot seqno when a node starts from one and remembered for
// the lifetime of the node
ccf::kv::Version startup_seqno = 0;
ccf::tasks::Task join_periodic_task;
ccf::tasks::Task snapshot_fetch_task;
std::shared_ptr<ccf::kv::AbstractTxEncryptor> make_encryptor()
{
#ifdef USE_NULL_ENCRYPTOR
return std::make_shared<ccf::kv::NullTxEncryptor>();
#else
return std::make_shared<NodeEncryptor>(network.ledger_secrets);
#endif
}
void find_local_startup_snapshot()
{
if (start_type != StartType::Join && start_type != StartType::Recover)
{
return;
}
std::vector<std::filesystem::path> directories;
directories.emplace_back(config.snapshots.directory);
const auto& read_only_dir = config.snapshots.read_only_directory;
if (read_only_dir.has_value())
{
directories.emplace_back(read_only_dir.value());
}
const auto committed_snapshots =
snapshots::find_committed_snapshots_in_directories(directories);
for (const auto& [snapshot_seqno, snapshot_path] : committed_snapshots)
{
auto snapshot_data = files::slurp(snapshot_path);
LOG_INFO_FMT(
"Found latest local snapshot file: {} (size: {})",
snapshot_path,
snapshot_data.size());
const auto segments = separate_segments(snapshot_data);
try
{
verify_snapshot(segments, config.recover.previous_service_identity);
}
catch (const std::exception& e)
{
LOG_FAIL_FMT(
"Error while verifying {}: {}", snapshot_path.string(), e.what());
const auto dir = snapshot_path.parent_path();
const auto file_name = snapshot_path.filename();
if (dir == config.snapshots.directory)
{
LOG_INFO_FMT(
"Ignoring corrupt snapshot {} in directory {} and looking for "
"next",
dir.string(),
snapshot_path.string());
try
{
snapshots::ignore_snapshot_file(dir, file_name.string());
}
catch (std::logic_error& e)
{
LOG_FAIL_FMT("Unable to mark snapshot as ignored: {}", e.what());
}
}
else
{
LOG_FAIL_FMT(
"Snapshot {} is in a read-only directory {}, so will not be "
"modified. Ignoring and looking for next",
snapshot_path.string(),
dir.string());
}
continue;
}
set_startup_snapshot(snapshot_seqno, std::move(snapshot_data));
return;
}
LOG_INFO_FMT("No local snapshot found");
}
void set_startup_snapshot(
ccf::kv::Version snapshot_seqno, std::vector<uint8_t>&& snapshot_data)
{
startup_snapshot_info = std::make_unique<StartupSnapshotInfo>(
snapshot_seqno, std::move(snapshot_data));
startup_seqno = startup_snapshot_info->seqno;
last_recovered_idx = startup_seqno;
last_recovered_signed_idx = last_recovered_idx;
if (start_type == StartType::Recover)
{
const auto segments = separate_segments(startup_snapshot_info->raw);
ccf::kv::ConsensusHookPtrs hooks;
deserialise_snapshot(
network.tables,
segments,
hooks,
&view_history,
true /* public_only */);
snapshotter->set_last_snapshot_idx(last_recovered_idx);
}
}
RecoveryDecisionProtocolSubsystem recovery_decision_protocol;
public:
NodeState(
ringbuffer::AbstractWriterFactory& writer_factory,
NetworkState& network,
std::shared_ptr<RPCSessions> rpcsessions,
ccf::crypto::CurveID curve_id_) :
sm("NodeState", NodeStartupState::uninitialized),
curve_id(curve_id_),
node_sign_kp(std::make_shared<ccf::crypto::ECKeyPair_OpenSSL>(curve_id_)),
self(compute_node_id_from_kp(node_sign_kp)),
node_encrypt_kp(ccf::crypto::make_rsa_key_pair()),
writer_factory(writer_factory),
to_host(writer_factory.create_writer_to_outside()),
network(network),
rpcsessions(std::move(rpcsessions)),
share_manager(network.ledger_secrets),
recovery_decision_protocol(this)
{}
QuoteVerificationResult verify_quote(
ccf::kv::ReadOnlyTx& tx,
const QuoteInfo& quote_info_,
const std::vector<uint8_t>& expected_node_public_key_der,
pal::PlatformAttestationMeasurement& measurement,
const std::optional<std::vector<uint8_t>>& code_transparent_statement,
std::shared_ptr<NetworkIdentitySubsystemInterface>
network_identity_subsystem) override
{
return AttestationProvider::verify_quote_against_store(
tx,
quote_info_,
expected_node_public_key_der,
measurement,
code_transparent_statement,
network_identity_subsystem);
}
//
// funcs in state "uninitialized"
//
void initialize(
const ccf::consensus::Configuration& consensus_config_,
std::shared_ptr<RPCMap> rpc_map_,
std::shared_ptr<AbstractRPCResponder> rpc_sessions_,
std::shared_ptr<indexing::Indexer> indexer_,
size_t sig_tx_interval_,
size_t sig_ms_interval_)
{
std::lock_guard<pal::Mutex> guard(lock);
sm.expect(NodeStartupState::uninitialized);
consensus_config = consensus_config_;
rpc_map = rpc_map_;
indexer = indexer_;
sig_tx_interval = sig_tx_interval_;
sig_ms_interval = sig_ms_interval_;
n2n_channels = std::make_shared<NodeToNodeChannelManager>(writer_factory);
cmd_forwarder = std::make_shared<Forwarder<NodeToNode>>(
rpc_sessions_, n2n_channels, rpc_map);
sm.advance(NodeStartupState::initialized);
for (auto& [actor, fe] : rpc_map->frontends())
{
fe->set_sig_intervals(sig_tx_interval, sig_ms_interval);
fe->set_cmd_forwarder(cmd_forwarder);
}
}
//
// funcs in state "initialized"
//
void launch_node()
{
auto measurement = AttestationProvider::get_measurement(quote_info);
if (measurement.has_value())
{
node_measurement = measurement.value();
}
else
{
throw std::logic_error("Failed to extract code id from quote");
}
auto snp_attestation =
AttestationProvider::get_snp_attestation(quote_info);
if (snp_attestation.has_value())
{
snp_tcb_version = snp_attestation.value().reported_tcb;
}
// Verify that the security policy matches the quoted digest of the policy
if (!config.attestation.environment.security_policy.has_value())
{
LOG_INFO_FMT(
"Security policy not set, skipping check against attestation host "
"data");
}
else
{
auto quoted_digest = AttestationProvider::get_host_data(quote_info);
if (!quoted_digest.has_value())
{
throw std::logic_error("Unable to find host data in attestation");
}
auto const& security_policy =
config.attestation.environment.security_policy.value();
auto security_policy_digest =
quote_info.format == QuoteFormat::amd_sev_snp_v1 ?
ccf::crypto::Sha256Hash(ccf::crypto::raw_from_b64(security_policy)) :
ccf::crypto::Sha256Hash(security_policy);
if (security_policy_digest != quoted_digest.value())
{
throw std::logic_error(fmt::format(
"Digest of decoded security policy \"{}\" {} does not match "
"attestation host data {}",
security_policy,
security_policy_digest.hex_str(),
quoted_digest.value().hex_str()));
}
LOG_INFO_FMT(
"Successfully verified attested security policy {}",
security_policy_digest);
}
if (quote_info.format == QuoteFormat::amd_sev_snp_v1)
{
if (!config.attestation.environment.uvm_endorsements.has_value())
{
LOG_INFO_FMT(
"UVM endorsements not set, skipping check against attestation "
"measurement");
}
else
{
try
{
auto uvm_endorsements_raw = ccf::crypto::raw_from_b64(
config.attestation.environment.uvm_endorsements.value());
// A node at this stage does not have a notion of what UVM
// descriptor is acceptable. That is decided either by the Joinee,
// or by Consortium endorsing the Start or Recovery node. For that
// reason, we extract an endorsement descriptor from the UVM
// endorsements and make it available in the ledger's initial or
// recovery transaction.
snp_uvm_endorsements = pal::verify_uvm_endorsements_descriptor(
uvm_endorsements_raw, node_measurement);
quote_info.uvm_endorsements = uvm_endorsements_raw;
LOG_INFO_FMT(
"Successfully verified attested UVM endorsements: {}",
snp_uvm_endorsements->to_str());
}
catch (const std::exception& e)
{
throw std::logic_error(
fmt::format("Error verifying UVM endorsements: {}", e.what()));
}
}
}
switch (start_type)
{
case StartType::Start:
{
create_and_send_boot_request(
aft::starting_view_change, true /* Create new consortium */);
return;
}
case StartType::Join:
{
find_local_startup_snapshot();
sm.advance(NodeStartupState::pending);
start_join_timer();
return;
}
case StartType::Recover:
{
setup_recovery_hook();
find_local_startup_snapshot();
sm.advance(NodeStartupState::readingPublicLedger);
start_ledger_recovery_unsafe();
return;
}
default:
{
throw std::logic_error(
fmt::format("Node was launched in unknown mode {}", start_type));
}
}
}
void initiate_quote_generation()
{
auto fetch_endorsements = [this](
const QuoteInfo& qi,
const pal::snp::
EndorsementEndpointsConfiguration&
endpoint_config) {
// Note: Node lock is already taken here as this is called back
// synchronously with the call to pal::generate_quote
this->quote_info = qi;
auto b64encoded_quote = ccf::crypto::b64url_from_raw(quote_info.quote);
nlohmann::json jq;
to_json(jq, quote_info.format);
LOG_INFO_FMT(
"Initial node attestation ({}): {}", jq.dump(), b64encoded_quote);
if (quote_info.format == QuoteFormat::amd_sev_snp_v1)
{
// Use endorsements retrieved from file, if available
if (config.attestation.environment.snp_endorsements.has_value())
{
try
{
const auto raw_data = ccf::crypto::raw_from_b64(
config.attestation.environment.snp_endorsements.value());
const auto j = nlohmann::json::parse(raw_data);
const auto aci_endorsements =
j.get<ccf::pal::snp::ACIReportEndorsements>();
// Check that tcbm in endorsement matches reported TCB in our
// retrieved attestation
const auto* quote =
reinterpret_cast<const ccf::pal::snp::Attestation*>(
quote_info.quote.data());
const auto reported_tcb = quote->reported_tcb;
// tcbm is a single hex value, like DB18000000000004. To match
// that with a TcbVersion, reverse the bytes.
const auto* tcb_begin =
reinterpret_cast<const uint8_t*>(&reported_tcb);
const std::span<const uint8_t> tcb_bytes{
tcb_begin, tcb_begin + sizeof(reported_tcb)};
auto tcb_as_hex = fmt::format(
"{:02x}", fmt::join(tcb_bytes.rbegin(), tcb_bytes.rend(), ""));
ccf::nonstd::to_upper(tcb_as_hex);
if (tcb_as_hex == aci_endorsements.tcbm)
{
LOG_INFO_FMT(
"Using SNP endorsements loaded from file, endorsing TCB {}",
tcb_as_hex);
auto& endorsements_pem = quote_info.endorsements;
endorsements_pem.insert(
endorsements_pem.end(),
aci_endorsements.vcek_cert.begin(),
aci_endorsements.vcek_cert.end());
endorsements_pem.insert(
endorsements_pem.end(),
aci_endorsements.certificate_chain.begin(),
aci_endorsements.certificate_chain.end());
try
{
launch_node();
return;
}
catch (const std::exception& e)
{
LOG_FAIL_FMT("Failed to launch node: {}", e.what());
throw;
}
}
else
{
LOG_FAIL_FMT(
"SNP endorsements loaded from disk ({}) contained tcbm {}, "
"which does not match reported TCB of current attestation "
"{}. "
"Falling back to fetching fresh endorsements from server.",
config.attestation.snp_endorsements_file.value(),
aci_endorsements.tcbm,
tcb_as_hex);
}
}
catch (const std::exception& e)
{
LOG_FAIL_FMT(
"Error attempting to use SNP endorsements from file: {}",
e.what());
}
}
if (config.attestation.snp_endorsements_servers.empty())
{
throw std::runtime_error(
"One or more SNP endorsements servers must be specified to fetch "
"the collateral for the attestation");
}
// On SEV-SNP, fetch endorsements from servers if specified
quote_endorsements_client = std::make_shared<QuoteEndorsementsClient>(
endpoint_config, [this](std::vector<uint8_t>&& endorsements) {
std::lock_guard<pal::Mutex> guard(lock);
quote_info.endorsements = std::move(endorsements);
try
{
launch_node();
}
catch (const std::exception& e)
{
LOG_FAIL_FMT("{}", e.what());
throw;
}
quote_endorsements_client.reset();
});
quote_endorsements_client->fetch_endorsements();
return;
}
if (quote_info.format != QuoteFormat::insecure_virtual)
{
throw std::runtime_error(fmt::format(
"Unsupported quote format: {}",
static_cast<int>(quote_info.format)));
}
launch_node();
};
pal::PlatformAttestationReportData report_data =
ccf::crypto::Sha256Hash((node_sign_kp->public_key_der()));
pal::generate_quote(
report_data,
fetch_endorsements,
config.attestation.snp_endorsements_servers);
}
NodeCreateInfo create(
StartType start_type_, const ccf::StartupConfig& config_)
{
std::lock_guard<pal::Mutex> guard(lock);
sm.expect(NodeStartupState::initialized);
start_type = start_type_;
config = config_;
subject_alt_names = get_subject_alternative_names();
js::register_class_ids();
self_signed_node_cert = create_self_signed_cert(
node_sign_kp,
config.node_certificate.subject_name,
subject_alt_names,
config.startup_host_time,
config.node_certificate.initial_validity_days);
accept_node_tls_connections();
open_frontend(ActorsType::nodes);
// Signatures are only emitted on a timer once the public ledger has been
// recovered
setup_history();
setup_snapshotter();
setup_encryptor();
initiate_quote_generation();
switch (start_type)
{
case StartType::Start:
{
network.identity = std::make_unique<ccf::NetworkIdentity>(
config.service_subject_name,
curve_id,
config.startup_host_time,
config.initial_service_certificate_validity_days);
network.ledger_secrets->init();
history->set_service_signing_identity(
network.identity->get_key_pair(), config.cose_signatures);
setup_consensus(false, endorsed_node_cert);
// Become the primary and force replication
consensus->force_become_primary();
LOG_INFO_FMT("Created new node {}", self);
return {self_signed_node_cert, network.identity->cert};
}
case StartType::Join:
{
LOG_INFO_FMT("Created join node {}", self);
return {self_signed_node_cert, {}};
}
case StartType::Recover:
{
if (!config.recover.previous_service_identity)
{
throw std::logic_error(
"Recovery requires the certificate of the previous service "
"identity");
}
ccf::crypto::Pem previous_service_identity_cert(
config.recover.previous_service_identity.value());
network.identity = std::make_unique<ccf::NetworkIdentity>(
ccf::crypto::get_subject_name(previous_service_identity_cert),
curve_id,
config.startup_host_time,
config.initial_service_certificate_validity_days);
LOG_INFO_FMT("Created recovery node {}", self);
return {self_signed_node_cert, network.identity->cert};
}
default:
{
throw std::logic_error(
fmt::format("Node was started in unknown mode {}", start_type));
}
}
}
//
// funcs in state "pending"
//
void initiate_join_unsafe()
{
sm.expect(NodeStartupState::pending);
auto network_ca = std::make_shared<::tls::CA>(std::string(
config.join.service_cert.begin(), config.join.service_cert.end()));
auto [target_host, target_port] =
split_net_address(config.join.target_rpc_address);
auto join_client_cert = std::make_unique<::tls::Cert>(
network_ca,
self_signed_node_cert,
node_sign_kp->private_key_pem(),
target_host);
// Create RPC client and connect to remote node
// Note: For now, assume that target node accepts same application
// protocol as this node's main RPC interface
auto join_client = rpcsessions->create_client(
std::move(join_client_cert),
rpcsessions->get_app_protocol_main_interface());
join_client->connect(
target_host,
target_port,
// Capture target_address by value, and use them when
// logging about this response. Do not use config target address, which
// may have updated in the interim.
[this, target_address = config.join.target_rpc_address](
ccf::http_status status,
http::HeaderMap&& headers,
std::vector<uint8_t>&& data) {
std::lock_guard<pal::Mutex> guard(lock);
if (!sm.check(NodeStartupState::pending))
{
return;
}
if (is_http_status_client_error(status))
{
std::optional<ccf::ODataErrorResponse> error_response =
std::nullopt;
try
{
auto j = nlohmann::json::parse(data);
error_response = j.get<ccf::ODataErrorResponse>();
}
catch (const nlohmann::json::exception& e)
{
// Leave error_response == nullopt
LOG_FAIL_FMT(
"Join request returned {}, body is not ODataErrorResponse: {}",
status,
std::string(data.begin(), data.end()));
}
if (
error_response.has_value() &&
error_response->error.code == ccf::errors::StartupSeqnoIsOld &&
config.join.fetch_recent_snapshot)
{
LOG_INFO_FMT(
"Join request to {} returned {} error. Attempting to fetch "
"fresher snapshot",
target_address,
ccf::errors::StartupSeqnoIsOld);
// If we've followed a redirect, it will have been updated in
// config.join. Note that this is fire-and-forget, it is assumed
// that it proceeds in the background, updating state when it
// completes, and the join timer separately re-attempts join after
// this succeeds
if (
snapshot_fetch_task != nullptr &&
!snapshot_fetch_task->is_cancelled())
{
LOG_INFO_FMT("Snapshot fetch already in progress, skipping");
}
else
{
snapshot_fetch_task = std::make_shared<FetchSnapshot>(
config.join, config.snapshots, this);
ccf::tasks::add_task(snapshot_fetch_task);
}
return;
}
auto error_msg = fmt::format(
"Join request to {} returned {} Bad Request: {}. Shutting "
"down node gracefully.",
target_address,
status,
std::string(data.begin(), data.end()));
LOG_FAIL_FMT("{}", error_msg);
RINGBUFFER_WRITE_MESSAGE(
AdminMessage::fatal_error_msg, to_host, error_msg);
return;
}
if (status != HTTP_STATUS_OK)
{
const auto& location = headers.find(http::headers::LOCATION);
if (
config.join.follow_redirect &&
(status == HTTP_STATUS_PERMANENT_REDIRECT ||
status == HTTP_STATUS_TEMPORARY_REDIRECT) &&
location != headers.end())
{
const auto& url = ::http::parse_url_full(location->second);
config.join.target_rpc_address =
make_net_address(url.host, url.port);
LOG_INFO_FMT("Target node redirected to {}", location->second);
}
else
{
LOG_FAIL_FMT(
"An error occurred while joining the network: {} {}{}",
status,
ccf::http_status_str(status),
data.empty() ?
"" :
fmt::format(" '{}'", std::string(data.begin(), data.end())));
}
return;
}
JoinNetworkNodeToNode::Out resp;
try
{
auto j = nlohmann::json::parse(data);
resp = j.get<JoinNetworkNodeToNode::Out>();
}
catch (const std::exception& e)
{
LOG_FAIL_FMT(
"An error occurred while parsing the join network response");
LOG_DEBUG_FMT("Join network response error: {}", e.what());
LOG_DEBUG_FMT(
"Join network response body: {}",
std::string(data.begin(), data.end()));
return;
}
// Set network secrets, node id and become part of network.
if (resp.node_status == NodeStatus::TRUSTED)
{
if (!resp.network_info.has_value())
{
throw std::logic_error("Expected network info in join response");
}
network.identity = std::make_unique<ccf::NetworkIdentity>(
resp.network_info->identity);
network.ledger_secrets->init_from_map(
std::move(resp.network_info->ledger_secrets));
history->set_service_signing_identity(
network.identity->get_key_pair(),
resp.network_info->cose_signatures_config.value_or(
ccf::COSESignaturesConfig{}));
ccf::crypto::Pem n2n_channels_cert;
if (!resp.network_info->endorsed_certificate.has_value())
{
// Endorsed certificate was added to join response in 2.x
throw std::logic_error(
"Expected endorsed certificate in join response");
}
n2n_channels_cert = resp.network_info->endorsed_certificate.value();
setup_consensus(resp.network_info->public_only, n2n_channels_cert);
auto_refresh_jwt_keys();