156 static std::chrono::system_clock::duration&
159 static std::chrono::system_clock::duration value =
160 std::chrono::seconds(2);
168 std::vector<uint8_t> raw_aad;
169 std::vector<uint8_t> raw_plain;
173 std::span<const uint8_t> raw_aad_,
174 std::span<const uint8_t> raw_plain_) :
176 raw_aad(raw_aad_.begin(), raw_aad_.end()),
177 raw_plain(raw_plain_.begin(), raw_plain_.end())
196 std::chrono::system_clock::time_point last_initiation_time;
197 static constexpr size_t salt_len = 32;
198 static constexpr size_t shared_key_size = 32;
199 std::vector<uint8_t> hkdf_salt;
200 size_t message_limit;
203 std::unique_ptr<ccf::crypto::KeyAesGcm> recv_key =
nullptr;
204 std::unique_ptr<ccf::crypto::KeyAesGcm> send_key =
nullptr;
207 std::atomic<MsgNonce> send_nonce{1};
211 std::optional<OutgoingMsg> outgoing_consensus_msg;
217 static constexpr size_t outgoing_forwarding_queue_size = 10;
218 std::vector<OutgoingMsg> outgoing_forwarding_msgs;
224 void check_message_limit()
229 const auto lower_limit = message_limit / 2;
230 size_t num_messages = send_nonce + local_recv_nonce;
234 "Reached message limit ({}+{} >= {}), triggering new key exchange",
238 reset_key_exchange();
241 else if (num_messages >= message_limit)
244 "Reached hard message limit ({}+{} >= {}), dropping previous keys",
252 local_recv_nonce = 0;
253 reset_key_exchange();
260 std::span<const uint8_t> aad,
261 std::span<const uint8_t> cipher,
262 std::vector<uint8_t>& plain)
264 if (recv_key ==
nullptr)
266 throw std::logic_error(
"Tried to decrypt, but have no receive key");
270 auto recv_nonce = wire_nonce.nonce;
273 "decrypt({} bytes, {} bytes) (nonce={})",
281 if (recv_nonce <= local_recv_nonce)
287 "Received past nonce, received:{}, "
295 recv_key->decrypt(header.get_iv(), header.tag, cipher, aad, plain);
300 local_recv_nonce = recv_nonce;
303 check_message_limit();
308 bool verify(
const GcmHdr& header, std::span<const uint8_t> aad)
310 std::vector<uint8_t> empty_plaintext;
311 return decrypt(header, aad, {}, empty_plaintext);
314 void send_key_exchange_init()
316 std::vector<uint8_t> payload;
325 std::span<const uint8_t>(node_cert.
data(), node_cert.
size()));
330 "send_key_exchange_init: node serial: {}",
342 void send_key_exchange_response()
344 std::vector<uint8_t> signature;
348 to_sign.insert(to_sign.end(), peer_ks.begin(), peer_ks.end());
349 signature = node_kp->sign(to_sign);
352 std::vector<uint8_t> payload;
360 std::span<const uint8_t>(node_cert.
data(), node_cert.
size()));
364 "send_key_exchange_response: oks={}, serialised_signed_share={}",
366 ds::to_hex(payload));
377 void send_key_exchange_final()
379 std::vector<uint8_t> payload;
389 "key_exchange_final: ks={}, serialised_signed_key_share={}",
391 ds::to_hex(payload));
402 void advance_connection_attempt()
412 const auto time_since_initiated =
413 decltype(last_initiation_time)::clock::now() - last_initiation_time;
437 bool recv_key_exchange_init(
438 const uint8_t* data,
size_t size,
bool they_have_priority =
false)
441 "recv_key_exchange_init({} bytes, {})", size, they_have_priority);
444 auto peer_version = serialized::read<size_t>(data, size);
448 "Protocol version mismatch (node={}, peer={})",
454 auto ks = extract_span(data, size);
461 auto sig = extract_span(data, size);
468 auto pc = extract_span(data, size);
475 auto salt = extract_span(data, size);
491 if (!verify_peer_certificate(pc, cert, verifier))
494 "Peer certificate verification failed - recv_key_exchange_init "
495 "failed to verify peer cert:\n{}\nUsing trusted service "
502 if (!verify_peer_signature(ks, sig, verifier))
525 "recv_key_exchange_init: version={} ks={} sig={} pc={} salt={}",
532 hkdf_salt = {salt.data(), salt.data() + salt.size()};
542 send_key_exchange_response();
544 flush_pending_outgoing();
549 bool recv_key_exchange_response(
const uint8_t* data,
size_t size)
560 auto peer_version = serialized::read<size_t>(data, size);
564 "Protocol version mismatch (node={}, peer={})",
570 auto ks = extract_span(data, size);
577 auto sig = extract_span(data, size);
584 auto pc = extract_span(data, size);
600 if (!verify_peer_certificate(pc, cert, verifier))
603 "Peer certificate verification failed - recv_key_exchange_response "
604 "failed to verify peer cert:\n{}\nUsing trusted service "
613 std::vector<uint8_t> signed_msg(ks.begin(), ks.end());
615 signed_msg.insert(signed_msg.end(), oks.begin(), oks.end());
617 if (!verify_peer_signature(signed_msg, sig, verifier))
621 "Peer certificate verification failed - recv_key_exchange_response "
622 "failed to verify signature from cert:\n{}",
635 send_key_exchange_final();
637 flush_pending_outgoing();
646 bool recv_key_exchange_final(
const uint8_t* data,
size_t size)
667 auto sig = extract_span(data, size);
677 "Peer certificate verification failed - recv_key_exchange_final "
678 "failed to verify signature from peer with serial number {}",
679 peer_cv->serial_number());
690 std::span<const uint8_t> extract_span(
691 const uint8_t*& data,
size_t& size)
const
698 auto sz = serialized::read<size_t>(data, size);
699 const uint8_t* data_start = data;
704 "Buffer header wants {} bytes, but only {} remain", sz, size);
711 return {data_start, sz};
714 bool verify_peer_certificate(
715 std::span<const uint8_t> pc,
727 if (!verifier->verify_certificate(
728 {&service_cert}, {},
true ))
734 "New peer certificate: {}\n{}",
735 verifier->serial_number(),
744 bool verify_peer_signature(
745 std::span<const uint8_t> msg,
746 std::span<const uint8_t> sig,
750 "Verifying peer signature with peer certificate serial {}",
751 verifier ? verifier->serial_number() :
"no peer_cv!");
753 return verifier && verifier->verify(msg, sig);
756 void update_send_key()
758 const std::string label_to = self.value() + peer_id.value();
759 const std::span<const uint8_t> label(
760 reinterpret_cast<const uint8_t*
>(label_to.c_str()), label_to.size());
772 void update_recv_key()
774 const std::string label_from = peer_id.value() + self.value();
775 const std::span<const uint8_t> label(
776 reinterpret_cast<const uint8_t*
>(label_from.c_str()),
786 local_recv_nonce = 0;
792 LOG_INFO_FMT(
"Node channel with {} is now established.", peer_id);
798 "Node certificate serial numbers: node={} peer={}",
799 node_cv->serial_number(),
800 peer_cv->serial_number());
803 void flush_pending_outgoing()
805 if (outgoing_consensus_msg.has_value())
808 outgoing_consensus_msg->type,
809 outgoing_consensus_msg->raw_aad,
810 outgoing_consensus_msg->raw_plain);
811 outgoing_consensus_msg.reset();
814 for (
auto& outgoing_msg : outgoing_forwarding_msgs)
817 outgoing_msg.type, outgoing_msg.raw_aad, outgoing_msg.raw_plain);
820 outgoing_forwarding_msgs.clear();
825 LOG_INFO_FMT(
"Initiating node channel with {}.", peer_id);
833 hkdf_salt = e->random(salt_len);
841 last_initiation_time =
decltype(last_initiation_time)::clock::now();
843 send_key_exchange_init();
846 void reset_key_exchange()
856 hkdf_salt = e->random(salt_len);
861 std::span<const uint8_t> aad,
862 std::span<const uint8_t> plain)
864 if (send_key ==
nullptr)
866 advance_connection_attempt();
871 if (outgoing_consensus_msg.has_value())
874 "Dropping outgoing consensus message - replaced by new "
875 "consensus message");
877 outgoing_consensus_msg = OutgoingMsg(type, aad, plain);
884 outgoing_forwarding_msgs.size() < outgoing_forwarding_queue_size)
886 outgoing_forwarding_msgs.emplace_back(type, aad, plain);
888 "Queueing outgoing forwarding message - the is the {}/{} "
890 outgoing_forwarding_msgs.size(),
891 outgoing_forwarding_queue_size);
896 "Unable to queue outgoing forwarding message - already queued "
897 "maximum {} messages",
898 outgoing_forwarding_queue_size);
905 "Cannot send channel message on unestablished channel");
912 "Cannot send message of unexpected type {} on unestablished "
914 static_cast<size_t>(type));
920 auto nonce = send_nonce.fetch_add(1);
921 WireNonce wire_nonce(nonce);
924 "send({}, {} bytes, {} bytes) (nonce={})",
932 reinterpret_cast<const uint8_t*
>(&wire_nonce),
sizeof(wire_nonce));
934 std::vector<uint8_t> cipher;
936 send_key->encrypt(gcm_hdr.get_iv(), plain, aad, cipher, gcm_hdr.tag);
938 const auto gcm_hdr_serialised = gcm_hdr.serialise();
947 {aad.
data(),
static_cast<size_t>(aad.size())},
948 {gcm_hdr_serialised.data(),
949 static_cast<size_t>(gcm_hdr_serialised.size())},
950 {cipher.data(),
static_cast<size_t>(cipher.size())}};
953 node_outbound, to_host, peer_id.value(), type, self.value(), payload);
955 check_message_limit();
970 size_t message_limit_) :
971 self(
std::move(self_)),
972 service_cert(service_cert_),
973 node_kp(
std::move(node_kp_)),
974 node_cert(node_cert_),
975 to_host(writer_factory.create_writer_to_outside()),
976 peer_id(
std::move(peer_id_)),
977 status(fmt::format(
"Channel to {}", peer_id),
INACTIVE),
978 message_limit(message_limit_)
981 hkdf_salt = e->random(salt_len);
986 std::lock_guard<ccf::pal::Mutex> guard(lock);
987 return recv_key !=
nullptr && send_key !=
nullptr;
1003 std::span<const uint8_t> aad,
1004 std::span<const uint8_t> plain = {})
1006 std::lock_guard<ccf::pal::Mutex> guard(lock);
1008 return send_unsafe(type, aad, plain);
1012 std::span<const uint8_t> aad,
const uint8_t*& data,
size_t& size)
1014 std::lock_guard<ccf::pal::Mutex> guard(lock);
1018 if (recv_key ==
nullptr)
1021 "Node channel with {} cannot receive authenticated message: not "
1022 "established a receive key, status={}",
1025 advance_connection_attempt();
1032 if (!verify(hdr, aad))
1043 std::lock_guard<ccf::pal::Mutex> guard(lock);
1049 if (recv_key ==
nullptr)
1052 "Node channel with {} cannot receive authenticated message with "
1053 "payload: not established a receive key, status={}",
1056 advance_connection_attempt();
1060 const uint8_t* data_ = data;
1061 size_t size_ = size;
1068 if (!verify(hdr, std::span<const uint8_t>(data, size)))
1078 std::span<const uint8_t> aad,
const uint8_t*& data,
size_t& size)
1080 std::lock_guard<ccf::pal::Mutex> guard(lock);
1083 if (recv_key ==
nullptr)
1086 "Node channel with {} cannot receive encrypted message: not "
1087 "established a receive key, status={}",
1090 advance_connection_attempt();
1091 return std::nullopt;
1097 std::vector<uint8_t> plain;
1098 if (!decrypt(hdr, aad, std::span<const uint8_t>(data, size), plain))
1101 return std::nullopt;
1109 std::lock_guard<ccf::pal::Mutex> guard(lock);
1112 reset_key_exchange();
1113 outgoing_consensus_msg.reset();
1121 std::lock_guard<ccf::pal::Mutex> guard(lock);
1125 auto chmsg = serialized::read<ChannelMsg>(data, size);
1132 return recv_key_exchange_init(data, size, self < peer_id);
1137 return recv_key_exchange_response(data, size);
1142 return recv_key_exchange_final(data, size);
1147 throw std::runtime_error(fmt::format(
1148 "Received message with initial bytes {} from {} - not recognised "
1149 "as a key exchange message",
1155 catch (
const std::exception& e)