arduino-emulator
Loading...
Searching...
No Matches
NetworkClientSecure.h
1/*
2 NetworkClientSecure.h
3 Copyright (c) 2025 Phil Schatzmann. All right reserved.
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18*/
19
20#pragma once
21#if defined(USE_HTTPS)
22#include <errno.h>
23#include <sys/ioctl.h>
24#include <sys/select.h>
25#include <sys/socket.h>
26#include <sys/types.h>
27
28#include <cstring>
29#include <ctime>
30#include <memory>
31#include <string>
32
33#include "Ethernet.h"
34#include "SocketImpl.h"
35
36// Two TLS backends: TinyTLS (default) or wolfSSL (USE_WOLFSSL).
37#if defined(USE_WOLFSSL)
38#include <wolfssl/options.h>
39#include <wolfssl/ssl.h>
40#else
41#include "TinyTLS.h"
42#endif
43
44namespace arduino {
45
46#define SOCKET_IMPL_SEC "SocketImplSecure"
47
48#if defined(USE_WOLFSSL)
49
50static int wolf_ssl_counter = 0;
51static WOLFSSL_CTX* wolf_ctx = nullptr;
52
57class SocketImplSecure : public SocketImpl {
58 public:
59 SocketImplSecure() {
60 if (wolf_ssl_counter++ == 0 || wolf_ctx == nullptr) {
61 wolfSSL_Init();
62 if ((wolf_ctx = wolfSSL_CTX_new(wolfTLS_client_method())) == NULL) {
63 Logger.error(SOCKET_IMPL_SEC, "wolfSSL_CTX_new error.");
64 }
65 }
66 if ((ssl = wolfSSL_new(wolf_ctx)) == NULL) {
67 Logger.error(SOCKET_IMPL_SEC, "wolfSSL_new error.");
68 }
69 }
70
71 ~SocketImplSecure() {
72 if (ssl) {
73 wolfSSL_free(ssl);
74 ssl = nullptr;
75 }
76 if (--wolf_ssl_counter == 0 && wolf_ctx) {
77 wolfSSL_CTX_free(wolf_ctx);
78 wolf_ctx = nullptr;
79 wolfSSL_Cleanup();
80 }
81 }
82 // direct read
83 int read(uint8_t* buffer, size_t len) override {
84 // size_t result = ::recv(sock, buffer, len, MSG_DONTWAIT );
85 if (ssl == nullptr) {
86 wolfSSL_set_fd(ssl, sock);
87 }
88 int result = ::wolfSSL_read(ssl, buffer, len);
89
90 if (result < 0) {
91 int error = wolfSSL_get_error(ssl, result);
92 if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) {
93 return 0;
94 }
95
96 is_connected = false;
97 return -1;
98 }
99
100 if (result == 0) {
101 is_connected = false;
102 return -1;
103 }
104
105 //
106 char lenStr[80];
107 sprintf(lenStr, "%ld -> %d", len, result);
108 Logger.debug(SOCKET_IMPL_SEC, "read->", lenStr);
109
110 return result;
111 }
112
113 int connect(const char* address, uint16_t port) override {
114 return connect(address, port, -1);
115 }
116
117 // opens a connection with a timeout in milliseconds for the TCP handshake.
118 // The TLS handshake below still runs to completion without its own
119 // timeout, matching the previous (2-arg) behavior.
120 int connect(const char* address, uint16_t port, int32_t timeout_ms) override {
121 // Create socket
122 sock = ::socket(AF_INET, SOCK_STREAM, 0);
123 if (sock < 0) {
124 Logger.error(SOCKET_IMPL_SEC, "Socket creation failed");
125 return -1;
126 }
127
128 // Setup server address
129 memset(&serv_addr, 0, sizeof(serv_addr));
130 serv_addr.sin_family = AF_INET;
131 serv_addr.sin_port = htons(port);
132 if (::inet_pton(AF_INET, address, &serv_addr.sin_addr) <= 0) {
133 Logger.error(SOCKET_IMPL_SEC, "Invalid address", address);
134 ::close(sock);
135 sock = -1;
136 return -1;
137 }
138
139 // Connect to server, honoring timeout_ms when >= 0
140 if (timeout_ms < 0) {
141 if (::connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
142 Logger.error(SOCKET_IMPL_SEC, "Connection failed");
143 ::close(sock);
144 sock = -1;
145 return -1;
146 }
147 } else {
148 setSocketNonBlocking(sock, true);
149
150 int result = ::connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
151 if (result < 0 && errno != EINPROGRESS && errno != EWOULDBLOCK) {
152 Logger.error(SOCKET_IMPL_SEC, "Connection failed");
153 setSocketNonBlocking(sock, false);
154 ::close(sock);
155 sock = -1;
156 return -1;
157 }
158
159 if (result < 0) {
160 fd_set writefds, errorfds;
161 FD_ZERO(&writefds);
162 FD_SET(sock, &writefds);
163 FD_ZERO(&errorfds);
164 FD_SET(sock, &errorfds);
165 timeval timeout{.tv_sec = timeout_ms / 1000,
166 .tv_usec = (timeout_ms % 1000) * 1000};
167
168 result = select(sock + 1, nullptr, &writefds, &errorfds, &timeout);
169 int error_code = 0;
170 socklen_t error_len = sizeof(error_code);
171 if (result <= 0 ||
172 getsockopt(sock, SOL_SOCKET, SO_ERROR, &error_code, &error_len) != 0 ||
173 error_code != 0) {
174 Logger.error(SOCKET_IMPL_SEC,
175 result == 0 ? "Connection timeout" : "Connection failed");
176 setSocketNonBlocking(sock, false);
177 ::close(sock);
178 sock = -1;
179 return -1;
180 }
181 }
182
183 setSocketNonBlocking(sock, false);
184 }
185
186 // Reset the TLS session for this connection - reusing ssl as-is
187 // across a stop()/connect() cycle (this object's owner, e.g.
188 // URLStream's own client_secure, is typically kept and reconnected
189 // rather than recreated) leaves it in stale post-handshake state, so
190 // a second connect() would send a request the server never replies
191 // to instead of doing a fresh handshake.
192 if (ssl != nullptr) {
193 wolfSSL_free(ssl);
194 }
195 ssl = wolfSSL_new(wolf_ctx);
196 if (is_insecure && ssl != nullptr) {
197 wolfSSL_set_verify(ssl, SSL_VERIFY_NONE, nullptr);
198 }
199
200 // Set SSL file descriptor
201 wolfSSL_set_fd(ssl, sock);
202
203 // Set SNI (Server Name Indication) if needed
204 wolfSSL_UseSNI(ssl, WOLFSSL_SNI_HOST_NAME, address, strlen(address));
205
206 // Perform SSL handshake
207 int rc = wolfSSL_connect(ssl);
208 if (rc != SSL_SUCCESS) {
209 int err = wolfSSL_get_error(ssl, rc);
210 const char* errStr = wolfSSL_ERR_reason_error_string(err);
211 char msg[160];
212 snprintf(msg, sizeof(msg),
213 "SSL handshake failed, error code: %d reason: %s", err,
214 errStr ? errStr : "unknown");
215 Logger.error(SOCKET_IMPL_SEC, msg);
216 ::close(sock);
217 sock = -1;
218 return -1;
219 }
220
221 is_connected = true;
222 return 1;
223 }
224
225 // send the data via the socket - returns the number of characters written or
226 // -1=>Error
227 size_t write(const uint8_t* str, size_t len) {
228 Logger.debug(SOCKET_IMPL_SEC, "write");
229 if (ssl == nullptr) {
230 wolfSSL_set_fd(ssl, sock);
231 }
232 // return ::send(sock , str , len , 0 );
233 return ::wolfSSL_write(ssl, str, len);
234 }
235
236 void setCACert(const char* cert) override {
237 if (wolf_ctx == nullptr) return;
238 // Load CA certificate from a PEM string
239 int ret =
240 wolfSSL_CTX_load_verify_buffer(wolf_ctx, (const unsigned char*)cert,
241 strlen(cert), WOLFSSL_FILETYPE_PEM);
242 if (ret != SSL_SUCCESS) {
243 Logger.error(SOCKET_IMPL_SEC, "Failed to load CA certificate");
244 }
245 }
246
247 void setInsecure() {
248 is_insecure = true;
249 if (wolf_ctx == nullptr) return;
250 // Disable certificate verification on context
251 wolfSSL_CTX_set_verify(wolf_ctx, SSL_VERIFY_NONE, nullptr);
252 // Also disable on SSL object if already created
253 if (ssl) wolfSSL_set_verify(ssl, SSL_VERIFY_NONE, nullptr);
254 }
255
256 protected:
257 WOLFSSL* ssl = nullptr;
258 bool is_insecure = false;
259};
260
261#else // TinyTLS (default)
262
263namespace tls_detail {
264// TinyTLS callbacks: monotonic clock (ms), wall clock (s) and idle wait
265static uint32_t clockMs() { return static_cast<uint32_t>(millis()); }
266static int64_t wallTime() { return static_cast<int64_t>(::time(nullptr)); }
267static void idleWait() { delay(1); }
268} // namespace tls_detail
269
274class SocketImplSecure : public SocketImpl {
275 public:
276 static constexpr uint32_t DEFAULT_HANDSHAKE_TIMEOUT_MS = 15000;
277
278 SocketImplSecure() {
279 tls_.attach(transport_);
280 tls_.setClock(tls_detail::clockMs);
281 tls_.setTimeSource(tls_detail::wallTime);
282 tls_.setIdleCallback(tls_detail::idleWait);
283 }
284
285 ~SocketImplSecure() { tls_.stop(); }
286
287 // opens a TCP connection and performs the TLS handshake
288 int connect(const char* address, uint16_t port) override {
289 return connect(address, port, -1);
290 }
291
292 int connect(const char* address, uint16_t port, int32_t timeout_ms) override {
293 tcp_timeout_ms_ = timeout_ms;
294 tls_.setTimeout(timeout_ms >= 0 ? static_cast<uint32_t>(timeout_ms)
295 : DEFAULT_HANDSHAKE_TIMEOUT_MS);
296 // use the host name (not the resolved IP) for SNI and certificate checks
297 const char* name = hostname_.empty() ? address : hostname_.c_str();
298 if (!tls_.connect(name, port)) {
299 char msg[160];
300 snprintf(msg, sizeof(msg), "TLS connect to %s failed: %s", name,
301 tls_.errorText());
302 Logger.error(SOCKET_IMPL_SEC, msg);
303 return -1;
304 }
305 return 1;
306 }
307
308 // name used for SNI and certificate verification
309 void setHostname(const char* name) override {
310 hostname_ = name ? name : "";
311 }
312
313 uint8_t connected() override { return tls_.connected(); }
314
315 // number of decrypted bytes that can be read without blocking
316 size_t available() override {
317 int n = tls_.available();
318 return (n > 0 ? static_cast<size_t>(n) : 0) + (has_peek_ ? 1 : 0);
319 }
320
321 // returns the decrypted bytes; 0 if none is available yet, -1 if closed
322 int read(uint8_t* buffer, size_t len) override {
323 if (len == 0) return 0;
324 if (has_peek_) {
325 buffer[0] = peek_byte_;
326 has_peek_ = false;
327 return 1;
328 }
329 int result = tls_.read(buffer, len);
330 if (result > 0) return result;
331 return tls_.connected() ? 0 : -1;
332 }
333
334 int peek() override {
335 if (!has_peek_) {
336 if (read(&peek_byte_, 1) != 1) return -1;
337 has_peek_ = true;
338 }
339 return peek_byte_;
340 }
341
342 size_t write(const uint8_t* str, size_t len) override {
343 return tls_.write(str, len);
344 }
345
346 void close() override { tls_.stop(); }
347
348 void setCACert(const char* cert) override {
349 if (cert == nullptr) return;
350 if (!roots_) roots_.reset(new tinytls::CertificateStore());
351 tinytls::Error rc = roots_->addPem(reinterpret_cast<const uint8_t*>(cert),
352 strlen(cert));
353 if (rc != tinytls::Error::Ok) {
354 Logger.error(SOCKET_IMPL_SEC, "Failed to load CA certificate");
355 }
356 tls_.setTrustStore(roots_.get());
357 }
358
359 // disables certificate verification (encryption only)
360 void setInsecure() override {
361 tls_.setVerifyMode(tinytls::VerifyMode::None);
362 }
363
364 private:
365 // Plain TCP operations used by the TLS session. They use the non-virtual
366 // SocketImpl methods, so base class callbacks cannot re-enter the TLS session.
367 class SocketTransport : public tinytls::Transport {
368 public:
369 explicit SocketTransport(SocketImplSecure& owner) : owner_(owner) {}
370
371 bool connect(const char* host, uint16_t port) override {
372 return owner_.SocketImpl::connect(host, port, owner_.tcp_timeout_ms_) > 0;
373 }
374
375 size_t write(const uint8_t* buf, size_t len) override {
376 if (owner_.sock < 0) return 0;
377 ssize_t n = ::send(owner_.sock, buf, len, MSG_NOSIGNAL);
378 if (n >= 0) return static_cast<size_t>(n);
379 if (errno == EAGAIN || errno == EWOULDBLOCK) return 0;
380 owner_.SocketImpl::close();
381 return 0;
382 }
383
384 int read(uint8_t* buf, size_t len) override {
385 if (owner_.sock < 0) return -1;
386 ssize_t n = ::recv(owner_.sock, buf, len, MSG_DONTWAIT);
387 if (n > 0) return static_cast<int>(n);
388 if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) return -1;
389 owner_.SocketImpl::close(); // peer closed or error
390 return -1;
391 }
392
393 int available() override {
394 if (owner_.sock < 0) return 0;
395 int bytes = 0;
396 if (ioctl(owner_.sock, FIONREAD, &bytes) != 0) return 0;
397 return bytes > 0 ? bytes : 0;
398 }
399
400 bool connected() override {
401 if (owner_.sock < 0) return false;
402 char c;
403 ssize_t n = ::recv(owner_.sock, &c, 1, MSG_PEEK | MSG_DONTWAIT);
404 if (n > 0 || (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))) return true;
405 owner_.SocketImpl::close();
406 return false;
407 }
408
409 void stop() override { owner_.SocketImpl::close(); }
410
411 private:
412 SocketImplSecure& owner_;
413 };
414
415 std::unique_ptr<tinytls::CertificateStore> roots_; // declared before tls_
416 SocketTransport transport_{*this}; // declared before tls_
417 TinyTLS tls_;
418 std::string hostname_;
419 int32_t tcp_timeout_ms_ = -1;
420 bool has_peek_ = false;
421 uint8_t peek_byte_ = 0;
422};
423
424#endif // USE_WOLFSSL
425
429class NetworkClientSecure : public EthernetClient {
430 public:
431 NetworkClientSecure(int bufferSize = 256, long timeout = 2000)
432 : EthernetClient(std::make_shared<SocketImplSecure>(), bufferSize, timeout) {}
433
434 using EthernetClient::connect;
435
436 // remember the host name so that TLS uses it for SNI and certificate checks
437 int connect(const char* host, uint16_t port) override {
438 p_sock->setHostname(host);
439 return EthernetClient::connect(host, port);
440 }
441
442 int connect(const char* host, uint16_t port, int32_t timeout_ms) {
443 p_sock->setHostname(host);
444 return EthernetClient::connect(host, port, timeout_ms);
445 }
446
447 void setCACert(const char* cert) override { p_sock->setCACert(cert); }
448 void setInsecure() override { p_sock->setInsecure(); }
449};
450
451} // namespace arduino
452
453#endif
Definition SocketImpl.h:30
SSL Socket using wolf ssl. For error codes see https://wolfssl.jp/docs-3/wolfssl-manual/appendix-c.
Definition NetworkClientSecure.h:57
We provide the WiFi class to simulate the Arduino WIFI. In in Linux we can expect that networking is ...
Definition CanMsg.cpp:31