ESPHome  2024.11.3
wireguard.cpp
Go to the documentation of this file.
1 #include "wireguard.h"
2 #ifdef USE_WIREGUARD
3 #include <cinttypes>
4 #include <ctime>
5 #include <functional>
6 
8 #include "esphome/core/log.h"
9 #include "esphome/core/time.h"
11 
12 #include <esp_wireguard.h>
13 #include <esp_wireguard_err.h>
14 
15 namespace esphome {
16 namespace wireguard {
17 
18 static const char *const TAG = "wireguard";
19 
20 /*
21  * Cannot use `static const char*` for LOGMSG_PEER_STATUS on esp8266 platform
22  * because log messages in `Wireguard::update()` method fail.
23  */
24 #define LOGMSG_PEER_STATUS "WireGuard remote peer is %s (latest handshake %s)"
25 
26 static const char *const LOGMSG_ONLINE = "online";
27 static const char *const LOGMSG_OFFLINE = "offline";
28 
30  ESP_LOGD(TAG, "initializing WireGuard...");
31 
32  this->wg_config_.address = this->address_.c_str();
33  this->wg_config_.private_key = this->private_key_.c_str();
34  this->wg_config_.endpoint = this->peer_endpoint_.c_str();
35  this->wg_config_.public_key = this->peer_public_key_.c_str();
36  this->wg_config_.port = this->peer_port_;
37  this->wg_config_.netmask = this->netmask_.c_str();
38  this->wg_config_.persistent_keepalive = this->keepalive_;
39 
40  if (this->preshared_key_.length() > 0)
41  this->wg_config_.preshared_key = this->preshared_key_.c_str();
42 
43  this->publish_enabled_state();
44 
45  this->wg_initialized_ = esp_wireguard_init(&(this->wg_config_), &(this->wg_ctx_));
46 
47  if (this->wg_initialized_ == ESP_OK) {
48  ESP_LOGI(TAG, "WireGuard initialized");
49  this->wg_peer_offline_time_ = millis();
51  this->defer(std::bind(&Wireguard::start_connection_, this)); // defer to avoid blocking setup
52 
53 #ifdef USE_TEXT_SENSOR
54  if (this->address_sensor_ != nullptr) {
56  }
57 #endif
58  } else {
59  ESP_LOGE(TAG, "cannot initialize WireGuard, error code %d", this->wg_initialized_);
60  this->mark_failed();
61  }
62 }
63 
65  if (!this->enabled_) {
66  return;
67  }
68 
69  if ((this->wg_initialized_ == ESP_OK) && (this->wg_connected_ == ESP_OK) && (!network::is_connected())) {
70  ESP_LOGV(TAG, "local network connection has been lost, stopping WireGuard...");
71  this->stop_connection_();
72  }
73 }
74 
76  bool peer_up = this->is_peer_up();
77  time_t lhs = this->get_latest_handshake();
78  bool lhs_updated = (lhs > this->latest_saved_handshake_);
79 
80  ESP_LOGV(TAG, "enabled=%d, connected=%d, peer_up=%d, handshake: current=%.0f latest=%.0f updated=%d",
81  (int) this->enabled_, (int) (this->wg_connected_ == ESP_OK), (int) peer_up, (double) lhs,
82  (double) this->latest_saved_handshake_, (int) lhs_updated);
83 
84  if (lhs_updated) {
85  this->latest_saved_handshake_ = lhs;
86  }
87 
88  std::string latest_handshake =
89  (this->latest_saved_handshake_ > 0)
90  ? ESPTime::from_epoch_local(this->latest_saved_handshake_).strftime("%Y-%m-%d %H:%M:%S %Z")
91  : "timestamp not available";
92 
93  if (peer_up) {
94  if (this->wg_peer_offline_time_ != 0) {
95  ESP_LOGI(TAG, LOGMSG_PEER_STATUS, LOGMSG_ONLINE, latest_handshake.c_str());
96  this->wg_peer_offline_time_ = 0;
97  } else {
98  ESP_LOGD(TAG, LOGMSG_PEER_STATUS, LOGMSG_ONLINE, latest_handshake.c_str());
99  }
100  } else {
101  if (this->wg_peer_offline_time_ == 0) {
102  ESP_LOGW(TAG, LOGMSG_PEER_STATUS, LOGMSG_OFFLINE, latest_handshake.c_str());
103  this->wg_peer_offline_time_ = millis();
104  } else if (this->enabled_) {
105  ESP_LOGD(TAG, LOGMSG_PEER_STATUS, LOGMSG_OFFLINE, latest_handshake.c_str());
106  this->start_connection_();
107  }
108 
109  // check reboot timeout every time the peer is down
110  if (this->enabled_ && this->reboot_timeout_ > 0) {
111  if (millis() - this->wg_peer_offline_time_ > this->reboot_timeout_) {
112  ESP_LOGE(TAG, "WireGuard remote peer is unreachable, rebooting...");
113  App.reboot();
114  }
115  }
116  }
117 
118 #ifdef USE_BINARY_SENSOR
119  if (this->status_sensor_ != nullptr) {
120  this->status_sensor_->publish_state(peer_up);
121  }
122 #endif
123 
124 #ifdef USE_SENSOR
125  if (this->handshake_sensor_ != nullptr && lhs_updated) {
126  this->handshake_sensor_->publish_state((double) this->latest_saved_handshake_);
127  }
128 #endif
129 }
130 
132  ESP_LOGCONFIG(TAG, "WireGuard:");
133  ESP_LOGCONFIG(TAG, " Address: %s", this->address_.c_str());
134  ESP_LOGCONFIG(TAG, " Netmask: %s", this->netmask_.c_str());
135  ESP_LOGCONFIG(TAG, " Private Key: " LOG_SECRET("%s"), mask_key(this->private_key_).c_str());
136  ESP_LOGCONFIG(TAG, " Peer Endpoint: " LOG_SECRET("%s"), this->peer_endpoint_.c_str());
137  ESP_LOGCONFIG(TAG, " Peer Port: " LOG_SECRET("%d"), this->peer_port_);
138  ESP_LOGCONFIG(TAG, " Peer Public Key: " LOG_SECRET("%s"), this->peer_public_key_.c_str());
139  ESP_LOGCONFIG(TAG, " Peer Pre-shared Key: " LOG_SECRET("%s"),
140  (this->preshared_key_.length() > 0 ? mask_key(this->preshared_key_).c_str() : "NOT IN USE"));
141  ESP_LOGCONFIG(TAG, " Peer Allowed IPs:");
142  for (auto &allowed_ip : this->allowed_ips_) {
143  ESP_LOGCONFIG(TAG, " - %s/%s", std::get<0>(allowed_ip).c_str(), std::get<1>(allowed_ip).c_str());
144  }
145  ESP_LOGCONFIG(TAG, " Peer Persistent Keepalive: %d%s", this->keepalive_,
146  (this->keepalive_ > 0 ? "s" : " (DISABLED)"));
147  ESP_LOGCONFIG(TAG, " Reboot Timeout: %" PRIu32 "%s", (this->reboot_timeout_ / 1000),
148  (this->reboot_timeout_ != 0 ? "s" : " (DISABLED)"));
149  // be careful: if proceed_allowed_ is true, require connection is false
150  ESP_LOGCONFIG(TAG, " Require Connection to Proceed: %s", (this->proceed_allowed_ ? "NO" : "YES"));
151  LOG_UPDATE_INTERVAL(this);
152 }
153 
155 
156 bool Wireguard::can_proceed() { return (this->proceed_allowed_ || this->is_peer_up() || !this->enabled_); }
157 
158 bool Wireguard::is_peer_up() const {
159  return (this->wg_initialized_ == ESP_OK) && (this->wg_connected_ == ESP_OK) &&
160  (esp_wireguardif_peer_is_up(&(this->wg_ctx_)) == ESP_OK);
161 }
162 
164  time_t result;
165  if (esp_wireguard_latest_handshake(&(this->wg_ctx_), &result) != ESP_OK) {
166  result = 0;
167  }
168  return result;
169 }
170 
171 void Wireguard::set_address(const std::string &address) { this->address_ = address; }
172 void Wireguard::set_netmask(const std::string &netmask) { this->netmask_ = netmask; }
173 void Wireguard::set_private_key(const std::string &key) { this->private_key_ = key; }
174 void Wireguard::set_peer_endpoint(const std::string &endpoint) { this->peer_endpoint_ = endpoint; }
175 void Wireguard::set_peer_public_key(const std::string &key) { this->peer_public_key_ = key; }
176 void Wireguard::set_peer_port(const uint16_t port) { this->peer_port_ = port; }
177 void Wireguard::set_preshared_key(const std::string &key) { this->preshared_key_ = key; }
178 
179 void Wireguard::add_allowed_ip(const std::string &ip, const std::string &netmask) {
180  this->allowed_ips_.emplace_back(ip, netmask);
181 }
182 
183 void Wireguard::set_keepalive(const uint16_t seconds) { this->keepalive_ = seconds; }
184 void Wireguard::set_reboot_timeout(const uint32_t seconds) { this->reboot_timeout_ = seconds; }
185 void Wireguard::set_srctime(time::RealTimeClock *srctime) { this->srctime_ = srctime; }
186 
187 #ifdef USE_BINARY_SENSOR
190 #endif
191 
192 #ifdef USE_SENSOR
194 #endif
195 
196 #ifdef USE_TEXT_SENSOR
198 #endif
199 
201 
203  this->enabled_ = true;
204  ESP_LOGI(TAG, "WireGuard enabled");
205  this->publish_enabled_state();
206 }
207 
209  this->enabled_ = false;
210  this->defer(std::bind(&Wireguard::stop_connection_, this)); // defer to avoid blocking running loop
211  ESP_LOGI(TAG, "WireGuard disabled");
212  this->publish_enabled_state();
213 }
214 
216 #ifdef USE_BINARY_SENSOR
217  if (this->enabled_sensor_ != nullptr) {
218  this->enabled_sensor_->publish_state(this->enabled_);
219  }
220 #endif
221 }
222 
223 bool Wireguard::is_enabled() { return this->enabled_; }
224 
226  if (!this->enabled_) {
227  ESP_LOGV(TAG, "WireGuard is disabled, cannot start connection");
228  return;
229  }
230 
231  if (this->wg_initialized_ != ESP_OK) {
232  ESP_LOGE(TAG, "cannot start WireGuard, initialization in error with code %d", this->wg_initialized_);
233  return;
234  }
235 
236  if (!network::is_connected()) {
237  ESP_LOGD(TAG, "WireGuard is waiting for local network connection to be available");
238  return;
239  }
240 
241  if (!this->srctime_->now().is_valid()) {
242  ESP_LOGD(TAG, "WireGuard is waiting for system time to be synchronized");
243  return;
244  }
245 
246  if (this->wg_connected_ == ESP_OK) {
247  ESP_LOGV(TAG, "WireGuard connection already started");
248  return;
249  }
250 
251  ESP_LOGD(TAG, "starting WireGuard connection...");
252  this->wg_connected_ = esp_wireguard_connect(&(this->wg_ctx_));
253 
254  if (this->wg_connected_ == ESP_OK) {
255  ESP_LOGI(TAG, "WireGuard connection started");
256  } else if (this->wg_connected_ == ESP_ERR_RETRY) {
257  ESP_LOGD(TAG, "WireGuard is waiting for endpoint IP address to be available");
258  return;
259  } else {
260  ESP_LOGW(TAG, "cannot start WireGuard connection, error code %d", this->wg_connected_);
261  return;
262  }
263 
264  ESP_LOGD(TAG, "configuring WireGuard allowed IPs list...");
265  bool allowed_ips_ok = true;
266  for (std::tuple<std::string, std::string> ip : this->allowed_ips_) {
267  allowed_ips_ok &=
268  (esp_wireguard_add_allowed_ip(&(this->wg_ctx_), std::get<0>(ip).c_str(), std::get<1>(ip).c_str()) == ESP_OK);
269  }
270 
271  if (allowed_ips_ok) {
272  ESP_LOGD(TAG, "allowed IPs list configured correctly");
273  } else {
274  ESP_LOGE(TAG, "cannot configure WireGuard allowed IPs list, aborting...");
275  this->stop_connection_();
276  this->mark_failed();
277  }
278 }
279 
281  if (this->wg_initialized_ == ESP_OK && this->wg_connected_ == ESP_OK) {
282  ESP_LOGD(TAG, "stopping WireGuard connection...");
283  esp_wireguard_disconnect(&(this->wg_ctx_));
284  this->wg_connected_ = ESP_FAIL;
285  }
286 }
287 
288 std::string mask_key(const std::string &key) { return (key.substr(0, 5) + "[...]="); }
289 
290 } // namespace wireguard
291 } // namespace esphome
292 #endif
void set_status_sensor(binary_sensor::BinarySensor *sensor)
Definition: wireguard.cpp:188
ESPTime now()
Get the time in the currently defined timezone.
wireguard_config_t wg_config_
Definition: wireguard.h:120
binary_sensor::BinarySensor * status_sensor_
Definition: wireguard.h:102
void set_preshared_key(const std::string &key)
Definition: wireguard.cpp:177
uint32_t wg_peer_offline_time_
The last time the remote peer become offline.
Definition: wireguard.h:127
text_sensor::TextSensor * address_sensor_
Definition: wireguard.h:111
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:15
sensor::Sensor * handshake_sensor_
Definition: wireguard.h:107
The RealTimeClock class exposes common timekeeping functions via the device&#39;s local real-time clock...
time::RealTimeClock * srctime_
Definition: wireguard.h:99
bool proceed_allowed_
Set to false to block the setup step until peer is connected.
Definition: wireguard.h:115
void defer(const std::string &name, std::function< void()> &&f)
Defer a callback to the next loop() call.
Definition: component.cpp:130
void add_on_time_sync_callback(std::function< void()> callback)
void disable_auto_proceed()
Block the setup step until peer is connected.
Definition: wireguard.cpp:200
void set_address(const std::string &address)
Definition: wireguard.cpp:171
void set_keepalive(uint16_t seconds)
Definition: wireguard.cpp:183
std::string mask_key(const std::string &key)
Strip most part of the key only for secure printing.
Definition: wireguard.cpp:288
void enable()
Enable the WireGuard component.
Definition: wireguard.cpp:202
void publish_state(const std::string &state)
Definition: text_sensor.cpp:9
bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition: util.cpp:15
void set_address_sensor(text_sensor::TextSensor *sensor)
Definition: wireguard.cpp:197
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
time_t latest_saved_handshake_
The latest saved handshake.
Definition: wireguard.h:135
void set_private_key(const std::string &key)
Definition: wireguard.cpp:173
bool enabled_
When false the wireguard link will not be established.
Definition: wireguard.h:118
void set_srctime(time::RealTimeClock *srctime)
Definition: wireguard.cpp:185
static ESPTime from_epoch_local(time_t epoch)
Convert an UTC epoch timestamp to a local time ESPTime instance.
Definition: time.h:83
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:39
void add_allowed_ip(const std::string &ip, const std::string &netmask)
Definition: wireguard.cpp:179
void set_reboot_timeout(uint32_t seconds)
Definition: wireguard.cpp:184
Application App
Global storage of Application pointer - only one Application can exist.
void set_netmask(const std::string &netmask)
Definition: wireguard.cpp:172
void publish_state(bool state)
Publish a new state to the front-end.
bool is_valid() const
Check if this ESPTime is valid (all fields in range and year is greater than 2018) ...
Definition: time.h:59
binary_sensor::BinarySensor * enabled_sensor_
Definition: wireguard.h:103
void disable()
Stop any running connection and disable the WireGuard component.
Definition: wireguard.cpp:208
void publish_enabled_state()
Publish the enabled state if the enabled binary sensor is configured.
Definition: wireguard.cpp:215
void set_peer_endpoint(const std::string &endpoint)
Definition: wireguard.cpp:174
virtual void mark_failed()
Mark this component as failed.
Definition: component.cpp:118
time_t get_latest_handshake() const
Definition: wireguard.cpp:163
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
uint8_t address
Definition: bl0906.h:211
Base class for all binary_sensor-type classes.
Definition: binary_sensor.h:37
bool is_enabled()
Return if the WireGuard component is or is not enabled.
Definition: wireguard.cpp:223
void set_handshake_sensor(sensor::Sensor *sensor)
Definition: wireguard.cpp:193
Base-class for all sensors.
Definition: sensor.h:57
void set_peer_public_key(const std::string &key)
Definition: wireguard.cpp:175
void set_enabled_sensor(binary_sensor::BinarySensor *sensor)
Definition: wireguard.cpp:189
void set_peer_port(uint16_t port)
Definition: wireguard.cpp:176
esphome::sensor::Sensor * sensor
Definition: statsd.h:38
std::vector< std::tuple< std::string, std::string > > allowed_ips_
Definition: wireguard.h:93