ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
xxtea_encryption.cpp
Go to the documentation of this file.
1#include "xxtea_encryption.h"
2#ifdef USE_PACKET_INTERFACE_XXTEA
3#include <algorithm>
4#include <cstring>
7#include "esphome/core/log.h"
8
10
11ESPHOME_LOG_TAG(TAG, "packet_interface.xxtea");
12
13static constexpr uint32_t PREF_HASH = fnv1a_hash("packet_interface.xxtea");
14// Different for each mode, so devices set up differently drop each other's packets
15static constexpr uint8_t CHECK_BYTES[3] = {0x58, 0x54, 0x45};
16static constexpr uint8_t ROLLING_CHECK_BYTES[3] = {0x58, 0x54, 0x52};
17static constexpr size_t CHECK_SIZE = 4;
18// Boot number, counter, and the echo of the receiver's boot number
19static constexpr size_t ROLLING_SIZE = 12;
20// XXTEA needs at least two words
21static constexpr size_t MIN_LENGTH = 8;
22static constexpr size_t MAX_PADDING = 4;
23
24static uint32_t get_uint32(const uint8_t *buf) { return encode_uint32(buf[3], buf[2], buf[1], buf[0]); }
25
26static constexpr size_t trailer_size(bool rolling_code) {
27 return rolling_code ? ROLLING_SIZE + CHECK_SIZE : CHECK_SIZE;
28}
29
31 // XXTEA works on whole 32-bit words
32 : PacketInterface(remaining_packet_size(lower->get_max_packet_size() & ~size_t{3}, trailer_size(rolling_code))),
33 lower_(lower),
34 trailer_size_(trailer_size(rolling_code)),
35 rolling_code_(rolling_code) {
36 this->stack_on_(lower, CAPABILITY_ENCRYPTION);
37}
38
39void XxteaEncryption::set_key(std::initializer_list<uint32_t> key) {
40 std::copy_n(key.begin(), std::min(key.size(), this->key_.size()), this->key_.begin());
41}
42
44 if (this->max_packet_size_ == 0) {
45 this->mark_failed(LOG_STR("max_packet_size too small for the configured layers"));
46 return;
47 }
48 size_t words = this->lower_->get_max_packet_size() / 4;
49 RAMAllocator<uint32_t> allocator;
50 this->tx_buffer_ = allocator.allocate(words * 2);
51 if (this->tx_buffer_ == nullptr) {
52 this->mark_failed(LOG_STR("Not enough memory for the packet buffers"));
53 return;
54 }
55 this->rx_buffer_ = this->tx_buffer_ + words;
56 if (this->rolling_code_) {
58 this->pref_.load(&this->boot_);
59 this->next_boot_();
60 }
62 [this](const PacketBuffer &data, const PacketMetaData &meta_data) { this->receive_(data, meta_data); });
63}
64
66 ESP_LOGCONFIG(TAG,
67 "XXTEA Encryption on '%s':\n"
68 " Max Packet Size: %zu\n"
69 " Rolling Code: %s",
70 this->name_, this->max_packet_size_, YESNO(this->rolling_code_));
71 if (this->rolling_code_) {
72 ESP_LOGCONFIG(TAG, " Boot Number: %" PRIu32, this->boot_);
73 }
74}
75
76// A new boot number must be saved before it is used, or a crash could make the peer see it again
78 this->boot_++;
79 this->counter_ = 0;
80 if (!this->pref_.save(&this->boot_) || !global_preferences->sync()) {
81 ESP_LOGW(TAG, "%s: Could not save the boot number, so a restart could reuse it", this->name_);
82 }
83}
84
86 if (this->tx_buffer_ == nullptr)
87 return false;
88 size_t size = data.size();
89 if (size > this->max_packet_size_) {
90 ESP_LOGW(TAG, "%s: Packet of %zu bytes is larger than %zu", this->name_, size, this->max_packet_size_);
91 return false;
92 }
93 size_t padding = (4 - (size + this->trailer_size_) % 4) % 4;
94 if (size + padding + this->trailer_size_ < MIN_LENGTH)
95 padding += 4;
96 size_t length = size + padding + this->trailer_size_;
97 auto *buf = reinterpret_cast<uint8_t *>(this->tx_buffer_);
98 data.copy_to(buf, size);
99 memset(buf + size, 0, padding);
100 uint8_t *check = buf + length - CHECK_SIZE;
101 if (this->rolling_code_) {
102 put_le32(check - ROLLING_SIZE, this->boot_);
103 put_le32(check - ROLLING_SIZE + 4, this->counter_);
104 put_le32(check - ROLLING_SIZE + 8, this->echo_boot_);
105 memcpy(check, ROLLING_CHECK_BYTES, sizeof(ROLLING_CHECK_BYTES));
106 if (++this->counter_ == 0)
107 this->next_boot_();
108 } else {
109 memcpy(check, CHECK_BYTES, sizeof(CHECK_BYTES));
110 }
111 check[CHECK_SIZE - 1] = padding;
112 xxtea::encrypt(this->tx_buffer_, length / 4, this->key_.data());
113 return this->lower_->send_to_interface(PacketBuffer(buf, length), meta_data);
114}
115
117 if (this->peer_seen_ && (boot < this->peer_boot_ || (boot == this->peer_boot_ && counter <= this->peer_counter_)))
118 return false;
119 this->peer_seen_ = true;
120 this->peer_boot_ = boot;
121 this->peer_counter_ = counter;
122 return true;
123}
124
125void XxteaEncryption::receive_(const PacketBuffer &data, const PacketMetaData &meta_data) {
126 size_t length = data.size();
127 if (length % 4 != 0 || length < std::max(MIN_LENGTH, this->trailer_size_) ||
128 length > this->lower_->get_max_packet_size()) {
129 ESP_LOGV(TAG, "%s: Packet of %zu bytes dropped", this->name_, length);
130 this->note_received_(false);
131 return;
132 }
133 auto *buf = reinterpret_cast<uint8_t *>(this->rx_buffer_);
134 data.copy_to(buf, length);
135 xxtea::decrypt(this->rx_buffer_, length / 4, this->key_.data());
136 const uint8_t *check = buf + length - CHECK_SIZE;
137 const uint8_t *expected = this->rolling_code_ ? ROLLING_CHECK_BYTES : CHECK_BYTES;
138 size_t padding = check[CHECK_SIZE - 1];
139 if (memcmp(check, expected, sizeof(CHECK_BYTES)) != 0 || padding > MAX_PADDING ||
140 padding > length - this->trailer_size_) {
141 ESP_LOGV(TAG, "%s: Packet failed authentication", this->name_);
142 this->note_received_(false);
143 return;
144 }
145 this->note_received_(true);
146 if (this->rolling_code_) {
147 uint32_t boot = get_uint32(check - ROLLING_SIZE);
148 uint32_t counter = get_uint32(check - ROLLING_SIZE + 4);
149 uint32_t echo = get_uint32(check - ROLLING_SIZE + 8);
150 // Learn the peer's boot number even from a packet that is then dropped, so both sides can catch up
151 if (boot > this->echo_boot_)
152 this->echo_boot_ = boot;
153 // A packet recorded before this boot cannot carry this boot's number
154 if (echo != this->boot_) {
155 ESP_LOGV(TAG, "%s: Packet for boot %" PRIu32 " dropped", this->name_, echo);
156 return;
157 }
158 if (!this->accept_counter_(boot, counter)) {
159 // A boot number lower than one already heard means the peer lost its saved boot number, or a replay
160 if (boot < this->peer_boot_ && !this->old_boot_warned_) {
161 this->old_boot_warned_ = true;
162 ESP_LOGW(TAG,
163 "%s: Packets from an older boot %" PRIu32 " of the peer are dropped; if its flash was erased, "
164 "restart this device",
165 this->name_, boot);
166 }
167 ESP_LOGV(TAG, "%s: Old packet %" PRIu32 ":%" PRIu32 " dropped", this->name_, boot, counter);
168 return;
169 }
170 }
171 this->on_receive_from_interface_(PacketBuffer(buf, length - this->trailer_size_ - padding), meta_data);
172}
173
174} // namespace esphome::packet_interface
175#endif
void mark_failed()
Mark this component as failed.
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2396
T * allocate(size_t n)
Definition helpers.h:2423
A buffer class that efficiently represents a composite buffer with three sections:
size_t copy_to(uint8_t *dest, size_t count, size_t offset=0) const
Copy data from the buffer to a destination pointer.
size_t size() const
Get the total size of the buffer.
A class that will transport data to and from an abstract channel.
size_t get_max_packet_size() const
The largest packet this layer accepts; fixed when the layer is constructed.
void note_received_(bool understood)
Called by a layer for each received packet it understood, or could not make sense of.
void stack_on_(PacketInterface *lower, Capability capability)
Called by a layer's constructor to record itself as the layer above lower, adding its own capability.
virtual bool send_to_interface(const PacketBuffer &data, const PacketMetaData &meta_data)=0
Method to be implemented by child classes to send data to the interface.
void add_packet_interface_listener(F &&callback)
Add a listener that will be called when data is received.
void on_receive_from_interface_(const PacketBuffer &data, const PacketMetaData &meta_data)
This function should be called by implementing classes with received data to be passed to any listene...
A struct to hold metadata about a packet.
XxteaEncryption(PacketInterface *lower, bool rolling_code)
bool accept_counter_(uint32_t boot, uint32_t counter)
bool send_to_interface(const PacketBuffer &data, const PacketMetaData &meta_data) override
void receive_(const PacketBuffer &data, const PacketMetaData &meta_data)
void set_key(std::initializer_list< uint32_t > key)
const char * key
constexpr size_t remaining_packet_size(size_t size, size_t used)
The room left for a packet of size bytes after used bytes, or 0 if it is too small.
ESPHOME_LOG_TAG(TAG, "packet_interface.session")
void encrypt(uint32_t *v, size_t n, const uint32_t *k)
Encrypt a block of data in-place using XXTEA algorithm with 256-bit key.
Definition xxtea.cpp:8
void decrypt(uint32_t *v, size_t n, const uint32_t *k)
Decrypt a block of data in-place using XXTEA algorithm with 256-bit key.
Definition xxtea.cpp:28
constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str)
Extend a FNV-1a hash with additional string data.
Definition helpers.h:995
uint16_t size
Definition helpers.cpp:34
ESPPreferences * global_preferences
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
Definition helpers.h:1051
constexpr uint8_t * put_le32(uint8_t *dst, uint32_t value)
Definition helpers.h:1135
constexpr uint32_t fnv1a_hash(const char *str)
Calculate a FNV-1a hash of str.
Definition helpers.h:1018
static void uint32_t
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24
bool sync()
Commit pending writes to flash.
Definition preferences.h:33