diff --git a/esphome/components/api/api.proto b/esphome/components/api/api.proto index f1bc9b003a..fd3bfba2c8 100644 --- a/esphome/components/api/api.proto +++ b/esphome/components/api/api.proto @@ -892,6 +892,20 @@ message NoiseEncryptionSetKeyResponse { bool success = 1; } +// Single-use session resume ticket, sent unsolicited by the device after a +// Noise connection authenticates. A client presents it in the ClientHello of +// its next connection to skip the curve25519 handshake; the device then +// issues a fresh ticket on that connection. Never sent on plaintext +// connections. Clients that do not understand it drop it silently. +message NoiseResumeTicket { + option (id) = 151; + option (source) = SOURCE_SERVER; + option (ifdef) = "USE_API_NOISE"; + + bytes session_id = 1; // 8 bytes + bytes secret = 2; // 32 bytes +} + // ==================== HOMEASSISTANT.SERVICE ==================== message SubscribeHomeassistantServicesRequest { option (id) = 34; diff --git a/esphome/components/api/api_connection.cpp b/esphome/components/api/api_connection.cpp index 91d13eed65..0441709bf3 100644 --- a/esphome/components/api/api_connection.cpp +++ b/esphome/components/api/api_connection.cpp @@ -1742,6 +1742,9 @@ void APIConnection::complete_authentication_() { this->send_time_request(); } #endif +#ifdef USE_API_NOISE + this->send_resume_ticket_(); +#endif #ifdef USE_ZWAVE_PROXY if (zwave_proxy::global_zwave_proxy != nullptr) { zwave_proxy::global_zwave_proxy->api_connection_authenticated(this); @@ -1749,6 +1752,25 @@ void APIConnection::complete_authentication_() { #endif } +#ifdef USE_API_NOISE +void APIConnection::send_resume_ticket_() { + // Only encrypted transports get a ticket: on dual-mode builds a plaintext + // connection has no frame footer + if (this->helper_->frame_footer_size() == 0) { + return; + } + noise::ResumeTicket ticket; + if (!this->parent_->get_noise_ctx().resume_cache().issue(ticket)) { + return; + } + NoiseResumeTicket msg; + msg.set_session_id(ticket.session_id, noise::RESUME_SESSION_ID_SIZE); + msg.set_secret(ticket.secret, noise::RESUME_SECRET_SIZE); + this->send_message(msg); + noise::resume_wipe(&ticket, sizeof(ticket)); +} +#endif + bool APIConnection::send_hello_response_(const HelloRequest &msg) { // Copy client name with truncation if needed (set_client_name handles truncation) this->helper_->set_client_name(msg.client_info.c_str(), msg.client_info.size()); diff --git a/esphome/components/api/api_connection.h b/esphome/components/api/api_connection.h index 1b47c23cfe..8b7705f028 100644 --- a/esphome/components/api/api_connection.h +++ b/esphome/components/api/api_connection.h @@ -388,6 +388,11 @@ class APIConnection final : public APIServerConnectionBase { // Helper function to handle authentication completion void complete_authentication_(); +#ifdef USE_API_NOISE + // Issue a fresh single-use session resume ticket over the encrypted channel + void send_resume_ticket_(); +#endif + // Pattern B helpers: send response and return success/failure bool send_hello_response_(const HelloRequest &msg); bool send_disconnect_response_(); diff --git a/esphome/components/api/api_frame_helper_noise.cpp b/esphome/components/api/api_frame_helper_noise.cpp index d7554e62c5..8275588ff6 100644 --- a/esphome/components/api/api_frame_helper_noise.cpp +++ b/esphome/components/api/api_frame_helper_noise.cpp @@ -265,7 +265,8 @@ APIError APINoiseFrameHelper::state_action_client_hello_() { if (aerr != APIError::OK) { return handle_handshake_frame_error_(aerr); } - // ignore contents, may be used in future for flags + // Contents are extension flags; today the only defined extension is the + // session resume offer. Everything is mixed into the prologue either way. // Resize for: existing prologue + 2 size bytes + frame data size_t old_size = this->prologue_.size(); size_t rx_size = this->rx_buf_.size(); @@ -276,10 +277,30 @@ APIError APINoiseFrameHelper::state_action_client_hello_() { std::memcpy(this->prologue_.data() + old_size + 2, this->rx_buf_.data(), rx_size); } + // A resume offer is decided on in the server hello step, which reads it + // from rx_buf_ (no frame is read in between, so the buffer stays intact). + this->resume_offer_pending_ = rx_size == noise::RESUME_OFFER_SIZE && this->rx_buf_[0] == noise::RESUME_OFFER_VERSION; + state_ = State::SERVER_HELLO; return APIError::OK; } APIError APINoiseFrameHelper::state_action_server_hello_() { + // A verified resume offer replaces the whole handshake: consume the ticket, + // prove possession of its secret in a trailing ServerHello extension (old + // clients ignore trailing bytes), and derive the transport keys via HKDF. + // Every failure on this path silently falls back to the full handshake. + uint8_t resume_secret[noise::RESUME_SECRET_SIZE]; + uint8_t server_nonce[noise::RESUME_NONCE_SIZE]; + uint8_t confirm_mac[noise::RESUME_MAC_SIZE]; + bool resume = + this->resume_offer_pending_ && this->ctx_.resume_cache().take_verified(this->rx_buf_.data(), resume_secret); + this->resume_offer_pending_ = false; + if (resume) { + resume = random_bytes(server_nonce, sizeof(server_nonce)) && + noise::resume_compute_confirm_mac(resume_secret, this->rx_buf_.data() + noise::RESUME_OFFER_NONCE_OFFSET, + server_nonce, confirm_mac); + } + // send server hello const auto &name = App.get_name(); char mac[MAC_ADDRESS_BUFFER_SIZE]; @@ -293,7 +314,9 @@ APIError APINoiseFrameHelper::state_action_server_hello_() { // 1 (proto) + name (max ESPHOME_DEVICE_NAME_MAX_LEN) + 1 (name null) // + mac (MAC_ADDRESS_BUFFER_SIZE - 1) + 1 (mac null) - constexpr size_t max_msg_size = 1 + ESPHOME_DEVICE_NAME_MAX_LEN + 1 + MAC_ADDRESS_BUFFER_SIZE; + // + optional resume accept extension + constexpr size_t max_msg_size = + 1 + ESPHOME_DEVICE_NAME_MAX_LEN + 1 + MAC_ADDRESS_BUFFER_SIZE + noise::RESUME_ACCEPT_SIZE; uint8_t msg[max_msg_size]; // chosen proto @@ -304,9 +327,27 @@ APIError APINoiseFrameHelper::state_action_server_hello_() { // node mac, terminated by null byte std::memcpy(msg + mac_offset, mac, MAC_ADDRESS_BUFFER_SIZE); + if (resume) { + // version | server_nonce | confirm_mac + uint8_t *ext = msg + total_size; + ext[0] = noise::RESUME_ACCEPT_VERSION; + std::memcpy(ext + 1, server_nonce, sizeof(server_nonce)); + std::memcpy(ext + 1 + sizeof(server_nonce), confirm_mac, sizeof(confirm_mac)); + total_size += noise::RESUME_ACCEPT_SIZE; + } + APIError aerr = write_frame_(msg, total_size); - if (aerr != APIError::OK) + if (aerr != APIError::OK) { + noise::resume_wipe(resume_secret, sizeof(resume_secret)); return aerr; + } + + if (resume) { + aerr = this->setup_resumed_session_(resume_secret, server_nonce); + noise::resume_wipe(resume_secret, sizeof(resume_secret)); + return aerr; + } + noise::resume_wipe(resume_secret, sizeof(resume_secret)); // start handshake aerr = init_handshake_(); @@ -316,7 +357,39 @@ APIError APINoiseFrameHelper::state_action_server_hello_() { state_ = State::HANDSHAKE; return APIError::OK; } + +/// Derive the resumed session's transport ciphers. The client's full +/// handshake message 1 is already in flight, so the connection stays in +/// HANDSHAKE state to read and discard it before switching to DATA. +APIError APINoiseFrameHelper::setup_resumed_session_(const uint8_t *resume_secret, const uint8_t *server_nonce) { + uint8_t k_c2d[32]; + uint8_t k_d2c[32]; + bool ok = noise::resume_derive_keys(resume_secret, this->rx_buf_.data() + noise::RESUME_OFFER_NONCE_OFFSET, + server_nonce, this->prologue_.data(), this->prologue_.size(), k_c2d, k_d2c); + if (ok) { + this->recv_cipher_ = noise::resume_make_cipher(k_c2d); + this->send_cipher_ = noise::resume_make_cipher(k_d2c); + ok = this->recv_cipher_ != nullptr && this->send_cipher_ != nullptr; + } + noise::resume_wipe(k_c2d, sizeof(k_c2d)); + noise::resume_wipe(k_d2c, sizeof(k_d2c)); + if (!ok) { + // The accept extension is already on the wire; the connection cannot + // fall back to a full handshake any more. Fail it; the client retries. + state_ = State::FAILED; + HELPER_LOG("Resume key derivation failed"); + return APIError::HANDSHAKESTATE_SETUP_FAILED; + } + this->prologue_.release(); + this->frame_footer_size_ = noise_cipherstate_get_mac_length(this->send_cipher_); + this->resume_discard_msg1_ = true; + state_ = State::HANDSHAKE; + return APIError::OK; +} APIError APINoiseFrameHelper::state_action_handshake_() { + if (this->resume_discard_msg1_) { + return this->state_action_resume_discard_(); + } noise::NoiseResponderHandshake::Action action = this->handshake_.action(); if (action == noise::NoiseResponderHandshake::Action::ACTION_READ) { return this->state_action_handshake_read_(); @@ -328,6 +401,25 @@ APIError APINoiseFrameHelper::state_action_handshake_() { HELPER_LOG("Bad action for handshake: %d", (int) action); return APIError::HANDSHAKESTATE_BAD_STATE; } +/// Resumed session: read and discard the client's full-handshake message 1, +/// which was already in flight when the resume offer was accepted, then +/// enter DATA. The same status byte rules apply as for a real handshake read. +APIError APINoiseFrameHelper::state_action_resume_discard_() { + APIError aerr = this->try_read_frame_(); + if (aerr != APIError::OK) { + return this->handle_handshake_frame_error_(aerr); + } + if (this->rx_buf_.empty() || this->rx_buf_[0] != noise::HANDSHAKE_STATUS_OK) { + state_ = State::FAILED; + HELPER_LOG("Bad discarded handshake message"); + return APIError::BAD_HANDSHAKE_ERROR_BYTE; + } + this->resume_discard_msg1_ = false; + HELPER_LOG("Session resumed!"); + state_ = State::DATA; + return APIError::OK; +} + APIError APINoiseFrameHelper::state_action_handshake_read_() { APIError aerr = this->try_read_frame_(); if (aerr != APIError::OK) { diff --git a/esphome/components/api/api_frame_helper_noise.h b/esphome/components/api/api_frame_helper_noise.h index 05060c77de..e90369b1ef 100644 --- a/esphome/components/api/api_frame_helper_noise.h +++ b/esphome/components/api/api_frame_helper_noise.h @@ -42,6 +42,8 @@ class APINoiseFrameHelper final : public APIFrameHelper { APIError state_action_handshake_(); APIError state_action_handshake_read_(); APIError state_action_handshake_write_(); + APIError state_action_resume_discard_(); + APIError setup_resumed_session_(const uint8_t *resume_secret, const uint8_t *server_nonce); APIError try_read_frame_(); APIError write_frame_(const uint8_t *data, uint16_t len); APIError encrypt_noise_message_(uint8_t *buf_start, uint16_t payload_size, uint8_t message_type, @@ -69,7 +71,14 @@ class APINoiseFrameHelper final : public APIFrameHelper { // Note: Maximum message size is UINT16_MAX (65535), with a limit of 128 bytes during handshake phase uint8_t rx_header_buf_[noise::FRAME_HEADER_SIZE]; uint8_t rx_header_buf_len_ = 0; - // 4 bytes total, no padding + // The ClientHello body carried a well-formed resume offer; decided on in + // state_action_server_hello_, which reads the offer from the still-intact + // rx_buf_. + bool resume_offer_pending_ = false; + // Resume accepted: the client's already-in-flight full-handshake message 1 + // must be read and discarded before the connection enters DATA. + bool resume_discard_msg1_ = false; + // 6 bytes total, 2 padding }; } // namespace esphome::api diff --git a/esphome/components/api/api_pb2.cpp b/esphome/components/api/api_pb2.cpp index 1b8c6b05bd..68efc930cc 100644 --- a/esphome/components/api/api_pb2.cpp +++ b/esphome/components/api/api_pb2.cpp @@ -1059,6 +1059,18 @@ uint32_t NoiseEncryptionSetKeyResponse::calculate_size() const { size += ProtoSize::calc_bool(1, this->success); return size; } +uint8_t *NoiseResumeTicket::encode(ProtoWriteBuffer &buffer PROTO_ENCODE_DEBUG_PARAM) const { + uint8_t *__restrict__ pos = buffer.get_pos(); + ProtoEncode::encode_bytes(pos PROTO_ENCODE_DEBUG_ARG, 1, this->session_id_ptr_, this->session_id_len_); + ProtoEncode::encode_bytes(pos PROTO_ENCODE_DEBUG_ARG, 2, this->secret_ptr_, this->secret_len_); + return pos; +} +uint32_t NoiseResumeTicket::calculate_size() const { + uint32_t size = 0; + size += ProtoSize::calc_length(1, this->session_id_len_); + size += ProtoSize::calc_length(1, this->secret_len_); + return size; +} #endif #ifdef USE_API_HOMEASSISTANT_SERVICES uint8_t *HomeassistantServiceMap::encode(ProtoWriteBuffer &buffer PROTO_ENCODE_DEBUG_PARAM) const { diff --git a/esphome/components/api/api_pb2.h b/esphome/components/api/api_pb2.h index 8335dae1f2..d5a16b8864 100644 --- a/esphome/components/api/api_pb2.h +++ b/esphome/components/api/api_pb2.h @@ -1133,6 +1133,33 @@ class NoiseEncryptionSetKeyResponse final : public ProtoMessage { protected: }; +class NoiseResumeTicket final : public ProtoMessage { + public: + static constexpr uint8_t MESSAGE_TYPE = 151; + static constexpr uint8_t ESTIMATED_SIZE = 38; +#ifdef HAS_PROTO_MESSAGE_DUMP + const LogString *message_name() const override { return LOG_STR("noise_resume_ticket"); } +#endif + const uint8_t *session_id_ptr_{nullptr}; + size_t session_id_len_{0}; + void set_session_id(const uint8_t *data, size_t len) { + this->session_id_ptr_ = data; + this->session_id_len_ = len; + } + const uint8_t *secret_ptr_{nullptr}; + size_t secret_len_{0}; + void set_secret(const uint8_t *data, size_t len) { + this->secret_ptr_ = data; + this->secret_len_ = len; + } + uint8_t *encode(ProtoWriteBuffer &buffer PROTO_ENCODE_DEBUG_PARAM) const; + uint32_t calculate_size() const; +#ifdef HAS_PROTO_MESSAGE_DUMP + const char *dump_to(DumpBuffer &out) const override; +#endif + + protected: +}; #endif #ifdef USE_API_HOMEASSISTANT_SERVICES class HomeassistantServiceMap final : public ProtoMessage { diff --git a/esphome/components/api/api_pb2_dump.cpp b/esphome/components/api/api_pb2_dump.cpp index 4d5829e45d..8acd2c3205 100644 --- a/esphome/components/api/api_pb2_dump.cpp +++ b/esphome/components/api/api_pb2_dump.cpp @@ -1372,6 +1372,12 @@ const char *NoiseEncryptionSetKeyResponse::dump_to(DumpBuffer &out) const { dump_field(out, ESPHOME_PSTR("success"), this->success); return out.c_str(); } +const char *NoiseResumeTicket::dump_to(DumpBuffer &out) const { + MessageDumpHelper helper(out, ESPHOME_PSTR("NoiseResumeTicket")); + dump_bytes_field(out, ESPHOME_PSTR("session_id"), this->session_id_ptr_, this->session_id_len_); + dump_bytes_field(out, ESPHOME_PSTR("secret"), this->secret_ptr_, this->secret_len_); + return out.c_str(); +} #endif #ifdef USE_API_HOMEASSISTANT_SERVICES const char *HomeassistantServiceMap::dump_to(DumpBuffer &out) const { diff --git a/esphome/components/noise/noise.h b/esphome/components/noise/noise.h index f9da8d35b8..fbba17298d 100644 --- a/esphome/components/noise/noise.h +++ b/esphome/components/noise/noise.h @@ -6,6 +6,8 @@ #include #include "esphome/core/log.h" +#include "noise_resume.h" + namespace esphome::noise { using psk_t = std::array; @@ -26,12 +28,16 @@ class NoiseContext { void set_psk(psk_t psk) { this->psk_ = psk; this->has_psk_ = !is_all_zeros(psk); + // Resume tickets were minted under the old key; forget them + this->resume_cache_.clear(); } const psk_t &get_psk() const { return this->psk_; } bool has_psk() const { return this->has_psk_; } + ResumeTicketCache &resume_cache() { return this->resume_cache_; } protected: psk_t psk_{}; + ResumeTicketCache resume_cache_; bool has_psk_{false}; }; diff --git a/esphome/components/noise/noise_resume.cpp b/esphome/components/noise/noise_resume.cpp new file mode 100644 index 0000000000..007220df25 --- /dev/null +++ b/esphome/components/noise/noise_resume.cpp @@ -0,0 +1,134 @@ +#include "noise_resume.h" +#ifdef USE_NOISE +#include + +#include "esphome/core/helpers.h" + +namespace esphome::noise { + +void resume_wipe(void *p, size_t len) { + volatile uint8_t *b = reinterpret_cast(p); + while (len--) { + *b++ = 0; + } +} + +static bool resume_ct_equal_(const uint8_t *a, const uint8_t *b, size_t len) { + uint8_t acc = 0; + for (size_t i = 0; i < len; i++) { + acc |= a[i] ^ b[i]; + } + return acc == 0; +} + +/// Noise-construction HKDF-SHA256; out2 may alias scratch the caller wipes. +static bool resume_hkdf_(const uint8_t *key, size_t key_len, const uint8_t *data, size_t data_len, uint8_t *out1, + size_t out1_len, uint8_t *out2, size_t out2_len) { + NoiseHashState *hash = nullptr; + if (noise_hashstate_new_by_id(&hash, NOISE_HASH_SHA256) != NOISE_ERROR_NONE) { + return false; + } + int err = noise_hashstate_hkdf(hash, key, key_len, data, data_len, out1, out1_len, out2, out2_len); + noise_hashstate_free(hash); + return err == NOISE_ERROR_NONE; +} + +static bool resume_mac_(const uint8_t *secret, const char *label, size_t label_len, const uint8_t *a, size_t a_len, + const uint8_t *b, size_t b_len, uint8_t *out_mac) { + // label || a || b, largest use is "confirm"(7) + 16 + 16 = 39 + uint8_t data[7 + RESUME_NONCE_SIZE + RESUME_NONCE_SIZE]; + uint8_t scratch[32]; + std::memcpy(data, label, label_len); + std::memcpy(data + label_len, a, a_len); + std::memcpy(data + label_len + a_len, b, b_len); + bool ok = resume_hkdf_(secret, RESUME_SECRET_SIZE, data, label_len + a_len + b_len, out_mac, RESUME_MAC_SIZE, scratch, + sizeof(scratch)); + resume_wipe(scratch, sizeof(scratch)); + return ok; +} + +bool ResumeTicketCache::issue(ResumeTicket &out) { + ResumeTicket ticket; + if (!random_bytes(ticket.session_id, RESUME_SESSION_ID_SIZE) || !random_bytes(ticket.secret, RESUME_SECRET_SIZE)) { + return false; + } + ticket.valid = true; + ResumeTicket &slot = this->slots_[this->next_]; + this->next_ = static_cast((this->next_ + 1) % SLOTS); + slot = ticket; + out = ticket; + resume_wipe(&ticket, sizeof(ticket)); + return true; +} + +bool ResumeTicketCache::take_verified(const uint8_t *offer, uint8_t *secret_out) { + const uint8_t *session_id = offer + RESUME_OFFER_SESSION_ID_OFFSET; + const uint8_t *client_nonce = offer + RESUME_OFFER_NONCE_OFFSET; + const uint8_t *offer_mac = offer + RESUME_OFFER_MAC_OFFSET; + for (ResumeTicket &slot : this->slots_) { + if (!slot.valid || std::memcmp(slot.session_id, session_id, RESUME_SESSION_ID_SIZE) != 0) { + continue; + } + uint8_t expected[RESUME_MAC_SIZE]; + bool ok = resume_mac_(slot.secret, "offer", 5, session_id, RESUME_SESSION_ID_SIZE, client_nonce, RESUME_NONCE_SIZE, + expected) && + resume_ct_equal_(expected, offer_mac, RESUME_MAC_SIZE); + resume_wipe(expected, sizeof(expected)); + if (!ok) { + // Bad MAC: leave the ticket so a forger cannot burn it + return false; + } + std::memcpy(secret_out, slot.secret, RESUME_SECRET_SIZE); + resume_wipe(&slot, sizeof(slot)); + slot.valid = false; + return true; + } + return false; +} + +void ResumeTicketCache::clear() { + resume_wipe(this->slots_, sizeof(this->slots_)); + for (ResumeTicket &slot : this->slots_) { + slot.valid = false; + } +} + +bool resume_compute_confirm_mac(const uint8_t *secret, const uint8_t *client_nonce, const uint8_t *server_nonce, + uint8_t *out_mac) { + return resume_mac_(secret, "confirm", 7, client_nonce, RESUME_NONCE_SIZE, server_nonce, RESUME_NONCE_SIZE, out_mac); +} + +bool resume_derive_keys(const uint8_t *secret, const uint8_t *client_nonce, const uint8_t *server_nonce, + const uint8_t *prologue, size_t prologue_len, uint8_t *k_c2d, uint8_t *k_d2c) { + NoiseHashState *hash = nullptr; + if (noise_hashstate_new_by_id(&hash, NOISE_HASH_SHA256) != NOISE_ERROR_NONE) { + return false; + } + // "keys"(4) || client_nonce(16) || server_nonce(16) || SHA256(prologue)(32) + uint8_t data[4 + RESUME_NONCE_SIZE + RESUME_NONCE_SIZE + 32]; + std::memcpy(data, "keys", 4); + std::memcpy(data + 4, client_nonce, RESUME_NONCE_SIZE); + std::memcpy(data + 4 + RESUME_NONCE_SIZE, server_nonce, RESUME_NONCE_SIZE); + int err = noise_hashstate_hash_one(hash, prologue, prologue_len, data + 4 + 2 * RESUME_NONCE_SIZE, 32); + if (err == NOISE_ERROR_NONE) { + err = noise_hashstate_hkdf(hash, secret, RESUME_SECRET_SIZE, data, sizeof(data), k_c2d, 32, k_d2c, 32); + } + noise_hashstate_free(hash); + resume_wipe(data, sizeof(data)); + return err == NOISE_ERROR_NONE; +} + +NoiseCipherState *resume_make_cipher(const uint8_t *key) { + NoiseCipherState *cipher = nullptr; + if (noise_cipherstate_new_by_id(&cipher, NOISE_CIPHER_CHACHAPOLY) != NOISE_ERROR_NONE) { + return nullptr; + } + if (noise_cipherstate_init_key(cipher, key, 32) != NOISE_ERROR_NONE) { + noise_cipherstate_free(cipher); + return nullptr; + } + return cipher; +} + +} // namespace esphome::noise +#endif // USE_NOISE diff --git a/esphome/components/noise/noise_resume.h b/esphome/components/noise/noise_resume.h new file mode 100644 index 0000000000..c037ce672e --- /dev/null +++ b/esphome/components/noise/noise_resume.h @@ -0,0 +1,92 @@ +#pragma once +#include "esphome/core/defines.h" +#ifdef USE_NOISE +#include +#include + +#include + +namespace esphome::noise { + +/** Session resume for the noise transports. + * + * After a full NNpsk0 handshake the responder issues a single-use ticket + * (session id + secret) over the encrypted channel. A client holding a + * ticket places a resume offer in its ClientHello; the responder proves + * possession of the secret in its ServerHello and both sides derive the + * transport keys with HKDF-SHA256 alone, skipping the two curve25519 + * operations of a full handshake (~37 ms on ESP32, ~290 ms on ESP8266 at + * 80 MHz). Old peers ignore the extension bytes on both sides, so every + * mismatch degrades to a normal full handshake on the same connection. + * + * All HKDF calls use the Noise construction (noise_hashstate_hkdf): + * temp = HMAC-SHA256(key, data); out1 = HMAC(temp, 0x01); + * out2 = HMAC(temp, out1 || 0x02). + * + * offer_mac = HKDF(secret, "offer" || session_id || client_nonce).out1[:16] + * confirm_mac = HKDF(secret, "confirm" || client_nonce || server_nonce).out1[:16] + * k_c2d, k_d2c = HKDF(secret, "keys" || client_nonce || server_nonce + * || SHA256(prologue)) (32 bytes each) + */ + +static constexpr uint8_t RESUME_OFFER_VERSION = 0x01; +static constexpr uint8_t RESUME_ACCEPT_VERSION = 0x01; +static constexpr size_t RESUME_SESSION_ID_SIZE = 8; +static constexpr size_t RESUME_NONCE_SIZE = 16; +static constexpr size_t RESUME_MAC_SIZE = 16; +static constexpr size_t RESUME_SECRET_SIZE = 32; + +// ClientHello body: version | session_id | client_nonce | offer_mac +static constexpr size_t RESUME_OFFER_SIZE = 1 + RESUME_SESSION_ID_SIZE + RESUME_NONCE_SIZE + RESUME_MAC_SIZE; // 41 +static constexpr size_t RESUME_OFFER_SESSION_ID_OFFSET = 1; +static constexpr size_t RESUME_OFFER_NONCE_OFFSET = RESUME_OFFER_SESSION_ID_OFFSET + RESUME_SESSION_ID_SIZE; +static constexpr size_t RESUME_OFFER_MAC_OFFSET = RESUME_OFFER_NONCE_OFFSET + RESUME_NONCE_SIZE; + +// ServerHello trailing extension: version | server_nonce | confirm_mac +static constexpr size_t RESUME_ACCEPT_SIZE = 1 + RESUME_NONCE_SIZE + RESUME_MAC_SIZE; // 33 + +struct ResumeTicket { + uint8_t session_id[RESUME_SESSION_ID_SIZE]; + uint8_t secret[RESUME_SECRET_SIZE]; + bool valid{false}; +}; + +/// Fixed-slot RAM cache of single-use resume tickets. Lost on reboot by +/// design: clients fall back to a full handshake. +class ResumeTicketCache { + public: + /// Generate and store a fresh ticket, evicting the oldest slot. + /// Returns false (and stores nothing) if the RNG fails. + bool issue(ResumeTicket &out); + /// Verify a wire offer (RESUME_OFFER_SIZE bytes, version already checked). + /// On a valid MAC the ticket is consumed (single use) and its secret is + /// copied to secret_out. A miss or a bad MAC leaves the cache unchanged so + /// an attacker cannot burn tickets. + bool take_verified(const uint8_t *offer, uint8_t *secret_out); + /// Forget every ticket (PSK change). + void clear(); + + protected: + static constexpr uint8_t SLOTS = 4; + ResumeTicket slots_[SLOTS]; + uint8_t next_{0}; +}; + +/// Best-effort secure wipe (not optimized away). +void resume_wipe(void *p, size_t len); + +/// confirm_mac for the ServerHello extension. +bool resume_compute_confirm_mac(const uint8_t *secret, const uint8_t *client_nonce, const uint8_t *server_nonce, + uint8_t *out_mac); + +/// Derive the transport keys. k_c2d encrypts client-to-device traffic, +/// k_d2c device-to-client. +bool resume_derive_keys(const uint8_t *secret, const uint8_t *client_nonce, const uint8_t *server_nonce, + const uint8_t *prologue, size_t prologue_len, uint8_t *k_c2d, uint8_t *k_d2c); + +/// Build a ChaChaPoly cipher state keyed with key (32 bytes); nullptr on +/// failure. Nonce counter starts at 0, exactly like a post-split cipher. +NoiseCipherState *resume_make_cipher(const uint8_t *key); + +} // namespace esphome::noise +#endif // USE_NOISE