Home IO Control
ESPHome add-on for IO-Homecontrol devices
Loading...
Searching...
No Matches
key_extraction_responder.cpp
Go to the documentation of this file.
2
3#include "log_helpers.h"
4
5#include "device_registry.h"
6#include "pairing_responder.h"
7#include "proto_commands.h"
8#include "proto_crypto.h"
9#include "radio_interface.h"
10#include "tuning_config.h"
11
12#include <esp_random.h>
13
14#include <cinttypes>
15#include <cstdio>
16#include <cstring>
17#include <string>
18
19/// @file key_extraction_responder.cpp
20/// @brief "Recover System Key" (key extraction) — device-role responder collaborator.
21/// @ingroup hioc_hub
22///
23/// Owns the impure side of the key-extraction feature: arming/disarming, throwaway node-ID
24/// generation, the 10-minute auto-off timer, the post-extraction grace window, transmitting
25/// device-role replies, and the security-sensitive result log block. The pure state-transition
26/// decisions live in pairing_responder.h/.cpp; the six RX branches
27/// (0x28/0x2C/0x31/0x32/0x36/0x3C) dispatch through try_handle_frame(), called from
28/// process_received_packet_() (hub_status.cpp).
29///
30/// @note Hardware-confirmed 2026-08-02: a full extraction (0x28 through 0x33) between two real
31/// boards — SX1276 running this responder, SX1262 running this project's own PairingEngine as
32/// the "hub" — recovered the hub's node_id/system_key byte-for-byte. That validates the crypto,
33/// the state machine, and the radio wiring end-to-end on real RF hardware.
34/// @warning What that test does NOT validate: compatibility with a genuine third-party hub
35/// (Somfy TaHoma/Smoove, Velux KLF200, etc.). The device-role frames built here
36/// (create_discover_resp(), create_challenge_req(), create_key_confirm()) were reverse-engineered
37/// from this project's own encoder and a small number of captures. The self-test above
38/// necessarily agrees with those conventions (it's the same codebase on both ends); a real hub's
39/// exact requirements (discovery-response field completeness, retry cadence) may still differ. It
40/// is blind to two things in particular: a device-role frame that is self-consistent but wrong on
41/// air, and a protocol step a real hub requires that this project's own controller role never
42/// sends. Both are real failure modes against real hubs; see
43/// tests/corpus/captures/pairing/velux_kig300_pairing_key_extraction_stall.yaml and
44/// tests/corpus/captures/pairing/somfy_connectivity_kit_pairing_key_extraction_stall.yaml.
45///
46/// The device-role builders (create_discover_resp(), create_challenge_req_device_role(),
47/// create_key_confirm(), create_discover_confirm_ack()) are each pinned against a real device's
48/// captured framing by tests/corpus/corpus_device_role_builder_test.cpp, including
49/// create_discover_resp()'s flags/timestamp bytes, which mirror a real Somfy Izymo dimmer's
50/// captured values (see KEY_EXTRACTION_DISCOVER_RESP_FLAGS/_TIMESTAMP in proto_commands.cpp for
51/// the derivation) but remain unconfirmed against a real hub like every device-role field here.
52///
53/// recover_system_key_from_transfer()'s IV-derivation formula itself is independently pinned
54/// against two externally-captured known-answer key transfers
55/// (ProtoCrypto.CryptKeyMatchesDocumented*Capture in proto_crypto_test.cpp), so that formula does
56/// not rest on this codebase's own conventions — though both captures are short requests and don't
57/// exercise construct_iv()'s 8-byte truncation window, so a real hub sending a longer request is an
58/// open question. Treat a recovered key as unconfirmed until it has been verified against a real
59/// hub, or by successfully controlling a device with it.
60
61namespace esphome {
62namespace home_io_control {
63
64namespace {
65
66constexpr uint32_t KEY_EXTRACTION_AUTO_OFF_MS = 10 * 60 * 1000; ///< Arm window: 10 minutes.
67// TODO(hardware-verify): confirm a real hub's pairing flow doesn't validate the advertised
68// manufacturer/type against a known-device allowlist before completing key exchange —
69// Somfy/roller-shutter is a plausible but unconfirmed default.
70constexpr uint8_t KEY_EXTRACTION_MANUFACTURER_ID = MANUFACTURER_SOMFY; ///< Plausible, widely-supported default.
71constexpr DeviceType KEY_EXTRACTION_ADVERTISED_TYPE = DeviceType::ROLLER_SHUTTER; ///< Plausible default device type.
72constexpr uint8_t KEY_EXTRACTION_ADVERTISED_SUBTYPE = 0;
73constexpr uint8_t KEY_EXTRACTION_ID_GEN_MAX_ATTEMPTS = 16; ///< Collision-retry budget for the throwaway node ID.
74constexpr const char *KEY_EXTRACTION_TIMEOUT_NAME = "key_extraction_auto_off";
75constexpr uint32_t RANDOM_LOW_BYTE_MASK = 0xFF; ///< Isolates one random byte from esp_random()'s 32-bit output.
76
77constexpr uint32_t KEY_EXTRACTION_MID_ATTEMPT_TIMEOUT_MS = 5000; ///< 5 seconds.
78// Bounds the CH2 hold (key_extraction_responder.h's key_extraction_hold_deadline_ms_ /
79// awaiting_reply()) for the 3 pre-extraction states (SENT_DISCOVER_RESP, SENT_CONFIRM_ACK,
80// SENT_CHALLENGE), none of which has a hold bound of its own otherwise -- CMD_DISCOVER_REQ is
81// handled before the throwaway-ID dst filter (try_handle_frame()), so *any* 0x28 from any hub in
82// range that then goes silent would otherwise pin CH2 for the rest of the arm window.
83//
84// This is purely a radio-scheduling optimization, not a protocol-recovery deadline: expiry only
85// stops loop() from holding CH2 for this responder (see key_extraction_hold_deadline_ms_'s doc
86// comment in key_extraction_responder.h) -- it does NOT touch key_extraction_ctx_.state, so a real
87// hub's frame arriving even slightly late is still accepted by the pure guards in
88// pairing_responder.cpp exactly as if the hold were still active, just without the CH2-parking
89// benefit for that one frame. That makes the cost of sizing this too small merely "occasionally
90// idle-hops away from CH2 a little early," not "silently drops a live attempt" -- so 5s is sized
91// generously rather than tightly: a real hub that's still trying should have its very next frame
92// land well inside this window -- comfortably above a single retry gap (EXCHANGE_RETRY_DELAY_MS=250ms)
93// plus the request/response windows either side of it
94// (PAIRING_KEY_CHALLENGE_TIMEOUT_MS/PAIRING_KEY_CONFIRM_TIMEOUT_MS=500ms each, pairing_engine.h) --
95// while staying "a few seconds", not minutes, sized against third-party hub timing (the whole
96// reason this feature exists), not this project's own controller role. Not hardware-measured;
97// deliberately generous rather than tight, matching KEY_EXTRACTION_POST_EXTRACT_GRACE_MS's own
98// reasoning below.
99
100constexpr uint32_t KEY_EXTRACTION_POST_EXTRACT_GRACE_MS = 60000; ///< One minute.
101// TODO(hardware-verify): no timing data exists for the 0x33->0x36 gap on real hardware (the only
102// capture of that gap is an untimed SPI trace). One minute is deliberately generous rather than
103// tight: every pre-EXTRACTED guard in pairing_responder.cpp still rejects EXTRACTED/SENT_ADDRESS_
104// RESP for 0x2C/0x31/0x32, so a *different* hub cannot interfere with a live round inside this
105// window. on_discover_request() is the one exception, deliberately: it accepts a fresh 0x28 from
106// the *same* hub as ctx.hub_node_id (see that function's doxygen for why), so the window is inert
107// to every hub except the one it's actually running a round with. It is still hard-capped by the
108// 10-minute auto-off timer above, and the only cost of overshooting is that the HA switch reports
109// "still listening" for longer. Undershooting, by contrast, silently drops a slow hub's
110// node-verification round — the exact failure this feature exists to fix. Not measured.
111constexpr const char *KEY_EXTRACTION_GRACE_TIMER_NAME = "key_extraction_post_extract_grace";
112
113} // namespace
114
115namespace detail {
116
117std::string build_key_extraction_report(const uint8_t node_id[NODE_ID_SIZE], const uint8_t key[AES_KEY_SIZE]) {
118 return "SYSTEM KEY EXTRACTED -- DO NOT SHARE YOUR SYSTEM KEY\n"
119 "Anyone with this key and node_id can control every device on this installation.\n"
120 "This exchange has not been independently confirmed against your specific hub -- test\n"
121 "this key (e.g. by controlling a device with it) before relying on it.\n"
122 "Copy the block below into a new hub's YAML.\n"
123 "home_io_control:\n"
124 " node_id: \"" +
125 node_id_to_string(node_id) + "\"\n" + " system_key: \"" + format_key_hex(key) + "\"";
126}
127
128} // namespace detail
129
130KeyExtractionResponder::KeyExtractionResponder(const uint8_t *node_id, RadioDriver **radio, const TuningConfig *tuning,
131 DeviceRegistry &registry, TransmitFrameFn transmit,
132 NamedTimeoutFn schedule_auto_off)
133 : node_id_(node_id),
134 radio_(radio),
135 tuning_(tuning),
136 registry_(registry),
137 transmit_(std::move(transmit)),
138 schedule_auto_off_(std::move(schedule_auto_off)) {}
139
140void KeyExtractionResponder::generate_throwaway_id(uint8_t out[NODE_ID_SIZE]) {
141 for (uint8_t attempt = 0; attempt < KEY_EXTRACTION_ID_GEN_MAX_ATTEMPTS; attempt++) {
142 for (uint8_t i = 0; i < NODE_ID_SIZE; i++)
143 out[i] = static_cast<uint8_t>(esp_random() & RANDOM_LOW_BYTE_MASK);
144 if (!stored_node_id_is_valid(out))
145 continue;
146 if (memcmp(out, this->node_id_, NODE_ID_SIZE) == 0)
147 continue;
148 if (memcmp(out, BROADCAST_DISCOVER, NODE_ID_SIZE) == 0 || memcmp(out, BROADCAST_DISCOVER_ALT, NODE_ID_SIZE) == 0)
149 continue;
150 if (this->registry_.get(node_id_to_string(out)) != nullptr)
151 continue;
152 return;
153 }
154 // Every attempt collided (astronomically unlikely for a 3-byte space against a handful of
155 // reserved/registered IDs) — fall through and use the last-generated candidate rather than
156 // leaving the buffer stale; a false collision here only degrades to "discovery/key-init from
157 // the colliding real device also gets intercepted," not a crash or security issue.
158}
159
161 if (!armed) {
163 return;
165 ESP_LOGI(detail::TAG, "Key extraction: disarmed");
166 if (this->armed_callback_)
167 this->armed_callback_(false);
168 return;
169 }
170
173 this->key_extraction_ctx_.advertised_type = KEY_EXTRACTION_ADVERTISED_TYPE;
174 this->key_extraction_ctx_.advertised_subtype = KEY_EXTRACTION_ADVERTISED_SUBTYPE;
176
177 ESP_LOGW(detail::TAG,
178 "Key extraction: ARMED for 10 minutes, throwaway ID %s. Put your existing hub into pairing/add-device "
179 "mode now.",
181
182 // This timer and arm_post_extraction_grace()'s below share one idiom (named set_timeout(),
183 // guarded by a state check so a stale callback from a disarm-and-rearm inside the window can't
184 // act on the wrong cycle, logging, then disarming) — two call sites, not enough to be worth
185 // extracting into a shared helper at the cost of an extra layer of indirection between the
186 // guard condition and what it's guarding.
187 this->schedule_auto_off_(KEY_EXTRACTION_TIMEOUT_NAME, KEY_EXTRACTION_AUTO_OFF_MS, [this]() {
188 // Guards against a stale timeout firing after a manual disarm/re-arm already ran; this hub's
189 // set_timeout() replaces any pending callback with the same name, but the check is cheap
190 // insurance and documents the intent either way.
192 return;
194 ESP_LOGW(detail::TAG, "Key extraction: window expired, no pairing attempt seen. Disarming.");
195 } else {
196 ESP_LOGW(detail::TAG, "Key extraction: window expired while in progress (reached stage=%s). Disarming.",
198 }
199 this->set_armed(false);
200 });
201
202 if (this->armed_callback_)
203 this->armed_callback_(true);
204}
205
208 return false;
209
210 if (frame.cmd == CMD_DISCOVER_REQ) {
211 this->handle_discover_(frame);
212 return true;
213 }
214 if (memcmp(frame.dst, this->key_extraction_ctx_.throwaway_id, NODE_ID_SIZE) != 0)
215 return false;
216 if (frame.cmd == CMD_DISCOVER_CONFIRM) {
217 this->handle_discover_confirm_(frame);
218 return true;
219 }
220 if (frame.cmd == CMD_KEY_INIT) {
221 this->handle_key_init_(frame);
222 return true;
223 }
224 if (frame.cmd == CMD_KEY_TRANSFER) {
225 this->handle_key_transfer_(frame);
226 return true;
227 }
228 if (frame.cmd == CMD_NODE_VERIFY_REQ) {
229 this->handle_node_verify_req_(frame);
230 return true;
231 }
232 if (frame.cmd == CMD_CHALLENGE_REQ) {
233 this->handle_node_verify_challenge_(frame);
234 return true;
235 }
236 return false;
237}
238
239void KeyExtractionResponder::broadcast_reply_(const IoFrame &frame) {
240 // Broadcast on all 3 channels like the CMD_STATUS_UPDATE_RESP ack in hub_status.cpp: we don't
241 // know which channel the foreign hub is listening on after transmitting its own frame.
242 //
243 // The preamble choice mirrors ExchangeEngine::send_and_receive() (exchange_engine.cpp), which
244 // already picks between a long and a short preamble via is_start() for the controller-role
245 // outbound path: a start-flagged frame (currently only 0x29, this responder's discovery reply)
246 // is the one reply a hopping/scanning peer has to catch cold, so it gets
247 // `cold_broadcast_reply_preamble` — long enough for that, short enough that broadcasting it on
248 // 3 channels doesn't meaningfully block the loop (~12x cheaper per leg than LONG_PREAMBLE by
249 // default). Every other device-role reply (0x2D, 0x3C, 0x33, 0x37, 0x3D) is `start=false` — it lands
250 // on a channel the peer already holds, so it keeps the driver's chip-tuned response_preamble()
251 // (12 bytes for SX1276, 8 for SX1262/LR1121), same as every other in-exchange reply in this
252 // codebase.
253 //
254 // Do NOT widen this to a flat LONG_PREAMBLE(1024) for every reply: hardware-confirmed
255 // 2026-08-02, that blocked the main loop long enough to blow through the hub's tight per-try
256 // wait windows and broke both directions. Scoping the long preamble to only the start-flagged
257 // reply is what keeps that regression from recurring while still fixing the hopping-catch case.
258 //
259 // CH2 goes last, deliberately: CH2 is the channel every non-discovery peer listen holds still
260 // on (unicast requests always go out on CH2 — see wait_for_key_challenge_()'s and
261 // wait_for_key_confirm_()'s own doc comments), so it's the one leg whose *completion* the peer
262 // is waiting to react to. Transmitting it mid-sequence would let a peer that hears it and
263 // replies immediately land its next frame while this responder is still transmitting a later
264 // leg — a structural TX-deafness miss, regardless of hop timing. Firing it last avoids that: by
265 // the time the peer reacts to hearing CH2, this responder has already finished transmitting and
266 // re-armed RX. This doesn't cost the one reply that behaves differently (0x29 discovery, whose
267 // peer listen explicitly *skips* CH2 — ROTATE_SKIPPING_REQUEST) anything either: CH1/CH3 (the
268 // channels that listen actually scans) both go out before CH2 instead of straddling it, so
269 // discovery reaches its useful channels sooner.
270 const uint16_t preamble =
271 is_start(frame) ? this->tuning_->cold_broadcast_reply_preamble : (*this->radio_)->response_preamble();
272 this->transmit_(frame, FREQ_CH1, preamble);
273 this->transmit_(frame, FREQ_CH3, preamble);
274 this->transmit_(frame, FREQ_CH2, preamble);
275}
276
277void KeyExtractionResponder::handle_discover_(const IoFrame &frame) {
279 return;
280
281 IoFrame resp;
282 if (!create_discover_resp(resp, this->key_extraction_ctx_.throwaway_id, frame.src,
283 this->key_extraction_ctx_.advertised_type, this->key_extraction_ctx_.advertised_subtype,
284 KEY_EXTRACTION_MANUFACTURER_ID)) {
285 ESP_LOGW(detail::TAG, "Key extraction: failed to build discovery response");
286 // Deliberately does NOT touch key_extraction_hold_deadline_ms_: on_discover_request() already
287 // advanced ctx.state above, but a failed builder means no reply went out, so there is nothing
288 // for the hub to be replying to yet. Leaving the deadline exactly as it was (0 on a fresh arm,
289 // safely "already expired" per key_extraction_hold_deadline_ms_'s doc comment; or whatever an
290 // earlier successful reply set it to, still correctly bounded) is what keeps a builder failure
291 // from either holding CH2 unboundedly or clobbering a still-valid earlier deadline.
292 return;
293 }
294 this->broadcast_reply_(resp);
295 this->key_extraction_hold_deadline_ms_ = millis() + KEY_EXTRACTION_MID_ATTEMPT_TIMEOUT_MS;
296 ESP_LOGI(detail::TAG, "Key extraction: replied to discovery from hub %s with throwaway ID %s",
297 node_id_to_string(frame.src).c_str(), node_id_to_string(this->key_extraction_ctx_.throwaway_id).c_str());
298}
299
300void KeyExtractionResponder::handle_discover_confirm_(const IoFrame &frame) {
302 return;
303
304 IoFrame resp;
305 if (!create_discover_confirm_ack(resp, this->key_extraction_ctx_.throwaway_id, frame.src)) {
306 ESP_LOGW(detail::TAG, "Key extraction: failed to build discovery-confirm ack");
307 // See handle_discover_()'s matching comment: leaving the hold deadline untouched on a builder
308 // failure is deliberate, not an oversight.
309 return;
310 }
311 this->broadcast_reply_(resp);
312 this->key_extraction_hold_deadline_ms_ = millis() + KEY_EXTRACTION_MID_ATTEMPT_TIMEOUT_MS;
313 ESP_LOGI(detail::TAG, "Key extraction: acknowledged discovery confirm from hub %s",
314 node_id_to_string(frame.src).c_str());
315}
316
317void KeyExtractionResponder::handle_key_init_(const IoFrame &frame) {
318 uint8_t candidate_challenge[HMAC_SIZE];
319 crypto::generate_challenge(candidate_challenge);
320 if (!pairing_responder::on_key_init(this->key_extraction_ctx_, candidate_challenge, frame.src))
321 return;
322
323 IoFrame resp;
324 if (!create_challenge_req_device_role(resp, frame.src, this->key_extraction_ctx_.throwaway_id,
325 this->key_extraction_ctx_.challenge)) {
326 ESP_LOGW(detail::TAG, "Key extraction: failed to build challenge request");
327 // See handle_discover_()'s matching comment: leaving the hold deadline untouched on a builder
328 // failure is deliberate, not an oversight.
329 return;
330 }
331 this->broadcast_reply_(resp);
332 this->key_extraction_hold_deadline_ms_ = millis() + KEY_EXTRACTION_MID_ATTEMPT_TIMEOUT_MS;
333 ESP_LOGI(detail::TAG, "Key extraction: sent challenge to hub %s", node_id_to_string(frame.src).c_str());
334}
335
336void KeyExtractionResponder::handle_key_transfer_(const IoFrame &frame) {
337 if (frame.data_len < AES_KEY_SIZE) {
338 ESP_LOGW(detail::TAG, "Key extraction: key-transfer payload too short (%u bytes)", frame.data_len);
339 return;
340 }
342 return;
343
344 IoFrame resp;
345 if (create_key_confirm(resp, this->key_extraction_ctx_.throwaway_id, frame.src)) {
346 this->broadcast_reply_(resp);
347 } else {
348 ESP_LOGW(detail::TAG, "Key extraction: failed to build key confirm");
349 }
350
351 // Log before the grace window can disarm us: disarm resets key_extraction_ctx_, which is where
352 // the recovered key and the hub's real node ID live.
353 this->log_result_();
354 ESP_LOGI(detail::TAG,
355 "Key extraction: still listening for up to %" PRIu32
356 " more seconds in case the hub verifies this device (CMD_NODE_VERIFY_REQ/0x36) — leave the "
357 "switch on until it turns off on its own.",
358 KEY_EXTRACTION_POST_EXTRACT_GRACE_MS / 1000);
359 // Don't disarm immediately: some hubs (Velux KLR200) follow the key exchange with a node
360 // verification request (0x36) and a challenge (0x3C) against our answer, and disarming here would make the
361 // responder deaf to that round before it can happen. A *different* hub attempting to pair
362 // mid-window still cannot succeed and produce a second, confusing log block — every pure guard in
363 // pairing_responder.cpp except on_discover_request() unconditionally rejects EXTRACTED/
364 // SENT_NODE_VERIFY_RESP, and on_discover_request() itself only accepts a fresh 0x28 from that same
365 // hub_node_id, so a different hub's traffic still cannot advance the state machine backwards. The
366 // grace timer below disarms once no further progress is seen from the real hub, instead of doing
367 // it at once.
369}
370
371void KeyExtractionResponder::handle_node_verify_req_(const IoFrame &frame) {
372 // Our throwaway ID is not a secret -- it went out in clear in our own 0x29/0x37 -- so the dst
373 // check in try_handle_frame() alone doesn't establish this frame actually came from the hub we
374 // exchanged keys with. hub_node_id was captured from the 0x31 that started this attempt
375 // (pairing_responder::on_key_init()); anything else claiming our throwaway ID as dst is not that
376 // hub and gets no reply, closing an otherwise-unbounded loop an onlooker could drive to keep
377 // re-arming the grace window for as long as the arm cycle lasts.
378 if (memcmp(frame.src, this->key_extraction_ctx_.hub_node_id, NODE_ID_SIZE) != 0)
379 return;
381 return;
382 IoFrame resp;
384 ESP_LOGW(detail::TAG, "Key extraction: failed to build address response");
385 return;
386 }
387 this->broadcast_reply_(resp);
388 this->arm_post_extraction_grace(); // Hub is still progressing — push the disarm back out.
389 ESP_LOGI(detail::TAG, "Key extraction: answered node verification request from hub %s",
390 node_id_to_string(frame.src).c_str());
391}
392
393void KeyExtractionResponder::handle_node_verify_challenge_(const IoFrame &frame) {
394 // Hub-identity guard, mirroring handle_node_verify_req_()'s: only the hub we actually exchanged keys
395 // with may drive this round.
396 if (memcmp(frame.src, this->key_extraction_ctx_.hub_node_id, NODE_ID_SIZE) != 0)
397 return;
398 // Length guard, mirroring handle_key_transfer_()'s: frame.data is passed straight into a
399 // `const uint8_t challenge[HMAC_SIZE]` parameter, so a short 0x3C would silently authenticate
400 // over stale bytes left in IoFrame::data from a previous parse.
401 if (frame.data_len < HMAC_SIZE) {
402 ESP_LOGW(detail::TAG, "Key extraction: address challenge payload too short (%u bytes)", frame.data_len);
403 return;
404 }
406 return;
407 // Rebuild the 0x37 we last sent — deterministic from ctx, nothing stored across the two calls.
408 // Only origin.cmd/origin.data/origin.data_len feed the transcript, so the dst passed here is
409 // irrelevant to the HMAC; the real builder is used anyway so the transcript cannot drift if the
410 // 0x37 payload ever changes.
411 IoFrame our_node_verify_resp;
412 if (!create_node_verify_resp_device_role(our_node_verify_resp, /*own=*/this->key_extraction_ctx_.throwaway_id,
413 /*dst=*/frame.src))
414 return;
415 IoFrame resp;
416 if (!create_challenge_resp_device_role(resp, /*dst=*/frame.src, /*src=*/this->key_extraction_ctx_.throwaway_id,
417 frame.data, our_node_verify_resp, this->key_extraction_ctx_.recovered_key)) {
418 ESP_LOGW(detail::TAG, "Key extraction: failed to build address challenge response");
419 return;
420 }
421 this->broadcast_reply_(resp);
422 ESP_LOGI(detail::TAG, "Key extraction: answered address challenge from hub %s", node_id_to_string(frame.src).c_str());
423 // Do NOT disarm here — re-arm the grace window instead and stay in SENT_NODE_VERIFY_RESP so a
424 // retried 0x3C is answered (on_node_verify_challenge() deliberately never advances state).
426}
427
429 // Same replace-on-reschedule idiom as KEY_EXTRACTION_TIMEOUT_NAME's 10-minute timer above —
430 // every new sign of hub progress (0x36 received, 0x3D sent, and this same call at extraction
431 // time) pushes the disarm back out, so a slow multi-retry hub isn't cut off mid-round. That
432 // 10-minute timer is deliberately neither cancelled nor extended here, so it still bounds the
433 // whole arm cycle: no amount of grace-window re-arming can keep the responder listening past the
434 // 10 minutes the switch entity documents.
435 //
436 // Also pushes out key_extraction_hold_deadline_ms_ (key_extraction_responder.h) by the same
437 // window: the CH2 hold that field governs is not just for the 3 pre-extraction states
438 // KEY_EXTRACTION_MID_ATTEMPT_TIMEOUT_MS bounds -- EXTRACTED/SENT_NODE_VERIFY_RESP are "awaiting
439 // reply" too (a hub may still send 0x36/0x3C to verify the address it was handed), and this
440 // grace window, not the 5s mid-attempt one, is what should bound the hold during that phase.
441 // Without this, the hold would (per key_extraction_hold_deadline_ms_'s default-past-if-unset
442 // behavior) never actually engage once the responder reaches EXTRACTED, silently losing the
443 // CH2-hold benefit for the very phase whose whole point is catching a hub's follow-up unicast
444 // frame.
445 this->schedule_auto_off_(KEY_EXTRACTION_GRACE_TIMER_NAME, KEY_EXTRACTION_POST_EXTRACT_GRACE_MS, [this]() {
446 // Only a still-running post-extraction cycle may be disarmed from here. Checking DISARMED
447 // alone is NOT enough: a user who toggles the switch off and back on inside the grace window
448 // leaves this callback pending against a brand-new, unrelated arm cycle (set_timeout() only
449 // replaces a *pending* timer of the same name, and re-arming schedules the 10-minute auto-off
450 // timer, not this one) — and that new cycle is ARMED_IDLE, not DISARMED, so a DISARMED-only
451 // guard would let a stale callback kill it.
452 // The converse worry — that the new cycle reaches EXTRACTED (a state this guard accepts)
453 // before the stale callback fires — cannot happen: reaching EXTRACTED calls this function,
454 // whose set_timeout() replaces the pending callback under the same name. The stale timer is
455 // destroyed exactly when the state becomes acceptable to it, so the only window it can fire in
456 // is one this guard rejects.
457 const auto state = this->key_extraction_ctx_.state;
460 return;
461 ESP_LOGI(detail::TAG, "Key extraction: post-extraction grace window elapsed (stage=%s). Disarming.",
463 this->set_armed(false);
464 });
465 this->key_extraction_hold_deadline_ms_ = millis() + KEY_EXTRACTION_POST_EXTRACT_GRACE_MS;
466}
467
468// TODO(hardware-verify): an authenticated read-back to the foreign hub using the recovered key,
469// to confirm it before trusting it. recover_system_key_from_transfer()'s IV-derivation formula is
470// independently pinned against externally-captured known-answer key transfers (see the file-level
471// @warning above), but nothing here confirms this specific extraction talks to a real third-party
472// hub correctly — the single highest-risk unverified piece of this feature. That read-back subflow
473// is deliberately not implemented: doubling the protocol-speculation surface for a feature that
474// already ships marked experimental is not worth it for a second unverified vendor-hub
475// interaction. The key is still always printed (gating it on an equally-unverified secondary check
476// risks hiding a correct key), but the log below says so.
477void KeyExtractionResponder::log_result_() {
478 // Deliberate, explicit exception to redaction.h's masking — see that file and README.md's
479 // "Reporting Unsupported Devices" section, which already warns about pairing logs and the
480 // shared TRANSFER_KEY in almost identical terms. Do NOT route this through the generic
481 // frame-log helpers (log_frame()/log_component_capture()); those must keep masking 0x32.
482 //
483 // Logged line-by-line via log_multiline_result(), not as one ESP_LOGW("%s", ...) call: a single
484 // call silently truncates at ESPHome's 512-byte log buffer -- see that function's doxygen
485 // (log_helpers.h) for the root cause, and build_oneway_adoption_report()'s caller for the
486 // identical reasoning on the 1W path.
487 ESP_LOGW(detail::TAG, "========================================");
488 detail::log_multiline_result(detail::TAG, /*is_warning=*/true, /*prefix=*/"",
490 this->key_extraction_ctx_.recovered_key));
491 ESP_LOGW(detail::TAG, "========================================");
492}
493
494} // namespace home_io_control
495} // namespace esphome
Owns the per-hub device table, update callbacks, and linked-remote associations.
void generate_throwaway_id(uint8_t out[NODE_ID_SIZE])
Generate a random throwaway node ID for one key-extraction arm cycle, avoiding collisions with the br...
void set_armed(bool armed)
Arm or disarm the "Recover System Key" (key extraction) responder.
void arm_post_extraction_grace()
(Re)arm the post-extraction grace window that replaces the old immediate disarm-on-extraction: called...
pairing_responder::ResponderContext key_extraction_ctx_
State for the current "Accept Foreign Pairing" (key-extraction) arm cycle; DISARMED by default so a f...
bool try_handle_frame(const IoFrame &frame)
Dispatch a frame to the responder if it's one of its 0x28/0x2C/0x31/0x32/0x36/0x3C frames and the res...
KeyExtractionResponder(const uint8_t *node_id, RadioDriver **radio, const TuningConfig *tuning, DeviceRegistry &registry, TransmitFrameFn transmit, NamedTimeoutFn schedule_auto_off)
uint32_t key_extraction_hold_deadline_ms_
Deadline (millis()) until which loop() should hold CH2 for the key-extraction responder,...
Abstract radio driver for IO-Homecontrol.
Per-hub device table, update-callback fan-out, and linked-remote map.
"Recover System Key" (key extraction) — device-role responder collaborator.
Hub-layer log tag and log/format helpers shared by the hub and its collaborators.
void generate_challenge(uint8_t out[HMAC_SIZE])
Generate 6 random bytes for a challenge using the ESP32 hardware RNG.
constexpr const char * TAG
Shared log tag for hub-level messages.
Definition log_helpers.h:31
void log_multiline_result(const char *tag, bool is_warning, const std::string &prefix, const std::string &message)
Log prefix followed by message, one line per log call rather than one call for the whole (possibly mu...
std::string build_key_extraction_report(const uint8_t node_id[NODE_ID_SIZE], const uint8_t key[AES_KEY_SIZE])
Build the ready-to-paste 2W system-key-extraction report: node_id:/system_key: as a home_io_control: ...
std::string format_key_hex(const uint8_t key[AES_KEY_SIZE])
Format a 16-byte key as an uppercase, unseparated hex string for display.
Definition log_helpers.h:61
bool on_key_transfer(ResponderContext &ctx, const uint8_t transfer_payload[AES_KEY_SIZE])
Decide how to react to an inbound CMD_KEY_TRANSFER (0x32) while armed.
const char * responder_stage_name(ResponderState state)
Get a short, log/telemetry-friendly name for a responder state.
bool on_discover_confirm(ResponderContext &ctx)
Decide how to react to an inbound CMD_DISCOVER_CONFIRM (0x2C) addressed to our throwaway ID.
bool on_node_verify_req(ResponderContext &ctx)
Decide how to react to an inbound CMD_NODE_VERIFY_REQ (0x36) addressed to our throwaway ID.
bool on_key_init(ResponderContext &ctx, const uint8_t challenge[HMAC_SIZE], const uint8_t hub_node_id[NODE_ID_SIZE])
Decide how to react to an inbound CMD_KEY_INIT (0x31) addressed to our throwaway ID.
bool on_node_verify_challenge(const ResponderContext &ctx)
Decide how to react to an inbound CMD_CHALLENGE_REQ (0x3C) — issued by the hub this time,...
@ ARMED_IDLE
Armed, listening for a discovery request (0x28).
@ DISARMED
Not armed; 0x28/0x2C/0x31/0x32 traffic is ignored.
@ SENT_NODE_VERIFY_RESP
Answered a hub's CMD_NODE_VERIFY_REQ (0x36) with our CMD_NODE_VERIFY_RESP (0x37); waiting for the hub...
bool on_discover_request(ResponderContext &ctx, const uint8_t hub_node_id[NODE_ID_SIZE])
Decide how to react to an inbound CMD_DISCOVER_REQ (0x28) while armed.
DeviceType
Device type identifiers reported by IO‑Homecontrol products.
bool create_node_verify_resp_device_role(IoFrame &f, const uint8_t *own, const uint8_t *dst)
Build an address response (0x37) — device side, used only by the key-extraction responder.
bool create_discover_resp(IoFrame &f, const uint8_t *own, const uint8_t *dst, DeviceType type, uint8_t subtype, uint8_t manufacturer_id)
Build a discovery response (0x29) — device side, used only by the key-extraction responder.
bool is_start(const IoFrame &f)
Check START flag.
bool create_key_confirm(IoFrame &f, const uint8_t *own, const uint8_t *dst)
Build a key-confirm frame (0x33) — device side, used only by the key-extraction responder.
std::function< bool(const IoFrame &frame, uint32_t freq_hz, uint16_t preamble)> TransmitFrameFn
Puts a frame on air on a given channel via the hub's protected transmit_frame_().
Definition hub_hooks.h:34
bool stored_node_id_is_valid(const uint8_t id[NODE_ID_SIZE])
Check whether a node ID is usable as an address: not all-zero and not all-0xFF, the two patterns blan...
bool create_discover_confirm_ack(IoFrame &f, const uint8_t *own, const uint8_t *dst)
Build a discovery-confirm acknowledgement (0x2D) — device side, used only by the key-extraction respo...
std::string node_id_to_string(const uint8_t id[NODE_ID_SIZE])
Format a 3‑byte node ID as a 6‑character uppercase hex string.
bool create_challenge_req_device_role(IoFrame &f, const uint8_t *dst, const uint8_t *src, const uint8_t challenge[HMAC_SIZE])
Build a device-role challenge request (0x3C) — device side, used only by the key-extraction responder...
std::function< void(const char *name, uint32_t delay_ms, std::function< void()> callback)> NamedTimeoutFn
Schedules a named, replace-on-same-name timeout on the hub's ESPHome scheduler.
Definition hub_hooks.h:27
bool create_challenge_resp_device_role(IoFrame &f, const uint8_t *dst, const uint8_t *src, const uint8_t challenge[HMAC_SIZE], const IoFrame &origin, const uint8_t *key)
Build a device-role challenge response (0x3D) — device side, used only by the key-extraction responde...
Pure decision logic for the device-role "Accept Foreign Pairing" (system-key extraction) responder.
Command builders for the IO‑Homecontrol protocol.
Cryptographic helpers for the IO‑Homecontrol protocol.
Radio abstraction layer for IO-Homecontrol.
Parsed IO‑Homecontrol frame (CTRL0/1 + addresses + command + data).
Definition proto_frame.h:93
uint8_t dst[NODE_ID_SIZE]
Destination node ID (3 bytes).
Definition proto_frame.h:96
All runtime tunable parameters for pairing and radio diagnostics.
uint16_t cold_broadcast_reply_preamble
Preamble for a start-flagged key-extraction broadcast reply (0x29).
DeviceType advertised_type
Device type advertised in our 0x29.
uint8_t throwaway_id[NODE_ID_SIZE]
Random per-arm-cycle node ID we advertise as ourselves.
uint8_t advertised_subtype
Device subtype advertised in our 0x29.
uint8_t hub_node_id[NODE_ID_SIZE]
Foreign hub's real node ID, captured from the 0x31's src.
Runtime tuning configuration for pairing and radio diagnostics.