ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
wireguard.cpp
Go to the documentation of this file.
1#include "wireguard.h"
2#ifdef USE_WIREGUARD
3#include <cinttypes>
4#include <ctime>
5
7#include "esphome/core/log.h"
8#include "esphome/core/time.h"
11
12#include <esp_wireguard.h>
13#include <esp_wireguard_err.h>
14
16
17ESPHOME_LOG_TAG(TAG, "wireguard");
18
19/*
20 * Cannot use `static const char*` for LOGMSG_PEER_STATUS on esp8266 platform
21 * because log messages in `Wireguard::update()` method fail.
22 */
23#define LOGMSG_PEER_STATUS "Remote peer is %s (latest handshake %s)"
24
25static const char *const LOGMSG_ONLINE = "online";
26static const char *const LOGMSG_OFFLINE = "offline";
27
28void Wireguard::setup() {
29 this->wg_config_.address = this->address_;
30 this->wg_config_.private_key = this->private_key_;
31 this->wg_config_.endpoint = this->peer_endpoint_;
32 this->wg_config_.public_key = this->peer_public_key_;
33 this->wg_config_.port = this->peer_port_;
34 this->wg_config_.netmask = this->netmask_;
35 this->wg_config_.persistent_keepalive = this->keepalive_;
36
37 if (this->preshared_key_ != nullptr)
38 this->wg_config_.preshared_key = this->preshared_key_;
39
40 this->publish_enabled_state();
41
42 {
44 this->wg_initialized_ = esp_wireguard_init(&(this->wg_config_), &(this->wg_ctx_));
45 }
46
47 if (this->wg_initialized_ == ESP_OK) {
48 ESP_LOGI(TAG, "Initialized");
50 this->srctime_->add_on_time_sync_callback([this]() { this->start_connection_(); });
51 this->defer([this]() { this->start_connection_(); }); // defer to avoid blocking setup
52
53#ifdef USE_TEXT_SENSOR
54 PUBLISH_STATE(this->address_text_sensor_, this->address_);
55#endif
56 } else {
57 ESP_LOGE(TAG, "Cannot initialize: error code %d", this->wg_initialized_);
58 this->mark_failed();
59 }
60}
61
62void Wireguard::loop() {
63 if (!this->enabled_) {
64 return;
65 }
66
67 if ((this->wg_initialized_ == ESP_OK) && (this->wg_connected_ == ESP_OK) && (!network::is_connected())) {
68 ESP_LOGV(TAG, "Local network connection has been lost, stopping");
69 this->stop_connection_();
70 }
71}
72
73void Wireguard::update() {
74 bool peer_up = this->is_peer_up();
75 time_t lhs = this->get_latest_handshake();
76 bool lhs_updated = (lhs > this->latest_saved_handshake_);
77
78 ESP_LOGV(TAG, "enabled=%d, connected=%d, peer_up=%d, handshake: current=%.0f latest=%.0f updated=%d",
79 (int) this->enabled_, (int) (this->wg_connected_ == ESP_OK), (int) peer_up, (double) lhs,
80 (double) this->latest_saved_handshake_, (int) lhs_updated);
81
82 if (lhs_updated) {
83 this->latest_saved_handshake_ = lhs;
84 }
85
86 std::string latest_handshake =
87 (this->latest_saved_handshake_ > 0)
88 ? ESPTime::from_epoch_local(this->latest_saved_handshake_).strftime("%Y-%m-%d %H:%M:%S %Z")
89 : "timestamp not available";
90
91 if (peer_up) {
92 if (this->wg_peer_offline_time_ != 0) {
93 ESP_LOGI(TAG, LOGMSG_PEER_STATUS, LOGMSG_ONLINE, latest_handshake.c_str());
94 this->wg_peer_offline_time_ = 0;
95 } else {
96 ESP_LOGD(TAG, LOGMSG_PEER_STATUS, LOGMSG_ONLINE, latest_handshake.c_str());
97 }
98 } else {
99 if (this->wg_peer_offline_time_ == 0) {
100 ESP_LOGW(TAG, LOGMSG_PEER_STATUS, LOGMSG_OFFLINE, latest_handshake.c_str());
103 } else if (this->enabled_) {
104 ESP_LOGD(TAG, LOGMSG_PEER_STATUS, LOGMSG_OFFLINE, latest_handshake.c_str());
105 if (millis() - this->wg_reconnect_time_ >= RECONNECT_INTERVAL_MS) {
106 this->wg_reconnect_time_ = millis();
107 this->stop_connection_();
108 }
109 this->start_connection_();
110 }
111
112 // check reboot timeout every time the peer is down
113 if (this->enabled_ && this->reboot_timeout_ > 0) {
114 if (millis() - this->wg_peer_offline_time_ > this->reboot_timeout_) {
115 ESP_LOGE(TAG, "Remote peer is unreachable; rebooting");
116 App.reboot();
117 }
118 }
119 }
120
121#ifdef USE_BINARY_SENSOR
122 PUBLISH_STATE(this->status_binary_sensor_, peer_up);
123#endif
124
125#ifdef USE_SENSOR
126 if (this->handshake_sensor_ != nullptr && lhs_updated) {
127 this->handshake_sensor_->publish_state((double) this->latest_saved_handshake_);
128 }
129#endif
130}
131
132void Wireguard::dump_config() {
133 char private_key_masked[MASK_KEY_BUFFER_SIZE];
134 char preshared_key_masked[MASK_KEY_BUFFER_SIZE];
135 mask_key_to(private_key_masked, sizeof(private_key_masked), this->private_key_);
136 mask_key_to(preshared_key_masked, sizeof(preshared_key_masked), this->preshared_key_);
137 // clang-format off
138 ESP_LOGCONFIG(
139 TAG,
140 "WireGuard:\n"
141 " Address: %s\n"
142 " Netmask: %s\n"
143 " Private Key: " LOG_SECRET("%s") "\n"
144 " Peer Endpoint: " LOG_SECRET("%s") "\n"
145 " Peer Port: " LOG_SECRET("%d") "\n"
146 " Peer Public Key: " LOG_SECRET("%s") "\n"
147 " Peer Pre-shared Key: " LOG_SECRET("%s"),
148 this->address_, this->netmask_, private_key_masked,
149 this->peer_endpoint_, this->peer_port_, this->peer_public_key_,
150 (this->preshared_key_ != nullptr ? preshared_key_masked : LOG_STR_LITERAL("NOT IN USE")));
151 // clang-format on
152 ESP_LOGCONFIG(TAG, " Peer Allowed IPs:");
153 for (const AllowedIP *it = this->allowed_ips_; it != nullptr && it->ip != nullptr; it++) {
154 ESP_LOGCONFIG(TAG, " - %s/%s", it->ip, it->netmask);
155 }
156 ESP_LOGCONFIG(TAG, " Peer Persistent Keepalive: %d%s", this->keepalive_,
157 (this->keepalive_ > 0 ? LOG_STR_LITERAL("s") : LOG_STR_LITERAL(" (DISABLED)")));
158 ESP_LOGCONFIG(TAG, " Reboot Timeout: %" PRIu32 "%s", (this->reboot_timeout_ / 1000),
159 (this->reboot_timeout_ != 0 ? LOG_STR_LITERAL("s") : LOG_STR_LITERAL(" (DISABLED)")));
160 // be careful: if proceed_allowed_ is true, require connection is false
161 ESP_LOGCONFIG(TAG, " Require Connection to Proceed: %s",
162 (this->proceed_allowed_ ? LOG_STR_LITERAL("NO") : LOG_STR_LITERAL("YES")));
163 LOG_UPDATE_INTERVAL(this);
164}
165
166void Wireguard::on_shutdown() { this->stop_connection_(); }
167
168bool Wireguard::can_proceed() { return (this->proceed_allowed_ || this->is_peer_up() || !this->enabled_); }
169
170bool Wireguard::is_peer_up() const {
171 return (this->wg_initialized_ == ESP_OK) && (this->wg_connected_ == ESP_OK) &&
172 (esp_wireguardif_peer_is_up(&(this->wg_ctx_)) == ESP_OK);
173}
174
175time_t Wireguard::get_latest_handshake() const {
176 time_t result;
177 if (esp_wireguard_latest_handshake(&(this->wg_ctx_), &result) != ESP_OK) {
178 result = 0;
179 }
180 return result;
181}
182
183void Wireguard::enable() {
184 this->enabled_ = true;
185 ESP_LOGI(TAG, "Enabled");
186 this->publish_enabled_state();
187}
188
189void Wireguard::disable() {
190 this->enabled_ = false;
191 this->defer([this]() { this->stop_connection_(); }); // defer to avoid blocking running loop
192 ESP_LOGI(TAG, "Disabled");
193 this->publish_enabled_state();
194}
195
196void Wireguard::publish_enabled_state() {
197#ifdef USE_BINARY_SENSOR
198 PUBLISH_STATE(this->enabled_binary_sensor_, this->enabled_);
199#endif
200}
201
203 if (!this->enabled_) {
204 ESP_LOGV(TAG, "Disabled, cannot start connection");
205 return;
206 }
207
208 if (this->wg_initialized_ != ESP_OK) {
209 ESP_LOGE(TAG, "Cannot start: error code %d", this->wg_initialized_);
210 return;
211 }
212
213 if (!network::is_connected()) {
214 ESP_LOGD(TAG, "Waiting for local network connection to be available");
215 return;
216 }
217
218 if (!this->srctime_->now().is_valid()) {
219 ESP_LOGD(TAG, "Waiting for system time to be synchronized");
220 return;
221 }
222
223 if (this->wg_connected_ == ESP_OK) {
224 ESP_LOGV(TAG, "Connection already started");
225 return;
226 }
227
228 ESP_LOGD(TAG, "Starting connection");
229 {
231 this->wg_connected_ = esp_wireguard_connect(&(this->wg_ctx_));
232 }
233
234 if (this->wg_connected_ == ESP_OK) {
235 ESP_LOGI(TAG, "Connection started");
236 } else if (this->wg_connected_ == ESP_ERR_RETRY) {
237 ESP_LOGD(TAG, "Waiting for endpoint IP address to be available");
238 return;
239 } else {
240 ESP_LOGW(TAG, "Cannot start connection, error code %d", this->wg_connected_);
241 return;
242 }
243
244 ESP_LOGD(TAG, "Configuring allowed IPs list");
245 bool allowed_ips_ok = true;
246 for (const AllowedIP *it = this->allowed_ips_; it != nullptr && it->ip != nullptr; it++) {
247 allowed_ips_ok &= (esp_wireguard_add_allowed_ip(&(this->wg_ctx_), it->ip, it->netmask) == ESP_OK);
248 }
249
250 if (allowed_ips_ok) {
251 ESP_LOGD(TAG, "Allowed IPs list configured correctly");
252 } else {
253 ESP_LOGE(TAG, "Cannot configure allowed IPs list, aborting");
254 this->stop_connection_();
255 this->mark_failed();
256 }
257}
258
260 if (this->wg_initialized_ == ESP_OK && this->wg_connected_ == ESP_OK) {
261 ESP_LOGD(TAG, "Stopping connection");
262 {
264 esp_wireguard_disconnect(&(this->wg_ctx_));
265 }
266 this->wg_connected_ = ESP_FAIL;
267 }
268}
269
270void mask_key_to(char *buffer, size_t len, const char *key) {
271 // Format: "XXXXX[...]=\0" = MASK_KEY_BUFFER_SIZE chars minimum
272 if (len < MASK_KEY_BUFFER_SIZE || key == nullptr) {
273 if (len > 0)
274 buffer[0] = '\0';
275 return;
276 }
277 // Copy first 5 characters of the key
278 size_t i = 0;
279 for (; i < 5 && key[i] != '\0'; ++i) {
280 buffer[i] = key[i];
281 }
282 // Append "[...]="
283 const char *suffix = "[...]=";
284 for (size_t j = 0; suffix[j] != '\0' && (i + j) < len - 1; ++j) {
285 buffer[i + j] = suffix[j];
286 }
287 buffer[i + 6] = '\0';
288}
289
290} // namespace esphome::wireguard
291#endif
void mark_failed()
Mark this component as failed.
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
void defer(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call with a const char* name.
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:2276
ESPTime now()
Get the time in the currently defined timezone.
void add_on_time_sync_callback(F &&callback)
bool enabled_
When false the wireguard link will not be established.
Definition wireguard.h:116
time::RealTimeClock * srctime_
Definition wireguard.h:110
bool proceed_allowed_
Set to false to block the setup step until peer is connected.
Definition wireguard.h:113
uint32_t wg_peer_offline_time_
The last time the remote peer become offline.
Definition wireguard.h:125
const AllowedIP * allowed_ips_
Definition wireguard.h:104
time_t latest_saved_handshake_
The latest saved handshake.
Definition wireguard.h:134
wireguard_config_t wg_config_
Definition wireguard.h:118
const char * key
uint32_t buffer
Definition gif.cpp:50
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.h:36
void mask_key_to(char *buffer, size_t len, const char *key)
Strip most part of the key only for secure printing.
ESPHOME_LOG_TAG(TAG, "wireguard")
const void size_t len
Definition hal.h:68
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
static ESPTime from_epoch_local(time_t epoch)
Convert an UTC epoch timestamp to a local time ESPTime instance.
Definition time.h:125
size_t strftime(char *buffer, size_t buffer_len, const char *format)
Convert this ESPTime struct to a null-terminated c string buffer as specified by the format argument.
Definition time.cpp:20
bool is_valid(bool check_day_of_week=true, bool check_day_of_year=true) const
Check if this ESPTime is valid (year >= 2019 and the requested fields are in range).
Definition time.h:82
Allowed IP entry for WireGuard peer configuration.
Definition wireguard.h:27
SemaphoreHandle_t lock